context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
// <file>
// <copyright see="prj:///doc/copyright.txt"/>
// <license see="prj:///doc/license.txt"/>
// <author name="Daniel Grunwald"/>
// <version>$Revision: 5584 $</version>
// </file>
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.TextFormatting;
using System.Windows.Threading;
using ICSharpCode.AvalonEdit.Document;
using ICSharpCode.AvalonEdit.Utils;
namespace ICSharpCode.AvalonEdit.Rendering
{
/// <summary>
/// A virtualizing panel producing+showing <see cref="VisualLine"/>s for a <see cref="TextDocument"/>.
///
/// This is the heart of the text editor, this class controls the text rendering process.
///
/// Taken as a standalone control, it's a text viewer without any editing capability.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable",
Justification = "The user usually doesn't work with TextView but with TextEditor; and nulling the Document property is sufficient to dispose everything.")]
public class TextView : FrameworkElement, IScrollInfo, IWeakEventListener, ITextEditorComponent, IServiceProvider
{
#region Constructor
static TextView()
{
ClipToBoundsProperty.OverrideMetadata(typeof(TextView), new FrameworkPropertyMetadata(Boxes.True));
FocusableProperty.OverrideMetadata(typeof(TextView), new FrameworkPropertyMetadata(Boxes.False));
}
/// <summary>
/// Creates a new TextView instance.
/// </summary>
public TextView()
{
services.AddService(typeof(TextView), this);
textLayer = new TextLayer(this);
elementGenerators = new ObserveAddRemoveCollection<VisualLineElementGenerator>(ElementGenerator_Added, ElementGenerator_Removed);
lineTransformers = new ObserveAddRemoveCollection<IVisualLineTransformer>(LineTransformer_Added, LineTransformer_Removed);
backgroundRenderers = new ObserveAddRemoveCollection<IBackgroundRenderer>(BackgroundRenderer_Added, BackgroundRenderer_Removed);
this.Options = new TextEditorOptions();
Debug.Assert(singleCharacterElementGenerator != null); // assert that the option change created the builtin element generators
layers = new UIElementCollection(this, this);
InsertLayer(textLayer, KnownLayer.Text, LayerInsertionPosition.Replace);
}
#endregion
#region Document Property
/// <summary>
/// Document property.
/// </summary>
public static readonly DependencyProperty DocumentProperty =
DependencyProperty.Register("Document", typeof(TextDocument), typeof(TextView),
new FrameworkPropertyMetadata(OnDocumentChanged));
TextDocument document;
HeightTree heightTree;
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// </summary>
public TextDocument Document {
get { return (TextDocument)GetValue(DocumentProperty); }
set { SetValue(DocumentProperty, value); }
}
static void OnDocumentChanged(DependencyObject dp, DependencyPropertyChangedEventArgs e)
{
((TextView)dp).OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
internal double FontSize {
get {
return (double)GetValue(TextBlock.FontSizeProperty);
}
}
/// <summary>
/// Occurs when the document property has changed.
/// </summary>
public event EventHandler DocumentChanged;
void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null) {
heightTree.Dispose();
heightTree = null;
formatter.Dispose();
formatter = null;
TextDocumentWeakEventManager.Changing.RemoveListener(oldValue, this);
}
this.document = newValue;
ClearScrollData();
ClearVisualLines();
if (newValue != null) {
TextDocumentWeakEventManager.Changing.AddListener(newValue, this);
heightTree = new HeightTree(newValue, FontSize + 3);
formatter = TextFormatterFactory.Create(this);
}
InvalidateMeasure(DispatcherPriority.Normal);
if (DocumentChanged != null)
DocumentChanged(this, EventArgs.Empty);
}
/// <summary>
/// Recreates the text formatter that is used internally
/// by calling <see cref="TextFormatterFactory.Create"/>.
/// </summary>
void RecreateTextFormatter()
{
if (formatter != null) {
formatter.Dispose();
formatter = TextFormatterFactory.Create(this);
Redraw();
}
}
/// <inheritdoc cref="IWeakEventListener.ReceiveWeakEvent"/>
protected virtual bool ReceiveWeakEvent(Type managerType, object sender, EventArgs e)
{
if (managerType == typeof(TextDocumentWeakEventManager.Changing)) {
// TODO: put redraw into background so that other input events can be handled before the redraw.
// Unfortunately the "easy" approach (just use DispatcherPriority.Background) here makes the editor twice as slow because
// the caret position change forces an immediate redraw, and the text input then forces a background redraw.
// When fixing this, make sure performance on the SharpDevelop "type text in C# comment" stress test doesn't get significantly worse.
DocumentChangeEventArgs change = (DocumentChangeEventArgs)e;
Redraw(change.Offset, change.RemovalLength, DispatcherPriority.Normal);
return true;
} else if (managerType == typeof(PropertyChangedWeakEventManager)) {
OnOptionChanged((PropertyChangedEventArgs)e);
return true;
}
return false;
}
bool IWeakEventListener.ReceiveWeakEvent(Type managerType, object sender, EventArgs e)
{
return ReceiveWeakEvent(managerType, sender, e);
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly DependencyProperty OptionsProperty =
DependencyProperty.Register("Options", typeof(TextEditorOptions), typeof(TextView),
new FrameworkPropertyMetadata(OnOptionsChanged));
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// </summary>
public TextEditorOptions Options {
get { return (TextEditorOptions)GetValue(OptionsProperty); }
set { SetValue(OptionsProperty, value); }
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
public event PropertyChangedEventHandler OptionChanged;
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
if (OptionChanged != null) {
OptionChanged(this, e);
}
UpdateBuiltinElementGeneratorsFromOptions();
Redraw();
}
static void OnOptionsChanged(DependencyObject dp, DependencyPropertyChangedEventArgs e)
{
((TextView)dp).OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null) {
PropertyChangedWeakEventManager.RemoveListener(oldValue, this);
}
if (newValue != null) {
PropertyChangedWeakEventManager.AddListener(newValue, this);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
#endregion
#region ElementGenerators+LineTransformers Properties
readonly ObserveAddRemoveCollection<VisualLineElementGenerator> elementGenerators;
/// <summary>
/// Gets a collection where element generators can be registered.
/// </summary>
public IList<VisualLineElementGenerator> ElementGenerators {
get { return elementGenerators; }
}
void ElementGenerator_Added(VisualLineElementGenerator generator)
{
ConnectToTextView(generator);
Redraw();
}
void ElementGenerator_Removed(VisualLineElementGenerator generator)
{
DisconnectFromTextView(generator);
Redraw();
}
readonly ObserveAddRemoveCollection<IVisualLineTransformer> lineTransformers;
/// <summary>
/// Gets a collection where line transformers can be registered.
/// </summary>
public IList<IVisualLineTransformer> LineTransformers {
get { return lineTransformers; }
}
void LineTransformer_Added(IVisualLineTransformer lineTransformer)
{
ConnectToTextView(lineTransformer);
Redraw();
}
void LineTransformer_Removed(IVisualLineTransformer lineTransformer)
{
DisconnectFromTextView(lineTransformer);
Redraw();
}
#endregion
#region Builtin ElementGenerators
NewLineElementGenerator newLineElementGenerator;
SingleCharacterElementGenerator singleCharacterElementGenerator;
LinkElementGenerator linkElementGenerator;
MailLinkElementGenerator mailLinkElementGenerator;
void UpdateBuiltinElementGeneratorsFromOptions()
{
TextEditorOptions options = this.Options;
AddRemoveDefaultElementGeneratorOnDemand(ref newLineElementGenerator, options.ShowEndOfLine);
AddRemoveDefaultElementGeneratorOnDemand(ref singleCharacterElementGenerator, options.ShowBoxForControlCharacters || options.ShowSpaces || options.ShowTabs);
AddRemoveDefaultElementGeneratorOnDemand(ref linkElementGenerator, options.EnableHyperlinks);
AddRemoveDefaultElementGeneratorOnDemand(ref mailLinkElementGenerator, options.EnableEmailHyperlinks);
}
void AddRemoveDefaultElementGeneratorOnDemand<T>(ref T generator, bool demand)
where T : VisualLineElementGenerator, IBuiltinElementGenerator, new()
{
bool hasGenerator = generator != null;
if (hasGenerator != demand) {
if (demand) {
generator = new T();
this.ElementGenerators.Add(generator);
} else {
this.ElementGenerators.Remove(generator);
generator = null;
}
}
if (generator != null)
generator.FetchOptions(this.Options);
}
#endregion
#region Layers
internal readonly TextLayer textLayer;
readonly UIElementCollection layers;
/// <summary>
/// Gets the list of layers displayed in the text view.
/// </summary>
public UIElementCollection Layers {
get { return layers; }
}
/// <summary>
/// Inserts a new layer at a position specified relative to an existing layer.
/// </summary>
/// <param name="layer">The new layer to insert.</param>
/// <param name="referencedLayer">The existing layer</param>
/// <param name="position">Specifies whether the layer is inserted above,below, or replaces the referenced layer</param>
public void InsertLayer(UIElement layer, KnownLayer referencedLayer, LayerInsertionPosition position)
{
if (layer == null)
throw new ArgumentNullException("layer");
if (!Enum.IsDefined(typeof(KnownLayer), referencedLayer))
throw new InvalidEnumArgumentException("referencedLayer", (int)referencedLayer, typeof(KnownLayer));
if (!Enum.IsDefined(typeof(LayerInsertionPosition), position))
throw new InvalidEnumArgumentException("position", (int)position, typeof(LayerInsertionPosition));
if (referencedLayer == KnownLayer.Background && position != LayerInsertionPosition.Above)
throw new InvalidOperationException("Cannot replace or insert below the background layer.");
LayerPosition newPosition = new LayerPosition(referencedLayer, position);
LayerPosition.SetLayerPosition(layer, newPosition);
for (int i = 0; i < layers.Count; i++) {
LayerPosition p = LayerPosition.GetLayerPosition(layers[i]);
if (p != null) {
if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Replace) {
// found the referenced layer
switch (position) {
case LayerInsertionPosition.Below:
layers.Insert(i, layer);
return;
case LayerInsertionPosition.Above:
layers.Insert(i + 1, layer);
return;
case LayerInsertionPosition.Replace:
layers[i] = layer;
return;
}
} else if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Above
|| p.KnownLayer > referencedLayer) {
// we skipped the insertion position (referenced layer does not exist?)
layers.Insert(i, layer);
return;
}
}
}
// inserting after all existing layers:
layers.Add(layer);
}
/// <inheritdoc/>
protected override int VisualChildrenCount {
get { return layers.Count; }
}
/// <inheritdoc/>
protected override Visual GetVisualChild(int index)
{
return layers[index];
}
/// <inheritdoc/>
protected override System.Collections.IEnumerator LogicalChildren {
get { return layers.GetEnumerator(); }
}
#endregion
#region Redraw methods / VisualLine invalidation
/// <summary>
/// Causes the text editor to regenerate all visual lines.
/// </summary>
public void Redraw()
{
Redraw(DispatcherPriority.Normal);
}
/// <summary>
/// Causes the text editor to regenerate all visual lines.
/// </summary>
public void Redraw(DispatcherPriority redrawPriority)
{
VerifyAccess();
ClearVisualLines();
InvalidateMeasure(redrawPriority);
}
/// <summary>
/// Causes the text editor to regenerate the specified visual line.
/// </summary>
public void Redraw(VisualLine visualLine, DispatcherPriority redrawPriority)
{
VerifyAccess();
if (allVisualLines.Remove(visualLine)) {
visibleVisualLines = null;
DisposeVisualLine(visualLine);
InvalidateMeasure(redrawPriority);
}
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// </summary>
public void Redraw(int offset, int length, DispatcherPriority redrawPriority)
{
VerifyAccess();
bool removedLine = false;
bool changedSomethingBeforeOrInLine = false;
for (int i = 0; i < allVisualLines.Count; i++) {
VisualLine visualLine = allVisualLines[i];
int lineStart = visualLine.FirstDocumentLine.Offset;
int lineEnd = visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength;
if (offset <= lineEnd) {
changedSomethingBeforeOrInLine = true;
if (offset + length >= lineStart) {
removedLine = true;
allVisualLines.RemoveAt(i--);
DisposeVisualLine(visualLine);
}
}
}
if (removedLine) {
visibleVisualLines = null;
}
if (changedSomethingBeforeOrInLine) {
// Repaint not only when something in visible area was changed, but also when anything in front of it
// was changed. We might have to redraw the line number margin. Or the highlighting changed.
// However, we'll try to reuse the existing VisualLines.
InvalidateMeasure(redrawPriority);
}
}
/// <summary>
/// Causes a known layer to redraw.
/// This method does not invalidate visual lines;
/// use the <see cref="Redraw()"/> method to do that.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "knownLayer",
Justification="This method is meant to invalidate only a specific layer - I just haven't figured out how to do that, yet.")]
public void InvalidateLayer(KnownLayer knownLayer)
{
InvalidateMeasure(DispatcherPriority.Normal);
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// Does nothing if segment is null.
/// </summary>
public void Redraw(ISegment segment, DispatcherPriority redrawPriority)
{
if (segment != null) {
Redraw(segment.Offset, segment.Length, redrawPriority);
}
}
/// <summary>
/// Invalidates all visual lines.
/// The caller of ClearVisualLines() must also call InvalidateMeasure() to ensure
/// that the visual lines will be recreated.
/// </summary>
void ClearVisualLines()
{
visibleVisualLines = null;
if (allVisualLines.Count != 0) {
foreach (VisualLine visualLine in allVisualLines) {
DisposeVisualLine(visualLine);
}
allVisualLines.Clear();
}
}
void DisposeVisualLine(VisualLine visualLine)
{
if (newVisualLines != null && newVisualLines.Contains(visualLine)) {
throw new ArgumentException("Cannot dispose visual line because it is in construction!");
}
visualLine.IsDisposed = true;
foreach (TextLine textLine in visualLine.TextLines) {
textLine.Dispose();
}
textLayer.RemoveInlineObjects(visualLine);
}
#endregion
#region InvalidateMeasure(DispatcherPriority)
DispatcherOperation invalidateMeasureOperation;
void InvalidateMeasure(DispatcherPriority priority)
{
if (priority >= DispatcherPriority.Render) {
if (invalidateMeasureOperation != null) {
invalidateMeasureOperation.Abort();
invalidateMeasureOperation = null;
}
base.InvalidateMeasure();
} else {
if (invalidateMeasureOperation != null) {
invalidateMeasureOperation.Priority = priority;
} else {
invalidateMeasureOperation = Dispatcher.BeginInvoke(
priority,
new Action(
delegate {
invalidateMeasureOperation = null;
base.InvalidateMeasure();
}
)
);
}
}
}
#endregion
#region Get(OrConstruct)VisualLine
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
/// Returns null if the document line is outside the visible range.
/// </summary>
public VisualLine GetVisualLine(int documentLineNumber)
{
// TODO: EnsureVisualLines() ?
foreach (VisualLine visualLine in allVisualLines) {
Debug.Assert(visualLine.IsDisposed == false);
int start = visualLine.FirstDocumentLine.LineNumber;
int end = visualLine.LastDocumentLine.LineNumber;
if (documentLineNumber >= start && documentLineNumber <= end)
return visualLine;
}
return null;
}
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
/// If that line is outside the visible range, a new VisualLine for that document line is constructed.
/// </summary>
public VisualLine GetOrConstructVisualLine(DocumentLine documentLine)
{
if (documentLine == null)
throw new ArgumentNullException("documentLine");
if (!this.Document.Lines.Contains(documentLine))
throw new InvalidOperationException("Line belongs to wrong document");
VerifyAccess();
VisualLine l = GetVisualLine(documentLine.LineNumber);
if (l == null) {
TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties();
TextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties);
while (heightTree.GetIsCollapsed(documentLine)) {
documentLine = heightTree.GetLineByNumber(documentLine.LineNumber - 1);
}
l = BuildVisualLine(documentLine,
globalTextRunProperties, paragraphProperties,
elementGenerators.ToArray(), lineTransformers.ToArray(),
lastAvailableSize);
l.VisualTop = heightTree.GetVisualPosition(documentLine);
allVisualLines.Add(l);
}
return l;
}
#endregion
#region Visual Lines (fields and properties)
List<VisualLine> allVisualLines = new List<VisualLine>();
ReadOnlyCollection<VisualLine> visibleVisualLines;
double clippedPixelsOnTop;
List<VisualLine> newVisualLines;
/// <summary>
/// Gets the currently visible visual lines.
/// </summary>
/// <exception cref="VisualLinesInvalidException">
/// Gets thrown if there are invalid visual lines when this property is accessed.
/// You can use the <see cref="VisualLinesValid"/> property to check for this case,
/// or use the <see cref="EnsureVisualLines()"/> method to force creating the visual lines
/// when they are invalid.
/// </exception>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")]
public ReadOnlyCollection<VisualLine> VisualLines {
get {
if (visibleVisualLines == null)
throw new VisualLinesInvalidException();
return visibleVisualLines;
}
}
/// <summary>
/// Gets whether the visual lines are valid.
/// Will return false after a call to Redraw().
/// Accessing the visual lines property will cause a <see cref="VisualLinesInvalidException"/>
/// if this property is <c>false</c>.
/// </summary>
public bool VisualLinesValid {
get { return visibleVisualLines != null; }
}
/// <summary>
/// Occurs when the TextView is about to be measured and will regenerate its visual lines.
/// This event may be used to mark visual lines as invalid that would otherwise be reused.
/// </summary>
public event EventHandler<VisualLineConstructionStartEventArgs> VisualLineConstructionStarting;
/// <summary>
/// Occurs when the TextView was measured and changed its visual lines.
/// </summary>
public event EventHandler VisualLinesChanged;
/// <summary>
/// If the visual lines are invalid, creates new visual lines for the visible part
/// of the document.
/// If all visual lines are valid, this method does nothing.
/// </summary>
/// <exception cref="InvalidOperationException">The visual line build process is already running.
/// It is not allowed to call this method during the construction of a visual line.</exception>
public void EnsureVisualLines()
{
Dispatcher.VerifyAccess();
if (inMeasure)
throw new InvalidOperationException("The visual line build process is already running! Cannot EnsureVisualLines() during Measure!");
if (!VisualLinesValid) {
// increase priority for re-measure
InvalidateMeasure(DispatcherPriority.Normal);
// force immediate re-measure
UpdateLayout();
}
// Sometimes we still have invalid lines after UpdateLayout - work around the problem
// by calling MeasureOverride directly.
if (!VisualLinesValid) {
Debug.WriteLine("UpdateLayout() failed in EnsureVisualLines");
MeasureOverride(lastAvailableSize);
}
if (!VisualLinesValid)
throw new VisualLinesInvalidException("Internal error: visual lines invalid after EnsureVisualLines call");
}
#endregion
#region Measure
/// <summary>
/// Additonal amount that allows horizontal scrolling past the end of the longest line.
/// This is necessary to ensure the caret always is visible, even when it is at the end of the longest line.
/// </summary>
const double AdditionalHorizontalScrollAmount = 30;
Size lastAvailableSize;
bool inMeasure;
/// <inheritdoc/>
protected override Size MeasureOverride(Size availableSize)
{
// We don't support infinite available width, so we'll limit it to 32000 pixels.
if (availableSize.Width > 32000)
availableSize.Width = 32000;
if (!canHorizontallyScroll && !availableSize.Width.IsClose(lastAvailableSize.Width))
ClearVisualLines();
lastAvailableSize = availableSize;
textLayer.RemoveInlineObjectsNow();
foreach (UIElement layer in layers) {
layer.Measure(availableSize);
}
InvalidateVisual(); // = InvalidateArrange+InvalidateRender
textLayer.InvalidateVisual();
double maxWidth;
if (document == null) {
// no document -> create empty list of lines
allVisualLines = new List<VisualLine>();
visibleVisualLines = allVisualLines.AsReadOnly();
maxWidth = 0;
} else {
inMeasure = true;
try {
maxWidth = CreateAndMeasureVisualLines(availableSize);
} finally {
inMeasure = false;
}
}
textLayer.RemoveInlineObjectsNow();
maxWidth += AdditionalHorizontalScrollAmount;
double heightTreeHeight = this.DocumentHeight;
TextEditorOptions options = this.Options;
if (options.AllowScrollBelowDocument) {
heightTreeHeight = Math.Max(heightTreeHeight, Math.Min(heightTreeHeight - 50, scrollOffset.Y) + scrollViewport.Height);
}
SetScrollData(availableSize,
new Size(maxWidth, heightTreeHeight),
scrollOffset);
if (VisualLinesChanged != null)
VisualLinesChanged(this, EventArgs.Empty);
return new Size(
canHorizontallyScroll ? Math.Min(availableSize.Width, maxWidth) : maxWidth,
canVerticallyScroll ? Math.Min(availableSize.Height, heightTreeHeight) : heightTreeHeight
);
}
/// <summary>
/// Build all VisualLines in the visible range.
/// </summary>
/// <returns>Width the longest line</returns>
double CreateAndMeasureVisualLines(Size availableSize)
{
TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties();
TextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties);
Debug.WriteLine("Measure availableSize=" + availableSize + ", scrollOffset=" + scrollOffset);
var firstLineInView = heightTree.GetLineByVisualPosition(scrollOffset.Y);
// number of pixels clipped from the first visual line(s)
clippedPixelsOnTop = scrollOffset.Y - heightTree.GetVisualPosition(firstLineInView);
Debug.Assert(clippedPixelsOnTop >= 0);
newVisualLines = new List<VisualLine>();
if (VisualLineConstructionStarting != null)
VisualLineConstructionStarting(this, new VisualLineConstructionStartEventArgs(firstLineInView));
var elementGeneratorsArray = elementGenerators.ToArray();
var lineTransformersArray = lineTransformers.ToArray();
var nextLine = firstLineInView;
double maxWidth = 0;
double yPos = -clippedPixelsOnTop;
while (yPos < availableSize.Height && nextLine != null) {
VisualLine visualLine = GetVisualLine(nextLine.LineNumber);
if (visualLine == null) {
visualLine = BuildVisualLine(nextLine,
globalTextRunProperties, paragraphProperties,
elementGeneratorsArray, lineTransformersArray,
availableSize);
}
visualLine.VisualTop = scrollOffset.Y + yPos;
nextLine = visualLine.LastDocumentLine.NextLine;
yPos += visualLine.Height;
foreach (TextLine textLine in visualLine.TextLines) {
if (textLine.WidthIncludingTrailingWhitespace > maxWidth)
maxWidth = textLine.WidthIncludingTrailingWhitespace;
}
newVisualLines.Add(visualLine);
}
foreach (VisualLine line in allVisualLines) {
Debug.Assert(line.IsDisposed == false);
if (!newVisualLines.Contains(line))
DisposeVisualLine(line);
}
allVisualLines = newVisualLines;
// visibleVisualLines = readonly copy of visual lines
visibleVisualLines = new ReadOnlyCollection<VisualLine>(newVisualLines.ToArray());
newVisualLines = null;
if (allVisualLines.Any(line => line.IsDisposed)) {
throw new InvalidOperationException("A visual line was disposed even though it is still in use.\n" +
"This can happen when Redraw() is called during measure for lines " +
"that are already constructed.");
}
return maxWidth;
}
#endregion
#region BuildVisualLine
TextFormatter formatter;
TextRunProperties CreateGlobalTextRunProperties()
{
return new GlobalTextRunProperties {
typeface = this.CreateTypeface(),
fontRenderingEmSize = FontSize,
foregroundBrush = (Brush)GetValue(Control.ForegroundProperty),
cultureInfo = CultureInfo.CurrentCulture
};
}
TextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties)
{
return new VisualLineTextParagraphProperties {
defaultTextRunProperties = defaultTextRunProperties,
textWrapping = canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap,
tabSize = Options.IndentationSize * WideSpaceWidth
};
}
VisualLine BuildVisualLine(DocumentLine documentLine,
TextRunProperties globalTextRunProperties,
TextParagraphProperties paragraphProperties,
VisualLineElementGenerator[] elementGeneratorsArray,
IVisualLineTransformer[] lineTransformersArray,
Size availableSize)
{
if (heightTree.GetIsCollapsed(documentLine))
throw new InvalidOperationException("Trying to build visual line from collapsed line");
Debug.WriteLine("Building line " + documentLine.LineNumber);
VisualLine visualLine = new VisualLine(this, documentLine);
VisualLineTextSource textSource = new VisualLineTextSource(visualLine) {
Document = document,
GlobalTextRunProperties = globalTextRunProperties,
TextView = this
};
visualLine.ConstructVisualElements(textSource, elementGeneratorsArray);
#if DEBUG
for (int i = visualLine.FirstDocumentLine.LineNumber + 1; i <= visualLine.LastDocumentLine.LineNumber; i++) {
if (!heightTree.GetIsCollapsed(document.GetLineByNumber(i)))
throw new InvalidOperationException("Line " + i + " was skipped by a VisualLineElementGenerator, but it is not collapsed.");
}
#endif
visualLine.RunTransformers(textSource, lineTransformersArray);
// now construct textLines:
int textOffset = 0;
TextLineBreak lastLineBreak = null;
var textLines = new List<TextLine>();
while (textOffset <= visualLine.VisualLength) {
TextLine textLine = formatter.FormatLine(
textSource,
textOffset,
availableSize.Width,
paragraphProperties,
lastLineBreak
);
textLines.Add(textLine);
textOffset += textLine.Length;
lastLineBreak = textLine.GetTextLineBreak();
}
visualLine.SetTextLines(textLines);
heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height);
return visualLine;
}
#endregion
#region Arrange
/// <summary>
/// Arrange implementation.
/// </summary>
protected override Size ArrangeOverride(Size finalSize)
{
EnsureVisualLines();
foreach (UIElement layer in layers) {
layer.Arrange(new Rect(new Point(0, 0), finalSize));
}
if (document == null || allVisualLines.Count == 0)
return finalSize;
// validate scroll position
Vector newScrollOffset = scrollOffset;
if (scrollOffset.X + finalSize.Width > scrollExtent.Width) {
newScrollOffset.X = Math.Max(0, scrollExtent.Width - finalSize.Width);
}
if (scrollOffset.Y + finalSize.Height > scrollExtent.Height) {
newScrollOffset.Y = Math.Max(0, scrollExtent.Height - finalSize.Height);
}
if (SetScrollData(scrollViewport, scrollExtent, newScrollOffset))
InvalidateMeasure(DispatcherPriority.Normal);
//Debug.WriteLine("Arrange finalSize=" + finalSize + ", scrollOffset=" + scrollOffset);
// double maxWidth = 0;
if (visibleVisualLines != null) {
Point pos = new Point(-scrollOffset.X, -clippedPixelsOnTop);
foreach (VisualLine visualLine in visibleVisualLines) {
int offset = 0;
foreach (TextLine textLine in visualLine.TextLines) {
foreach (var span in textLine.GetTextRunSpans()) {
InlineObjectRun inline = span.Value as InlineObjectRun;
if (inline != null && inline.VisualLine != null) {
Debug.Assert(textLayer.inlineObjects.Contains(inline));
double distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset, 0));
inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize));
}
offset += span.Length;
}
pos.Y += textLine.Height;
}
}
}
InvalidateCursor();
return finalSize;
}
#endregion
#region Render
readonly ObserveAddRemoveCollection<IBackgroundRenderer> backgroundRenderers;
/// <summary>
/// Gets the list of background renderers.
/// </summary>
public IList<IBackgroundRenderer> BackgroundRenderers {
get { return backgroundRenderers; }
}
void BackgroundRenderer_Added(IBackgroundRenderer renderer)
{
ConnectToTextView(renderer);
InvalidateLayer(renderer.Layer);
}
void BackgroundRenderer_Removed(IBackgroundRenderer renderer)
{
DisconnectFromTextView(renderer);
InvalidateLayer(renderer.Layer);
}
/// <inheritdoc/>
protected override void OnRender(DrawingContext drawingContext)
{
RenderBackground(drawingContext, KnownLayer.Background);
}
internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer)
{
foreach (IBackgroundRenderer bg in backgroundRenderers) {
if (bg.Layer == layer) {
bg.Draw(this, drawingContext);
}
}
}
internal void RenderTextLayer(DrawingContext drawingContext)
{
Point pos = new Point(-scrollOffset.X, -clippedPixelsOnTop);
foreach (VisualLine visualLine in allVisualLines) {
foreach (TextLine textLine in visualLine.TextLines) {
textLine.Draw(drawingContext, pos, InvertAxes.None);
pos.Y += textLine.Height;
}
}
}
#endregion
#region IScrollInfo implementation
/// <summary>
/// Size of the document, in pixels.
/// </summary>
Size scrollExtent;
/// <summary>
/// Offset of the scroll position.
/// </summary>
Vector scrollOffset;
/// <summary>
/// Size of the viewport.
/// </summary>
Size scrollViewport;
void ClearScrollData()
{
SetScrollData(new Size(), new Size(), new Vector());
}
bool SetScrollData(Size viewport, Size extent, Vector offset)
{
if (!(viewport.IsClose(this.scrollViewport)
&& extent.IsClose(this.scrollExtent)
&& offset.IsClose(this.scrollOffset)))
{
this.scrollViewport = viewport;
this.scrollExtent = extent;
SetScrollOffset(offset);
this.OnScrollChange();
return true;
}
return false;
}
void OnScrollChange()
{
ScrollViewer scrollOwner = ((IScrollInfo)this).ScrollOwner;
if (scrollOwner != null) {
scrollOwner.InvalidateScrollInfo();
}
}
bool canVerticallyScroll;
bool IScrollInfo.CanVerticallyScroll {
get { return canVerticallyScroll; }
set {
if (canVerticallyScroll != value) {
canVerticallyScroll = value;
InvalidateMeasure(DispatcherPriority.Normal);
}
}
}
bool canHorizontallyScroll;
bool IScrollInfo.CanHorizontallyScroll {
get { return canHorizontallyScroll; }
set {
if (canHorizontallyScroll != value) {
canHorizontallyScroll = value;
ClearVisualLines();
InvalidateMeasure(DispatcherPriority.Normal);
}
}
}
double IScrollInfo.ExtentWidth {
get { return scrollExtent.Width; }
}
double IScrollInfo.ExtentHeight {
get { return scrollExtent.Height; }
}
double IScrollInfo.ViewportWidth {
get { return scrollViewport.Width; }
}
double IScrollInfo.ViewportHeight {
get { return scrollViewport.Height; }
}
/// <summary>
/// Gets the horizontal scroll offset.
/// </summary>
public double HorizontalOffset {
get { return scrollOffset.X; }
}
/// <summary>
/// Gets the vertical scroll offset.
/// </summary>
public double VerticalOffset {
get { return scrollOffset.Y; }
}
/// <summary>
/// Gets the scroll offset;
/// </summary>
public Vector ScrollOffset {
get { return scrollOffset; }
}
/// <summary>
/// Occurs when the scroll offset has changed.
/// </summary>
public event EventHandler ScrollOffsetChanged;
void SetScrollOffset(Vector vector)
{
if (!scrollOffset.IsClose(vector)) {
scrollOffset = vector;
if (ScrollOffsetChanged != null)
ScrollOffsetChanged(this, EventArgs.Empty);
}
}
ScrollViewer IScrollInfo.ScrollOwner { get; set; }
void IScrollInfo.LineUp()
{
((IScrollInfo)this).SetVerticalOffset(scrollOffset.Y - FontSize);
}
void IScrollInfo.LineDown()
{
((IScrollInfo)this).SetVerticalOffset(scrollOffset.Y + FontSize);
}
void IScrollInfo.LineLeft()
{
((IScrollInfo)this).SetHorizontalOffset(scrollOffset.X - WideSpaceWidth);
}
void IScrollInfo.LineRight()
{
((IScrollInfo)this).SetHorizontalOffset(scrollOffset.X + WideSpaceWidth);
}
void IScrollInfo.PageUp()
{
((IScrollInfo)this).SetVerticalOffset(scrollOffset.Y - scrollViewport.Height);
}
void IScrollInfo.PageDown()
{
((IScrollInfo)this).SetVerticalOffset(scrollOffset.Y + scrollViewport.Height);
}
void IScrollInfo.PageLeft()
{
((IScrollInfo)this).SetHorizontalOffset(scrollOffset.X - scrollViewport.Width);
}
void IScrollInfo.PageRight()
{
((IScrollInfo)this).SetHorizontalOffset(scrollOffset.X + scrollViewport.Width);
}
void IScrollInfo.MouseWheelUp()
{
((IScrollInfo)this).SetVerticalOffset(
scrollOffset.Y - (SystemParameters.WheelScrollLines * FontSize));
OnScrollChange();
}
void IScrollInfo.MouseWheelDown()
{
((IScrollInfo)this).SetVerticalOffset(
scrollOffset.Y + (SystemParameters.WheelScrollLines * FontSize));
OnScrollChange();
}
void IScrollInfo.MouseWheelLeft()
{
((IScrollInfo)this).SetHorizontalOffset(
scrollOffset.X - (SystemParameters.WheelScrollLines * WideSpaceWidth));
OnScrollChange();
}
void IScrollInfo.MouseWheelRight()
{
((IScrollInfo)this).SetHorizontalOffset(
scrollOffset.X + (SystemParameters.WheelScrollLines * WideSpaceWidth));
OnScrollChange();
}
double WideSpaceWidth {
get {
return FontSize / 2;
}
}
static double ValidateVisualOffset(double offset)
{
if (double.IsNaN(offset))
throw new ArgumentException("offset must not be NaN");
if (offset < 0)
return 0;
else
return offset;
}
void IScrollInfo.SetHorizontalOffset(double offset)
{
offset = ValidateVisualOffset(offset);
if (!scrollOffset.X.IsClose(offset)) {
SetScrollOffset(new Vector(offset, scrollOffset.Y));
InvalidateVisual();
textLayer.InvalidateVisual();
}
}
void IScrollInfo.SetVerticalOffset(double offset)
{
offset = ValidateVisualOffset(offset);
if (!scrollOffset.Y.IsClose(offset)) {
SetScrollOffset(new Vector(scrollOffset.X, offset));
InvalidateMeasure(DispatcherPriority.Normal);
}
}
Rect IScrollInfo.MakeVisible(Visual visual, Rect rectangle)
{
if (rectangle.IsEmpty || visual == null || visual == this || !this.IsAncestorOf(visual)) {
return Rect.Empty;
}
// Convert rectangle into our coordinate space.
GeneralTransform childTransform = visual.TransformToAncestor(this);
rectangle = childTransform.TransformBounds(rectangle);
MakeVisible(Rect.Offset(rectangle, scrollOffset));
return rectangle;
}
/// <summary>
/// Scrolls the text view so that the specified rectangle gets visible.
/// </summary>
public void MakeVisible(Rect rectangle)
{
Rect visibleRectangle = new Rect(scrollOffset.X, scrollOffset.Y,
scrollViewport.Width, scrollViewport.Height);
Vector newScrollOffset = scrollOffset;
if (rectangle.Left < visibleRectangle.Left) {
if (rectangle.Right > visibleRectangle.Right) {
newScrollOffset.X = rectangle.Left + rectangle.Width / 2;
} else {
newScrollOffset.X = rectangle.Left;
}
} else if (rectangle.Right > visibleRectangle.Right) {
newScrollOffset.X = rectangle.Right - scrollViewport.Width;
}
if (rectangle.Top < visibleRectangle.Top) {
if (rectangle.Bottom > visibleRectangle.Bottom) {
newScrollOffset.Y = rectangle.Top + rectangle.Height / 2;
} else {
newScrollOffset.Y = rectangle.Top;
}
} else if (rectangle.Bottom > visibleRectangle.Bottom) {
newScrollOffset.Y = rectangle.Bottom - scrollViewport.Height;
}
newScrollOffset.X = ValidateVisualOffset(newScrollOffset.X);
newScrollOffset.Y = ValidateVisualOffset(newScrollOffset.Y);
if (!scrollOffset.IsClose(newScrollOffset)) {
SetScrollOffset(newScrollOffset);
this.OnScrollChange();
InvalidateMeasure(DispatcherPriority.Normal);
}
}
#endregion
#region Visual element mouse handling
/// <inheritdoc/>
protected override HitTestResult HitTestCore(PointHitTestParameters hitTestParameters)
{
// accept clicks even where the text area draws no background
return new PointHitTestResult(this, hitTestParameters.HitPoint);
}
[ThreadStatic] static bool invalidCursor;
/// <summary>
/// Updates the mouse cursor by calling <see cref="Mouse.UpdateCursor"/>, but with input priority.
/// </summary>
public static void InvalidateCursor()
{
if (!invalidCursor) {
invalidCursor = true;
Dispatcher.CurrentDispatcher.BeginInvoke(
DispatcherPriority.Input,
new Action(
delegate {
invalidCursor = false;
Mouse.UpdateCursor();
}));
}
}
/// <inheritdoc/>
protected override void OnQueryCursor(QueryCursorEventArgs e)
{
VisualLineElement element = GetVisualLineElementFromPosition(e.GetPosition(this) + scrollOffset);
if (element != null) {
element.OnQueryCursor(e);
}
}
/// <inheritdoc/>
protected override void OnMouseDown(MouseButtonEventArgs e)
{
base.OnMouseDown(e);
if (!e.Handled) {
EnsureVisualLines();
VisualLineElement element = GetVisualLineElementFromPosition(e.GetPosition(this) + scrollOffset);
if (element != null) {
element.OnMouseDown(e);
}
}
}
/// <inheritdoc/>
protected override void OnMouseUp(MouseButtonEventArgs e)
{
base.OnMouseUp(e);
if (!e.Handled) {
EnsureVisualLines();
VisualLineElement element = GetVisualLineElementFromPosition(e.GetPosition(this) + scrollOffset);
if (element != null) {
element.OnMouseUp(e);
}
}
}
#endregion
#region Getting elements from Visual Position
/// <summary>
/// Gets the visual line at the specified document position (relative to start of document).
/// Returns null if there is no visual line for the position (e.g. the position is outside the visible
/// text area).
/// </summary>
public VisualLine GetVisualLineFromVisualTop(double visualTop)
{
// TODO: change this method to also work outside the visible range -
// required to make GetPosition work as expected!
EnsureVisualLines();
foreach (VisualLine vl in this.VisualLines) {
if (visualTop < vl.VisualTop)
continue;
if (visualTop < vl.VisualTop + vl.Height)
return vl;
}
return null;
}
VisualLineElement GetVisualLineElementFromPosition(Point visualPosition)
{
VisualLine vl = GetVisualLineFromVisualTop(visualPosition.Y);
if (vl != null) {
int column = vl.GetVisualColumn(visualPosition);
// Debug.WriteLine(vl.FirstDocumentLine.LineNumber + " vc " + column);
foreach (VisualLineElement element in vl.Elements) {
if (element.VisualColumn + element.VisualLength < column)
continue;
return element;
}
}
return null;
}
#endregion
#region Visual Position <-> TextViewPosition
/// <summary>
/// Gets the visual position from a text view position.
/// </summary>
/// <param name="position">The text view position.</param>
/// <param name="yPositionMode">The mode how to retrieve the Y position.</param>
/// <returns>The position in WPF device-independent pixels relative
/// to the top left corner of the document.</returns>
public Point GetVisualPosition(TextViewPosition position, VisualYPosition yPositionMode)
{
VerifyAccess();
if (this.Document == null)
throw ThrowUtil.NoDocumentAssigned();
DocumentLine documentLine = this.Document.GetLineByNumber(position.Line);
VisualLine visualLine = GetOrConstructVisualLine(documentLine);
int visualColumn = position.VisualColumn;
if (visualColumn < 0) {
int offset = documentLine.Offset + position.Column - 1;
visualColumn = visualLine.GetVisualColumn(offset - visualLine.FirstDocumentLine.Offset);
}
return visualLine.GetVisualPosition(visualColumn, yPositionMode);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// </summary>
/// <param name="visualPosition">The position in WPF device-independent pixels relative
/// to the top left corner of the document.</param>
/// <returns>The logical position, or null if the position is outside the document.</returns>
public TextViewPosition? GetPosition(Point visualPosition)
{
VerifyAccess();
if (this.Document == null)
throw ThrowUtil.NoDocumentAssigned();
VisualLine line = GetVisualLineFromVisualTop(visualPosition.Y);
if (line == null)
return null;
int visualColumn = line.GetVisualColumn(visualPosition);
int documentOffset = line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset;
return new TextViewPosition(document.GetLocation(documentOffset), visualColumn);
}
#endregion
#region Service Provider
readonly ServiceContainer services = new ServiceContainer();
/// <summary>
/// Gets a service container used to associate services with the text view.
/// </summary>
public ServiceContainer Services {
get { return services; }
}
object IServiceProvider.GetService(Type serviceType)
{
return services.GetService(serviceType);
}
void ConnectToTextView(object obj)
{
ITextViewConnect c = obj as ITextViewConnect;
if (c != null)
c.AddToTextView(this);
}
void DisconnectFromTextView(object obj)
{
ITextViewConnect c = obj as ITextViewConnect;
if (c != null)
c.RemoveFromTextView(this);
}
#endregion
#region MouseHover
/// <summary>
/// The PreviewMouseHover event.
/// </summary>
public static readonly RoutedEvent PreviewMouseHoverEvent =
EventManager.RegisterRoutedEvent("PreviewMouseHover", RoutingStrategy.Tunnel,
typeof(MouseEventHandler), typeof(TextView));
/// <summary>
/// The MouseHover event.
/// </summary>
public static readonly RoutedEvent MouseHoverEvent =
EventManager.RegisterRoutedEvent("MouseHover", RoutingStrategy.Bubble,
typeof(MouseEventHandler), typeof(TextView));
/// <summary>
/// The PreviewMouseHoverStopped event.
/// </summary>
public static readonly RoutedEvent PreviewMouseHoverStoppedEvent =
EventManager.RegisterRoutedEvent("PreviewMouseHoverStopped", RoutingStrategy.Tunnel,
typeof(MouseEventHandler), typeof(TextView));
/// <summary>
/// The MouseHoverStopped event.
/// </summary>
public static readonly RoutedEvent MouseHoverStoppedEvent =
EventManager.RegisterRoutedEvent("MouseHoverStopped", RoutingStrategy.Bubble,
typeof(MouseEventHandler), typeof(TextView));
/// <summary>
/// Occurs when the mouse has hovered over a fixed location for some time.
/// </summary>
public event MouseEventHandler PreviewMouseHover {
add { AddHandler(PreviewMouseHoverEvent, value); }
remove { RemoveHandler(PreviewMouseHoverEvent, value); }
}
/// <summary>
/// Occurs when the mouse has hovered over a fixed location for some time.
/// </summary>
public event MouseEventHandler MouseHover {
add { AddHandler(MouseHoverEvent, value); }
remove { RemoveHandler(MouseHoverEvent, value); }
}
/// <summary>
/// Occurs when the mouse had previously hovered but now started moving again.
/// </summary>
public event MouseEventHandler PreviewMouseHoverStopped {
add { AddHandler(PreviewMouseHoverStoppedEvent, value); }
remove { RemoveHandler(PreviewMouseHoverStoppedEvent, value); }
}
/// <summary>
/// Occurs when the mouse had previously hovered but now started moving again.
/// </summary>
public event MouseEventHandler MouseHoverStopped {
add { AddHandler(MouseHoverStoppedEvent, value); }
remove { RemoveHandler(MouseHoverStoppedEvent, value); }
}
DispatcherTimer mouseHoverTimer;
Point mouseHoverStartPoint;
MouseEventArgs mouseHoverLastEventArgs;
bool mouseHovering;
/// <inheritdoc/>
protected override void OnMouseMove(MouseEventArgs e)
{
base.OnMouseMove(e);
Point newPosition = e.GetPosition(this);
Vector mouseMovement = mouseHoverStartPoint - newPosition;
if (Math.Abs(mouseMovement.X) > SystemParameters.MouseHoverWidth
|| Math.Abs(mouseMovement.Y) > SystemParameters.MouseHoverHeight)
{
StopHovering();
mouseHoverStartPoint = newPosition;
mouseHoverLastEventArgs = e;
mouseHoverTimer = new DispatcherTimer(SystemParameters.MouseHoverTime, DispatcherPriority.Background,
OnMouseHoverTimerElapsed, this.Dispatcher);
mouseHoverTimer.Start();
}
// do not set e.Handled - allow others to also handle MouseMove
}
/// <inheritdoc/>
protected override void OnMouseLeave(MouseEventArgs e)
{
base.OnMouseLeave(e);
StopHovering();
// do not set e.Handled - allow others to also handle MouseLeave
}
void StopHovering()
{
if (mouseHoverTimer != null) {
mouseHoverTimer.Stop();
mouseHoverTimer = null;
}
if (mouseHovering) {
mouseHovering = false;
RaiseHoverEventPair(PreviewMouseHoverStoppedEvent, MouseHoverStoppedEvent);
}
}
void OnMouseHoverTimerElapsed(object sender, EventArgs e)
{
mouseHoverTimer.Stop();
mouseHoverTimer = null;
mouseHovering = true;
RaiseHoverEventPair(PreviewMouseHoverEvent, MouseHoverEvent);
}
void RaiseHoverEventPair(RoutedEvent tunnelingEvent, RoutedEvent bubblingEvent)
{
var mouseDevice = mouseHoverLastEventArgs.MouseDevice;
var stylusDevice = mouseHoverLastEventArgs.StylusDevice;
int inputTime = Environment.TickCount;
var args1 = new MouseEventArgs(mouseDevice, inputTime, stylusDevice) {
RoutedEvent = tunnelingEvent,
Source = this
};
RaiseEvent(args1);
var args2 = new MouseEventArgs(mouseDevice, inputTime, stylusDevice) {
RoutedEvent = bubblingEvent,
Source = this,
Handled = args1.Handled
};
RaiseEvent(args2);
}
#endregion
/// <summary>
/// Collapses lines for the purpose of scrolling. This method is meant for
/// <see cref="VisualLineElementGenerator"/>s that cause <see cref="VisualLine"/>s to span
/// multiple <see cref="DocumentLine"/>s. Do not call it without providing a corresponding
/// <see cref="VisualLineElementGenerator"/>.
/// If you want to create collapsible text sections, see <see cref="Folding.FoldingManager"/>.
/// </summary>
public CollapsedLineSection CollapseLines(DocumentLine start, DocumentLine end)
{
VerifyAccess();
if (heightTree == null)
throw ThrowUtil.NoDocumentAssigned();
return heightTree.CollapseText(start, end);
}
/// <summary>
/// Gets the height of the document.
/// </summary>
public double DocumentHeight {
get {
// return 0 if there is no document = no heightTree
return heightTree != null ? heightTree.TotalHeight : 0;
}
}
/// <summary>
/// Gets the document line at the specified visual position.
/// </summary>
public DocumentLine GetDocumentLineByVisualTop(double visualTop)
{
VerifyAccess();
if (heightTree == null)
throw ThrowUtil.NoDocumentAssigned();
return heightTree.GetLineByVisualPosition(visualTop);
}
/// <inheritdoc/>
protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e)
{
base.OnPropertyChanged(e);
if (TextFormatterFactory.PropertyChangeAffectsTextFormatter(e.Property)) {
RecreateTextFormatter();
}
if (e.Property == Control.ForegroundProperty
|| e.Property == Control.FontFamilyProperty
|| e.Property == Control.FontSizeProperty
|| e.Property == Control.FontStretchProperty
|| e.Property == Control.FontStyleProperty
|| e.Property == Control.FontWeightProperty)
{
Redraw();
}
}
}
}
| |
namespace AutoMapper.Configuration
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using Execution;
using QueryableExtensions.Impl;
using static System.Linq.Expressions.Expression;
public class MappingExpression : MappingExpression<object, object>, IMappingExpression
{
public MappingExpression(TypePair types, MemberList memberList) : base(memberList, types.SourceType, types.DestinationType)
{
}
public new IMappingExpression ReverseMap() => (IMappingExpression) base.ReverseMap();
public IMappingExpression Substitute(Func<object, object> substituteFunc)
=> (IMappingExpression) base.Substitute(substituteFunc);
public new IMappingExpression ConstructUsingServiceLocator()
=> (IMappingExpression)base.ConstructUsingServiceLocator();
public void ForAllMembers(Action<IMemberConfigurationExpression> memberOptions)
=> base.ForAllMembers(opts => memberOptions((IMemberConfigurationExpression)opts));
void IMappingExpression.ConvertUsing<TTypeConverter>()
=> ConvertUsing(typeof(TTypeConverter));
public void ConvertUsing(Type typeConverterType)
=> TypeMapActions.Add(tm => tm.TypeConverterType = typeConverterType);
public void As(Type typeOverride)
=> TypeMapActions.Add(tm => tm.DestinationTypeOverride = typeOverride);
public void ForAllOtherMembers(Action<IMemberConfigurationExpression> memberOptions)
=> base.ForAllOtherMembers(o => memberOptions((IMemberConfigurationExpression)o));
public IMappingExpression ForMember(string name, Action<IMemberConfigurationExpression> memberOptions)
=> (IMappingExpression)base.ForMember(name, c => memberOptions((IMemberConfigurationExpression)c));
public new IMappingExpression ForSourceMember(string sourceMemberName, Action<ISourceMemberConfigurationExpression> memberOptions)
=> (IMappingExpression)base.ForSourceMember(sourceMemberName, memberOptions);
public new IMappingExpression Include(Type otherSourceType, Type otherDestinationType)
=> (IMappingExpression)base.Include(otherSourceType, otherDestinationType);
public new IMappingExpression IgnoreAllPropertiesWithAnInaccessibleSetter()
=> (IMappingExpression)base.IgnoreAllPropertiesWithAnInaccessibleSetter();
public new IMappingExpression IgnoreAllSourcePropertiesWithAnInaccessibleSetter()
=> (IMappingExpression)base.IgnoreAllSourcePropertiesWithAnInaccessibleSetter();
public new IMappingExpression IncludeBase(Type sourceBase, Type destinationBase)
=> (IMappingExpression)base.IncludeBase(sourceBase, destinationBase);
public new IMappingExpression BeforeMap(Action<object, object> beforeFunction)
=> (IMappingExpression)base.BeforeMap(beforeFunction);
public new IMappingExpression BeforeMap<TMappingAction>() where TMappingAction : IMappingAction<object, object>
=> (IMappingExpression)base.BeforeMap<TMappingAction>();
public new IMappingExpression AfterMap(Action<object, object> afterFunction)
=> (IMappingExpression)base.AfterMap(afterFunction);
public new IMappingExpression AfterMap<TMappingAction>() where TMappingAction : IMappingAction<object, object>
=> (IMappingExpression)base.AfterMap<TMappingAction>();
public new IMappingExpression ConstructUsing(Func<object, object> ctor)
=> (IMappingExpression)base.ConstructUsing(ctor);
public new IMappingExpression ConstructUsing(Func<object, ResolutionContext, object> ctor)
=> (IMappingExpression)base.ConstructUsing(ctor);
public IMappingExpression ConstructProjectionUsing(LambdaExpression ctor)
{
TypeMapActions.Add(tm => tm.ConstructExpression = ctor);
return this;
}
public new IMappingExpression MaxDepth(int depth)
=> (IMappingExpression)base.MaxDepth(depth);
public new IMappingExpression ForCtorParam(string ctorParamName, Action<ICtorParamConfigurationExpression<object>> paramOptions)
=> (IMappingExpression)base.ForCtorParam(ctorParamName, paramOptions);
public new IMappingExpression PreserveReferences() => (IMappingExpression)base.PreserveReferences();
protected override IMemberConfiguration CreateMemberConfigurationExpression<TMember>(IMemberAccessor member, Type sourceType)
=> new MemberConfigurationExpression(member, sourceType);
protected override MappingExpression<object, object> CreateReverseMapExpression()
=> new MappingExpression(new TypePair(DestinationType, SourceType), MemberList.Source);
private class MemberConfigurationExpression : MemberConfigurationExpression<object, object, object>, IMemberConfigurationExpression
{
public MemberConfigurationExpression(IMemberAccessor destinationMember, Type sourceType)
: base(destinationMember, sourceType)
{
}
public void ResolveUsing(Type valueResolverType)
{
var config = new ValueResolverConfiguration(valueResolverType);
PropertyMapActions.Add(pm => pm.ValueResolverConfig = config);
}
public void ResolveUsing(Type valueResolverType, string memberName)
{
var config = new ValueResolverConfiguration(valueResolverType)
{
SourceMemberName = memberName
};
PropertyMapActions.Add(pm => pm.ValueResolverConfig = config);
}
public void ResolveUsing<TSource, TSourceMember>(IValueResolver<TSource, TSourceMember> resolver, string memberName)
{
var config = new ValueResolverConfiguration(resolver)
{
SourceMemberName = memberName
};
PropertyMapActions.Add(pm => pm.ValueResolverConfig = config);
}
}
}
public class MappingExpression<TSource, TDestination> : IMappingExpression<TSource, TDestination>, ITypeMapConfiguration
{
private readonly List<IMemberConfiguration> _memberConfigurations = new List<IMemberConfiguration>();
private readonly List<SourceMappingExpression> _sourceMemberConfigurations = new List<SourceMappingExpression>();
private readonly List<CtorParamConfigurationExpression<TSource>> _ctorParamConfigurations = new List<CtorParamConfigurationExpression<TSource>>();
private MappingExpression<TDestination, TSource> _reverseMap;
private Action<IMemberConfigurationExpression<TSource, TDestination, object>> _allMemberOptions;
private Func<IMemberAccessor, bool> _memberFilter;
public MappingExpression(MemberList memberList)
{
MemberList = memberList;
Types = new TypePair(typeof(TSource), typeof(TDestination));
}
public MappingExpression(MemberList memberList, Type sourceType, Type destinationType)
{
MemberList = memberList;
Types = new TypePair(sourceType, destinationType);
}
public MemberList MemberList { get; }
public TypePair Types { get; }
public Type SourceType => Types.SourceType;
public Type DestinationType => Types.DestinationType;
public ITypeMapConfiguration ReverseTypeMap => _reverseMap;
protected List<Action<TypeMap>> TypeMapActions { get; } = new List<Action<TypeMap>>();
public IMappingExpression<TSource, TDestination> PreserveReferences()
{
TypeMapActions.Add(tm => tm.PreserveReferences = true);
return this;
}
protected virtual IMemberConfiguration CreateMemberConfigurationExpression<TMember>(IMemberAccessor member, Type sourceType)
{
return new MemberConfigurationExpression<TSource, TDestination, TMember>(member, sourceType);
}
protected virtual MappingExpression<TDestination, TSource> CreateReverseMapExpression()
{
return new MappingExpression<TDestination, TSource>(MemberList.Source, DestinationType, SourceType);
}
public IMappingExpression<TSource, TDestination> ForMember<TMember>(Expression<Func<TDestination, TMember>> destinationMember,
Action<IMemberConfigurationExpression<TSource, TDestination, TMember>> memberOptions)
{
var memberInfo = ReflectionHelper.FindProperty(destinationMember);
IMemberAccessor destProperty = memberInfo.ToMemberAccessor();
ForDestinationMember(destProperty, memberOptions);
return this;
}
public IMappingExpression<TSource, TDestination> ForMember(string name,
Action<IMemberConfigurationExpression<TSource, TDestination, object>> memberOptions)
{
var member = DestinationType.GetFieldOrProperty(name);
ForDestinationMember(member.ToMemberAccessor(), memberOptions);
return this;
}
public void ForAllOtherMembers(Action<IMemberConfigurationExpression<TSource, TDestination, object>> memberOptions)
{
_allMemberOptions = memberOptions;
_memberFilter = m => _memberConfigurations.All(c=>c.DestinationMember.MemberInfo != m.MemberInfo);
}
public void ForAllMembers(Action<IMemberConfigurationExpression<TSource, TDestination, object>> memberOptions)
{
_allMemberOptions = memberOptions;
_memberFilter = _ => true;
}
public IMappingExpression<TSource, TDestination> IgnoreAllPropertiesWithAnInaccessibleSetter()
{
var properties = DestinationType.GetDeclaredProperties().Where(pm => pm.HasAnInaccessibleSetter());
foreach (var property in properties)
ForMember(property.Name, opt => opt.Ignore());
return this;
}
public IMappingExpression<TSource, TDestination> IgnoreAllSourcePropertiesWithAnInaccessibleSetter()
{
var properties = SourceType.GetDeclaredProperties().Where(pm => pm.HasAnInaccessibleSetter());
foreach (var property in properties)
ForSourceMember(property.Name, opt => opt.Ignore());
return this;
}
public IMappingExpression<TSource, TDestination> Include<TOtherSource, TOtherDestination>()
where TOtherSource : TSource
where TOtherDestination : TDestination
{
return Include(typeof(TOtherSource), typeof(TOtherDestination));
}
public IMappingExpression<TSource, TDestination> Include(Type otherSourceType, Type otherDestinationType)
{
TypeMapActions.Add(tm => tm.IncludeDerivedTypes(otherSourceType, otherDestinationType));
return this;
}
public IMappingExpression<TSource, TDestination> IncludeBase<TSourceBase, TDestinationBase>()
{
return IncludeBase(typeof(TSourceBase), typeof(TDestinationBase));
}
public IMappingExpression<TSource, TDestination> IncludeBase(Type sourceBase, Type destinationBase)
{
TypeMapActions.Add(tm => tm.IncludeBaseTypes(sourceBase, destinationBase));
return this;
}
public void ProjectUsing(Expression<Func<TSource, TDestination>> projectionExpression)
{
TypeMapActions.Add(tm => tm.CustomProjection = projectionExpression);
}
public IMappingExpression<TSource, TDestination> MaxDepth(int depth)
{
TypeMapActions.Add(tm => tm.MaxDepth = depth);
return PreserveReferences();
}
public IMappingExpression<TSource, TDestination> ConstructUsingServiceLocator()
{
TypeMapActions.Add(tm => tm.ConstructDestinationUsingServiceLocator = true);
return this;
}
public IMappingExpression<TDestination, TSource> ReverseMap()
{
var mappingExpression = CreateReverseMapExpression();
_reverseMap = mappingExpression;
return mappingExpression;
}
public IMappingExpression<TSource, TDestination> ForSourceMember(Expression<Func<TSource, object>> sourceMember, Action<ISourceMemberConfigurationExpression> memberOptions)
{
var memberInfo = ReflectionHelper.FindProperty(sourceMember);
var srcConfig = new SourceMappingExpression(memberInfo);
memberOptions(srcConfig);
_sourceMemberConfigurations.Add(srcConfig);
return this;
}
public IMappingExpression<TSource, TDestination> ForSourceMember(string sourceMemberName, Action<ISourceMemberConfigurationExpression> memberOptions)
{
var memberInfo = SourceType.GetMember(sourceMemberName).First();
var srcConfig = new SourceMappingExpression(memberInfo);
memberOptions(srcConfig);
_sourceMemberConfigurations.Add(srcConfig);
return this;
}
public IMappingExpression<TSource, TDestination> Substitute<TSubstitute>(Func<TSource, TSubstitute> substituteFunc)
{
TypeMapActions.Add(tm =>
{
Expression<Func<TSource, TDestination, ResolutionContext, TSubstitute>> expr = (src, dest, ctxt) => substituteFunc(src);
tm.Substitution = expr;
});
return this;
}
public void ConvertUsing(Func<TSource, TDestination> mappingFunction)
{
TypeMapActions.Add(tm =>
{
Expression<Func<TSource, TDestination, ResolutionContext, TDestination>> expr =
(src, dest, ctxt) => mappingFunction(src);
tm.CustomMapper = expr;
});
}
public void ConvertUsing(Func<TSource, ResolutionContext, TDestination> mappingFunction)
{
TypeMapActions.Add(tm =>
{
Expression<Func<TSource, TDestination, ResolutionContext, TDestination>> expr =
(src, dest, ctxt) => mappingFunction(src, ctxt);
tm.CustomMapper = expr;
});
}
public void ConvertUsing(ITypeConverter<TSource, TDestination> converter)
{
ConvertUsing(converter.Convert);
}
public void ConvertUsing<TTypeConverter>() where TTypeConverter : ITypeConverter<TSource, TDestination>
{
TypeMapActions.Add(tm => tm.TypeConverterType = typeof (TTypeConverter));
}
public IMappingExpression<TSource, TDestination> BeforeMap(Action<TSource, TDestination> beforeFunction)
{
TypeMapActions.Add(tm =>
{
Expression<Action<TSource, TDestination, ResolutionContext>> expr =
(src, dest, ctxt) => beforeFunction(src, dest);
tm.AddBeforeMapAction(expr);
});
return this;
}
public IMappingExpression<TSource, TDestination> BeforeMap(Action<TSource, TDestination, ResolutionContext> beforeFunction)
{
TypeMapActions.Add(tm =>
{
Expression<Action<TSource, TDestination, ResolutionContext>> expr =
(src, dest, ctxt) => beforeFunction(src, dest, ctxt);
tm.AddBeforeMapAction(expr);
});
return this;
}
public IMappingExpression<TSource, TDestination> BeforeMap<TMappingAction>() where TMappingAction : IMappingAction<TSource, TDestination>
{
Action<TSource, TDestination, ResolutionContext> beforeFunction = (src, dest, ctxt) =>
((TMappingAction)ctxt.Options.ServiceCtor(typeof(TMappingAction))).Process(src, dest);
return BeforeMap(beforeFunction);
}
public IMappingExpression<TSource, TDestination> AfterMap(Action<TSource, TDestination> afterFunction)
{
TypeMapActions.Add(tm =>
{
Expression<Action<TSource, TDestination, ResolutionContext>> expr =
(src, dest, ctxt) => afterFunction(src, dest);
tm.AddAfterMapAction(expr);
});
return this;
}
public IMappingExpression<TSource, TDestination> AfterMap(Action<TSource, TDestination, ResolutionContext> afterFunction)
{
TypeMapActions.Add(tm =>
{
Expression<Action<TSource, TDestination, ResolutionContext>> expr =
(src, dest, ctxt) => afterFunction(src, dest, ctxt);
tm.AddAfterMapAction(expr);
});
return this;
}
public IMappingExpression<TSource, TDestination> AfterMap<TMappingAction>() where TMappingAction : IMappingAction<TSource, TDestination>
{
Action<TSource, TDestination, ResolutionContext> afterFunction = (src, dest, ctxt)
=> ((TMappingAction)ctxt.Options.ServiceCtor(typeof(TMappingAction))).Process(src, dest);
return AfterMap(afterFunction);
}
public IMappingExpression<TSource, TDestination> ConstructUsing(Func<TSource, TDestination> ctor)
{
TypeMapActions.Add(tm =>
{
Expression<Func<TSource, ResolutionContext, TDestination>> expr = (src, ctxt) => ctor(src);
tm.DestinationCtor = expr;
});
return this;
}
public IMappingExpression<TSource, TDestination> ConstructUsing(Func<TSource, ResolutionContext, TDestination> ctor)
{
TypeMapActions.Add(tm =>
{
Expression<Func<TSource, ResolutionContext, TDestination>> expr = (src, ctxt) => ctor(src, ctxt);
tm.DestinationCtor = expr;
});
return this;
}
public IMappingExpression<TSource, TDestination> ConstructProjectionUsing(Expression<Func<TSource, TDestination>> ctor)
{
TypeMapActions.Add(tm =>
{
tm.ConstructExpression = ctor;
var ctxtParam = Parameter(typeof (ResolutionContext), "ctxt");
var srcParam = Parameter(typeof (TSource), "src");
var body = ctor.ReplaceParameters(srcParam);
tm.DestinationCtor = Lambda(body, srcParam, ctxtParam);
});
return this;
}
private void ForDestinationMember<TMember>(IMemberAccessor destinationProperty, Action<IMemberConfigurationExpression<TSource, TDestination, TMember>> memberOptions)
{
var expression = (MemberConfigurationExpression<TSource, TDestination, TMember>) CreateMemberConfigurationExpression<TMember>(destinationProperty, SourceType);
_memberConfigurations.Add(expression);
memberOptions(expression);
}
public void As<T>()
{
TypeMapActions.Add(tm => tm.DestinationTypeOverride = typeof(T));
}
public IMappingExpression<TSource, TDestination> ForCtorParam(string ctorParamName, Action<ICtorParamConfigurationExpression<TSource>> paramOptions)
{
var ctorParamExpression = new CtorParamConfigurationExpression<TSource>(ctorParamName);
paramOptions(ctorParamExpression);
_ctorParamConfigurations.Add(ctorParamExpression);
return this;
}
public void Configure(IProfileConfiguration profile, TypeMap typeMap)
{
foreach (var destProperty in typeMap.DestinationTypeDetails.PublicWriteAccessors)
{
var attrs = destProperty.GetCustomAttributes(true);
if (attrs.Any(x => x is IgnoreMapAttribute))
{
ForMember(destProperty.Name, y => y.Ignore());
_reverseMap?.ForMember(destProperty.Name, opt => opt.Ignore());
}
if (profile.GlobalIgnores.Contains(destProperty.Name))
{
ForMember(destProperty.Name, y => y.Ignore());
}
}
if (_allMemberOptions != null)
{
foreach (var accessor in typeMap.DestinationTypeDetails.PublicReadAccessors.Select(m=>m.ToMemberAccessor()).Where(_memberFilter))
{
ForDestinationMember(accessor, _allMemberOptions);
}
}
foreach (var action in TypeMapActions)
{
action(typeMap);
}
foreach (var memberConfig in _memberConfigurations)
{
memberConfig.Configure(typeMap);
}
foreach (var memberConfig in _sourceMemberConfigurations)
{
memberConfig.Configure(typeMap);
}
foreach (var paramConfig in _ctorParamConfigurations)
{
paramConfig.Configure(typeMap);
}
if (_reverseMap != null)
{
foreach (var destProperty in typeMap.GetPropertyMaps().Where(pm => pm.Ignored))
{
_reverseMap.ForSourceMember(destProperty.DestinationProperty.Name, opt => opt.Ignore());
}
foreach (var includedDerivedType in typeMap.IncludedDerivedTypes)
{
_reverseMap.Include(includedDerivedType.DestinationType, includedDerivedType.SourceType);
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using Xamarin.Forms.Internals;
namespace Xamarin.Forms
{
public partial class VisualElement : Element, IAnimatable, IVisualElementController, IResourcesProvider
{
internal static readonly BindablePropertyKey NavigationPropertyKey = BindableProperty.CreateReadOnly("Navigation", typeof(INavigation), typeof(VisualElement), default(INavigation));
public static readonly BindableProperty NavigationProperty = NavigationPropertyKey.BindableProperty;
public static readonly BindableProperty InputTransparentProperty = BindableProperty.Create("InputTransparent", typeof(bool), typeof(VisualElement), default(bool));
public static readonly BindableProperty IsEnabledProperty = BindableProperty.Create("IsEnabled", typeof(bool), typeof(VisualElement), true);
static readonly BindablePropertyKey XPropertyKey = BindableProperty.CreateReadOnly("X", typeof(double), typeof(VisualElement), default(double));
public static readonly BindableProperty XProperty = XPropertyKey.BindableProperty;
static readonly BindablePropertyKey YPropertyKey = BindableProperty.CreateReadOnly("Y", typeof(double), typeof(VisualElement), default(double));
public static readonly BindableProperty YProperty = YPropertyKey.BindableProperty;
public static readonly BindableProperty AnchorXProperty = BindableProperty.Create("AnchorX", typeof(double), typeof(VisualElement), .5d);
public static readonly BindableProperty AnchorYProperty = BindableProperty.Create("AnchorY", typeof(double), typeof(VisualElement), .5d);
public static readonly BindableProperty TranslationXProperty = BindableProperty.Create("TranslationX", typeof(double), typeof(VisualElement), 0d);
public static readonly BindableProperty TranslationYProperty = BindableProperty.Create("TranslationY", typeof(double), typeof(VisualElement), 0d);
static readonly BindablePropertyKey WidthPropertyKey = BindableProperty.CreateReadOnly("Width", typeof(double), typeof(VisualElement), -1d,
coerceValue: (bindable, value) => double.IsNaN((double)value) ? 0d : value);
public static readonly BindableProperty WidthProperty = WidthPropertyKey.BindableProperty;
static readonly BindablePropertyKey HeightPropertyKey = BindableProperty.CreateReadOnly("Height", typeof(double), typeof(VisualElement), -1d,
coerceValue: (bindable, value) => double.IsNaN((double)value) ? 0d : value);
public static readonly BindableProperty HeightProperty = HeightPropertyKey.BindableProperty;
public static readonly BindableProperty RotationProperty = BindableProperty.Create("Rotation", typeof(double), typeof(VisualElement), default(double));
public static readonly BindableProperty RotationXProperty = BindableProperty.Create("RotationX", typeof(double), typeof(VisualElement), default(double));
public static readonly BindableProperty RotationYProperty = BindableProperty.Create("RotationY", typeof(double), typeof(VisualElement), default(double));
public static readonly BindableProperty ScaleProperty = BindableProperty.Create("Scale", typeof(double), typeof(VisualElement), 1d);
public static readonly BindableProperty IsVisibleProperty = BindableProperty.Create("IsVisible", typeof(bool), typeof(VisualElement), true,
propertyChanged: (bindable, oldvalue, newvalue) => ((VisualElement)bindable).OnIsVisibleChanged((bool)oldvalue, (bool)newvalue));
public static readonly BindableProperty OpacityProperty = BindableProperty.Create("Opacity", typeof(double), typeof(VisualElement), 1d, coerceValue: (bindable, value) => ((double)value).Clamp(0, 1));
public static readonly BindableProperty BackgroundColorProperty = BindableProperty.Create("BackgroundColor", typeof(Color), typeof(VisualElement), Color.Default);
internal static readonly BindablePropertyKey BehaviorsPropertyKey = BindableProperty.CreateReadOnly("Behaviors", typeof(IList<Behavior>), typeof(VisualElement), default(IList<Behavior>),
defaultValueCreator: bindable =>
{
var collection = new AttachedCollection<Behavior>();
collection.AttachTo(bindable);
return collection;
});
public static readonly BindableProperty BehaviorsProperty = BehaviorsPropertyKey.BindableProperty;
internal static readonly BindablePropertyKey TriggersPropertyKey = BindableProperty.CreateReadOnly("Triggers", typeof(IList<TriggerBase>), typeof(VisualElement), default(IList<TriggerBase>),
defaultValueCreator: bindable =>
{
var collection = new AttachedCollection<TriggerBase>();
collection.AttachTo(bindable);
return collection;
});
public static readonly BindableProperty TriggersProperty = TriggersPropertyKey.BindableProperty;
public static readonly BindableProperty StyleProperty = BindableProperty.Create("Style", typeof(Style), typeof(VisualElement), default(Style),
propertyChanged: (bindable, oldvalue, newvalue) => ((VisualElement)bindable)._mergedStyle.Style = (Style)newvalue);
public static readonly BindableProperty WidthRequestProperty = BindableProperty.Create("WidthRequest", typeof(double), typeof(VisualElement), -1d, propertyChanged: OnRequestChanged);
public static readonly BindableProperty HeightRequestProperty = BindableProperty.Create("HeightRequest", typeof(double), typeof(VisualElement), -1d, propertyChanged: OnRequestChanged);
public static readonly BindableProperty MinimumWidthRequestProperty = BindableProperty.Create("MinimumWidthRequest", typeof(double), typeof(VisualElement), -1d, propertyChanged: OnRequestChanged);
public static readonly BindableProperty MinimumHeightRequestProperty = BindableProperty.Create("MinimumHeightRequest", typeof(double), typeof(VisualElement), -1d, propertyChanged: OnRequestChanged);
internal static readonly BindablePropertyKey IsFocusedPropertyKey = BindableProperty.CreateReadOnly("IsFocused", typeof(bool), typeof(VisualElement), default(bool),
propertyChanged: OnIsFocusedPropertyChanged);
public static readonly BindableProperty IsFocusedProperty = IsFocusedPropertyKey.BindableProperty;
readonly Dictionary<Size, SizeRequest> _measureCache = new Dictionary<Size, SizeRequest>();
readonly MergedStyle _mergedStyle;
int _batched;
LayoutConstraint _computedConstraint;
bool _isInNativeLayout;
bool _isNativeStateConsistent = true;
bool _isPlatformEnabled;
double _mockHeight = -1;
double _mockWidth = -1;
double _mockX = -1;
double _mockY = -1;
ResourceDictionary _resources;
LayoutConstraint _selfConstraint;
internal VisualElement()
{
Navigation = new NavigationProxy();
_mergedStyle = new MergedStyle(GetType(), this);
}
public double AnchorX
{
get { return (double)GetValue(AnchorXProperty); }
set { SetValue(AnchorXProperty, value); }
}
public double AnchorY
{
get { return (double)GetValue(AnchorYProperty); }
set { SetValue(AnchorYProperty, value); }
}
public Color BackgroundColor
{
get { return (Color)GetValue(BackgroundColorProperty); }
set { SetValue(BackgroundColorProperty, value); }
}
public IList<Behavior> Behaviors
{
get { return (IList<Behavior>)GetValue(BehaviorsProperty); }
}
public Rectangle Bounds
{
get { return new Rectangle(X, Y, Width, Height); }
private set
{
if (value.X == X && value.Y == Y && value.Height == Height && value.Width == Width)
return;
BatchBegin();
X = value.X;
Y = value.Y;
SetSize(value.Width, value.Height);
BatchCommit();
}
}
public double Height
{
get { return _mockHeight == -1 ? (double)GetValue(HeightProperty) : _mockHeight; }
private set { SetValue(HeightPropertyKey, value); }
}
public double HeightRequest
{
get { return (double)GetValue(HeightRequestProperty); }
set { SetValue(HeightRequestProperty, value); }
}
public bool InputTransparent
{
get { return (bool)GetValue(InputTransparentProperty); }
set { SetValue(InputTransparentProperty, value); }
}
public bool IsEnabled
{
get { return (bool)GetValue(IsEnabledProperty); }
set { SetValue(IsEnabledProperty, value); }
}
public bool IsFocused
{
get { return (bool)GetValue(IsFocusedProperty); }
}
public bool IsVisible
{
get { return (bool)GetValue(IsVisibleProperty); }
set { SetValue(IsVisibleProperty, value); }
}
public double MinimumHeightRequest
{
get { return (double)GetValue(MinimumHeightRequestProperty); }
set { SetValue(MinimumHeightRequestProperty, value); }
}
public double MinimumWidthRequest
{
get { return (double)GetValue(MinimumWidthRequestProperty); }
set { SetValue(MinimumWidthRequestProperty, value); }
}
public INavigation Navigation
{
get { return (INavigation)GetValue(NavigationProperty); }
internal set { SetValue(NavigationPropertyKey, value); }
}
public double Opacity
{
get { return (double)GetValue(OpacityProperty); }
set { SetValue(OpacityProperty, value); }
}
public double Rotation
{
get { return (double)GetValue(RotationProperty); }
set { SetValue(RotationProperty, value); }
}
public double RotationX
{
get { return (double)GetValue(RotationXProperty); }
set { SetValue(RotationXProperty, value); }
}
public double RotationY
{
get { return (double)GetValue(RotationYProperty); }
set { SetValue(RotationYProperty, value); }
}
public double Scale
{
get { return (double)GetValue(ScaleProperty); }
set { SetValue(ScaleProperty, value); }
}
public Style Style
{
get { return (Style)GetValue(StyleProperty); }
set { SetValue(StyleProperty, value); }
}
[TypeConverter (typeof(ListStringTypeConverter))]
public IList<string> StyleClass
{
get { return _mergedStyle.StyleClass; }
set { _mergedStyle.StyleClass = value; }
}
public double TranslationX
{
get { return (double)GetValue(TranslationXProperty); }
set { SetValue(TranslationXProperty, value); }
}
public double TranslationY
{
get { return (double)GetValue(TranslationYProperty); }
set { SetValue(TranslationYProperty, value); }
}
public IList<TriggerBase> Triggers
{
get { return (IList<TriggerBase>)GetValue(TriggersProperty); }
}
public double Width
{
get { return _mockWidth == -1 ? (double)GetValue(WidthProperty) : _mockWidth; }
private set { SetValue(WidthPropertyKey, value); }
}
public double WidthRequest
{
get { return (double)GetValue(WidthRequestProperty); }
set { SetValue(WidthRequestProperty, value); }
}
public double X
{
get { return _mockX == -1 ? (double)GetValue(XProperty) : _mockX; }
private set { SetValue(XPropertyKey, value); }
}
public double Y
{
get { return _mockY == -1 ? (double)GetValue(YProperty) : _mockY; }
private set { SetValue(YPropertyKey, value); }
}
internal bool Batched
{
get { return _batched > 0; }
}
internal LayoutConstraint ComputedConstraint
{
get { return _computedConstraint; }
set
{
if (_computedConstraint == value)
return;
LayoutConstraint oldConstraint = Constraint;
_computedConstraint = value;
LayoutConstraint newConstraint = Constraint;
if (oldConstraint != newConstraint)
OnConstraintChanged(oldConstraint, newConstraint);
}
}
internal LayoutConstraint Constraint
{
get { return ComputedConstraint | SelfConstraint; }
}
internal bool DisableLayout { get; set; }
internal bool IsInNativeLayout
{
get
{
if (_isInNativeLayout)
return true;
Element parent = RealParent;
while (parent != null)
{
var visualElement = parent as VisualElement;
if (visualElement != null && visualElement.IsInNativeLayout)
return true;
parent = parent.RealParent;
}
return false;
}
set { _isInNativeLayout = value; }
}
internal bool IsNativeStateConsistent
{
get { return _isNativeStateConsistent; }
set
{
if (_isNativeStateConsistent == value)
return;
_isNativeStateConsistent = value;
if (value && IsPlatformEnabled)
InvalidateMeasureInternal(InvalidationTrigger.RendererReady);
}
}
internal bool IsPlatformEnabled
{
get { return _isPlatformEnabled; }
set
{
if (value == _isPlatformEnabled)
return;
_isPlatformEnabled = value;
if (value && IsNativeStateConsistent)
InvalidateMeasureInternal(InvalidationTrigger.RendererReady);
OnIsPlatformEnabledChanged();
}
}
internal NavigationProxy NavigationProxy
{
get { return Navigation as NavigationProxy; }
}
internal LayoutConstraint SelfConstraint
{
get { return _selfConstraint; }
set
{
if (_selfConstraint == value)
return;
LayoutConstraint oldConstraint = Constraint;
_selfConstraint = value;
LayoutConstraint newConstraint = Constraint;
if (oldConstraint != newConstraint)
{
OnConstraintChanged(oldConstraint, newConstraint);
}
}
}
public void BatchBegin()
{
_batched++;
}
public void BatchCommit()
{
_batched = Math.Max(0, _batched - 1);
if (!Batched && BatchCommitted != null)
BatchCommitted(this, new EventArg<VisualElement>(this));
}
public ResourceDictionary Resources
{
get { return _resources; }
set
{
if (_resources == value)
return;
OnPropertyChanging();
if (_resources != null)
((IResourceDictionary)_resources).ValuesChanged -= OnResourcesChanged;
_resources = value;
OnResourcesChanged(value);
if (_resources != null)
((IResourceDictionary)_resources).ValuesChanged += OnResourcesChanged;
OnPropertyChanged();
}
}
void IVisualElementController.NativeSizeChanged()
{
InvalidateMeasureInternal(InvalidationTrigger.MeasureChanged);
}
public event EventHandler ChildrenReordered;
public bool Focus()
{
if (IsFocused)
return true;
if (FocusChangeRequested == null)
return false;
var arg = new FocusRequestArgs { Focus = true };
FocusChangeRequested(this, arg);
return arg.Result;
}
public event EventHandler<FocusEventArgs> Focused;
[Obsolete("Use Measure")]
public virtual SizeRequest GetSizeRequest(double widthConstraint, double heightConstraint)
{
SizeRequest cachedResult;
var constraintSize = new Size(widthConstraint, heightConstraint);
if (_measureCache.TryGetValue(constraintSize, out cachedResult))
{
return cachedResult;
}
double widthRequest = WidthRequest;
double heightRequest = HeightRequest;
if (widthRequest >= 0)
widthConstraint = Math.Min(widthConstraint, widthRequest);
if (heightRequest >= 0)
heightConstraint = Math.Min(heightConstraint, heightRequest);
SizeRequest result = OnMeasure(widthConstraint, heightConstraint);
bool hasMinimum = result.Minimum != result.Request;
Size request = result.Request;
Size minimum = result.Minimum;
if (heightRequest != -1)
{
request.Height = heightRequest;
if (!hasMinimum)
minimum.Height = heightRequest;
}
if (widthRequest != -1)
{
request.Width = widthRequest;
if (!hasMinimum)
minimum.Width = widthRequest;
}
double minimumHeightRequest = MinimumHeightRequest;
double minimumWidthRequest = MinimumWidthRequest;
if (minimumHeightRequest != -1)
minimum.Height = minimumHeightRequest;
if (minimumWidthRequest != -1)
minimum.Width = minimumWidthRequest;
minimum.Height = Math.Min(request.Height, minimum.Height);
minimum.Width = Math.Min(request.Width, minimum.Width);
var r = new SizeRequest(request, minimum);
if (r.Request.Width > 0 && r.Request.Height > 0)
{
_measureCache[constraintSize] = r;
}
return r;
}
public void Layout(Rectangle bounds)
{
Bounds = bounds;
}
public SizeRequest Measure(double widthConstraint, double heightConstraint, MeasureFlags flags = MeasureFlags.None)
{
bool includeMargins = (flags & MeasureFlags.IncludeMargins) != 0;
Thickness margin = default(Thickness);
if (includeMargins)
{
var view = this as View;
if (view != null)
margin = view.Margin;
widthConstraint = Math.Max(0, widthConstraint - margin.HorizontalThickness);
heightConstraint = Math.Max(0, heightConstraint - margin.VerticalThickness);
}
#pragma warning disable 0618 // retain until GetSizeRequest removed
SizeRequest result = GetSizeRequest(widthConstraint, heightConstraint);
#pragma warning restore 0618
if (includeMargins)
{
if (!margin.IsDefault)
{
result.Minimum = new Size(result.Minimum.Width + margin.HorizontalThickness, result.Minimum.Height + margin.VerticalThickness);
result.Request = new Size(result.Request.Width + margin.HorizontalThickness, result.Request.Height + margin.VerticalThickness);
}
}
return result;
}
public event EventHandler MeasureInvalidated;
public event EventHandler SizeChanged;
public void Unfocus()
{
if (!IsFocused)
return;
EventHandler<FocusRequestArgs> unfocus = FocusChangeRequested;
if (unfocus != null)
{
unfocus(this, new FocusRequestArgs());
}
}
public event EventHandler<FocusEventArgs> Unfocused;
protected virtual void InvalidateMeasureInternal()
{
InvalidateMeasureInternal(InvalidationTrigger.MeasureChanged);
}
protected override void OnChildAdded(Element child)
{
base.OnChildAdded(child);
var view = child as View;
if (view != null)
ComputeConstraintForView(view);
}
protected override void OnChildRemoved(Element child)
{
base.OnChildRemoved(child);
var view = child as View;
if (view != null)
view.ComputedConstraint = LayoutConstraint.None;
}
protected void OnChildrenReordered()
{
if (ChildrenReordered != null)
ChildrenReordered(this, EventArgs.Empty);
}
protected virtual SizeRequest OnMeasure(double widthConstraint, double heightConstraint)
{
#pragma warning disable 0618 // retain until OnSizeRequest removed
return OnSizeRequest(widthConstraint, heightConstraint);
#pragma warning restore 0618
}
protected override void OnParentSet()
{
#pragma warning disable 0618 // retain until ParentView removed
base.OnParentSet();
if (ParentView != null)
{
NavigationProxy.Inner = ParentView.NavigationProxy;
}
else
{
NavigationProxy.Inner = null;
}
#pragma warning restore 0618
}
protected virtual void OnSizeAllocated(double width, double height)
{
}
[Obsolete("Use OnMeasure")]
protected virtual SizeRequest OnSizeRequest(double widthConstraint, double heightConstraint)
{
if (Platform == null || !IsPlatformEnabled)
{
return new SizeRequest(new Size(-1, -1));
}
return Platform.GetNativeSize(this, widthConstraint, heightConstraint);
}
protected void SizeAllocated(double width, double height)
{
OnSizeAllocated(width, height);
}
internal event EventHandler<EventArg<VisualElement>> BatchCommitted;
internal void ComputeConstrainsForChildren()
{
for (var i = 0; i < LogicalChildren.Count; i++)
{
var child = LogicalChildren[i] as View;
if (child != null)
ComputeConstraintForView(child);
}
}
internal virtual void ComputeConstraintForView(View view)
{
view.ComputedConstraint = LayoutConstraint.None;
}
internal event EventHandler<FocusRequestArgs> FocusChangeRequested;
internal virtual void InvalidateMeasureInternal(InvalidationTrigger trigger)
{
_measureCache.Clear();
MeasureInvalidated?.Invoke(this, new InvalidationEventArgs(trigger));
}
void IVisualElementController.InvalidateMeasure(InvalidationTrigger trigger)
{
InvalidateMeasureInternal(trigger);
}
internal void MockBounds(Rectangle bounds)
{
_mockX = bounds.X;
_mockY = bounds.Y;
_mockWidth = bounds.Width;
_mockHeight = bounds.Height;
}
internal virtual void OnConstraintChanged(LayoutConstraint oldConstraint, LayoutConstraint newConstraint)
{
ComputeConstrainsForChildren();
}
internal virtual void OnIsPlatformEnabledChanged()
{
}
internal virtual void OnIsVisibleChanged(bool oldValue, bool newValue)
{
InvalidateMeasureInternal(InvalidationTrigger.Undefined);
}
internal override void OnParentResourcesChanged(IEnumerable<KeyValuePair<string, object>> values)
{
if (values == null)
return;
if (Resources == null || Resources.Count == 0)
{
base.OnParentResourcesChanged(values);
return;
}
var innerKeys = new HashSet<string>();
var changedResources = new List<KeyValuePair<string, object>>();
foreach (KeyValuePair<string, object> c in Resources)
innerKeys.Add(c.Key);
foreach (KeyValuePair<string, object> value in values)
{
if (innerKeys.Add(value.Key))
changedResources.Add(value);
else if (value.Key.StartsWith(Style.StyleClassPrefix, StringComparison.Ordinal))
{
var mergedClassStyles = new List<Style>(Resources[value.Key] as List<Style>);
mergedClassStyles.AddRange(value.Value as List<Style>);
changedResources.Add(new KeyValuePair<string, object>(value.Key, mergedClassStyles));
}
}
if (changedResources.Count != 0)
OnResourcesChanged(changedResources);
}
internal void UnmockBounds()
{
_mockX = _mockY = _mockWidth = _mockHeight = -1;
}
void OnFocused()
{
EventHandler<FocusEventArgs> focus = Focused;
if (focus != null)
focus(this, new FocusEventArgs(this, true));
}
static void OnIsFocusedPropertyChanged(BindableObject bindable, object oldvalue, object newvalue)
{
var element = bindable as VisualElement;
var isFocused = (bool)newvalue;
if (isFocused)
{
element.OnFocused();
}
else
{
element.OnUnfocus();
}
}
static void OnRequestChanged(BindableObject bindable, object oldvalue, object newvalue)
{
var constraint = LayoutConstraint.None;
var element = (VisualElement)bindable;
if (element.WidthRequest >= 0 && element.MinimumWidthRequest >= 0)
{
constraint |= LayoutConstraint.HorizontallyFixed;
}
if (element.HeightRequest >= 0 && element.MinimumHeightRequest >= 0)
{
constraint |= LayoutConstraint.VerticallyFixed;
}
element.SelfConstraint = constraint;
((VisualElement)bindable).InvalidateMeasureInternal(InvalidationTrigger.SizeRequestChanged);
}
void OnUnfocus()
{
EventHandler<FocusEventArgs> unFocus = Unfocused;
if (unFocus != null)
unFocus(this, new FocusEventArgs(this, false));
}
void SetSize(double width, double height)
{
if (Width == width && Height == height)
return;
Width = width;
Height = height;
SizeAllocated(width, height);
if (SizeChanged != null)
SizeChanged(this, EventArgs.Empty);
}
internal class FocusRequestArgs : EventArgs
{
public bool Focus { get; set; }
public bool Result { get; set; }
}
}
}
| |
// snippet-sourcedescription:[ ]
// snippet-service:[dynamodb]
// snippet-keyword:[dotNET]
// snippet-keyword:[Amazon DynamoDB]
// snippet-keyword:[Code Sample]
// snippet-keyword:[ ]
// snippet-sourcetype:[full-example]
// snippet-sourcedate:[ ]
// snippet-sourceauthor:[AWS]
// snippet-start:[dynamodb.dotNET.CodeExample.LowLevelLocalSecondaryIndexExample]
/**
* Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* This file is licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License. A copy of
* the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using Amazon.DynamoDBv2;
using Amazon.DynamoDBv2.DataModel;
using Amazon.DynamoDBv2.DocumentModel;
using Amazon.DynamoDBv2.Model;
using Amazon.Runtime;
using Amazon.SecurityToken;
namespace com.amazonaws.codesamples
{
class LowLevelLocalSecondaryIndexExample
{
private static AmazonDynamoDBClient client = new AmazonDynamoDBClient();
private static string tableName = "CustomerOrders";
static void Main(string[] args)
{
try
{
CreateTable();
LoadData();
Query(null);
Query("IsOpenIndex");
Query("OrderCreationDateIndex");
DeleteTable(tableName);
Console.WriteLine("To continue, press Enter");
Console.ReadLine();
}
catch (AmazonDynamoDBException e) { Console.WriteLine(e.Message); }
catch (AmazonServiceException e) { Console.WriteLine(e.Message); }
catch (Exception e) { Console.WriteLine(e.Message); }
}
private static void CreateTable()
{
var createTableRequest =
new CreateTableRequest()
{
TableName = tableName,
ProvisionedThroughput =
new ProvisionedThroughput()
{
ReadCapacityUnits = (long)1,
WriteCapacityUnits = (long)1
}
};
var attributeDefinitions = new List<AttributeDefinition>()
{
// Attribute definitions for table primary key
{ new AttributeDefinition() {
AttributeName = "CustomerId", AttributeType = "S"
} },
{ new AttributeDefinition() {
AttributeName = "OrderId", AttributeType = "N"
} },
// Attribute definitions for index primary key
{ new AttributeDefinition() {
AttributeName = "OrderCreationDate", AttributeType = "N"
} },
{ new AttributeDefinition() {
AttributeName = "IsOpen", AttributeType = "N"
}}
};
createTableRequest.AttributeDefinitions = attributeDefinitions;
// Key schema for table
var tableKeySchema = new List<KeySchemaElement>()
{
{ new KeySchemaElement() {
AttributeName = "CustomerId", KeyType = "HASH"
} }, //Partition key
{ new KeySchemaElement() {
AttributeName = "OrderId", KeyType = "RANGE"
} } //Sort key
};
createTableRequest.KeySchema = tableKeySchema;
var localSecondaryIndexes = new List<LocalSecondaryIndex>();
// OrderCreationDateIndex
LocalSecondaryIndex orderCreationDateIndex = new LocalSecondaryIndex()
{
IndexName = "OrderCreationDateIndex"
};
// Key schema for OrderCreationDateIndex
var indexKeySchema = new List<KeySchemaElement>()
{
{ new KeySchemaElement() {
AttributeName = "CustomerId", KeyType = "HASH"
} }, //Partition key
{ new KeySchemaElement() {
AttributeName = "OrderCreationDate", KeyType = "RANGE"
} } //Sort key
};
orderCreationDateIndex.KeySchema = indexKeySchema;
// Projection (with list of projected attributes) for
// OrderCreationDateIndex
var projection = new Projection()
{
ProjectionType = "INCLUDE"
};
var nonKeyAttributes = new List<string>()
{
"ProductCategory",
"ProductName"
};
projection.NonKeyAttributes = nonKeyAttributes;
orderCreationDateIndex.Projection = projection;
localSecondaryIndexes.Add(orderCreationDateIndex);
// IsOpenIndex
LocalSecondaryIndex isOpenIndex
= new LocalSecondaryIndex()
{
IndexName = "IsOpenIndex"
};
// Key schema for IsOpenIndex
indexKeySchema = new List<KeySchemaElement>()
{
{ new KeySchemaElement() {
AttributeName = "CustomerId", KeyType = "HASH"
}}, //Partition key
{ new KeySchemaElement() {
AttributeName = "IsOpen", KeyType = "RANGE"
}} //Sort key
};
// Projection (all attributes) for IsOpenIndex
projection = new Projection()
{
ProjectionType = "ALL"
};
isOpenIndex.KeySchema = indexKeySchema;
isOpenIndex.Projection = projection;
localSecondaryIndexes.Add(isOpenIndex);
// Add index definitions to CreateTable request
createTableRequest.LocalSecondaryIndexes = localSecondaryIndexes;
Console.WriteLine("Creating table " + tableName + "...");
client.CreateTable(createTableRequest);
WaitUntilTableReady(tableName);
}
public static void Query(string indexName)
{
Console.WriteLine("\n***********************************************************\n");
Console.WriteLine("Querying table " + tableName + "...");
QueryRequest queryRequest = new QueryRequest()
{
TableName = tableName,
ConsistentRead = true,
ScanIndexForward = true,
ReturnConsumedCapacity = "TOTAL"
};
String keyConditionExpression = "CustomerId = :v_customerId";
Dictionary<string, AttributeValue> expressionAttributeValues = new Dictionary<string, AttributeValue> {
{":v_customerId", new AttributeValue {
S = "bob@example.com"
}}
};
if (indexName == "IsOpenIndex")
{
Console.WriteLine("\nUsing index: '" + indexName
+ "': Bob's orders that are open.");
Console.WriteLine("Only a user-specified list of attributes are returned\n");
queryRequest.IndexName = indexName;
keyConditionExpression += " and IsOpen = :v_isOpen";
expressionAttributeValues.Add(":v_isOpen", new AttributeValue
{
N = "1"
});
// ProjectionExpression
queryRequest.ProjectionExpression = "OrderCreationDate, ProductCategory, ProductName, OrderStatus";
}
else if (indexName == "OrderCreationDateIndex")
{
Console.WriteLine("\nUsing index: '" + indexName
+ "': Bob's orders that were placed after 01/31/2013.");
Console.WriteLine("Only the projected attributes are returned\n");
queryRequest.IndexName = indexName;
keyConditionExpression += " and OrderCreationDate > :v_Date";
expressionAttributeValues.Add(":v_Date", new AttributeValue
{
N = "20130131"
});
// Select
queryRequest.Select = "ALL_PROJECTED_ATTRIBUTES";
}
else
{
Console.WriteLine("\nNo index: All of Bob's orders, by OrderId:\n");
}
queryRequest.KeyConditionExpression = keyConditionExpression;
queryRequest.ExpressionAttributeValues = expressionAttributeValues;
var result = client.Query(queryRequest);
var items = result.Items;
foreach (var currentItem in items)
{
foreach (string attr in currentItem.Keys)
{
if (attr == "OrderId" || attr == "IsOpen"
|| attr == "OrderCreationDate")
{
Console.WriteLine(attr + "---> " + currentItem[attr].N);
}
else
{
Console.WriteLine(attr + "---> " + currentItem[attr].S);
}
}
Console.WriteLine();
}
Console.WriteLine("\nConsumed capacity: " + result.ConsumedCapacity.CapacityUnits + "\n");
}
private static void DeleteTable(string tableName)
{
Console.WriteLine("Deleting table " + tableName + "...");
client.DeleteTable(new DeleteTableRequest()
{
TableName = tableName
});
WaitForTableToBeDeleted(tableName);
}
public static void LoadData()
{
Console.WriteLine("Loading data into table " + tableName + "...");
Dictionary<string, AttributeValue> item = new Dictionary<string, AttributeValue>();
item["CustomerId"] = new AttributeValue
{
S = "alice@example.com"
};
item["OrderId"] = new AttributeValue
{
N = "1"
};
item["IsOpen"] = new AttributeValue
{
N = "1"
};
item["OrderCreationDate"] = new AttributeValue
{
N = "20130101"
};
item["ProductCategory"] = new AttributeValue
{
S = "Book"
};
item["ProductName"] = new AttributeValue
{
S = "The Great Outdoors"
};
item["OrderStatus"] = new AttributeValue
{
S = "PACKING ITEMS"
};
/* no ShipmentTrackingId attribute */
PutItemRequest putItemRequest = new PutItemRequest
{
TableName = tableName,
Item = item,
ReturnItemCollectionMetrics = "SIZE"
};
client.PutItem(putItemRequest);
item = new Dictionary<string, AttributeValue>();
item["CustomerId"] = new AttributeValue
{
S = "alice@example.com"
};
item["OrderId"] = new AttributeValue
{
N = "2"
};
item["IsOpen"] = new AttributeValue
{
N = "1"
};
item["OrderCreationDate"] = new AttributeValue
{
N = "20130221"
};
item["ProductCategory"] = new AttributeValue
{
S = "Bike"
};
item["ProductName"] = new AttributeValue
{
S = "Super Mountain"
};
item["OrderStatus"] = new AttributeValue
{
S = "ORDER RECEIVED"
};
/* no ShipmentTrackingId attribute */
putItemRequest = new PutItemRequest
{
TableName = tableName,
Item = item,
ReturnItemCollectionMetrics = "SIZE"
};
client.PutItem(putItemRequest);
item = new Dictionary<string, AttributeValue>();
item["CustomerId"] = new AttributeValue
{
S = "alice@example.com"
};
item["OrderId"] = new AttributeValue
{
N = "3"
};
/* no IsOpen attribute */
item["OrderCreationDate"] = new AttributeValue
{
N = "20130304"
};
item["ProductCategory"] = new AttributeValue
{
S = "Music"
};
item["ProductName"] = new AttributeValue
{
S = "A Quiet Interlude"
};
item["OrderStatus"] = new AttributeValue
{
S = "IN TRANSIT"
};
item["ShipmentTrackingId"] = new AttributeValue
{
S = "176493"
};
putItemRequest = new PutItemRequest
{
TableName = tableName,
Item = item,
ReturnItemCollectionMetrics = "SIZE"
};
client.PutItem(putItemRequest);
item = new Dictionary<string, AttributeValue>();
item["CustomerId"] = new AttributeValue
{
S = "bob@example.com"
};
item["OrderId"] = new AttributeValue
{
N = "1"
};
/* no IsOpen attribute */
item["OrderCreationDate"] = new AttributeValue
{
N = "20130111"
};
item["ProductCategory"] = new AttributeValue
{
S = "Movie"
};
item["ProductName"] = new AttributeValue
{
S = "Calm Before The Storm"
};
item["OrderStatus"] = new AttributeValue
{
S = "SHIPPING DELAY"
};
item["ShipmentTrackingId"] = new AttributeValue
{
S = "859323"
};
putItemRequest = new PutItemRequest
{
TableName = tableName,
Item = item,
ReturnItemCollectionMetrics = "SIZE"
};
client.PutItem(putItemRequest);
item = new Dictionary<string, AttributeValue>();
item["CustomerId"] = new AttributeValue
{
S = "bob@example.com"
};
item["OrderId"] = new AttributeValue
{
N = "2"
};
/* no IsOpen attribute */
item["OrderCreationDate"] = new AttributeValue
{
N = "20130124"
};
item["ProductCategory"] = new AttributeValue
{
S = "Music"
};
item["ProductName"] = new AttributeValue
{
S = "E-Z Listening"
};
item["OrderStatus"] = new AttributeValue
{
S = "DELIVERED"
};
item["ShipmentTrackingId"] = new AttributeValue
{
S = "756943"
};
putItemRequest = new PutItemRequest
{
TableName = tableName,
Item = item,
ReturnItemCollectionMetrics = "SIZE"
};
client.PutItem(putItemRequest);
item = new Dictionary<string, AttributeValue>();
item["CustomerId"] = new AttributeValue
{
S = "bob@example.com"
};
item["OrderId"] = new AttributeValue
{
N = "3"
};
/* no IsOpen attribute */
item["OrderCreationDate"] = new AttributeValue
{
N = "20130221"
};
item["ProductCategory"] = new AttributeValue
{
S = "Music"
};
item["ProductName"] = new AttributeValue
{
S = "Symphony 9"
};
item["OrderStatus"] = new AttributeValue
{
S = "DELIVERED"
};
item["ShipmentTrackingId"] = new AttributeValue
{
S = "645193"
};
putItemRequest = new PutItemRequest
{
TableName = tableName,
Item = item,
ReturnItemCollectionMetrics = "SIZE"
};
client.PutItem(putItemRequest);
item = new Dictionary<string, AttributeValue>();
item["CustomerId"] = new AttributeValue
{
S = "bob@example.com"
};
item["OrderId"] = new AttributeValue
{
N = "4"
};
item["IsOpen"] = new AttributeValue
{
N = "1"
};
item["OrderCreationDate"] = new AttributeValue
{
N = "20130222"
};
item["ProductCategory"] = new AttributeValue
{
S = "Hardware"
};
item["ProductName"] = new AttributeValue
{
S = "Extra Heavy Hammer"
};
item["OrderStatus"] = new AttributeValue
{
S = "PACKING ITEMS"
};
/* no ShipmentTrackingId attribute */
putItemRequest = new PutItemRequest
{
TableName = tableName,
Item = item,
ReturnItemCollectionMetrics = "SIZE"
};
client.PutItem(putItemRequest);
item = new Dictionary<string, AttributeValue>();
item["CustomerId"] = new AttributeValue
{
S = "bob@example.com"
};
item["OrderId"] = new AttributeValue
{
N = "5"
};
/* no IsOpen attribute */
item["OrderCreationDate"] = new AttributeValue
{
N = "20130309"
};
item["ProductCategory"] = new AttributeValue
{
S = "Book"
};
item["ProductName"] = new AttributeValue
{
S = "How To Cook"
};
item["OrderStatus"] = new AttributeValue
{
S = "IN TRANSIT"
};
item["ShipmentTrackingId"] = new AttributeValue
{
S = "440185"
};
putItemRequest = new PutItemRequest
{
TableName = tableName,
Item = item,
ReturnItemCollectionMetrics = "SIZE"
};
client.PutItem(putItemRequest);
item = new Dictionary<string, AttributeValue>();
item["CustomerId"] = new AttributeValue
{
S = "bob@example.com"
};
item["OrderId"] = new AttributeValue
{
N = "6"
};
/* no IsOpen attribute */
item["OrderCreationDate"] = new AttributeValue
{
N = "20130318"
};
item["ProductCategory"] = new AttributeValue
{
S = "Luggage"
};
item["ProductName"] = new AttributeValue
{
S = "Really Big Suitcase"
};
item["OrderStatus"] = new AttributeValue
{
S = "DELIVERED"
};
item["ShipmentTrackingId"] = new AttributeValue
{
S = "893927"
};
putItemRequest = new PutItemRequest
{
TableName = tableName,
Item = item,
ReturnItemCollectionMetrics = "SIZE"
};
client.PutItem(putItemRequest);
item = new Dictionary<string, AttributeValue>();
item["CustomerId"] = new AttributeValue
{
S = "bob@example.com"
};
item["OrderId"] = new AttributeValue
{
N = "7"
};
/* no IsOpen attribute */
item["OrderCreationDate"] = new AttributeValue
{
N = "20130324"
};
item["ProductCategory"] = new AttributeValue
{
S = "Golf"
};
item["ProductName"] = new AttributeValue
{
S = "PGA Pro II"
};
item["OrderStatus"] = new AttributeValue
{
S = "OUT FOR DELIVERY"
};
item["ShipmentTrackingId"] = new AttributeValue
{
S = "383283"
};
putItemRequest = new PutItemRequest
{
TableName = tableName,
Item = item,
ReturnItemCollectionMetrics = "SIZE"
};
client.PutItem(putItemRequest);
}
private static void WaitUntilTableReady(string tableName)
{
string status = null;
// Let us wait until table is created. Call DescribeTable.
do
{
System.Threading.Thread.Sleep(5000); // Wait 5 seconds.
try
{
var res = client.DescribeTable(new DescribeTableRequest
{
TableName = tableName
});
Console.WriteLine("Table name: {0}, status: {1}",
res.Table.TableName,
res.Table.TableStatus);
status = res.Table.TableStatus;
}
catch (ResourceNotFoundException)
{
// DescribeTable is eventually consistent. So you might
// get resource not found. So we handle the potential exception.
}
} while (status != "ACTIVE");
}
private static void WaitForTableToBeDeleted(string tableName)
{
bool tablePresent = true;
while (tablePresent)
{
System.Threading.Thread.Sleep(5000); // Wait 5 seconds.
try
{
var res = client.DescribeTable(new DescribeTableRequest
{
TableName = tableName
});
Console.WriteLine("Table name: {0}, status: {1}",
res.Table.TableName,
res.Table.TableStatus);
}
catch (ResourceNotFoundException)
{
tablePresent = false;
}
}
}
}
}
// snippet-end:[dynamodb.dotNET.CodeExample.LowLevelLocalSecondaryIndexExample]
| |
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Reactive;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using System.Threading.Tasks;
using Toggl.Core.Analytics;
using Toggl.Core.Calendar;
using Toggl.Core.Extensions;
using Toggl.Core.Interactors;
using Toggl.Core.Models.Interfaces;
using Toggl.Core.Services;
using Toggl.Core.UI.Extensions;
using Toggl.Core.UI.Navigation;
using Toggl.Core.UI.Parameters;
using Toggl.Core.UI.Views;
using Toggl.Shared;
using Toggl.Shared.Extensions;
namespace Toggl.Core.UI.ViewModels.Calendar.ContextualMenu
{
public class CalendarContextualMenuViewModel : ViewModel
{
private readonly ISubject<CalendarContextualMenu> currentMenuSubject;
private readonly Dictionary<ContextualMenuType, CalendarContextualMenu> contextualMenus;
private readonly ISubject<Unit> discardChangesSubject = new Subject<Unit>();
private readonly BehaviorSubject<bool> menuVisibilitySubject = new BehaviorSubject<bool>(false);
private readonly ISubject<TimeEntryDisplayInfo> timeEntryInfoSubject = new Subject<TimeEntryDisplayInfo>();
private readonly BehaviorSubject<TimeSpan?> currentDuration = new BehaviorSubject<TimeSpan?>(default);
private readonly BehaviorSubject<DateTimeOffset> currentStartTimeOffset = new BehaviorSubject<DateTimeOffset>(default);
private readonly ISubject<CalendarItem?> calendarItemInEditMode = new Subject<CalendarItem?>();
private readonly ISubject<CalendarItem> calendarItemRemoved = new Subject<CalendarItem>();
private readonly ISubject<CalendarItem> calendarItemUpdated = new Subject<CalendarItem>();
private readonly IInteractorFactory interactorFactory;
private readonly ISchedulerProvider schedulerProvider;
private readonly IAnalyticsService analyticsService;
private readonly IRxActionFactory rxActionFactory;
private readonly ITimeService timeService;
private CalendarItem? calendarItemThatOriginallyTriggeredTheMenu = null;
private CalendarItem currentCalendarItem;
private TimeEntryDisplayInfo currentTimeEntryDisplayInfo;
private ContextualMenuType currentMenuType = ContextualMenuType.Closed;
public IObservable<CalendarContextualMenu> CurrentMenu { get; }
public IObservable<Unit> DiscardChanges { get; }
public IObservable<bool> MenuVisible { get; }
public IObservable<TimeEntryDisplayInfo> TimeEntryInfo { get; }
public IObservable<string> TimeEntryPeriod { get; }
public IObservable<CalendarItem?> CalendarItemInEditMode { get; }
public IObservable<CalendarItem> CalendarItemRemoved { get; }
public IObservable<CalendarItem> CalendarItemUpdated { get; }
public InputAction<CalendarItem?> OnCalendarItemUpdated { get; }
public CalendarContextualMenuViewModel(
IInteractorFactory interactorFactory,
ISchedulerProvider schedulerProvider,
IAnalyticsService analyticsService,
IRxActionFactory rxActionFactory,
ITimeService timeService,
INavigationService navigationService)
: base(navigationService)
{
Ensure.Argument.IsNotNull(interactorFactory, nameof(interactorFactory));
Ensure.Argument.IsNotNull(schedulerProvider, nameof(schedulerProvider));
Ensure.Argument.IsNotNull(analyticsService, nameof(analyticsService));
Ensure.Argument.IsNotNull(rxActionFactory, nameof(rxActionFactory));
Ensure.Argument.IsNotNull(timeService, nameof(timeService));
this.interactorFactory = interactorFactory;
this.schedulerProvider = schedulerProvider;
this.analyticsService = analyticsService;
this.rxActionFactory = rxActionFactory;
this.timeService = timeService;
OnCalendarItemUpdated = rxActionFactory.FromAsync<CalendarItem?>(handleCalendarItemInput);
var closedMenu = new CalendarContextualMenu(ContextualMenuType.Closed, ImmutableList<CalendarMenuAction>.Empty, rxActionFactory.FromAction(CommonFunctions.DoNothing));
contextualMenus = new Dictionary<ContextualMenuType, CalendarContextualMenu>
{
{ ContextualMenuType.CalendarEvent, setupCalendarEventActions() },
{ ContextualMenuType.RunningTimeEntry, setupRunningTimeEntryActions() },
{ ContextualMenuType.StoppedTimeEntry, setupStoppedTimeEntryActions() },
{ ContextualMenuType.NewTimeEntry, setupNewTimeEntryContextualActions() },
{ ContextualMenuType.Closed, closedMenu }
};
currentMenuSubject = new BehaviorSubject<CalendarContextualMenu>(closedMenu);
CurrentMenu = currentMenuSubject.AsDriver(schedulerProvider);
DiscardChanges = discardChangesSubject.AsDriver(schedulerProvider);
TimeEntryInfo = timeEntryInfoSubject.AsDriver(schedulerProvider);
MenuVisible = menuVisibilitySubject.AsDriver(schedulerProvider);
CalendarItemInEditMode = calendarItemInEditMode.AsDriver(schedulerProvider);
CalendarItemRemoved = calendarItemRemoved.AsDriver(schedulerProvider);
CalendarItemUpdated = calendarItemUpdated.AsDriver(schedulerProvider);
var useTwentyFourHourFormatObservable = interactorFactory
.ObserveCurrentPreferences().Execute()
.Select(p => p.TimeOfDayFormat.IsTwentyFourHoursFormat)
.DistinctUntilChanged();
TimeEntryPeriod = Observable.CombineLatest(
currentStartTimeOffset.DistinctUntilChanged(),
currentDuration.DistinctUntilChanged(),
useTwentyFourHourFormatObservable,
formatCurrentPeriod)
.DistinctUntilChanged()
.AsDriver(schedulerProvider);
}
private async Task handleCalendarItemInput(CalendarItem? calendarItem)
{
if (!calendarItem.HasValue)
{
if (needsToConfirmDestructiveChangesBeforeClosingMenu())
{
var willCloseMenu = await View.ConfirmDestructiveAction(ActionType.DiscardEditingChanges);
if (!willCloseMenu)
return;
}
closeMenuDismissingUncommittedChanges();
return;
}
var newCalendarItem = calendarItem.Value;
if (contextualMenuIsAlreadyOpen() && isADifferentCalendarItem(newCalendarItem))
{
if (changesWereMadeToTheCurrentItem())
{
var willUpdateCurrentItem = await View.ConfirmDestructiveAction(ActionType.DiscardEditingChanges);
if (!willUpdateCurrentItem)
return;
}
discardChangesSubject.OnNext(Unit.Default);
}
updateCalendarItem(newCalendarItem);
}
private void updateCalendarItem(CalendarItem newCalendarItem)
{
if (!calendarItemThatOriginallyTriggeredTheMenu.HasValue || isADifferentCalendarItem(newCalendarItem))
{
calendarItemThatOriginallyTriggeredTheMenu = newCalendarItem;
calendarItemInEditMode.OnNext(newCalendarItem);
}
var newCalendarItemContextualMenuType = selectContextualMenuTypeFrom(newCalendarItem);
handleMenuUpdate(newCalendarItemContextualMenuType);
handleCalendarItemUpdate(newCalendarItem);
currentCalendarItem = newCalendarItem;
}
private bool needsToConfirmDestructiveChangesBeforeClosingMenu()
=> contextualMenuIsAlreadyOpen() && changesWereMadeToTheCurrentItem();
private bool changesWereMadeToTheCurrentItem()
{
if (!calendarItemThatOriginallyTriggeredTheMenu.HasValue)
return false;
if (currentCalendarItem.Source == CalendarItemSource.Calendar)
return false;
var originalCalendarItem = calendarItemThatOriginallyTriggeredTheMenu.Value;
return originalCalendarItem.StartTime != currentCalendarItem.StartTime
|| originalCalendarItem.Duration != currentCalendarItem.Duration;
}
private bool isADifferentCalendarItem(CalendarItem newCalendarItem)
{
return newCalendarItem.Source != currentCalendarItem.Source
|| (newCalendarItem.Source == CalendarItemSource.TimeEntry && newCalendarItem.TimeEntryId != currentCalendarItem.TimeEntryId)
|| (newCalendarItem.Source == CalendarItemSource.Calendar && newCalendarItem.CalendarId != currentCalendarItem.CalendarId);
}
private bool contextualMenuIsAlreadyOpen() => menuVisibilitySubject.Value;
private void handleMenuUpdate(ContextualMenuType contextualMenuType)
{
if (!contextualMenus.TryGetValue(contextualMenuType, out var actions))
return;
if (contextualMenuType == currentMenuType)
return;
currentMenuType = contextualMenuType;
currentMenuSubject.OnNext(actions);
menuVisibilitySubject.OnNext(true);
}
private void handleCalendarItemUpdate(CalendarItem calendarItem)
{
if (!hasSameTimeEntryDisplayInfoAs(calendarItem))
{
currentTimeEntryDisplayInfo = new TimeEntryDisplayInfo(calendarItem);
timeEntryInfoSubject.OnNext(currentTimeEntryDisplayInfo);
}
currentStartTimeOffset.OnNext(calendarItem.StartTime);
currentDuration.OnNext(calendarItem.Duration);
}
private string formatCurrentPeriod(DateTimeOffset startTime, TimeSpan? duration, bool useTwentyFourHoursFormat)
{
var format = useTwentyFourHoursFormat ? Resources.EditingTwentyFourHoursFormat : Resources.EditingTwelveHoursFormat;
var startTimeString = startTime.ToLocalTime().ToString(format);
var endTime = startTime.ToLocalTime() + duration;
var endTimeString = endTime.HasValue
? endTime.Value.ToString(format)
: Resources.Now;
return $"{startTimeString} - {endTimeString}";
}
private void closeMenuDismissingUncommittedChanges()
{
currentCalendarItem = default;
calendarItemThatOriginallyTriggeredTheMenu = null;
currentMenuType = ContextualMenuType.Closed;
discardChangesSubject.OnNext(Unit.Default);
calendarItemInEditMode.OnNext(null);
currentMenuSubject.OnNext(contextualMenus[ContextualMenuType.Closed]);
menuVisibilitySubject.OnNext(false);
}
private void closeMenuWithCommittedChanges()
{
currentCalendarItem = default;
calendarItemThatOriginallyTriggeredTheMenu = null;
currentMenuType = ContextualMenuType.Closed;
currentMenuSubject.OnNext(contextualMenus[ContextualMenuType.Closed]);
menuVisibilitySubject.OnNext(false);
}
private CalendarContextualMenu setupCalendarEventActions()
{
var actions = ImmutableList.Create(
createCalendarMenuActionFor(ContextualMenuType.CalendarEvent, CalendarMenuActionKind.Copy, Resources.CalendarCopyEventToTimeEntry,
trackThenRunCalendarEventCreationAsync(
CalendarTimeEntryCreatedType.CopyFromCalendarEvent,
CalendarContextualMenuActionType.CopyAsTimeEntry,
createTimeEntryFromCalendarItem)
),
createCalendarMenuActionFor(ContextualMenuType.CalendarEvent, CalendarMenuActionKind.Start, Resources.Start,
trackThenRunCalendarEventCreationAsync(
CalendarTimeEntryCreatedType.StartFromCalendarEvent,
CalendarContextualMenuActionType.StartFromCalendarEvent,
startTimeEntryFromCalendarItem)
));
return new CalendarContextualMenu(ContextualMenuType.CalendarEvent, actions, trackThenDismiss(analyticsService.CalendarEventContextualMenu));
}
private void trackCalendarEventCreation(CalendarItem item, CalendarTimeEntryCreatedType eventCreationType, CalendarContextualMenuActionType menuType)
{
var today = timeService.CurrentDateTime;
var daysSinceToday = (int)(item.StartTime - today).TotalDays;
var dayOfTheWeek = item.StartTime.DayOfWeek;
analyticsService.CalendarEventContextualMenu.Track(menuType);
analyticsService.CalendarTimeEntryCreated.Track(eventCreationType, daysSinceToday, dayOfTheWeek.ToString());
}
private void trackLongPressCreation(CalendarItem item, CalendarTimeEntryCreatedType eventCreationType, CalendarContextualMenuActionType menuType)
{
var today = timeService.CurrentDateTime;
var daysSinceToday = (int)(item.StartTime - today).TotalDays;
var dayOfTheWeek = item.StartTime.DayOfWeek;
analyticsService.CalendarNewTimeEntryContextualMenu.Track(menuType);
analyticsService.CalendarTimeEntryCreated.Track(eventCreationType, daysSinceToday, dayOfTheWeek.ToString());
}
private async Task createTimeEntryFromCalendarItem(CalendarItem calendarItem)
{
var workspace = await interactorFactory.GetDefaultWorkspace()
.TrackException<InvalidOperationException, IThreadSafeWorkspace>("CalendarContextualMenuViewModel.createTimeEntryFromCalendarItem")
.Execute();
var prototype = calendarItem.AsTimeEntryPrototype(workspace.Id);
await interactorFactory.CreateTimeEntry(prototype, TimeEntryStartOrigin.CalendarEvent).Execute();
closeMenuWithCommittedChanges();
}
private async Task startTimeEntryFromCalendarItem(CalendarItem calendarItem)
{
var timeEntryToStart = calendarItem
.WithStartTime(timeService.CurrentDateTime)
.WithDuration(null);
var workspace = await interactorFactory.GetDefaultWorkspace()
.TrackException<InvalidOperationException, IThreadSafeWorkspace>("CalendarContextualMenuViewModel.startTimeEntryFromCalendarItem")
.Execute();
var prototype = timeEntryToStart.AsTimeEntryPrototype(workspace.Id);
await interactorFactory.CreateTimeEntry(prototype, TimeEntryStartOrigin.CalendarEvent).Execute();
closeMenuWithCommittedChanges();
}
private CalendarContextualMenu setupRunningTimeEntryActions()
{
var analyticsEvent = analyticsService.CalendarRunningTimeEntryContextualMenu;
var actions = ImmutableList.Create(
createCalendarMenuDiscardAction(ContextualMenuType.RunningTimeEntry, trackThenRunAsync(analyticsEvent, CalendarContextualMenuActionType.Discard, deleteTimeEntry)),
createCalendarMenuEditAction(ContextualMenuType.RunningTimeEntry, trackThenRunAsync(analyticsEvent, CalendarContextualMenuActionType.Edit, editTimeEntry)),
createCalendarMenuSaveAction(ContextualMenuType.RunningTimeEntry, trackThenRunAsync(analyticsEvent, CalendarContextualMenuActionType.Save, saveTimeEntry)),
createCalendarMenuActionFor(ContextualMenuType.RunningTimeEntry, CalendarMenuActionKind.Stop, Resources.Stop, trackThenRunAsync(analyticsEvent, CalendarContextualMenuActionType.Stop, stopTimeEntry))
);
return new CalendarContextualMenu(ContextualMenuType.RunningTimeEntry, actions, trackThenDismiss(analyticsEvent));
}
private async Task deleteTimeEntry(CalendarItem calendarItem)
{
if (!calendarItem.TimeEntryId.HasValue)
return;
var view = View;
if (view == null)
return;
var shouldDelete = await view.ConfirmDestructiveAction(ActionType.DeleteExistingTimeEntry);
if (!shouldDelete)
return;
calendarItemRemoved.OnNext(calendarItem);
await interactorFactory.DeleteTimeEntry(calendarItem.TimeEntryId.Value).Execute();
closeMenuWithCommittedChanges();
}
private async Task editTimeEntry(CalendarItem calendarItem)
{
if (!calendarItem.TimeEntryId.HasValue)
return;
analyticsService.EditViewOpenedFromCalendar.Track();
await Navigate<EditTimeEntryViewModel, long[]>(new[] { calendarItem.TimeEntryId.Value });
closeMenuWithCommittedChanges();
}
private async Task saveTimeEntry(CalendarItem calendarItem)
{
if (!calendarItem.TimeEntryId.HasValue)
return;
var timeEntry = await interactorFactory.GetTimeEntryById(calendarItem.TimeEntryId.Value).Execute();
var dto = new DTOs.EditTimeEntryDto
{
Id = timeEntry.Id,
Description = timeEntry.Description,
StartTime = calendarItem.StartTime,
StopTime = calendarItem.Duration.HasValue ? calendarItem.EndTime : timeEntry.StopTime(),
ProjectId = timeEntry.ProjectId,
TaskId = timeEntry.TaskId,
Billable = timeEntry.Billable,
WorkspaceId = timeEntry.WorkspaceId,
TagIds = timeEntry.TagIds
};
await interactorFactory.UpdateTimeEntry(dto).Execute();
closeMenuWithCommittedChanges();
}
private async Task stopTimeEntry(CalendarItem calendarItem)
{
var currentDateTime = timeService.CurrentDateTime;
calendarItemUpdated.OnNext(calendarItem.WithDuration(currentDateTime - calendarItem.StartTime));
await interactorFactory.StopTimeEntry(currentDateTime, TimeEntryStopOrigin.CalendarContextualMenu).Execute();
closeMenuWithCommittedChanges();
}
private CalendarContextualMenu setupStoppedTimeEntryActions()
{
var analyticsEvent = analyticsService.CalendarExistingTimeEntryContextualMenu;
var actions = ImmutableList.Create(
createCalendarMenuActionFor(ContextualMenuType.StoppedTimeEntry, CalendarMenuActionKind.Delete, Resources.Delete, trackThenRunAsync(analyticsEvent, CalendarContextualMenuActionType.Delete, deleteTimeEntry)),
createCalendarMenuEditAction(ContextualMenuType.StoppedTimeEntry, trackThenRunAsync(analyticsEvent, CalendarContextualMenuActionType.Edit, editTimeEntry)),
createCalendarMenuSaveAction(ContextualMenuType.StoppedTimeEntry, trackThenRunAsync(analyticsEvent, CalendarContextualMenuActionType.Save, saveTimeEntry)),
createCalendarMenuActionFor(ContextualMenuType.StoppedTimeEntry, CalendarMenuActionKind.Continue, Resources.Continue, trackThenRunAsync(analyticsEvent, CalendarContextualMenuActionType.Continue, continueTimeEntry))
);
return new CalendarContextualMenu(ContextualMenuType.StoppedTimeEntry, actions, trackThenDismiss(analyticsEvent));
}
private async Task continueTimeEntry(CalendarItem calendarItem)
{
if (!calendarItem.TimeEntryId.HasValue)
return;
await interactorFactory
.ContinueTimeEntry(calendarItem.TimeEntryId.Value, ContinueTimeEntryMode.CalendarContextualMenu)
.Execute();
closeMenuWithCommittedChanges();
}
private CalendarContextualMenu setupNewTimeEntryContextualActions()
{
var analyticsEvent = analyticsService.CalendarNewTimeEntryContextualMenu;
var actions = ImmutableList.Create(
createCalendarMenuDiscardAction(ContextualMenuType.NewTimeEntry, trackThenRun(analyticsEvent, CalendarContextualMenuActionType.Discard, discardCurrentItemInEditMode)),
createCalendarMenuEditAction(ContextualMenuType.NewTimeEntry, trackThenRunAsync(analyticsEvent, CalendarContextualMenuActionType.Edit, startTimeEntryFrom)),
createCalendarMenuSaveAction(ContextualMenuType.NewTimeEntry, trackThenRunManualCreationAsync(CalendarTimeEntryCreatedType.LongPress, CalendarContextualMenuActionType.Save, createTimeEntryFromCalendarItem))
);
return new CalendarContextualMenu(ContextualMenuType.NewTimeEntry, actions, trackThenDismiss(analyticsEvent));
}
private async Task startTimeEntryFrom(CalendarItem calendarItem)
{
var workspace = await interactorFactory.GetDefaultWorkspace()
.TrackException<InvalidOperationException, IThreadSafeWorkspace>("CalendarContextualMenuViewModel.startTimeEntryFromCalendarItem")
.Execute();
var timeEntryParams = new StartTimeEntryParameters(
calendarItem.StartTime,
string.Empty,
calendarItem.Duration,
workspace.Id);
var createdEntry = await Navigate<StartTimeEntryViewModel, StartTimeEntryParameters, IThreadSafeTimeEntry>(timeEntryParams);
if (createdEntry != null)
closeMenuWithCommittedChanges();
}
private void discardCurrentItemInEditMode(CalendarItem calendarItem)
{
closeMenuDismissingUncommittedChanges();
}
private ContextualMenuType selectContextualMenuTypeFrom(CalendarItem calendarItem)
{
if (calendarItemIsANewTimeEntry(calendarItem))
return ContextualMenuType.NewTimeEntry;
if (calendarItemIsFromAnExistingTimeEntry(calendarItem))
{
return calendarItem.Duration.HasValue
? ContextualMenuType.StoppedTimeEntry
: ContextualMenuType.RunningTimeEntry;
}
return ContextualMenuType.CalendarEvent;
}
private bool calendarItemIsFromAnExistingTimeEntry(CalendarItem calendarItem)
=> calendarItem.Source == CalendarItemSource.TimeEntry
&& !string.IsNullOrEmpty(calendarItem.Id)
&& calendarItem.TimeEntryId.HasValue;
private bool calendarItemIsANewTimeEntry(CalendarItem calendarItem)
=> string.IsNullOrEmpty(calendarItem.Id);
private bool hasSameTimeEntryDisplayInfoAs(CalendarItem calendarItem)
=> calendarItem.Description == currentTimeEntryDisplayInfo.Description
&& calendarItem.Project == currentTimeEntryDisplayInfo.Project
&& calendarItem.Task == currentTimeEntryDisplayInfo.Task
&& calendarItem.Color == currentTimeEntryDisplayInfo.ProjectTaskColor;
private ViewAction trackThenRun(IAnalyticsEvent<CalendarContextualMenuActionType> analyticsEvent, CalendarContextualMenuActionType eventValue, Action<CalendarItem> action)
=> rxActionFactory.FromAction(() =>
{
analyticsEvent.Track(eventValue);
action(currentCalendarItem);
});
private ViewAction trackThenRunAsync(IAnalyticsEvent<CalendarContextualMenuActionType> analyticsEvent, CalendarContextualMenuActionType eventValue, Func<CalendarItem, Task> action)
=> rxActionFactory.FromAsync(() =>
{
analyticsEvent.Track(eventValue);
return action(currentCalendarItem);
});
private ViewAction trackThenRunCalendarEventCreationAsync(CalendarTimeEntryCreatedType eventCreationType, CalendarContextualMenuActionType menuType, Func<CalendarItem, Task> action)
=> rxActionFactory.FromAsync(() =>
{
trackCalendarEventCreation(currentCalendarItem, eventCreationType, menuType);
return action(currentCalendarItem);
});
private ViewAction trackThenRunManualCreationAsync(CalendarTimeEntryCreatedType eventCreationType, CalendarContextualMenuActionType menuType, Func<CalendarItem, Task> action)
=> rxActionFactory.FromAsync(() =>
{
trackLongPressCreation(currentCalendarItem, eventCreationType, menuType);
return action(currentCalendarItem);
});
private ViewAction trackThenDismiss(IAnalyticsEvent<CalendarContextualMenuActionType> analyticsEvent)
=> rxActionFactory.FromAsync(() =>
{
analyticsEvent.Track(CalendarContextualMenuActionType.Dismiss);
return confirmThenCloseMenuDismissingUncommittedChanges();
});
private async Task confirmThenCloseMenuDismissingUncommittedChanges()
{
if (!changesWereMadeToTheCurrentItem() || await View.ConfirmDestructiveAction(ActionType.DiscardEditingChanges))
closeMenuDismissingUncommittedChanges();
}
private CalendarMenuAction createCalendarMenuActionFor(ContextualMenuType sourceMenuType, CalendarMenuActionKind calendarMenuActionKind, string title, ViewAction action)
=> new CalendarMenuAction(sourceMenuType, calendarMenuActionKind, title, action);
private CalendarMenuAction createCalendarMenuSaveAction(ContextualMenuType sourceMenuType, ViewAction action)
=> createCalendarMenuActionFor(sourceMenuType, CalendarMenuActionKind.Save, Resources.Save, action);
private CalendarMenuAction createCalendarMenuEditAction(ContextualMenuType sourceMenuType, ViewAction action)
=> createCalendarMenuActionFor(sourceMenuType, CalendarMenuActionKind.Edit, Resources.Edit, action);
private CalendarMenuAction createCalendarMenuDiscardAction(ContextualMenuType sourceMenuType, ViewAction action)
=> createCalendarMenuActionFor(sourceMenuType, CalendarMenuActionKind.Discard, Resources.Discard, action);
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Automation
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// DscCompilationJobOperations operations.
/// </summary>
internal partial class DscCompilationJobOperations : IServiceOperations<AutomationClient>, IDscCompilationJobOperations
{
/// <summary>
/// Initializes a new instance of the DscCompilationJobOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal DscCompilationJobOperations(AutomationClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the AutomationClient
/// </summary>
public AutomationClient Client { get; private set; }
/// <summary>
/// Creates the Dsc compilation job of the configuration.
/// <see href="http://aka.ms/azureautomationsdk/dscconfigurationcompilejoboperations" />
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='automationAccountName'>
/// The automation account name.
/// </param>
/// <param name='compilationJobId'>
/// The the DSC configuration Id.
/// </param>
/// <param name='parameters'>
/// The parameters supplied to the create compilation job operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<DscCompilationJob>> CreateWithHttpMessagesAsync(string resourceGroupName, string automationAccountName, System.Guid compilationJobId, DscCompilationJobCreateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (resourceGroupName != null)
{
if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._]+$"))
{
throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._]+$");
}
}
if (automationAccountName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "automationAccountName");
}
if (parameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "parameters");
}
if (parameters != null)
{
parameters.Validate();
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2015-10-31";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("automationAccountName", automationAccountName);
tracingParameters.Add("compilationJobId", compilationJobId);
tracingParameters.Add("parameters", parameters);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Create", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Automation/automationAccounts/{automationAccountName}/compilationjobs/{compilationJobId}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{automationAccountName}", System.Uri.EscapeDataString(automationAccountName));
_url = _url.Replace("{compilationJobId}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(compilationJobId, Client.SerializationSettings).Trim('"')));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(parameters != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 201)
{
var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<DscCompilationJob>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<DscCompilationJob>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Retrieve the Dsc configuration compilation job identified by job id.
/// <see href="http://aka.ms/azureautomationsdk/dsccompilationjoboperations" />
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='automationAccountName'>
/// The automation account name.
/// </param>
/// <param name='compilationJobId'>
/// The Dsc configuration compilation job id.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<DscCompilationJob>> GetWithHttpMessagesAsync(string resourceGroupName, string automationAccountName, System.Guid compilationJobId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (resourceGroupName != null)
{
if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._]+$"))
{
throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._]+$");
}
}
if (automationAccountName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "automationAccountName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2015-10-31";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("automationAccountName", automationAccountName);
tracingParameters.Add("compilationJobId", compilationJobId);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Automation/automationAccounts/{automationAccountName}/compilationjobs/{compilationJobId}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{automationAccountName}", System.Uri.EscapeDataString(automationAccountName));
_url = _url.Replace("{compilationJobId}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(compilationJobId, Client.SerializationSettings).Trim('"')));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<DscCompilationJob>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<DscCompilationJob>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Retrieve a list of dsc compilation jobs.
/// <see href="http://aka.ms/azureautomationsdk/compilationjoboperations" />
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='automationAccountName'>
/// The automation account name.
/// </param>
/// <param name='filter'>
/// The filter to apply on the operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<DscCompilationJob>>> ListByAutomationAccountWithHttpMessagesAsync(string resourceGroupName, string automationAccountName, string filter = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (resourceGroupName != null)
{
if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._]+$"))
{
throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._]+$");
}
}
if (automationAccountName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "automationAccountName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2015-10-31";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("automationAccountName", automationAccountName);
tracingParameters.Add("filter", filter);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListByAutomationAccount", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Automation/automationAccounts/{automationAccountName}/compilationjobs").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{automationAccountName}", System.Uri.EscapeDataString(automationAccountName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (filter != null)
{
_queryParameters.Add(string.Format("$filter={0}", System.Uri.EscapeDataString(filter)));
}
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<DscCompilationJob>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<DscCompilationJob>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Retrieve the job stream identified by job stream id.
/// <see href="http://aka.ms/azureautomationsdk/jobstreamoperations" />
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='automationAccountName'>
/// The automation account name.
/// </param>
/// <param name='jobId'>
/// The job id.
/// </param>
/// <param name='jobStreamId'>
/// The job stream id.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<JobStream>> GetStreamWithHttpMessagesAsync(string resourceGroupName, string automationAccountName, System.Guid jobId, string jobStreamId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (resourceGroupName != null)
{
if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._]+$"))
{
throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._]+$");
}
}
if (automationAccountName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "automationAccountName");
}
if (jobStreamId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "jobStreamId");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2015-10-31";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("automationAccountName", automationAccountName);
tracingParameters.Add("jobId", jobId);
tracingParameters.Add("jobStreamId", jobStreamId);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetStream", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Automation/automationAccounts/{automationAccountName}/compilationjobs/{jobId}/streams/{jobStreamId}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{automationAccountName}", System.Uri.EscapeDataString(automationAccountName));
_url = _url.Replace("{jobId}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(jobId, Client.SerializationSettings).Trim('"')));
_url = _url.Replace("{jobStreamId}", System.Uri.EscapeDataString(jobStreamId));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<JobStream>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<JobStream>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Retrieve a list of dsc compilation jobs.
/// <see href="http://aka.ms/azureautomationsdk/compilationjoboperations" />
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<DscCompilationJob>>> ListByAutomationAccountNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListByAutomationAccountNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<DscCompilationJob>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<DscCompilationJob>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
//
// BestEncodingFilter.cs
//
// Author: Jeffrey Stedfast <jeff@xamarin.com>
//
// Copyright (c) 2013-2015 Xamarin Inc. (www.xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
using System;
namespace MimeKit.IO.Filters {
/// <summary>
/// A filter that can be used to determine the most efficient Content-Transfer-Encoding.
/// </summary>
/// <remarks>
/// Keeps track of the content that gets passed through the filter in order to
/// determine the most efficient <see cref="ContentEncoding"/> to use.
/// </remarks>
public class BestEncodingFilter : IMimeFilter
{
readonly byte[] marker = new byte[6];
bool midline, hasMarker;
int maxline, linelen;
int count0, count8;
int markerLength;
int total;
/// <summary>
/// Initializes a new instance of the <see cref="BestEncodingFilter"/> class.
/// </summary>
/// <remarks>
/// Creates a new <see cref="BestEncodingFilter"/>.
/// </remarks>
public BestEncodingFilter ()
{
}
/// <summary>
/// Gets the best encoding given the specified constraints.
/// </summary>
/// <remarks>
/// Gets the best encoding given the specified constraints.
/// </remarks>
/// <returns>The best encoding.</returns>
/// <param name="constraint">The encoding constraint.</param>
/// <param name="maxLineLength">The maximum allowable line length (not counting the CRLF). Must be between <c>72</c> and <c>998</c> (inclusive).</param>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <para><paramref name="maxLineLength"/> is not between <c>72</c> and <c>998</c> (inclusive).</para>
/// <para>-or-</para>
/// <para><paramref name="constraint"/> is not a valid value.</para>
/// </exception>
public ContentEncoding GetBestEncoding (EncodingConstraint constraint, int maxLineLength = 78)
{
if (maxLineLength < 72 || maxLineLength > 998)
throw new ArgumentOutOfRangeException ("maxLineLength");
switch (constraint) {
case EncodingConstraint.SevenBit:
if (count0 > 0)
return ContentEncoding.Base64;
if (count8 > 0) {
if (count8 >= (int) (total * (17.0 / 100.0)))
return ContentEncoding.Base64;
return ContentEncoding.QuotedPrintable;
}
if (maxline > maxLineLength)
return ContentEncoding.QuotedPrintable;
break;
case EncodingConstraint.EightBit:
if (count0 > 0)
return ContentEncoding.Base64;
if (maxline > maxLineLength)
return ContentEncoding.QuotedPrintable;
if (count8 > 0)
return ContentEncoding.EightBit;
break;
case EncodingConstraint.None:
if (count0 > 0)
return ContentEncoding.Binary;
if (maxline > maxLineLength)
return ContentEncoding.QuotedPrintable;
if (count8 > 0)
return ContentEncoding.EightBit;
break;
default:
throw new ArgumentOutOfRangeException ("constraint");
}
if (hasMarker)
return ContentEncoding.QuotedPrintable;
return ContentEncoding.SevenBit;
}
#region IMimeFilter implementation
static unsafe bool IsMboxMarker (byte[] marker)
{
const uint FromMask = 0xFFFFFFFF;
const uint From = 0x6D6F7246;
fixed (byte* buf = marker) {
uint* word = (uint*) buf;
if ((*word & FromMask) != From)
return false;
return *(buf + 4) == (byte) ' ';
}
}
unsafe void Scan (byte* inptr, byte* inend)
{
while (inptr < inend) {
if (midline) {
byte c = 0;
while (inptr < inend && (c = *inptr++) != (byte) '\n') {
if (c == 0)
count0++;
else if ((c & 0x80) != 0)
count8++;
if (!hasMarker && markerLength > 0 && markerLength < 5)
marker[markerLength++] = c;
linelen++;
}
if (c == (byte) '\n') {
maxline = Math.Max (maxline, linelen);
midline = false;
linelen = 0;
}
}
// check our from-save buffer for "From "
if (!hasMarker && markerLength == 5 && IsMboxMarker (marker))
hasMarker = true;
markerLength = 0;
midline = true;
}
}
static void ValidateArguments (byte[] input, int startIndex, int length)
{
if (input == null)
throw new ArgumentNullException ("input");
if (startIndex < 0 || startIndex > input.Length)
throw new ArgumentOutOfRangeException ("startIndex");
if (length < 0 || length > (input.Length - startIndex))
throw new ArgumentOutOfRangeException ("length");
}
/// <summary>
/// Filters the specified input.
/// </summary>
/// <remarks>
/// Filters the specified input buffer starting at the given index,
/// spanning across the specified number of bytes.
/// </remarks>
/// <returns>The filtered output.</returns>
/// <param name="input">The input buffer.</param>
/// <param name="startIndex">The starting index of the input buffer.</param>
/// <param name="length">The number of bytes of the input to filter.</param>
/// <param name="outputIndex">The starting index of the output in the returned buffer.</param>
/// <param name="outputLength">The length of the output buffer.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="input"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="startIndex"/> and <paramref name="length"/> do not specify
/// a valid range in the <paramref name="input"/> byte array.
/// </exception>
public byte[] Filter (byte[] input, int startIndex, int length, out int outputIndex, out int outputLength)
{
ValidateArguments (input, startIndex, length);
unsafe {
fixed (byte* inptr = input) {
Scan (inptr + startIndex, inptr + startIndex + length);
}
}
maxline = Math.Max (maxline, linelen);
total += length;
outputIndex = startIndex;
outputLength = length;
return input;
}
/// <summary>
/// Filters the specified input, flushing all internally buffered data to the output.
/// </summary>
/// <remarks>
/// Filters the specified input buffer starting at the given index,
/// spanning across the specified number of bytes.
/// </remarks>
/// <returns>The filtered output.</returns>
/// <param name="input">The input buffer.</param>
/// <param name="startIndex">The starting index of the input buffer.</param>
/// <param name="length">The number of bytes of the input to filter.</param>
/// <param name="outputIndex">The starting index of the output in the returned buffer.</param>
/// <param name="outputLength">The length of the output buffer.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="input"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="startIndex"/> and <paramref name="length"/> do not specify
/// a valid range in the <paramref name="input"/> byte array.
/// </exception>
public byte[] Flush (byte[] input, int startIndex, int length, out int outputIndex, out int outputLength)
{
return Filter (input, startIndex, length, out outputIndex, out outputLength);
}
/// <summary>
/// Resets the filter.
/// </summary>
/// <remarks>
/// Resets the filter.
/// </remarks>
public void Reset ()
{
hasMarker = false;
markerLength = 0;
midline = false;
linelen = 0;
maxline = 0;
count0 = 0;
count8 = 0;
total = 0;
}
#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 Microsoft.Rest.Azure;
using Models;
/// <summary>
/// Extension methods for CertificateOperations.
/// </summary>
public static partial class CertificateOperationsExtensions
{
/// <summary>
/// Adds a certificate to the specified account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='certificate'>
/// The certificate to be added.
/// </param>
/// <param name='certificateAddOptions'>
/// Additional parameters for the operation
/// </param>
public static CertificateAddHeaders Add(this ICertificateOperations operations, CertificateAddParameter certificate, CertificateAddOptions certificateAddOptions = default(CertificateAddOptions))
{
return ((ICertificateOperations)operations).AddAsync(certificate, certificateAddOptions).GetAwaiter().GetResult();
}
/// <summary>
/// Adds a certificate to the specified account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='certificate'>
/// The certificate to be added.
/// </param>
/// <param name='certificateAddOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<CertificateAddHeaders> AddAsync(this ICertificateOperations operations, CertificateAddParameter certificate, CertificateAddOptions certificateAddOptions = default(CertificateAddOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.AddWithHttpMessagesAsync(certificate, certificateAddOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Headers;
}
}
/// <summary>
/// Lists all of the certificates that have been added to the specified
/// account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='certificateListOptions'>
/// Additional parameters for the operation
/// </param>
public static Microsoft.Rest.Azure.IPage<Certificate> List(this ICertificateOperations operations, CertificateListOptions certificateListOptions = default(CertificateListOptions))
{
return ((ICertificateOperations)operations).ListAsync(certificateListOptions).GetAwaiter().GetResult();
}
/// <summary>
/// Lists all of the certificates that have been added to the specified
/// account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='certificateListOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<Microsoft.Rest.Azure.IPage<Certificate>> ListAsync(this ICertificateOperations operations, CertificateListOptions certificateListOptions = default(CertificateListOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(certificateListOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Cancels a failed deletion of a certificate from the specified account.
/// </summary>
/// <remarks>
/// If you try to delete a certificate that is being used by a pool or compute
/// node, the status of the certificate changes to deleteFailed. If you decide
/// that you want to continue using the certificate, you can use this operation
/// to set the status of the certificate back to active. If you intend to
/// delete the certificate, you do not need to run this operation after the
/// deletion failed. You must make sure that the certificate is not being used
/// by any resources, and then you can try again to delete the certificate.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='thumbprintAlgorithm'>
/// The algorithm used to derive the thumbprint parameter. This must be sha1.
/// </param>
/// <param name='thumbprint'>
/// The thumbprint of the certificate being deleted.
/// </param>
/// <param name='certificateCancelDeletionOptions'>
/// Additional parameters for the operation
/// </param>
public static CertificateCancelDeletionHeaders CancelDeletion(this ICertificateOperations operations, string thumbprintAlgorithm, string thumbprint, CertificateCancelDeletionOptions certificateCancelDeletionOptions = default(CertificateCancelDeletionOptions))
{
return ((ICertificateOperations)operations).CancelDeletionAsync(thumbprintAlgorithm, thumbprint, certificateCancelDeletionOptions).GetAwaiter().GetResult();
}
/// <summary>
/// Cancels a failed deletion of a certificate from the specified account.
/// </summary>
/// <remarks>
/// If you try to delete a certificate that is being used by a pool or compute
/// node, the status of the certificate changes to deleteFailed. If you decide
/// that you want to continue using the certificate, you can use this operation
/// to set the status of the certificate back to active. If you intend to
/// delete the certificate, you do not need to run this operation after the
/// deletion failed. You must make sure that the certificate is not being used
/// by any resources, and then you can try again to delete the certificate.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='thumbprintAlgorithm'>
/// The algorithm used to derive the thumbprint parameter. This must be sha1.
/// </param>
/// <param name='thumbprint'>
/// The thumbprint of the certificate being deleted.
/// </param>
/// <param name='certificateCancelDeletionOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<CertificateCancelDeletionHeaders> CancelDeletionAsync(this ICertificateOperations operations, string thumbprintAlgorithm, string thumbprint, CertificateCancelDeletionOptions certificateCancelDeletionOptions = default(CertificateCancelDeletionOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.CancelDeletionWithHttpMessagesAsync(thumbprintAlgorithm, thumbprint, certificateCancelDeletionOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Headers;
}
}
/// <summary>
/// Deletes a certificate from the specified account.
/// </summary>
/// <remarks>
/// You cannot delete a certificate if a resource (pool or compute node) is
/// using it. Before you can delete a certificate, you must therefore make sure
/// that the certificate is not associated with any existing pools, the
/// certificate is not installed on any compute nodes (even if you remove a
/// certificate from a pool, it is not removed from existing compute nodes in
/// that pool until they restart), and no running tasks depend on the
/// certificate. If you try to delete a certificate that is in use, the
/// deletion fails. The certificate status changes to deleteFailed. You can use
/// Cancel Delete Certificate to set the status back to active if you decide
/// that you want to continue using the certificate.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='thumbprintAlgorithm'>
/// The algorithm used to derive the thumbprint parameter. This must be sha1.
/// </param>
/// <param name='thumbprint'>
/// The thumbprint of the certificate to be deleted.
/// </param>
/// <param name='certificateDeleteOptions'>
/// Additional parameters for the operation
/// </param>
public static CertificateDeleteHeaders Delete(this ICertificateOperations operations, string thumbprintAlgorithm, string thumbprint, CertificateDeleteOptions certificateDeleteOptions = default(CertificateDeleteOptions))
{
return ((ICertificateOperations)operations).DeleteAsync(thumbprintAlgorithm, thumbprint, certificateDeleteOptions).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes a certificate from the specified account.
/// </summary>
/// <remarks>
/// You cannot delete a certificate if a resource (pool or compute node) is
/// using it. Before you can delete a certificate, you must therefore make sure
/// that the certificate is not associated with any existing pools, the
/// certificate is not installed on any compute nodes (even if you remove a
/// certificate from a pool, it is not removed from existing compute nodes in
/// that pool until they restart), and no running tasks depend on the
/// certificate. If you try to delete a certificate that is in use, the
/// deletion fails. The certificate status changes to deleteFailed. You can use
/// Cancel Delete Certificate to set the status back to active if you decide
/// that you want to continue using the certificate.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='thumbprintAlgorithm'>
/// The algorithm used to derive the thumbprint parameter. This must be sha1.
/// </param>
/// <param name='thumbprint'>
/// The thumbprint of the certificate to be deleted.
/// </param>
/// <param name='certificateDeleteOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<CertificateDeleteHeaders> DeleteAsync(this ICertificateOperations operations, string thumbprintAlgorithm, string thumbprint, CertificateDeleteOptions certificateDeleteOptions = default(CertificateDeleteOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.DeleteWithHttpMessagesAsync(thumbprintAlgorithm, thumbprint, certificateDeleteOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Headers;
}
}
/// <summary>
/// Gets information about the specified certificate.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='thumbprintAlgorithm'>
/// The algorithm used to derive the thumbprint parameter. This must be sha1.
/// </param>
/// <param name='thumbprint'>
/// The thumbprint of the certificate to get.
/// </param>
/// <param name='certificateGetOptions'>
/// Additional parameters for the operation
/// </param>
public static Certificate Get(this ICertificateOperations operations, string thumbprintAlgorithm, string thumbprint, CertificateGetOptions certificateGetOptions = default(CertificateGetOptions))
{
return ((ICertificateOperations)operations).GetAsync(thumbprintAlgorithm, thumbprint, certificateGetOptions).GetAwaiter().GetResult();
}
/// <summary>
/// Gets information about the specified certificate.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='thumbprintAlgorithm'>
/// The algorithm used to derive the thumbprint parameter. This must be sha1.
/// </param>
/// <param name='thumbprint'>
/// The thumbprint of the certificate to get.
/// </param>
/// <param name='certificateGetOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<Certificate> GetAsync(this ICertificateOperations operations, string thumbprintAlgorithm, string thumbprint, CertificateGetOptions certificateGetOptions = default(CertificateGetOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(thumbprintAlgorithm, thumbprint, certificateGetOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists all of the certificates that have been added to the specified
/// account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='certificateListNextOptions'>
/// Additional parameters for the operation
/// </param>
public static Microsoft.Rest.Azure.IPage<Certificate> ListNext(this ICertificateOperations operations, string nextPageLink, CertificateListNextOptions certificateListNextOptions = default(CertificateListNextOptions))
{
return ((ICertificateOperations)operations).ListNextAsync(nextPageLink, certificateListNextOptions).GetAwaiter().GetResult();
}
/// <summary>
/// Lists all of the certificates that have been added to the specified
/// account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='certificateListNextOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<Microsoft.Rest.Azure.IPage<Certificate>> ListNextAsync(this ICertificateOperations operations, string nextPageLink, CertificateListNextOptions certificateListNextOptions = default(CertificateListNextOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, certificateListNextOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Xml;
#if (FULL_BUILD)
using System.Web;
using System.Xml.XPath;
using Weborb.Activation;
using Weborb.Cloud;
using Weborb.Handler;
using Weborb.Data;
using Weborb.Management.CodeGen;
using Weborb.Security;
using Weborb.V3Types.Core;
using Weborb.Util.Config;
#endif
#if CLOUD
using Weborb.Cloud;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.ServiceRuntime;
using Microsoft.WindowsAzure.StorageClient;
#endif
using Weborb.Util;
using Weborb.Types;
using Weborb.Protocols;
using Weborb.Registry;
using Weborb.Util.Logging;
using Weborb.Writer;
namespace Weborb.Config
{
public delegate void ConfigRetrieved( ORBConfig config );
public class ORBConfig
{
// public delegate void InitializedHandler();
// public static event InitializedHandler Initialized;
public event ConfigRetrieved GetConfigInstanceListener;
private static object configLockObject = new object();
private static volatile object _lock = new object();
#if (FULL_BUILD)
private IDictionary configObjects = new Hashtable();
#else
private IDictionary configObjects = new Dictionary<string, object>();
#endif
#if (FULL_BUILD)
private Activators activators = new Activators();
#endif
private ObjectFactories objectFactories = new ObjectFactories();
private Types.Types typeMapper = new Types.Types();
#if (FULL_BUILD)
private Handlers handlers = new Handlers();
private ProtocolRegistry protocolRegistry = new ProtocolRegistry();
#endif
private ServiceRegistry serviceRegistry = new ServiceRegistry();
//private bool _serializePrivateFields;
//private bool serializeGenericCollectionsAsVector;
private static ORBConfig instance;
//private static bool _initialized;
//private static bool _initializing;
#if (FULL_BUILD)
private ORBSecurity security = new ORBSecurity();
private DataServices dataServices = new DataServices();
private BusinessIntelligenceConfig businessIntelligenceConfig = new BusinessIntelligenceConfig();
private Dictionary<int, CodegenFormat> _codegenFormats = new Dictionary<int, CodegenFormat>();
private Dictionary<int, CodegenFormat> _codegenMessagingFormats = new Dictionary<int, CodegenFormat>();
private Dictionary<int, MessagingCodegenFormat> _codegenMessagingApplicationFormats = new Dictionary<int, MessagingCodegenFormat>();
private Dictionary<int, MessagingCodegenFeature> _codegenMessagingApplicationFeatures = new Dictionary<int, MessagingCodegenFeature>();
#endif
internal static ORBConfig GetInitializedConfig()
{
ORBConfig config = null;
AutoResetEvent autoResetEvent = new AutoResetEvent( false );
ThreadPool.QueueUserWorkItem( state =>
{
config = GetInstance();
autoResetEvent.Set();
});
WaitHandle.WaitAll(new WaitHandle[] {autoResetEvent});
return config;
}
public static ORBConfig GetInstance()
{
if( instance == null )
lock ( _lock )
{
if ( instance == null )
instance = new ORBConfig();
}
if ( instance.GetConfigInstanceListener != null )
instance.GetConfigInstanceListener( instance );
return instance;
}
public static void reset()
{
// to support hot deploy some clean up needs to be done
MessageWriter.CleanAdditionalWriters();
#if( FULL_BUILD)
instance.Initialize( null );
#endif
}
private ORBConfig()
{
instance = this;
#if( FULL_BUILD)
Initialize( null );
#endif
#if ( PURE_CLIENT_LIB || WINDOWS_PHONE8 )
getTypeMapper()._AddClientClassMapping( "flex.messaging.messages.AsyncMessage", typeof( Weborb.V3Types.AsyncMessage ));
getTypeMapper()._AddClientClassMapping( "flex.messaging.messages.CommandMessage", typeof( Weborb.V3Types.CommandMessage ));
getTypeMapper()._AddClientClassMapping( "flex.messaging.messages.RemotingMessage", typeof( Weborb.V3Types.ReqMessage ));
getTypeMapper()._AddClientClassMapping( "flex.messaging.messages.AcknowledgeMessage", typeof( Weborb.V3Types.AckMessage ));
getTypeMapper()._AddClientClassMapping( "flex.messaging.messages.ErrorMessage", typeof( Weborb.V3Types.ErrMessage ));
getTypeMapper()._AddClientClassMapping( "flex.messaging.io.ObjectProxy", typeof( Weborb.Util.ObjectProxy ));
getTypeMapper()._AddClientClassMapping( "weborb.v3types.V3Message", typeof( Weborb.V3Types.V3Message ) );
IArgumentObjectFactory factory = (IArgumentObjectFactory) getObjectFactories()._CreateServiceObject( "Weborb.V3Types.BodyHolderFactory" );
getObjectFactories().AddArgumentObjectFactory( "Weborb.V3Types.BodyHolder", factory );
getTypeMapper()._AddAbstractTypeMapping( typeof( System.Collections.Generic.IList<> ), typeof( System.Collections.Generic.List<> ) );
ITypeWriter writerObject = (ITypeWriter) getObjectFactories()._CreateServiceObject( "Weborb.V3Types.BodyHolderWriter" );
Type mappedType = typeof( Weborb.V3Types.BodyHolder );
MessageWriter.AddAdditionalTypeWriter( mappedType, writerObject );
#endif
#if( PURE_CLIENT_LIB )
getTypeMapper()._AddAbstractTypeMapping( typeof( System.Collections.ICollection ), typeof( System.Collections.ArrayList ) );
getTypeMapper()._AddAbstractTypeMapping( typeof( System.Collections.IList ), typeof( System.Collections.ArrayList ) );
getTypeMapper()._AddAbstractTypeMapping( typeof( System.Collections.IDictionary ), typeof( System.Collections.Hashtable ) );
#endif
#if( WINDOWS_PHONE8 )
getTypeMapper()._AddAbstractTypeMapping(typeof(System.Collections.ICollection), typeof(System.Collections.Generic.List<>));
getTypeMapper()._AddAbstractTypeMapping(typeof(System.Collections.IList), typeof(System.Collections.Generic.List<>));
getTypeMapper()._AddAbstractTypeMapping(typeof(System.Collections.IDictionary), typeof(System.Collections.Generic.Dictionary<,>));
#endif
}
public ObjectFactories getObjectFactories()
{
return objectFactories;
}
public Types.Types getTypeMapper()
{
return typeMapper;
}
public ServiceRegistry GetServiceRegistry()
{
return serviceRegistry;
}
public object GetConfig( string configName )
{
return configObjects[ configName ];
}
#if (FULL_BUILD)
public Activators getActivators()
{
return activators;
}
internal Hashtable GetConfigObjects()
{
if ( configObjects == null )
configObjects = new Hashtable();
return configObjects as Hashtable;
}
public Handlers getHandlers()
{
return handlers;
}
public ProtocolRegistry getProtocolRegistry()
{
return protocolRegistry;
}
public ORBSecurity getSecurity()
{
return security;
}
internal void setSecurity(ORBSecurity security)
{
this.security = security;
}
public Dictionary<int, CodegenFormat> CodegenFormats
{
get { return _codegenFormats; }
}
public Dictionary<int, CodegenFormat> CodegenMessagingFormats
{
get { return _codegenMessagingFormats; }
}
public Dictionary<int, MessagingCodegenFeature> CodegenMessagingApplicationFeatures
{
get { return _codegenMessagingApplicationFeatures; }
}
public Dictionary<int, MessagingCodegenFormat> CodegenMessagingApplicationFormats
{
get { return _codegenMessagingApplicationFormats; }
}
public DataServices GetDataServices()
{
return dataServices;
}
public string GetConfigFilePath()
{
return Path.Combine( Paths.GetWebORBPath(), "weborb.config" );
}
public string GetAlternateConfigFilePath()
{
return Path.Combine( (string) GetConfig( "weborb/alternateConfigPath" ), "weborb.config" );
}
public string GetFlexConfigPath()
{
return Path.Combine( Paths.GetWebORBPath(), "WEB-INF" + Path.DirectorySeparatorChar + "flex" );
}
private void ConfigHotDeployCheck()
{
bool enableHotDeploy = false;
XmlTextReader reader = null;
try
{
reader = new XmlTextReader( GetConfigFilePath() );
XPathDocument xpathDoc = new XPathDocument( reader );
XPathNavigator navigator = xpathDoc.CreateNavigator();
XPathNodeIterator nodeIterator = navigator.Select( "/configuration/weborb[@hotDeploy]" );
if( nodeIterator != null && nodeIterator.Count == 1 )
{
nodeIterator.MoveNext();
String value = nodeIterator.Current.GetAttribute( "hotDeploy", "" );
if( value.Equals( "yes" ) )
enableHotDeploy = true;
}
}
catch( Exception )
{
}
finally
{
if( reader != null )
reader.Close();
}
if( enableHotDeploy )
DeploymentMode.GetConfigurator().EnableConfigHotDeploy( this );
}
private volatile Object _initializeLock = new Object();
private void Initialize( ArrayList sectionToConfig )
{
lock (_initializeLock)
{
WebORBConfigurator configurator = DeploymentMode.GetConfigurator();
configObjects = configurator.Configure(this, sectionToConfig);
new FlexDynamicServiceConfig().Configure(GetFlexConfigPath(), this);
new FlexRemotingServiceConfig().Configure(GetFlexConfigPath(), this);
new FlexDataServiceConfig().Configure(GetFlexConfigPath(), this);
new FlexMessagingServiceConfig().Configure(GetFlexConfigPath(), this);
new FlexServicesConfig().Configure(GetFlexConfigPath(), this);
new FlexWeborbServicesConfig().Configure(GetFlexConfigPath(), this);
getHandlers().LockLicense();
ConfigHotDeployCheck();
if (Initialized != null)
Initialized();
}
}
public BusinessIntelligenceConfig getBusinessIntelligenceConfig()
{
return GetInstance().businessIntelligenceConfig;
}
#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.
namespace System.Xml.Xsl.XsltOld
{
using System;
using System.Diagnostics;
using System.Xml;
using System.Xml.XPath;
using System.Collections;
internal class Stylesheet
{
private ArrayList _imports = new ArrayList();
private Hashtable _modeManagers;
private Hashtable _templateNameTable = new Hashtable();
private Hashtable _attributeSetTable;
private int _templateCount;
//private ArrayList preserveSpace;
private Hashtable _queryKeyTable;
private ArrayList _whitespaceList;
private bool _whitespace;
private Hashtable _scriptObjectTypes = new Hashtable();
private TemplateManager _templates;
private class WhitespaceElement
{
private int _key;
private double _priority;
private bool _preserveSpace;
internal double Priority
{
get { return _priority; }
}
internal int Key
{
get { return _key; }
}
internal bool PreserveSpace
{
get { return _preserveSpace; }
}
internal WhitespaceElement(int Key, double priority, bool PreserveSpace)
{
_key = Key;
_priority = priority;
_preserveSpace = PreserveSpace;
}
internal void ReplaceValue(bool PreserveSpace)
{
_preserveSpace = PreserveSpace;
}
}
internal bool Whitespace { get { return _whitespace; } }
internal ArrayList Imports { get { return _imports; } }
internal Hashtable AttributeSetTable { get { return _attributeSetTable; } }
internal void AddSpace(Compiler compiler, String query, double Priority, bool PreserveSpace)
{
WhitespaceElement elem;
if (_queryKeyTable != null)
{
if (_queryKeyTable.Contains(query))
{
elem = (WhitespaceElement)_queryKeyTable[query];
elem.ReplaceValue(PreserveSpace);
return;
}
}
else
{
_queryKeyTable = new Hashtable();
_whitespaceList = new ArrayList();
}
int key = compiler.AddQuery(query);
elem = new WhitespaceElement(key, Priority, PreserveSpace);
_queryKeyTable[query] = elem;
_whitespaceList.Add(elem);
}
internal void SortWhiteSpace()
{
if (_queryKeyTable != null)
{
for (int i = 0; i < _whitespaceList.Count; i++)
{
for (int j = _whitespaceList.Count - 1; j > i; j--)
{
WhitespaceElement elem1, elem2;
elem1 = (WhitespaceElement)_whitespaceList[j - 1];
elem2 = (WhitespaceElement)_whitespaceList[j];
if (elem2.Priority < elem1.Priority)
{
_whitespaceList[j - 1] = elem2;
_whitespaceList[j] = elem1;
}
}
}
_whitespace = true;
}
if (_imports != null)
{
for (int importIndex = _imports.Count - 1; importIndex >= 0; importIndex--)
{
Stylesheet stylesheet = (Stylesheet)_imports[importIndex];
if (stylesheet.Whitespace)
{
stylesheet.SortWhiteSpace();
_whitespace = true;
}
}
}
}
internal bool PreserveWhiteSpace(Processor proc, XPathNavigator node)
{
// last one should win. I.E. We starting from the end. I.E. Lowest priority should go first
if (_whitespaceList != null)
{
for (int i = _whitespaceList.Count - 1; 0 <= i; i--)
{
WhitespaceElement elem = (WhitespaceElement)_whitespaceList[i];
if (proc.Matches(node, elem.Key))
{
return elem.PreserveSpace;
}
}
}
if (_imports != null)
{
for (int importIndex = _imports.Count - 1; importIndex >= 0; importIndex--)
{
Stylesheet stylesheet = (Stylesheet)_imports[importIndex];
if (!stylesheet.PreserveWhiteSpace(proc, node))
return false;
}
}
return true;
}
internal void AddAttributeSet(AttributeSetAction attributeSet)
{
Debug.Assert(attributeSet.Name != null);
if (_attributeSetTable == null)
{
_attributeSetTable = new Hashtable();
}
Debug.Assert(_attributeSetTable != null);
if (_attributeSetTable.ContainsKey(attributeSet.Name) == false)
{
_attributeSetTable[attributeSet.Name] = attributeSet;
}
else
{
// merge the attribute-sets
((AttributeSetAction)_attributeSetTable[attributeSet.Name]).Merge(attributeSet);
}
}
internal void AddTemplate(TemplateAction template)
{
XmlQualifiedName mode = template.Mode;
//
// Ensure template has a unique name
//
Debug.Assert(_templateNameTable != null);
if (template.Name != null)
{
if (_templateNameTable.ContainsKey(template.Name) == false)
{
_templateNameTable[template.Name] = template;
}
else
{
throw XsltException.Create(SR.Xslt_DupTemplateName, template.Name.ToString());
}
}
if (template.MatchKey != Compiler.InvalidQueryKey)
{
if (_modeManagers == null)
{
_modeManagers = new Hashtable();
}
Debug.Assert(_modeManagers != null);
if (mode == null)
{
mode = XmlQualifiedName.Empty;
}
TemplateManager manager = (TemplateManager)_modeManagers[mode];
if (manager == null)
{
manager = new TemplateManager(this, mode);
_modeManagers[mode] = manager;
if (mode.IsEmpty)
{
Debug.Assert(_templates == null);
_templates = manager;
}
}
Debug.Assert(manager != null);
template.TemplateId = ++_templateCount;
manager.AddTemplate(template);
}
}
internal void ProcessTemplates()
{
if (_modeManagers != null)
{
IDictionaryEnumerator enumerator = _modeManagers.GetEnumerator();
while (enumerator.MoveNext())
{
Debug.Assert(enumerator.Value is TemplateManager);
TemplateManager manager = (TemplateManager)enumerator.Value;
manager.ProcessTemplates();
}
}
if (_imports != null)
{
for (int importIndex = _imports.Count - 1; importIndex >= 0; importIndex--)
{
Debug.Assert(_imports[importIndex] is Stylesheet);
Stylesheet stylesheet = (Stylesheet)_imports[importIndex];
Debug.Assert(stylesheet != null);
//
// Process templates in imported stylesheet
//
stylesheet.ProcessTemplates();
}
}
}
internal void ReplaceNamespaceAlias(Compiler compiler)
{
if (_modeManagers != null)
{
IDictionaryEnumerator enumerator = _modeManagers.GetEnumerator();
while (enumerator.MoveNext())
{
TemplateManager manager = (TemplateManager)enumerator.Value;
if (manager.templates != null)
{
for (int i = 0; i < manager.templates.Count; i++)
{
TemplateAction template = (TemplateAction)manager.templates[i];
template.ReplaceNamespaceAlias(compiler);
}
}
}
}
if (_templateNameTable != null)
{
IDictionaryEnumerator enumerator = _templateNameTable.GetEnumerator();
while (enumerator.MoveNext())
{
TemplateAction template = (TemplateAction)enumerator.Value;
template.ReplaceNamespaceAlias(compiler);
}
}
if (_imports != null)
{
for (int importIndex = _imports.Count - 1; importIndex >= 0; importIndex--)
{
Stylesheet stylesheet = (Stylesheet)_imports[importIndex];
stylesheet.ReplaceNamespaceAlias(compiler);
}
}
}
internal TemplateAction FindTemplate(Processor processor, XPathNavigator navigator, XmlQualifiedName mode)
{
Debug.Assert(processor != null && navigator != null);
Debug.Assert(mode != null);
TemplateAction action = null;
//
// Try to find template within this stylesheet first
//
if (_modeManagers != null)
{
TemplateManager manager = (TemplateManager)_modeManagers[mode];
if (manager != null)
{
Debug.Assert(manager.Mode.Equals(mode));
action = manager.FindTemplate(processor, navigator);
}
}
//
// If unsuccessful, search in imported documents from backwards
//
if (action == null)
{
action = FindTemplateImports(processor, navigator, mode);
}
return action;
}
internal TemplateAction FindTemplateImports(Processor processor, XPathNavigator navigator, XmlQualifiedName mode)
{
TemplateAction action = null;
//
// Do we have imported stylesheets?
//
if (_imports != null)
{
for (int importIndex = _imports.Count - 1; importIndex >= 0; importIndex--)
{
Debug.Assert(_imports[importIndex] is Stylesheet);
Stylesheet stylesheet = (Stylesheet)_imports[importIndex];
Debug.Assert(stylesheet != null);
//
// Search in imported stylesheet
//
action = stylesheet.FindTemplate(processor, navigator, mode);
if (action != null)
{
return action;
}
}
}
return action;
}
internal TemplateAction FindTemplate(Processor processor, XPathNavigator navigator)
{
Debug.Assert(processor != null && navigator != null);
Debug.Assert(_templates == null && _modeManagers == null || _templates == _modeManagers[XmlQualifiedName.Empty]);
TemplateAction action = null;
//
// Try to find template within this stylesheet first
//
if (_templates != null)
{
action = _templates.FindTemplate(processor, navigator);
}
//
// If unsuccessful, search in imported documents from backwards
//
if (action == null)
{
action = FindTemplateImports(processor, navigator);
}
return action;
}
internal TemplateAction FindTemplate(XmlQualifiedName name)
{
//Debug.Assert(this.templateNameTable == null);
TemplateAction action = null;
//
// Try to find template within this stylesheet first
//
if (_templateNameTable != null)
{
action = (TemplateAction)_templateNameTable[name];
}
//
// If unsuccessful, search in imported documents from backwards
//
if (action == null && _imports != null)
{
for (int importIndex = _imports.Count - 1; importIndex >= 0; importIndex--)
{
Debug.Assert(_imports[importIndex] is Stylesheet);
Stylesheet stylesheet = (Stylesheet)_imports[importIndex];
Debug.Assert(stylesheet != null);
//
// Search in imported stylesheet
//
action = stylesheet.FindTemplate(name);
if (action != null)
{
return action;
}
}
}
return action;
}
internal TemplateAction FindTemplateImports(Processor processor, XPathNavigator navigator)
{
TemplateAction action = null;
//
// Do we have imported stylesheets?
//
if (_imports != null)
{
for (int importIndex = _imports.Count - 1; importIndex >= 0; importIndex--)
{
Debug.Assert(_imports[importIndex] is Stylesheet);
Stylesheet stylesheet = (Stylesheet)_imports[importIndex];
Debug.Assert(stylesheet != null);
//
// Search in imported stylesheet
//
action = stylesheet.FindTemplate(processor, navigator);
if (action != null)
{
return action;
}
}
}
return action;
}
internal Hashtable ScriptObjectTypes
{
get { return _scriptObjectTypes; }
}
}
}
| |
// ReSharper disable All
using System.Collections.Generic;
using System.Diagnostics;
using System.Dynamic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Frapid.ApplicationState.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Frapid.Core.DataAccess;
using Frapid.Core.Api.Fakes;
using Frapid.DataAccess;
using Frapid.DataAccess.Models;
using Xunit;
namespace Frapid.Core.Api.Tests
{
public class OfficeTests
{
public static OfficeController Fixture()
{
OfficeController controller = new OfficeController(new OfficeRepository());
return controller;
}
[Fact]
[Conditional("Debug")]
public void CountEntityColumns()
{
EntityView entityView = Fixture().GetEntityView();
Assert.Null(entityView.Columns);
}
[Fact]
[Conditional("Debug")]
public void Count()
{
long count = Fixture().Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void GetAll()
{
int count = Fixture().GetAll().Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void Export()
{
int count = Fixture().Export().Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void Get()
{
Frapid.Core.Entities.Office office = Fixture().Get(0);
Assert.NotNull(office);
}
[Fact]
[Conditional("Debug")]
public void First()
{
Frapid.Core.Entities.Office office = Fixture().GetFirst();
Assert.NotNull(office);
}
[Fact]
[Conditional("Debug")]
public void Previous()
{
Frapid.Core.Entities.Office office = Fixture().GetPrevious(0);
Assert.NotNull(office);
}
[Fact]
[Conditional("Debug")]
public void Next()
{
Frapid.Core.Entities.Office office = Fixture().GetNext(0);
Assert.NotNull(office);
}
[Fact]
[Conditional("Debug")]
public void Last()
{
Frapid.Core.Entities.Office office = Fixture().GetLast();
Assert.NotNull(office);
}
[Fact]
[Conditional("Debug")]
public void GetMultiple()
{
IEnumerable<Frapid.Core.Entities.Office> offices = Fixture().Get(new int[] { });
Assert.NotNull(offices);
}
[Fact]
[Conditional("Debug")]
public void GetPaginatedResult()
{
int count = Fixture().GetPaginatedResult().Count();
Assert.Equal(1, count);
count = Fixture().GetPaginatedResult(1).Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void CountWhere()
{
long count = Fixture().CountWhere(new JArray());
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void GetWhere()
{
int count = Fixture().GetWhere(1, new JArray()).Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void CountFiltered()
{
long count = Fixture().CountFiltered("");
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void GetFiltered()
{
int count = Fixture().GetFiltered(1, "").Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void GetDisplayFields()
{
int count = Fixture().GetDisplayFields().Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void GetCustomFields()
{
int count = Fixture().GetCustomFields().Count();
Assert.Equal(1, count);
count = Fixture().GetCustomFields("").Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void AddOrEdit()
{
try
{
var form = new JArray { null, null };
Fixture().AddOrEdit(form);
}
catch (HttpResponseException ex)
{
Assert.Equal(HttpStatusCode.MethodNotAllowed, ex.Response.StatusCode);
}
}
[Fact]
[Conditional("Debug")]
public void Add()
{
try
{
Fixture().Add(null);
}
catch (HttpResponseException ex)
{
Assert.Equal(HttpStatusCode.MethodNotAllowed, ex.Response.StatusCode);
}
}
[Fact]
[Conditional("Debug")]
public void Edit()
{
try
{
Fixture().Edit(0, null);
}
catch (HttpResponseException ex)
{
Assert.Equal(HttpStatusCode.MethodNotAllowed, ex.Response.StatusCode);
}
}
[Fact]
[Conditional("Debug")]
public void BulkImport()
{
var collection = new JArray { null, null, null, null };
var actual = Fixture().BulkImport(collection);
Assert.NotNull(actual);
}
[Fact]
[Conditional("Debug")]
public void Delete()
{
try
{
Fixture().Delete(0);
}
catch (HttpResponseException ex)
{
Assert.Equal(HttpStatusCode.InternalServerError, ex.Response.StatusCode);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Orleans.Configuration;
using Orleans.Internal;
namespace Orleans.Runtime.Scheduler
{
[DebuggerDisplay("WorkItemGroup Name={Name} State={state}")]
internal class WorkItemGroup : IWorkItem, IDisposable, IWorkItemScheduler
{
private enum WorkGroupStatus
{
Waiting = 0,
Runnable = 1,
Running = 2
}
private readonly ILogger log;
private WorkGroupStatus state;
private readonly object lockable;
private readonly Queue<Task> workItems;
private long totalItemsEnqueued;
private long totalItemsProcessed;
private long lastLongQueueWarningTimestamp;
private Task currentTask;
private long currentTaskStarted;
private readonly QueueTrackingStatistic queueTracking;
private readonly int workItemGroupStatisticsNumber;
private readonly SchedulingOptions schedulingOptions;
private readonly SchedulerStatisticsGroup schedulerStatistics;
internal ActivationTaskScheduler TaskScheduler { get; }
public IGrainContext GrainContext { get; set; }
internal bool IsSystemGroup => this.GrainContext is ISystemTargetBase;
public string Name => GrainContext?.ToString() ?? "Unknown";
internal int ExternalWorkItemCount
{
get { lock (lockable) { return WorkItemCount; } }
}
private Task CurrentTask
{
get => currentTask;
set
{
currentTask = value;
currentTaskStarted = Environment.TickCount64;
}
}
private int WorkItemCount => workItems.Count;
public WorkItemGroup(
IGrainContext grainContext,
ILogger<WorkItemGroup> logger,
ILogger<ActivationTaskScheduler> activationTaskSchedulerLogger,
SchedulerStatisticsGroup schedulerStatistics,
IOptions<StatisticsOptions> statisticsOptions,
IOptions<SchedulingOptions> schedulingOptions)
{
GrainContext = grainContext;
this.schedulingOptions = schedulingOptions.Value;
this.schedulerStatistics = schedulerStatistics;
state = WorkGroupStatus.Waiting;
workItems = new Queue<Task>();
lockable = new object();
totalItemsEnqueued = 0;
totalItemsProcessed = 0;
TaskScheduler = new ActivationTaskScheduler(this, activationTaskSchedulerLogger);
log = logger;
if (schedulerStatistics.CollectShedulerQueuesStats)
{
queueTracking = new QueueTrackingStatistic("Scheduler." + this.Name, statisticsOptions);
queueTracking.OnStartExecution();
}
if (schedulerStatistics.CollectPerWorkItemStats)
{
workItemGroupStatisticsNumber = schedulerStatistics.RegisterWorkItemGroup(this.Name, this.GrainContext,
() =>
{
var sb = new StringBuilder();
lock (lockable)
{
sb.Append("QueueLength = " + WorkItemCount);
sb.Append($", State = {state}");
if (state == WorkGroupStatus.Runnable)
sb.Append($"; oldest item is {(workItems.Count >= 0 ? workItems.Peek().ToString() : "null")} old");
}
return sb.ToString();
});
}
}
/// <summary>
/// Adds a task to this activation.
/// If we're adding it to the run list and we used to be waiting, now we're runnable.
/// </summary>
/// <param name="task">The work item to add.</param>
public void EnqueueTask(Task task)
{
#if DEBUG
if (log.IsEnabled(LogLevel.Trace))
{
this.log.LogTrace(
"EnqueueWorkItem {Task} into {GrainContext} when TaskScheduler.Current={TaskScheduler}",
task,
this.GrainContext,
System.Threading.Tasks.TaskScheduler.Current);
}
#endif
lock (lockable)
{
long thisSequenceNumber = totalItemsEnqueued++;
int count = WorkItemCount;
workItems.Enqueue(task);
int maxPendingItemsLimit = schedulingOptions.MaxPendingWorkItemsSoftLimit;
if (maxPendingItemsLimit > 0 && count > maxPendingItemsLimit)
{
var now = ValueStopwatch.GetTimestamp();
if (ValueStopwatch.FromTimestamp(this.lastLongQueueWarningTimestamp, now).Elapsed > TimeSpan.FromSeconds(10))
{
log.LogWarning(
(int)ErrorCode.SchedulerTooManyPendingItems,
"{PendingWorkItemCount} pending work items for group {WorkGroupName}, exceeding the warning threshold of {WarningThreshold}",
count,
this.Name,
maxPendingItemsLimit);
}
lastLongQueueWarningTimestamp = now;
}
if (state != WorkGroupStatus.Waiting) return;
state = WorkGroupStatus.Runnable;
#if DEBUG
if (log.IsEnabled(LogLevel.Trace))
{
log.LogTrace(
"Add to RunQueue {Task}, #{SequenceNumber}, onto {GrainContext}",
task,
thisSequenceNumber,
GrainContext);
}
#endif
ScheduleExecution(this);
}
}
/// <summary>
/// For debugger purposes only.
/// </summary>
internal IEnumerable<Task> GetScheduledTasks()
{
foreach (var task in this.workItems)
{
yield return task;
}
}
private static object DumpAsyncState(object o)
{
if (o is Delegate action)
return action.Target is null ? action.Method.DeclaringType + "." + action.Method.Name
: action.Method.DeclaringType.Name + "." + action.Method.Name + ": " + DumpAsyncState(action.Target);
if (o?.GetType() is { Name: "ContinuationWrapper" } wrapper
&& (wrapper.GetField("_continuation", BindingFlags.Instance | BindingFlags.NonPublic)
?? wrapper.GetField("m_continuation", BindingFlags.Instance | BindingFlags.NonPublic)
)?.GetValue(o) is Action continuation)
return DumpAsyncState(continuation);
return o;
}
// Execute one or more turns for this activation.
// This method is always called in a single-threaded environment -- that is, no more than one
// thread will be in this method at once -- but other asynch threads may still be queueing tasks, etc.
public void Execute()
{
try
{
RuntimeContext.SetExecutionContext(this.GrainContext);
// Process multiple items -- drain the applicationMessageQueue (up to max items) for this physical activation
int count = 0;
var stopwatch = ValueStopwatch.StartNew();
do
{
lock (lockable)
{
state = WorkGroupStatus.Running;
}
// Get the first Work Item on the list
Task task;
lock (lockable)
{
if (workItems.Count > 0)
CurrentTask = task = workItems.Dequeue();
else // If the list is empty, then we're done
break;
}
#if DEBUG
if (log.IsEnabled(LogLevel.Trace))
{
log.LogTrace(
"About to execute task {Task} in GrainContext={GrainContext}",
OrleansTaskExtentions.ToString(task),
this.GrainContext);
}
#endif
var taskStart = stopwatch.Elapsed;
try
{
TaskScheduler.RunTask(task);
}
catch (Exception ex)
{
this.log.LogError(
(int)ErrorCode.SchedulerExceptionFromExecute,
ex,
"Worker thread caught an exception thrown from Execute by task {Task}. Exception: {Exception}",
OrleansTaskExtentions.ToString(task),
ex);
throw;
}
finally
{
totalItemsProcessed++;
var taskLength = stopwatch.Elapsed - taskStart;
if (taskLength > schedulingOptions.TurnWarningLengthThreshold)
{
this.schedulerStatistics.NumLongRunningTurns.Increment();
this.log.LogWarning(
(int)ErrorCode.SchedulerTurnTooLong3,
"Task {Task} in WorkGroup {GrainContext} took elapsed time {Duration} for execution, which is longer than {TurnWarningLengthThreshold}. Running on thread {Thread}",
OrleansTaskExtentions.ToString(task),
this.GrainContext.ToString(),
taskLength.ToString("g"),
schedulingOptions.TurnWarningLengthThreshold,
Thread.CurrentThread.ManagedThreadId.ToString());
}
CurrentTask = null;
}
count++;
}
while (schedulingOptions.ActivationSchedulingQuantum <= TimeSpan.Zero || stopwatch.Elapsed < schedulingOptions.ActivationSchedulingQuantum);
}
catch (Exception ex)
{
this.log.LogError(
(int)ErrorCode.Runtime_Error_100032,
ex,
"Worker thread {Thread} caught an exception thrown from IWorkItem.Execute: {Exception}",
Thread.CurrentThread.ManagedThreadId,
ex);
}
finally
{
// Now we're not Running anymore.
// If we left work items on our run list, we're Runnable, and need to go back on the silo run queue;
// If our run list is empty, then we're waiting.
lock (lockable)
{
if (WorkItemCount > 0)
{
state = WorkGroupStatus.Runnable;
ScheduleExecution(this);
}
else
{
state = WorkGroupStatus.Waiting;
}
}
RuntimeContext.ResetExecutionContext();
}
}
public override string ToString() => $"{(IsSystemGroup ? "System*" : "")}WorkItemGroup:Name={Name},WorkGroupStatus={state}";
public string DumpStatus()
{
lock (lockable)
{
var sb = new StringBuilder();
sb.Append(this);
sb.AppendFormat(". Currently QueuedWorkItems={0}; Total Enqueued={1}; Total processed={2}; ",
WorkItemCount, totalItemsEnqueued, totalItemsProcessed);
if (CurrentTask is Task task)
{
sb.AppendFormat(" Executing Task Id={0} Status={1} for {2}.",
task.Id, task.Status, TimeSpan.FromMilliseconds(Environment.TickCount64 - currentTaskStarted));
}
sb.AppendFormat("TaskRunner={0}; ", TaskScheduler);
if (GrainContext != null)
{
var detailedStatus = this.GrainContext switch
{
ActivationData activationData => activationData.ToDetailedString(includeExtraDetails: true),
SystemTarget systemTarget => systemTarget.ToDetailedString(),
object obj => obj.ToString(),
_ => "None"
};
sb.AppendFormat("Detailed context=<{0}>", detailedStatus);
}
return sb.ToString();
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void ScheduleExecution(WorkItemGroup workItem)
{
ThreadPool.UnsafeQueueUserWorkItem(workItem, preferLocal: true);
}
public void Dispose()
{
this.schedulerStatistics.UnregisterWorkItemGroup(workItemGroupStatisticsNumber);
}
public void QueueAction(Action action) => TaskScheduler.QueueAction(action);
public void QueueTask(Task task) => task.Start(TaskScheduler);
public void QueueWorkItem(IThreadPoolWorkItem workItem) => TaskScheduler.QueueThreadPoolWorkItem(workItem);
}
}
| |
#region License
/*
* WebSocketServer.cs
*
* A C# implementation of the WebSocket protocol server.
*
* The MIT License
*
* Copyright (c) 2012-2015 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 Contributors
/*
* Contributors:
* - Juan Manuel Lallana <juan.manuel.lallana@gmail.com>
* - Jonas Hovgaard <j@jhovgaard.dk>
* - Liryna <liryna.stark@gmail.com>
* - Rohan Singh <rohan-singh@hotmail.com>
*/
#endregion
using System;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Security.Cryptography.X509Certificates;
using System.Security.Principal;
using System.Text;
using System.Threading;
using CustomWebSocketSharp.Net;
using CustomWebSocketSharp.Net.WebSockets;
namespace CustomWebSocketSharp.Server
{
/// <summary>
/// Provides a WebSocket protocol server.
/// </summary>
/// <remarks>
/// This class can provide multiple WebSocket services.
/// </remarks>
public class WebSocketServer
{
#region Private Fields
private System.Net.IPAddress _address;
private bool _allowForwardedRequest;
private AuthenticationSchemes _authSchemes;
private static readonly string _defaultRealm;
private bool _dnsStyle;
private string _hostname;
private TcpListener _listener;
private Logger _log;
private int _port;
private string _realm;
private string _realmInUse;
private Thread _receiveThread;
private bool _reuseAddress;
private bool _secure;
private WebSocketServiceManager _services;
private ServerSslConfiguration _sslConfig;
private ServerSslConfiguration _sslConfigInUse;
private volatile ServerState _state;
private object _sync;
private Func<IIdentity, NetworkCredential> _userCredFinder;
#endregion
#region Static Constructor
static WebSocketServer ()
{
_defaultRealm = "SECRET AREA";
}
#endregion
#region Public Constructors
/// <summary>
/// Initializes a new instance of the <see cref="WebSocketServer"/> class.
/// </summary>
/// <remarks>
/// The new instance listens for the incoming handshake requests on port 80.
/// </remarks>
public WebSocketServer ()
{
var addr = System.Net.IPAddress.Any;
init (addr.ToString (), addr, 80, false);
}
/// <summary>
/// Initializes a new instance of the <see cref="WebSocketServer"/> class
/// with the specified <paramref name="port"/>.
/// </summary>
/// <remarks>
/// <para>
/// The new instance listens for the incoming handshake requests on
/// <paramref name="port"/>.
/// </para>
/// <para>
/// It provides secure connections if <paramref name="port"/> is 443.
/// </para>
/// </remarks>
/// <param name="port">
/// An <see cref="int"/> that represents the port number on which to listen.
/// </param>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="port"/> is less than 1 or greater than 65535.
/// </exception>
public WebSocketServer (int port)
: this (port, port == 443)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="WebSocketServer"/> class
/// with the specified WebSocket URL.
/// </summary>
/// <remarks>
/// <para>
/// The new instance listens for the incoming handshake requests on
/// the host name and port of <paramref name="url"/>.
/// </para>
/// <para>
/// It provides secure connections if the scheme of <paramref name="url"/>
/// is wss.
/// </para>
/// <para>
/// If <paramref name="url"/> includes no port, either port 80 or 443 is
/// used on which to listen. It is determined by the scheme (ws or wss)
/// of <paramref name="url"/>.
/// </para>
/// </remarks>
/// <param name="url">
/// A <see cref="string"/> that represents the WebSocket URL for the server.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="url"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="url"/> is empty.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="url"/> is invalid.
/// </para>
/// </exception>
public WebSocketServer (string url)
{
if (url == null)
throw new ArgumentNullException ("url");
if (url.Length == 0)
throw new ArgumentException ("An empty string.", "url");
Uri uri;
string msg;
if (!tryCreateUri (url, out uri, out msg))
throw new ArgumentException (msg, "url");
var host = uri.DnsSafeHost;
var addr = host.ToIPAddress ();
if (addr == null) {
msg = "The host part could not be converted to an IP address.";
throw new ArgumentException (msg, "url");
}
if (!addr.IsLocal ()) {
msg = "The IP address is not a local IP address.";
throw new ArgumentException (msg, "url");
}
init (host, addr, uri.Port, uri.Scheme == "wss");
}
/// <summary>
/// Initializes a new instance of the <see cref="WebSocketServer"/> class with
/// the specified <paramref name="port"/> and <paramref name="secure"/>.
/// </summary>
/// <remarks>
/// The new instance listens for the incoming handshake requests on
/// <paramref name="port"/>.
/// </remarks>
/// <param name="port">
/// An <see cref="int"/> that represents the port number on which to listen.
/// </param>
/// <param name="secure">
/// A <see cref="bool"/> that specifies providing secure connections or not.
/// <c>true</c> specifies providing secure connections.
/// </param>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="port"/> is less than 1 or greater than 65535.
/// </exception>
public WebSocketServer (int port, bool secure)
{
if (!port.IsPortNumber ()) {
var msg = "It is less than 1 or greater than 65535.";
throw new ArgumentOutOfRangeException ("port", msg);
}
var addr = System.Net.IPAddress.Any;
init (addr.ToString (), addr, port, secure);
}
/// <summary>
/// Initializes a new instance of the <see cref="WebSocketServer"/> class with
/// the specified <paramref name="address"/> and <paramref name="port"/>.
/// </summary>
/// <remarks>
/// <para>
/// The new instance listens for the incoming handshake requests on
/// <paramref name="address"/> and <paramref name="port"/>.
/// </para>
/// <para>
/// It provides secure connections if <paramref name="port"/> is 443.
/// </para>
/// </remarks>
/// <param name="address">
/// A <see cref="System.Net.IPAddress"/> that represents the local IP address
/// for the server.
/// </param>
/// <param name="port">
/// An <see cref="int"/> that represents the port number on which to listen.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="address"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="address"/> is not a local IP address.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="port"/> is less than 1 or greater than 65535.
/// </exception>
public WebSocketServer (System.Net.IPAddress address, int port)
: this (address, port, port == 443)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="WebSocketServer"/> class
/// with the specified <paramref name="address"/>, <paramref name="port"/>,
/// and <paramref name="secure"/>.
/// </summary>
/// <remarks>
/// The new instance listens for the incoming handshake requests on
/// <paramref name="address"/> and <paramref name="port"/>.
/// </remarks>
/// <param name="address">
/// A <see cref="System.Net.IPAddress"/> that represents the local IP address
/// for the server.
/// </param>
/// <param name="port">
/// An <see cref="int"/> that represents the port number on which to listen.
/// </param>
/// <param name="secure">
/// A <see cref="bool"/> that specifies providing secure connections or not.
/// <c>true</c> specifies providing secure connections.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="address"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="address"/> is not a local IP address.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="port"/> is less than 1 or greater than 65535.
/// </exception>
public WebSocketServer (System.Net.IPAddress address, int port, bool secure)
{
if (address == null)
throw new ArgumentNullException ("address");
if (!address.IsLocal ())
throw new ArgumentException ("Not a local IP address.", "address");
if (!port.IsPortNumber ()) {
var msg = "It is less than 1 or greater than 65535.";
throw new ArgumentOutOfRangeException ("port", msg);
}
init (address.ToString (), address, port, secure);
}
#endregion
#region Public Properties
/// <summary>
/// Gets the IP address of the server.
/// </summary>
/// <value>
/// A <see cref="System.Net.IPAddress"/> that represents
/// the IP address of the server.
/// </value>
public System.Net.IPAddress Address {
get {
return _address;
}
}
/// <summary>
/// Gets or sets a value indicating whether the server accepts
/// a handshake request without checking the request URI.
/// </summary>
/// <remarks>
/// The set operation does nothing if the server has already started or
/// it is shutting down.
/// </remarks>
/// <value>
/// <c>true</c> if the server accepts a handshake request without
/// checking the request URI; otherwise, <c>false</c>. The default
/// value is <c>false</c>.
/// </value>
public bool AllowForwardedRequest {
get {
return _allowForwardedRequest;
}
set {
string msg;
if (!canSet (out msg)) {
_log.Warn (msg);
return;
}
lock (_sync) {
if (!canSet (out msg)) {
_log.Warn (msg);
return;
}
_allowForwardedRequest = value;
}
}
}
/// <summary>
/// Gets or sets the scheme used to authenticate the clients.
/// </summary>
/// <remarks>
/// The set operation does nothing if the server has already started or
/// it is shutting down.
/// </remarks>
/// <value>
/// One of the <see cref="CustomWebSocketSharp.Net.AuthenticationSchemes"/> enum
/// values. It specifies the scheme used to authenticate the clients.
/// The default value is
/// <see cref="CustomWebSocketSharp.Net.AuthenticationSchemes.Anonymous"/>.
/// </value>
public AuthenticationSchemes AuthenticationSchemes {
get {
return _authSchemes;
}
set {
string msg;
if (!canSet (out msg)) {
_log.Warn (msg);
return;
}
lock (_sync) {
if (!canSet (out msg)) {
_log.Warn (msg);
return;
}
_authSchemes = value;
}
}
}
/// <summary>
/// Gets a value indicating whether the server has started.
/// </summary>
/// <value>
/// <c>true</c> if the server has started; otherwise, <c>false</c>.
/// </value>
public bool IsListening {
get {
return _state == ServerState.Start;
}
}
/// <summary>
/// Gets a value indicating whether the server provides secure connections.
/// </summary>
/// <value>
/// <c>true</c> if the server provides secure connections;
/// otherwise, <c>false</c>.
/// </value>
public bool IsSecure {
get {
return _secure;
}
}
/// <summary>
/// Gets or sets a value indicating whether the server cleans up
/// the inactive sessions periodically.
/// </summary>
/// <remarks>
/// The set operation does nothing if the server has already started or
/// it is shutting down.
/// </remarks>
/// <value>
/// <c>true</c> if the server cleans up the inactive sessions every 60
/// seconds; otherwise, <c>false</c>. The default value is <c>true</c>.
/// </value>
public bool KeepClean {
get {
return _services.KeepClean;
}
set {
string msg;
if (!canSet (out msg)) {
_log.Warn (msg);
return;
}
lock (_sync) {
if (!canSet (out msg)) {
_log.Warn (msg);
return;
}
_services.KeepClean = value;
}
}
}
/// <summary>
/// Gets the logging function for the server.
/// </summary>
/// <remarks>
/// <para>
/// The default logging level is <see cref="LogLevel.Error"/>.
/// </para>
/// <para>
/// If you would like to change the logging level,
/// you should set the <c>Log.Level</c> property to
/// any of the <see cref="LogLevel"/> enum values.
/// </para>
/// </remarks>
/// <value>
/// A <see cref="Logger"/> that provides the logging function.
/// </value>
public Logger Log {
get {
return _log;
}
}
/// <summary>
/// Gets the port number of the server.
/// </summary>
/// <value>
/// An <see cref="int"/> that represents the port number on which to
/// listen for the incoming handshake requests.
/// </value>
public int Port {
get {
return _port;
}
}
/// <summary>
/// Gets or sets the name of the realm for the server.
/// </summary>
/// <remarks>
/// <para>
/// The set operation does nothing if the server has
/// already started or it is shutting down.
/// </para>
/// <para>
/// If this property is <see langword="null"/> or empty,
/// SECRET AREA will be used as the name.
/// </para>
/// </remarks>
/// <value>
/// A <see cref="string"/> that represents the name of
/// the realm or <see langword="null"/> by default.
/// </value>
public string Realm {
get {
return _realm;
}
set {
string msg;
if (!canSet (out msg)) {
_log.Warn (msg);
return;
}
lock (_sync) {
if (!canSet (out msg)) {
_log.Warn (msg);
return;
}
_realm = value;
}
}
}
/// <summary>
/// Gets or sets a value indicating whether the server is allowed to
/// be bound to an address that is already in use.
/// </summary>
/// <remarks>
/// <para>
/// The set operation does nothing if the server has already started or
/// it is shutting down.
/// </para>
/// <para>
/// If you would like to resolve to wait for socket in TIME_WAIT state,
/// you should set this property to <c>true</c>.
/// </para>
/// </remarks>
/// <value>
/// <c>true</c> if the server is allowed to be bound to an address that
/// is already in use; otherwise, <c>false</c>. The default value is
/// <c>false</c>.
/// </value>
public bool ReuseAddress {
get {
return _reuseAddress;
}
set {
string msg;
if (!canSet (out msg)) {
_log.Warn (msg);
return;
}
lock (_sync) {
if (!canSet (out msg)) {
_log.Warn (msg);
return;
}
_reuseAddress = value;
}
}
}
/// <summary>
/// Gets the configuration used to provide secure connections.
/// </summary>
/// <remarks>
/// The configuration will be referenced when the server starts.
/// So you must configure it before calling the start method.
/// </remarks>
/// <value>
/// A <see cref="ServerSslConfiguration"/> that represents
/// the configuration used to provide secure connections.
/// </value>
public ServerSslConfiguration SslConfiguration {
get {
if (_sslConfig == null)
_sslConfig = new ServerSslConfiguration (null);
return _sslConfig;
}
}
/// <summary>
/// Gets or sets the delegate called to find the credentials for
/// an identity used to authenticate a client.
/// </summary>
/// <remarks>
/// The set operation does nothing if the server has already started or
/// it is shutting down.
/// </remarks>
/// <value>
/// A <c>Func<IIdentity, NetworkCredential></c> delegate
/// that invokes the method used to find the credentials or
/// <see langword="null"/> by default.
/// </value>
public Func<IIdentity, NetworkCredential> UserCredentialsFinder {
get {
return _userCredFinder;
}
set {
string msg;
if (!canSet (out msg)) {
_log.Warn (msg);
return;
}
lock (_sync) {
if (!canSet (out msg)) {
_log.Warn (msg);
return;
}
_userCredFinder = value;
}
}
}
/// <summary>
/// Gets or sets the wait time for the response to
/// the WebSocket Ping or Close.
/// </summary>
/// <remarks>
/// The set operation does nothing if the server has already
/// started or it is shutting down.
/// </remarks>
/// <value>
/// A <see cref="TimeSpan"/> that represents the wait time for
/// the response. The default value is the same as 1 second.
/// </value>
/// <exception cref="ArgumentException">
/// The value specified for a set operation is zero or less.
/// </exception>
public TimeSpan WaitTime {
get {
return _services.WaitTime;
}
set {
string msg;
if (!value.CheckWaitTime (out msg))
throw new ArgumentException (msg, "value");
if (!canSet (out msg)) {
_log.Warn (msg);
return;
}
lock (_sync) {
if (!canSet (out msg)) {
_log.Warn (msg);
return;
}
_services.WaitTime = value;
}
}
}
/// <summary>
/// Gets the management function for the WebSocket services
/// provided by the server.
/// </summary>
/// <value>
/// A <see cref="WebSocketServiceManager"/> that manages
/// the WebSocket services provided by the server.
/// </value>
public WebSocketServiceManager WebSocketServices {
get {
return _services;
}
}
#endregion
#region Private Methods
private void abort ()
{
lock (_sync) {
if (_state != ServerState.Start)
return;
_state = ServerState.ShuttingDown;
}
try {
try {
_listener.Stop ();
}
finally {
_services.Stop (1006, String.Empty);
}
}
catch {
}
_state = ServerState.Stop;
}
private bool canSet (out string message)
{
message = null;
if (_state == ServerState.Start) {
message = "The server has already started.";
return false;
}
if (_state == ServerState.ShuttingDown) {
message = "The server is shutting down.";
return false;
}
return true;
}
private bool checkHostNameForRequest (string name)
{
return !_dnsStyle
|| Uri.CheckHostName (name) != UriHostNameType.Dns
|| name == _hostname;
}
private bool checkSslConfiguration (
ServerSslConfiguration configuration, out string message
)
{
message = null;
if (!_secure)
return true;
if (configuration == null) {
message = "There is no configuration.";
return false;
}
if (configuration.ServerCertificate == null) {
message = "The configuration has no server certificate.";
return false;
}
return true;
}
private string getRealm ()
{
var realm = _realm;
return realm != null && realm.Length > 0 ? realm : _defaultRealm;
}
private ServerSslConfiguration getSslConfiguration ()
{
var sslConfig = _sslConfig;
if (sslConfig == null)
return null;
var ret =
new ServerSslConfiguration (
sslConfig.ServerCertificate,
sslConfig.ClientCertificateRequired,
sslConfig.EnabledSslProtocols,
sslConfig.CheckCertificateRevocation
);
ret.ClientCertificateValidationCallback =
sslConfig.ClientCertificateValidationCallback;
return ret;
}
private void init (
string hostname, System.Net.IPAddress address, int port, bool secure
)
{
_hostname = hostname;
_address = address;
_port = port;
_secure = secure;
_authSchemes = AuthenticationSchemes.Anonymous;
_dnsStyle = Uri.CheckHostName (hostname) == UriHostNameType.Dns;
_listener = new TcpListener (address, port);
_log = new Logger ();
_services = new WebSocketServiceManager (_log);
_sync = new object ();
}
private void processRequest (TcpListenerWebSocketContext context)
{
var uri = context.RequestUri;
if (uri == null) {
context.Close (HttpStatusCode.BadRequest);
return;
}
if (!_allowForwardedRequest) {
if (uri.Port != _port) {
context.Close (HttpStatusCode.BadRequest);
return;
}
if (!checkHostNameForRequest (uri.DnsSafeHost)) {
context.Close (HttpStatusCode.NotFound);
return;
}
}
WebSocketServiceHost host;
if (!_services.InternalTryGetServiceHost (uri.AbsolutePath, out host)) {
context.Close (HttpStatusCode.NotImplemented);
return;
}
host.StartSession (context);
}
private void receiveRequest ()
{
while (true) {
TcpClient cl = null;
try {
cl = _listener.AcceptTcpClient ();
ThreadPool.QueueUserWorkItem (
state => {
try {
var ctx =
cl.GetWebSocketContext (null, _secure, _sslConfigInUse, _log);
if (!ctx.Authenticate (_authSchemes, _realmInUse, _userCredFinder))
return;
processRequest (ctx);
}
catch (Exception ex) {
_log.Fatal (ex.Message);
_log.Debug (ex.ToString ());
cl.Close ();
}
}
);
}
catch (SocketException ex) {
if (_state == ServerState.ShuttingDown) {
_log.Info ("The receiving is stopped.");
break;
}
_log.Fatal (ex.Message);
_log.Debug (ex.ToString ());
break;
}
catch (Exception ex) {
_log.Fatal (ex.Message);
_log.Debug (ex.ToString ());
if (cl != null)
cl.Close ();
break;
}
}
if (_state != ServerState.ShuttingDown)
abort ();
}
private void start (ServerSslConfiguration sslConfig)
{
if (_state == ServerState.Start) {
_log.Info ("The server has already started.");
return;
}
if (_state == ServerState.ShuttingDown) {
_log.Warn ("The server is shutting down.");
return;
}
lock (_sync) {
if (_state == ServerState.Start) {
_log.Info ("The server has already started.");
return;
}
if (_state == ServerState.ShuttingDown) {
_log.Warn ("The server is shutting down.");
return;
}
_sslConfigInUse = sslConfig;
_realmInUse = getRealm ();
_services.Start ();
try {
startReceiving ();
}
catch {
_services.Stop (1011, String.Empty);
throw;
}
_state = ServerState.Start;
}
}
private void startReceiving ()
{
if (_reuseAddress) {
_listener.Server.SetSocketOption (
SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true
);
}
_listener.Start ();
_receiveThread = new Thread (new ThreadStart (receiveRequest));
_receiveThread.IsBackground = true;
_receiveThread.Start ();
}
private void stop (ushort code, string reason)
{
if (_state == ServerState.Ready) {
_log.Info ("The server is not started.");
return;
}
if (_state == ServerState.ShuttingDown) {
_log.Info ("The server is shutting down.");
return;
}
if (_state == ServerState.Stop) {
_log.Info ("The server has already stopped.");
return;
}
lock (_sync) {
if (_state == ServerState.ShuttingDown) {
_log.Info ("The server is shutting down.");
return;
}
if (_state == ServerState.Stop) {
_log.Info ("The server has already stopped.");
return;
}
_state = ServerState.ShuttingDown;
}
try {
var threw = false;
try {
stopReceiving (5000);
}
catch {
threw = true;
throw;
}
finally {
try {
_services.Stop (code, reason);
}
catch {
if (!threw)
throw;
}
}
}
finally {
_state = ServerState.Stop;
}
}
private void stopReceiving (int millisecondsTimeout)
{
_listener.Stop ();
_receiveThread.Join (millisecondsTimeout);
}
private static bool tryCreateUri (
string uriString, out Uri result, out string message
)
{
if (!uriString.TryCreateWebSocketUri (out result, out message))
return false;
if (result.PathAndQuery != "/") {
result = null;
message = "It includes the path or query component.";
return false;
}
return true;
}
#endregion
#region Public Methods
/// <summary>
/// Adds a WebSocket service with the specified behavior,
/// <paramref name="path"/>, and <paramref name="creator"/>.
/// </summary>
/// <remarks>
/// <paramref name="path"/> is converted to a URL-decoded string and
/// / is trimmed from the end of the converted string if any.
/// </remarks>
/// <param name="path">
/// A <see cref="string"/> that represents an absolute path to
/// the service to add.
/// </param>
/// <param name="creator">
/// A <c>Func<TBehavior></c> delegate that invokes
/// the method used to create a new session instance for
/// the service. The method must create a new instance of
/// the specified behavior class and return it.
/// </param>
/// <typeparam name="TBehavior">
/// The type of the behavior for the service. It must inherit
/// the <see cref="WebSocketBehavior"/> class.
/// </typeparam>
/// <exception cref="ArgumentNullException">
/// <para>
/// <paramref name="path"/> is <see langword="null"/>.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="creator"/> is <see langword="null"/>.
/// </para>
/// </exception>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="path"/> is empty.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="path"/> is not an absolute path.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="path"/> includes either or both
/// query and fragment components.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="path"/> is already in use.
/// </para>
/// </exception>
[Obsolete ("This method will be removed. Use added one instead.")]
public void AddWebSocketService<TBehavior> (
string path, Func<TBehavior> creator
)
where TBehavior : WebSocketBehavior
{
if (path == null)
throw new ArgumentNullException ("path");
if (creator == null)
throw new ArgumentNullException ("creator");
if (path.Length == 0)
throw new ArgumentException ("An empty string.", "path");
if (path[0] != '/')
throw new ArgumentException ("Not an absolute path.", "path");
if (path.IndexOfAny (new[] { '?', '#' }) > -1) {
var msg = "It includes either or both query and fragment components.";
throw new ArgumentException (msg, "path");
}
_services.Add<TBehavior> (path, creator);
}
/// <summary>
/// Adds a WebSocket service with the specified behavior and
/// <paramref name="path"/>.
/// </summary>
/// <remarks>
/// <paramref name="path"/> is converted to a URL-decoded string and
/// / is trimmed from the end of the converted string if any.
/// </remarks>
/// <param name="path">
/// A <see cref="string"/> that represents an absolute path to
/// the service to add.
/// </param>
/// <typeparam name="TBehaviorWithNew">
/// The type of the behavior for the service. It must inherit
/// the <see cref="WebSocketBehavior"/> class and it must have
/// a public parameterless constructor.
/// </typeparam>
/// <exception cref="ArgumentNullException">
/// <paramref name="path"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="path"/> is empty.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="path"/> is not an absolute path.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="path"/> includes either or both
/// query and fragment components.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="path"/> is already in use.
/// </para>
/// </exception>
public void AddWebSocketService<TBehaviorWithNew> (string path)
where TBehaviorWithNew : WebSocketBehavior, new ()
{
_services.AddService<TBehaviorWithNew> (path, null);
}
/// <summary>
/// Adds a WebSocket service with the specified behavior,
/// <paramref name="path"/>, and <paramref name="initializer"/>.
/// </summary>
/// <remarks>
/// <paramref name="path"/> is converted to a URL-decoded string and
/// / is trimmed from the end of the converted string if any.
/// </remarks>
/// <param name="path">
/// A <see cref="string"/> that represents an absolute path to
/// the service to add.
/// </param>
/// <param name="initializer">
/// An <c>Action<TBehaviorWithNew></c> delegate that invokes
/// the method used to initialize a new session instance for
/// the service or <see langword="null"/> if not needed.
/// </param>
/// <typeparam name="TBehaviorWithNew">
/// The type of the behavior for the service. It must inherit
/// the <see cref="WebSocketBehavior"/> class and it must have
/// a public parameterless constructor.
/// </typeparam>
/// <exception cref="ArgumentNullException">
/// <paramref name="path"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="path"/> is empty.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="path"/> is not an absolute path.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="path"/> includes either or both
/// query and fragment components.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="path"/> is already in use.
/// </para>
/// </exception>
public void AddWebSocketService<TBehaviorWithNew> (
string path, Action<TBehaviorWithNew> initializer
)
where TBehaviorWithNew : WebSocketBehavior, new ()
{
_services.AddService<TBehaviorWithNew> (path, initializer);
}
/// <summary>
/// Removes a WebSocket service with the specified <paramref name="path"/>.
/// </summary>
/// <remarks>
/// <para>
/// <paramref name="path"/> is converted to a URL-decoded string and
/// / is trimmed from the end of the converted string if any.
/// </para>
/// <para>
/// The service is stopped with close status 1001 (going away)
/// if it has already started.
/// </para>
/// </remarks>
/// <returns>
/// <c>true</c> if the service is successfully found and removed;
/// otherwise, <c>false</c>.
/// </returns>
/// <param name="path">
/// A <see cref="string"/> that represents an absolute path to
/// the service to remove.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="path"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="path"/> is empty.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="path"/> is not an absolute path.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="path"/> includes either or both
/// query and fragment components.
/// </para>
/// </exception>
public bool RemoveWebSocketService (string path)
{
return _services.RemoveService (path);
}
/// <summary>
/// Starts receiving the WebSocket handshake requests.
/// </summary>
/// <remarks>
/// This method does nothing if the server has already started or
/// it is shutting down.
/// </remarks>
/// <exception cref="InvalidOperationException">
/// There is no configuration used to provide secure connections or
/// the configuration has no server certificate.
/// </exception>
/// <exception cref="SocketException">
/// The underlying <see cref="TcpListener"/> has failed to start.
/// </exception>
public void Start ()
{
var sslConfig = getSslConfiguration ();
string msg;
if (!checkSslConfiguration (sslConfig, out msg))
throw new InvalidOperationException (msg);
start (sslConfig);
}
/// <summary>
/// Stops receiving the WebSocket handshake requests,
/// and closes the WebSocket connections.
/// </summary>
/// <remarks>
/// This method does nothing if the server is not started,
/// it is shutting down, or it has already stopped.
/// </remarks>
/// <exception cref="SocketException">
/// The underlying <see cref="TcpListener"/> has failed to stop.
/// </exception>
public void Stop ()
{
stop (1005, String.Empty);
}
/// <summary>
/// Stops receiving the WebSocket handshake requests,
/// and closes the WebSocket connections with the specified
/// <paramref name="code"/> and <paramref name="reason"/>.
/// </summary>
/// <remarks>
/// This method does nothing if the server is not started,
/// it is shutting down, or it has already stopped.
/// </remarks>
/// <param name="code">
/// <para>
/// A <see cref="ushort"/> that represents the status code
/// indicating the reason for the close.
/// </para>
/// <para>
/// The status codes are defined in
/// <see href="http://tools.ietf.org/html/rfc6455#section-7.4">
/// Section 7.4</see> of RFC 6455.
/// </para>
/// </param>
/// <param name="reason">
/// A <see cref="string"/> that represents the reason for
/// the close. The size must be 123 bytes or less in UTF-8.
/// </param>
/// <exception cref="SocketException">
/// The underlying <see cref="TcpListener"/> has failed to stop.
/// </exception>
public void Stop (ushort code, string reason)
{
string msg;
if (!WebSocket.CheckParametersForClose (code, reason, false, out msg)) {
_log.Error (msg);
return;
}
stop (code, reason);
}
/// <summary>
/// Stops receiving the WebSocket handshake requests,
/// and closes the WebSocket connections with the specified
/// <paramref name="code"/> and <paramref name="reason"/>.
/// </summary>
/// <remarks>
/// This method does nothing if the server is not started,
/// it is shutting down, or it has already stopped.
/// </remarks>
/// <param name="code">
/// One of the <see cref="CloseStatusCode"/> enum values.
/// It represents the status code indicating the reason for
/// the close.
/// </param>
/// <param name="reason">
/// A <see cref="string"/> that represents the reason for
/// the close. The size must be 123 bytes or less in UTF-8.
/// </param>
/// <exception cref="SocketException">
/// The underlying <see cref="TcpListener"/> has failed to stop.
/// </exception>
public void Stop (CloseStatusCode code, string reason)
{
string msg;
if (!WebSocket.CheckParametersForClose (code, reason, false, out msg)) {
_log.Error (msg);
return;
}
stop ((ushort) code, reason);
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Primitives;
using Xunit;
namespace Microsoft.AspNetCore.Mvc.ModelBinding
{
public class DefaultModelBindingContextTest
{
[Fact]
public void EnterNestedScope_CopiesProperties()
{
// Arrange
var bindingContext = new DefaultModelBindingContext
{
Model = new object(),
ModelMetadata = new TestModelMetadataProvider().GetMetadataForType(typeof(object)),
ModelName = "theName",
ValueProvider = new SimpleValueProvider(),
ModelState = new ModelStateDictionary(),
};
var metadataProvider = new TestModelMetadataProvider();
metadataProvider.ForType<object>().BindingDetails(d =>
{
d.BindingSource = BindingSource.Custom;
d.BinderType = typeof(TestModelBinder);
d.BinderModelName = "custom";
});
var newModelMetadata = metadataProvider.GetMetadataForType(typeof(object));
// Act
var originalBinderModelName = bindingContext.BinderModelName;
var originalBindingSource = bindingContext.BindingSource;
var originalValueProvider = bindingContext.ValueProvider;
var disposable = bindingContext.EnterNestedScope(
modelMetadata: newModelMetadata,
fieldName: "fieldName",
modelName: "modelprefix.fieldName",
model: null);
// Assert
Assert.Same(newModelMetadata.BinderModelName, bindingContext.BinderModelName);
Assert.Same(newModelMetadata.BindingSource, bindingContext.BindingSource);
Assert.Equal("fieldName", bindingContext.FieldName);
Assert.False(bindingContext.IsTopLevelObject);
Assert.Null(bindingContext.Model);
Assert.Same(newModelMetadata, bindingContext.ModelMetadata);
Assert.Equal("modelprefix.fieldName", bindingContext.ModelName);
Assert.Same(originalValueProvider, bindingContext.ValueProvider);
disposable.Dispose();
}
[Fact]
public void CreateBindingContext_FiltersValueProviders_ForValueProviderSource()
{
// Arrange
var metadataProvider = new TestModelMetadataProvider();
var original = CreateDefaultValueProvider();
// Act
var context = DefaultModelBindingContext.CreateBindingContext(
GetActionContext(),
original,
metadataProvider.GetMetadataForType(typeof(object)),
new BindingInfo() { BindingSource = BindingSource.Query },
"model");
// Assert
Assert.Collection(
Assert.IsType<CompositeValueProvider>(context.ValueProvider),
vp => Assert.Same(original[1], vp));
}
[Fact]
public void EnterNestedScope_FiltersValueProviders_ForValueProviderSource()
{
// Arrange
var metadataProvider = new TestModelMetadataProvider();
metadataProvider
.ForProperty(typeof(string), nameof(string.Length))
.BindingDetails(b => b.BindingSource = BindingSource.Query);
var original = CreateDefaultValueProvider();
var context = DefaultModelBindingContext.CreateBindingContext(
GetActionContext(),
original,
metadataProvider.GetMetadataForType(typeof(string)),
new BindingInfo(),
"model");
var propertyMetadata = metadataProvider.GetMetadataForProperty(typeof(string), nameof(string.Length));
// Act
context.EnterNestedScope(propertyMetadata, "Length", "Length", model: null);
// Assert
Assert.Collection(
Assert.IsType<CompositeValueProvider>(context.ValueProvider),
vp => Assert.Same(original[1], vp));
}
[Fact]
public void EnterNestedScope_FiltersValueProviders_BasedOnTopLevelValueProviders()
{
// Arrange
var metadataProvider = new TestModelMetadataProvider();
metadataProvider
.ForProperty(typeof(string), nameof(string.Length))
.BindingDetails(b => b.BindingSource = BindingSource.Form);
var original = CreateDefaultValueProvider();
var context = DefaultModelBindingContext.CreateBindingContext(
GetActionContext(),
original,
metadataProvider.GetMetadataForType(typeof(string)),
new BindingInfo() { BindingSource = BindingSource.Query },
"model");
var propertyMetadata = metadataProvider.GetMetadataForProperty(typeof(string), nameof(string.Length));
// Act
context.EnterNestedScope(propertyMetadata, "Length", "Length", model: null);
// Assert
Assert.Collection(
Assert.IsType<CompositeValueProvider>(context.ValueProvider),
vp => Assert.Same(original[2], vp));
}
[Fact]
public void ModelTypeAreFedFromModelMetadata()
{
// Act
var bindingContext = new DefaultModelBindingContext
{
ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(typeof(int))
};
// Assert
Assert.Equal(typeof(int), bindingContext.ModelType);
}
private static ActionContext GetActionContext()
{
var services = new ServiceCollection();
services.AddSingleton<ILoggerFactory>(NullLoggerFactory.Instance);
return new ActionContext()
{
HttpContext = new DefaultHttpContext()
{
RequestServices = services.BuildServiceProvider()
}
};
}
private static CompositeValueProvider CreateDefaultValueProvider()
{
var result = new CompositeValueProvider();
result.Add(new RouteValueProvider(BindingSource.Path, new RouteValueDictionary()));
result.Add(new QueryStringValueProvider(
BindingSource.Query,
new QueryCollection(),
CultureInfo.InvariantCulture));
result.Add(new FormValueProvider(
BindingSource.Form,
new FormCollection(new Dictionary<string, StringValues>()),
CultureInfo.CurrentCulture));
return result;
}
private class TestModelBinder : IModelBinder
{
public Task BindModelAsync(ModelBindingContext bindingContext)
{
if (bindingContext == null)
{
throw new ArgumentNullException(nameof(bindingContext));
}
throw new NotImplementedException();
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace Cocos2D
{
public enum CCMenuState
{
Waiting,
TrackingTouch,
Focused
};
/// <summary>
/// A CCMenu
/// Features and Limitation:
/// You can add MenuItem objects in runtime using addChild:
/// But the only accecpted children are MenuItem objects
/// </summary>
public class CCMenu : CCLayerRGBA
{
public const float kDefaultPadding = 5;
public const int kCCMenuHandlerPriority = -128;
protected bool m_bEnabled;
protected CCMenuState m_eState;
protected CCMenuItem m_pSelectedItem;
private LinkedList<CCMenuItem> _Items = new LinkedList<CCMenuItem>();
/// <summary>
/// Default ctor that sets the content size of the menu to match the window size.
/// </summary>
private CCMenu()
{
Init();
// ContentSize = CCDirector.SharedDirector.WinSize;
}
public CCMenu(params CCMenuItem[] items)
{
InitWithItems(items);
}
public override bool HasFocus
{
set
{
base.HasFocus = value;
// Set the first menu item to have the focus
if (FocusedItem == null)
{
_Items.First.Value.HasFocus = true;
}
}
}
/// <summary>
/// Handles the button press event to track which focused menu item will get the activation
/// </summary>
/// <param name="backButton"></param>
/// <param name="startButton"></param>
/// <param name="systemButton"></param>
/// <param name="aButton"></param>
/// <param name="bButton"></param>
/// <param name="xButton"></param>
/// <param name="yButton"></param>
/// <param name="leftShoulder"></param>
/// <param name="rightShoulder"></param>
/// <param name="player"></param>
protected override void OnGamePadButtonUpdate(CCGamePadButtonStatus backButton, CCGamePadButtonStatus startButton, CCGamePadButtonStatus systemButton, CCGamePadButtonStatus aButton, CCGamePadButtonStatus bButton, CCGamePadButtonStatus xButton, CCGamePadButtonStatus yButton, CCGamePadButtonStatus leftShoulder, CCGamePadButtonStatus rightShoulder, Microsoft.Xna.Framework.PlayerIndex player)
{
base.OnGamePadButtonUpdate(backButton, startButton, systemButton, aButton, bButton, xButton, yButton, leftShoulder, rightShoulder, player);
if (!HasFocus)
{
return;
}
if (backButton == CCGamePadButtonStatus.Pressed || aButton == CCGamePadButtonStatus.Pressed || bButton == CCGamePadButtonStatus.Pressed ||
xButton == CCGamePadButtonStatus.Pressed || yButton == CCGamePadButtonStatus.Pressed || leftShoulder == CCGamePadButtonStatus.Pressed ||
rightShoulder == CCGamePadButtonStatus.Pressed)
{
CCMenuItem item = FocusedItem;
item.Selected();
m_pSelectedItem = item;
m_eState = CCMenuState.TrackingTouch;
}
else if (backButton == CCGamePadButtonStatus.Released || aButton == CCGamePadButtonStatus.Released || bButton == CCGamePadButtonStatus.Released ||
xButton == CCGamePadButtonStatus.Released || yButton == CCGamePadButtonStatus.Released || leftShoulder == CCGamePadButtonStatus.Released ||
rightShoulder == CCGamePadButtonStatus.Released)
{
if (m_eState == CCMenuState.TrackingTouch)
{
// Now we are selecting the menu item
CCMenuItem item = FocusedItem;
if (item != null && m_pSelectedItem == item)
{
// Activate this item
item.Unselected();
item.Activate();
m_eState = CCMenuState.Waiting;
m_pSelectedItem = null;
}
}
}
}
/// <summary>
/// Returns the menu item with the focus. Note that this only has a value if the GamePad or Keyboard is enabled. Touch
/// devices do not have a "focus" concept.
/// </summary>
public CCMenuItem FocusedItem
{
get
{
// Find the item with the focus
foreach(CCMenuItem item in _Items)
{
if (item.HasFocus)
{
return (item);
}
}
return (null);
}
}
public bool Enabled
{
get { return m_bEnabled; }
set { m_bEnabled = value; }
}
public override bool Init()
{
return InitWithArray(null);
}
public bool InitWithItems(params CCMenuItem[] items)
{
return InitWithArray(items);
}
/// <summary>
/// The position of the menu is set to the center of the main screen
/// </summary>
/// <param name="items"></param>
/// <returns></returns>
private bool InitWithArray(params CCMenuItem[] items)
{
if (_Items.Count > 0)
{
List<CCMenuItem> copy = new List<CCMenuItem>(_Items);
foreach (CCMenuItem i in copy)
{
RemoveChild(i, false);
}
}
if (base.Init())
{
TouchPriority = kCCMenuHandlerPriority;
TouchMode = CCTouchMode.OneByOne;
TouchEnabled = true;
m_bEnabled = true;
// menu in the center of the screen
CCSize s = CCDirector.SharedDirector.WinSize;
IgnoreAnchorPointForPosition = true;
AnchorPoint = new CCPoint(0.5f, 0.5f);
ContentSize = s;
Position = (new CCPoint(s.Width / 2, s.Height / 2));
if (items != null)
{
int z = 0;
foreach (CCMenuItem item in items)
{
AddChild(item, z);
z++;
}
}
// [self alignItemsVertically];
m_pSelectedItem = null;
m_eState = CCMenuState.Waiting;
// enable cascade color and opacity on menus
CascadeColorEnabled = true;
CascadeOpacityEnabled = true;
return true;
}
return false;
}
/*
* override add:
*/
public override void AddChild(CCNode child, int zOrder, int tag)
{
Debug.Assert(child is CCMenuItem, "Menu only supports MenuItem objects as children");
base.AddChild(child, zOrder, tag);
if (_Items.Count == 0)
{
_Items.AddFirst(child as CCMenuItem);
}
else
{
_Items.AddLast(child as CCMenuItem);
}
}
public override void RemoveChild(CCNode child, bool cleanup)
{
Debug.Assert(child is CCMenuItem, "Menu only supports MenuItem objects as children");
if (m_pSelectedItem == child)
{
m_pSelectedItem = null;
}
base.RemoveChild(child, cleanup);
if (_Items.Contains(child as CCMenuItem))
{
_Items.Remove(child as CCMenuItem);
}
}
public override void OnEnter()
{
base.OnEnter();
foreach (CCMenuItem item in _Items)
{
CCFocusManager.Instance.Add(item);
}
}
public override void OnExit()
{
if (m_eState == CCMenuState.TrackingTouch)
{
if (m_pSelectedItem != null)
{
m_pSelectedItem.Unselected();
m_pSelectedItem = null;
}
m_eState = CCMenuState.Waiting;
}
foreach (CCMenuItem item in _Items)
{
CCFocusManager.Instance.Remove(item);
}
base.OnExit();
}
#region Menu - Events
public void SetHandlerPriority(int newPriority)
{
CCTouchDispatcher pDispatcher = CCDirector.SharedDirector.TouchDispatcher;
pDispatcher.SetPriority(newPriority, this);
}
public override void RegisterWithTouchDispatcher()
{
CCDirector pDirector = CCDirector.SharedDirector;
pDirector.TouchDispatcher.AddTargetedDelegate(this, kCCMenuHandlerPriority, true);
}
public override bool TouchBegan(CCTouch touch)
{
if (m_eState != CCMenuState.Waiting || !m_bVisible || !m_bEnabled)
{
return false;
}
for (CCNode c = m_pParent; c != null; c = c.Parent)
{
if (c.Visible == false)
{
return false;
}
}
m_pSelectedItem = ItemForTouch(touch);
if (m_pSelectedItem != null)
{
m_eState = CCMenuState.TrackingTouch;
m_pSelectedItem.Selected();
return true;
}
return false;
}
public override void TouchEnded(CCTouch touch)
{
Debug.Assert(m_eState == CCMenuState.TrackingTouch, "[Menu TouchEnded] -- invalid state");
if (m_pSelectedItem != null)
{
m_pSelectedItem.Unselected();
m_pSelectedItem.Activate();
}
m_eState = CCMenuState.Waiting;
}
public override void TouchCancelled(CCTouch touch)
{
Debug.Assert(m_eState == CCMenuState.TrackingTouch, "[Menu ccTouchCancelled] -- invalid state");
if (m_pSelectedItem != null)
{
m_pSelectedItem.Unselected();
}
m_eState = CCMenuState.Waiting;
}
public override void TouchMoved(CCTouch touch)
{
Debug.Assert(m_eState == CCMenuState.TrackingTouch, "[Menu TouchMoved] -- invalid state");
CCMenuItem currentItem = ItemForTouch(touch);
if (currentItem != m_pSelectedItem)
{
if (m_pSelectedItem != null)
{
m_pSelectedItem.Unselected();
}
m_pSelectedItem = currentItem;
if (m_pSelectedItem != null)
{
m_pSelectedItem.Selected();
}
}
}
#endregion
#region Menu - Alignment
public void AlignItemsVertically()
{
AlignItemsVerticallyWithPadding(kDefaultPadding);
}
public void AlignItemsVerticallyWithPadding(float padding)
{
float width = 0f;
float height = -padding;
if (m_pChildren != null && m_pChildren.count > 0)
{
for (int i = 0, count = m_pChildren.count; i < count; i++)
{
CCNode pChild = m_pChildren[i];
if (!pChild.Visible)
{
continue;
}
height += pChild.ContentSize.Height * pChild.ScaleY + padding;
width = Math.Max(width, pChild.ContentSize.Width);
}
}
float y = height / 2.0f;
if (m_pChildren != null && m_pChildren.count > 0)
{
for (int i = 0, count = m_pChildren.count; i < count; i++)
{
CCNode pChild = m_pChildren[i];
if (!pChild.Visible)
{
continue;
}
pChild.Position = new CCPoint(0, y - pChild.ContentSize.Height * pChild.ScaleY / 2.0f);
y -= pChild.ContentSize.Height * pChild.ScaleY + padding;
width = Math.Max(width, pChild.ContentSize.Width);
}
}
ContentSize = new CCSize(width, height);
}
public void AlignItemsHorizontally()
{
AlignItemsHorizontallyWithPadding(kDefaultPadding);
}
public void AlignItemsHorizontallyWithPadding(float padding)
{
float height = 0f;
float width = -padding;
if (m_pChildren != null && m_pChildren.count > 0)
{
for (int i = 0, count = m_pChildren.count; i < count; i++)
{
CCNode pChild = m_pChildren[i];
if (pChild.Visible)
{
width += pChild.ContentSize.Width * pChild.ScaleX + padding;
height = Math.Max(height, pChild.ContentSize.Height);
}
}
}
float x = -width / 2.0f;
if (m_pChildren != null && m_pChildren.count > 0)
{
for (int i = 0, count = m_pChildren.count; i < count; i++)
{
CCNode pChild = m_pChildren[i];
if (pChild.Visible)
{
pChild.Position = new CCPoint(x + pChild.ContentSize.Width * pChild.ScaleX / 2.0f, 0);
x += pChild.ContentSize.Width * pChild.ScaleX + padding;
height = Math.Max(height, pChild.ContentSize.Height);
}
}
}
ContentSize = new CCSize(width, height);
}
public void AlignItemsInColumns(params int[] columns)
{
int[] rows = columns;
int height = -5;
int row = 0;
int rowHeight = 0;
int columnsOccupied = 0;
int rowColumns;
if (m_pChildren != null && m_pChildren.count > 0)
{
for (int i = 0, count = m_pChildren.count; i < count; i++)
{
CCNode pChild = m_pChildren.Elements[i];
if (!pChild.Visible)
{
continue;
}
Debug.Assert(row < rows.Length, "");
rowColumns = rows[row];
// can not have zero columns on a row
Debug.Assert(rowColumns > 0, "");
float tmp = pChild.ContentSize.Height;
rowHeight = (int) ((rowHeight >= tmp || float.IsNaN(tmp)) ? rowHeight : tmp);
++columnsOccupied;
if (columnsOccupied >= rowColumns)
{
height += rowHeight + (int)kDefaultPadding;
columnsOccupied = 0;
rowHeight = 0;
++row;
}
}
}
// check if too many rows/columns for available menu items
Debug.Assert(columnsOccupied == 0, "");
CCSize winSize = ContentSize; // CCDirector.SharedDirector.WinSize;
row = 0;
rowHeight = 0;
rowColumns = 0;
float w = 0.0f;
float x = 0.0f;
float y = (height / 2f);
if (m_pChildren != null && m_pChildren.count > 0)
{
for (int i = 0, count = m_pChildren.count; i < count; i++)
{
CCNode pChild = m_pChildren.Elements[i];
if (!pChild.Visible)
{
continue;
}
if (rowColumns == 0)
{
rowColumns = rows[row];
if (rowColumns == 0)
{
throw (new ArgumentException("Can not have a zero column size for a row."));
}
w = (winSize.Width - 2 * kDefaultPadding) / rowColumns; // 1 + rowColumns
x = w/2f; // center of column
}
float tmp = pChild.ContentSize.Height*pChild.ScaleY;
rowHeight = (int) ((rowHeight >= tmp || float.IsNaN(tmp)) ? rowHeight : tmp);
pChild.Position = new CCPoint(kDefaultPadding + x - (winSize.Width - 2*kDefaultPadding) / 2,
y - pChild.ContentSize.Height*pChild.ScaleY / 2);
x += w;
++columnsOccupied;
if (columnsOccupied >= rowColumns)
{
y -= rowHeight + 5;
columnsOccupied = 0;
rowColumns = 0;
rowHeight = 0;
++row;
}
}
}
}
public void AlignItemsInRows(params int[] rows)
{
int[] columns = rows;
List<int> columnWidths = new List<int>();
List<int> columnHeights = new List<int>();
int width = -10;
int columnHeight = -5;
int column = 0;
int columnWidth = 0;
int rowsOccupied = 0;
int columnRows;
if (m_pChildren != null && m_pChildren.count > 0)
{
for (int i = 0, count = m_pChildren.count; i < count; i++)
{
CCNode pChild = m_pChildren.Elements[i];
if (!pChild.Visible)
{
continue;
}
// check if too many menu items for the amount of rows/columns
Debug.Assert(column < columns.Length, "");
columnRows = columns[column];
// can't have zero rows on a column
Debug.Assert(columnRows > 0, "");
// columnWidth = fmaxf(columnWidth, [item contentSize].width);
float tmp = pChild.ContentSize.Width * pChild.ScaleX;
columnWidth = (int)((columnWidth >= tmp || float.IsNaN(tmp)) ? columnWidth : tmp);
columnHeight += (int)(pChild.ContentSize.Height * pChild.ScaleY + 5);
++rowsOccupied;
if (rowsOccupied >= columnRows)
{
columnWidths.Add(columnWidth);
columnHeights.Add(columnHeight);
width += columnWidth + 10;
rowsOccupied = 0;
columnWidth = 0;
columnHeight = -5;
++column;
}
}
}
// check if too many rows/columns for available menu items.
Debug.Assert(rowsOccupied == 0, "");
CCSize winSize = ContentSize; // CCDirector.SharedDirector.WinSize;
column = 0;
columnWidth = 0;
columnRows = 0;
float x = (-width / 2f);
float y = 0.0f;
if (m_pChildren != null && m_pChildren.count > 0)
{
for (int i = 0, count = m_pChildren.count; i < count; i++)
{
CCNode pChild = m_pChildren.Elements[i];
if (!pChild.Visible)
{
continue;
}
if (columnRows == 0)
{
columnRows = columns[column];
y = columnHeights[column];
}
// columnWidth = fmaxf(columnWidth, [item contentSize].width);
float tmp = pChild.ContentSize.Width * pChild.ScaleX;
columnWidth = (int)((columnWidth >= tmp || float.IsNaN(tmp)) ? columnWidth : tmp);
pChild.Position = new CCPoint(x + columnWidths[column] / 2,
y - winSize.Height / 2);
y -= pChild.ContentSize.Height * pChild.ScaleY + 10;
++rowsOccupied;
if (rowsOccupied >= columnRows)
{
x += columnWidth + 5;
rowsOccupied = 0;
columnRows = 0;
columnWidth = 0;
++column;
}
}
}
}
#endregion
protected virtual CCMenuItem ItemForTouch(CCTouch touch)
{
CCPoint touchLocation = touch.Location;
if (m_pChildren != null && m_pChildren.count > 0)
{
for (int i = m_pChildren.count-1; i >= 0; i--)
{
var pChild = m_pChildren.Elements[i] as CCMenuItem;
if (pChild != null && pChild.Visible && pChild.Enabled)
{
CCPoint local = pChild.ConvertToNodeSpace(touchLocation);
CCRect r = pChild.Rectangle;
r.Origin = CCPoint.Zero;
if (r.ContainsPoint(local))
{
return pChild;
}
}
}
}
return null;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.IO;
using System.Reflection;
using System.Collections;
using Microsoft.Build.Framework;
using Microsoft.Build.Tasks;
using Microsoft.Build.Utilities;
using System.Text.RegularExpressions;
using Microsoft.Build.Shared.LanguageParser;
using Xunit;
namespace Microsoft.Build.UnitTests
{
sealed public class CSharpTokenizerTests
{
// Simple whitespace handling.
[Fact]
public void Empty() { AssertTokenize("", "", 0); }
[Fact]
public void OneSpace() { AssertTokenize(" ", " \x0d", ".Whitespace"); }
[Fact]
public void TwoSpace() { AssertTokenize(" ", " \x0d", ".Whitespace"); }
[Fact]
public void Tab() { AssertTokenize("\t", "\t\x0d", ".Whitespace"); }
[Fact]
public void TwoTab() { AssertTokenize("\t\t", "\t\t\x0d", ".Whitespace"); }
[Fact]
public void SpaceTab() { AssertTokenize(" \t", " \t\x0d", ".Whitespace"); }
[Fact]
public void CrLf() { AssertTokenize("\x0d\x0a", ".Whitespace"); }
[Fact]
public void SpaceCrLfSpace() { AssertTokenize(" \x0d\x0a ", " \x0d\x0a \x0d", ".Whitespace"); }
// From section 2.3.3 of the C# spec, these are also whitespace.
[Fact]
public void LineSeparator() { AssertTokenizeUnicode("\x2028", ".Whitespace"); }
[Fact]
public void ParagraphSeparator() { AssertTokenizeUnicode("\x2029", ".Whitespace"); }
/*
Special whitespace handling.
Horizontal tab character (U+0009)
Vertical tab character (U+000B)
Form feed character (U+000C)
*/
[Fact]
public void SpecialWhitespace() { AssertTokenize("\x09\x0b\x0c\x0d", ".Whitespace"); }
// One-line comments (i.e. those starting with //)
[Fact]
public void OneLineComment() { AssertTokenize("// My one line comment.\x0d", ".Comment.Whitespace"); }
[Fact]
public void SpaceOneLineComment() { AssertTokenize(" // My one line comment.\x0d", ".Whitespace.Comment.Whitespace"); }
[Fact]
public void OneLineCommentTab() { AssertTokenize(" //\tMy one line comment.\x0d", ".Whitespace.Comment.Whitespace"); }
[Fact]
public void OneLineCommentCr() { AssertTokenize("// My one line comment.\x0d", ".Comment.Whitespace"); }
[Fact]
public void OneLineCommentLf() { AssertTokenize("// My one line comment.\x0a", ".Comment.Whitespace"); }
[Fact]
public void OneLineCommentLineSeparator() { AssertTokenizeUnicode("// My one line comment.\x2028", ".Comment.Whitespace"); }
[Fact]
public void OneLineCommentParagraphSeparator() { AssertTokenizeUnicode("// My one line comment.\x2029", ".Comment.Whitespace"); }
[Fact]
public void OneLineCommentWithEmbeddedMultiLine() { AssertTokenize("// /* */\x0d", ".Comment.Whitespace"); }
// Multi-line comments (i.e those like /* */)
[Fact]
public void OneLineMultilineComment() { AssertTokenize("/* My comment. */\x0d", ".Comment.Whitespace"); }
[Fact]
public void MultilineComment() { AssertTokenize("/* My comment. \x0d\x0a Second Line*/\x0d", ".Comment.Whitespace", 3); }
[Fact]
public void MultilineCommentWithEmbeddedSingleLine() { AssertTokenize("/* // */\x0d", ".Comment.Whitespace"); }
[Fact]
public void LeftHalfOfUnbalanceMultilineComment() { AssertTokenize("/*\x0d", ".EndOfFileInsideComment"); }
[Fact]
public void LeftHalfOfUnbalanceMultilineCommentWithStuff() { AssertTokenize("/* unbalanced\x0d", ".EndOfFileInsideComment"); }
// If the last character of the source file is a Control-Z character (U+001A), this character is deleted.
[Fact]
public void NothingPlustControlZatEOF() { AssertTokenize("\x1A", "", "", 0); }
[Fact]
public void SomethingPlusControlZatEOF() { AssertTokenize("// My comment\x1A", "// My comment\x0d", ".Comment.Whitespace"); }
// A carriage-return character (U+000D) is added to the end of the source file if that source file is non-empty and if the last character
// of the source file is not a carriage return (U+000D), a line feed (U+000A), a line separator (U+2028), or a paragraph separator
// (U+2029).
[Fact]
public void NoEOLatEOF() { AssertTokenize("// My comment", "// My comment\x0d", ".Comment.Whitespace"); }
[Fact]
public void NoEOLatEOFButFileIsEmpty() { AssertTokenize("", "", "", 0); }
// An identifier that has a "_" embedded somewhere
[Fact]
public void IdentifierWithEmbeddedUnderscore() { AssertTokenize("_x_\xd", ".Identifier.Whitespace"); }
// An identifier with a number
[Fact]
public void IdentifierWithNumber() { AssertTokenize("x3\xd", ".Identifier.Whitespace"); }
// An non-identifier with a @ and a number
[Fact]
public void EscapedIdentifierWithNumber() { AssertTokenize("@3Identifier\xd", ".ExpectedIdentifier"); }
// A very simple namespace and class.
[Fact]
public void NamespacePlusClass()
{
AssertTokenize
("namespace MyNamespace { class MyClass {} }\x0d",
".Keyword.Whitespace.Identifier.Whitespace.OpenScope.Whitespace.Keyword.Whitespace.Identifier.Whitespace.OpenScope.CloseScope.Whitespace.CloseScope.Whitespace");
}
// If a keyword has '@' in front, then its treated as an identifier.
[Fact]
public void EscapedKeywordMakesIdentifier()
{
AssertTokenize
(
"namespace @namespace { class @class {} }\x0d",
"namespace namespace { class class {} }\x0d", // Resulting tokens have '@' stripped.
".Keyword.Whitespace.Identifier.Whitespace.OpenScope.Whitespace.Keyword.Whitespace.Identifier.Whitespace.OpenScope.CloseScope.Whitespace.CloseScope.Whitespace"
);
}
// Check boolean literals
[Fact]
public void LiteralTrue() { AssertTokenize("true\x0d", ".BooleanLiteral.Whitespace"); }
[Fact]
public void LiteralFalse() { AssertTokenize("false\x0d", ".BooleanLiteral.Whitespace"); }
[Fact]
public void LiteralNull() { AssertTokenize("null\x0d", ".NullLiteral.Whitespace"); }
// Check integer literals
[Fact]
public void HexIntegerLiteral() { AssertTokenize("0x123F\x0d", ".HexIntegerLiteral.Whitespace"); }
[Fact]
public void HexUppercaseXIntegerLiteral() { AssertTokenize("0X1f23\x0d", ".HexIntegerLiteral.Whitespace"); }
[Fact]
public void IntegerLiteral() { AssertTokenize("123\x0d", ".DecimalIntegerLiteral.Whitespace"); }
[Fact]
public void InvalidHexIntegerWithNoneValid() { AssertTokenize("0xG\x0d", ".ExpectedValidHexDigit"); }
// Hex literal long suffix: U u L l UL Ul uL ul LU Lu lU lu
[Fact]
public void HexIntegerLiteralUpperU() { AssertTokenize("0x123FU\x0d", ".HexIntegerLiteral.Whitespace"); }
[Fact]
public void HexIntegerLiteralLowerU() { AssertTokenize("0x123Fu\x0d", ".HexIntegerLiteral.Whitespace"); }
[Fact]
public void HexIntegerLiteralUpperL() { AssertTokenize("0x123FL\x0d", ".HexIntegerLiteral.Whitespace"); }
[Fact]
public void HexIntegerLiteralLowerL() { AssertTokenize("0x123Fl\x0d", ".HexIntegerLiteral.Whitespace"); }
[Fact]
public void HexIntegerLiteralUpperUUpperL() { AssertTokenize("0x123FUL\x0d", ".HexIntegerLiteral.Whitespace"); }
[Fact]
public void HexIntegerLiteralUpperULowerL() { AssertTokenize("0x123FUl\x0d", ".HexIntegerLiteral.Whitespace"); }
[Fact]
public void HexIntegerLiteralLowerUUpperL() { AssertTokenize("0x123FuL\x0d", ".HexIntegerLiteral.Whitespace"); }
[Fact]
public void HexIntegerLiteralUpperLUpperU() { AssertTokenize("0x123FLU\x0d", ".HexIntegerLiteral.Whitespace"); }
[Fact]
public void HexIntegerLiteralUpperLLowerU() { AssertTokenize("0x123FLu\x0d", ".HexIntegerLiteral.Whitespace"); }
[Fact]
public void HexIntegerLiteralLowerLUpperU() { AssertTokenize("0x123FlU\x0d", ".HexIntegerLiteral.Whitespace"); }
[Fact]
public void HexIntegerLiteralLowerLLowerU() { AssertTokenize("0x123Flu\x0d", ".HexIntegerLiteral.Whitespace"); }
// Decimal literal long suffix: U u L l UL Ul uL ul LU Lu lU lu
[Fact]
public void DecimalIntegerLiteralUpperU() { AssertTokenize("1234U\x0d", ".DecimalIntegerLiteral.Whitespace"); }
[Fact]
public void DecimalIntegerLiteralLowerU() { AssertTokenize("1234u\x0d", ".DecimalIntegerLiteral.Whitespace"); }
[Fact]
public void DecimalIntegerLiteralUpperL() { AssertTokenize("1234L\x0d", ".DecimalIntegerLiteral.Whitespace"); }
[Fact]
public void DecimalIntegerLiteralLowerL() { AssertTokenize("1234l\x0d", ".DecimalIntegerLiteral.Whitespace"); }
[Fact]
public void DecimalIntegerLiteralUpperUUpperL() { AssertTokenize("1234UL\x0d", ".DecimalIntegerLiteral.Whitespace"); }
[Fact]
public void DecimalIntegerLiteralUpperULowerL() { AssertTokenize("1234Ul\x0d", ".DecimalIntegerLiteral.Whitespace"); }
[Fact]
public void DecimalIntegerLiteralLowerUUpperL() { AssertTokenize("1234uL\x0d", ".DecimalIntegerLiteral.Whitespace"); }
[Fact]
public void DecimalIntegerLiteralUpperLUpperU() { AssertTokenize("1234LU\x0d", ".DecimalIntegerLiteral.Whitespace"); }
[Fact]
public void DecimalIntegerLiteralUpperLLowerU() { AssertTokenize("1234Lu\x0d", ".DecimalIntegerLiteral.Whitespace"); }
[Fact]
public void DecimalIntegerLiteralLowerLUpperU() { AssertTokenize("1234lU\x0d", ".DecimalIntegerLiteral.Whitespace"); }
[Fact]
public void DecimalIntegerLiteralLowerLLowerU() { AssertTokenize("1234lu\x0d", ".DecimalIntegerLiteral.Whitespace"); }
// Reals aren't supported yet.
// Reals can take many different forms: 1.1, .1, 1.1e6, etc.
// If you turn this on, please create test for the other forms too.
[Fact(Skip = "Ignored in MSTest")]
public void RealLiteral1() { AssertTokenize("1.1\x0d", ".RealLiteral.Whitespace"); }
// Char literals aren't supported yet.
[Fact]
public void CharLiteral1() { AssertTokenize("'c'\x0d", ".CharLiteral.Whitespace"); }
[Fact(Skip = "Ignored in MSTest")]
public void CharLiteralIllegalEscapeSequence() { AssertTokenize("'\\z'\x0d", ".SyntaxErrorIllegalEscapeSequence"); }
[Fact(Skip = "Ignored in MSTest")]
public void CharLiteralHexEscapeSequence() { AssertTokenize("'\\x0022a'\x0d", "'\"a'\x0d", ".CharLiteral.Whitespace"); }
// Check string literals
[Fact]
public void LiteralStringBasic() { AssertTokenize("\"string\"\x0d", ".StringLiteral.Whitespace"); }
[Fact]
public void LiteralStringAllEscapes() { AssertTokenize("\"\\'\\\"\\\\\\0\\a\\b\\f\\n\\r\\t\\x0\\v\"\x0d", ".StringLiteral.Whitespace"); }
[Fact]
public void LiteralStringUnclosed() { AssertTokenize("\"string\x0d", ".NewlineInsideString"); }
[Fact]
public void LiteralVerbatimStringBasic() { AssertTokenize("@\"string\"\x0d", "\"string\"\x0d", ".StringLiteral.Whitespace"); }
[Fact]
public void LiteralVerbatimStringAllEscapes() { AssertTokenize("@\"\\a\\b\\c\"\x0d", "\"\\a\\b\\c\"\x0d", ".StringLiteral.Whitespace"); }
[Fact]
public void LiteralVerbatimStringUnclosed() { AssertTokenize("@\"string\x0d", ".EndOfFileInsideString"); }
[Fact]
public void LiteralVerbatimStringQuoteEscapeSequence() { AssertTokenize("@\"\"\"\"\x0d", "\"\"\"\"\x0d", ".StringLiteral.Whitespace"); }
// Single-digit operators and punctuators.
[Fact]
public void PunctuatorOpenBracket() { AssertTokenize("[\x0d", ".OperatorOrPunctuator.Whitespace"); }
[Fact]
public void PunctuatorCloseBracket() { AssertTokenize("]\x0d", ".OperatorOrPunctuator.Whitespace"); }
[Fact]
public void PunctuatorOpenParen() { AssertTokenize("(\x0d", ".OperatorOrPunctuator.Whitespace"); }
[Fact]
public void PunctuatorCloseParen() { AssertTokenize(")\x0d", ".OperatorOrPunctuator.Whitespace"); }
[Fact]
public void PunctuatorDot() { AssertTokenize(".\x0d", ".OperatorOrPunctuator.Whitespace"); }
[Fact]
public void PunctuatorColon() { AssertTokenize(":\x0d", ".OperatorOrPunctuator.Whitespace"); }
[Fact]
public void PunctuatorSemicolon() { AssertTokenize(";\x0d", ".OperatorOrPunctuator.Whitespace"); }
// Preprocessor.
[Fact]
public void Preprocessor() { AssertTokenize("#if\x0d", ".OpenConditionalDirective.Whitespace"); }
/*
* Method: AssertTokenize
*
* Tokenize a string ('source') and compare it to the expected set of tokens.
* Also, the source must be regenerated exactly when the tokens are concatenated
* back together,
*/
static private void AssertTokenize(string source, string expectedTokenKey)
{
// Most of the time, we expect the rebuilt source to be the same as the input source.
AssertTokenize(source, source, expectedTokenKey);
}
/*
* Method: AssertTokenizeUnicode
*
* Tokenize a string ('source') and compare it to the expected set of tokens.
* Also, the source must be regenerated exactly when the tokens are concatenated
* back together,
*/
static private void AssertTokenizeUnicode(string source, string expectedTokenKey)
{
// Most of the time, we expect the rebuilt source to be the same as the input source.
AssertTokenizeUnicode(source, source, expectedTokenKey);
}
/*
* Method: AssertTokenize
*
* Tokenize a string ('source') and compare it to the expected set of tokens.
* Also, the source must be regenerated exactly when the tokens are concatenated
* back together,
*/
static private void AssertTokenize
(
string source,
string expectedTokenKey,
int expectedLastLineNumber
)
{
// Most of the time, we expect the rebuilt source to be the same as the input source.
AssertTokenize(source, source, expectedTokenKey, expectedLastLineNumber);
}
/*
* Method: AssertTokenizeUnicode
*
* Tokenize a string ('source') and compare it to the expected set of tokens.
* Also, the source must be regenerated exactly when the tokens are concatenated
* back together,
*/
static private void AssertTokenizeUnicode
(
string source,
string expectedTokenKey,
int expectedLastLineNumber
)
{
// Most of the time, we expect the rebuilt source to be the same as the input source.
AssertTokenizeUnicode(source, source, expectedTokenKey, expectedLastLineNumber);
}
/*
* Method: AssertTokenize
*
* Tokenize a string ('source') and compare it to the expected set of tokens.
* Also compare the source that is regenerated by concatenating all of the tokens
* to 'expectedSource'.
*/
static private void AssertTokenize
(
string source,
string expectedSource,
string expectedTokenKey
)
{
// Two lines is the most common test case.
AssertTokenize(source, expectedSource, expectedTokenKey, 1);
}
/*
* Method: AssertTokenizeUnicode
*
* Tokenize a string ('source') and compare it to the expected set of tokens.
* Also compare the source that is regenerated by concatenating all of the tokens
* to 'expectedSource'.
*/
static private void AssertTokenizeUnicode
(
string source,
string expectedSource,
string expectedTokenKey
)
{
// Two lines is the most common test case.
AssertTokenizeUnicode(source, expectedSource, expectedTokenKey, 1);
}
/*
* Method: AssertTokenizeUnicode
*
* Tokenize a string ('source') and compare it to the expected set of tokens.
* Also compare the source that is regenerated by concatenating all of the tokens
* to 'expectedSource'.
*/
static private void AssertTokenizeUnicode
(
string source,
string expectedSource,
string expectedTokenKey,
int expectedLastLineNumber
)
{
AssertTokenizeStream
(
StreamHelpers.StringToStream(source, System.Text.Encoding.Unicode),
expectedSource,
expectedTokenKey,
expectedLastLineNumber
);
}
/*
* Method: AssertTokenize
*
* Tokenize a string ('source') and compare it to the expected set of tokens.
* Also compare the source that is regenerated by concatenating all of the tokens
* to 'expectedSource'.
*/
static private void AssertTokenize
(
string source,
string expectedSource,
string expectedTokenKey,
int expectedLastLineNumber
)
{
// This version of AssertTokenize tests several different encodings.
// The reason is that we want to be sure each of these works in the
// various encoding formats supported by C#
AssertTokenizeStream(StreamHelpers.StringToStream(source), expectedSource, expectedTokenKey, expectedLastLineNumber);
AssertTokenizeStream(StreamHelpers.StringToStream(source, System.Text.Encoding.Unicode), expectedSource, expectedTokenKey, expectedLastLineNumber);
AssertTokenizeStream(StreamHelpers.StringToStream(source, System.Text.Encoding.UTF8), expectedSource, expectedTokenKey, expectedLastLineNumber);
AssertTokenizeStream(StreamHelpers.StringToStream(source, System.Text.Encoding.BigEndianUnicode), expectedSource, expectedTokenKey, expectedLastLineNumber);
AssertTokenizeStream(StreamHelpers.StringToStream(source, System.Text.Encoding.UTF32), expectedSource, expectedTokenKey, expectedLastLineNumber);
AssertTokenizeStream(StreamHelpers.StringToStream(source, System.Text.Encoding.ASCII), expectedSource, expectedTokenKey, expectedLastLineNumber);
}
/*
* Method: AssertTokenizeStream
*
* Tokenize a string ('source') and compare it to the expected set of tokens.
* Also compare the source that is regenerated by concatenating all of the tokens
* to 'expectedSource'.
*/
static private void AssertTokenizeStream
(
Stream source,
string expectedSource,
string expectedTokenKey,
int expectedLastLineNumber
)
{
CSharpTokenizer tokens = new CSharpTokenizer
(
source,
false
);
string results = "";
string tokenKey = "";
int lastLine = 0;
bool syntaxError = false;
foreach (Token t in tokens)
{
results += t.InnerText;
lastLine = t.Line;
if (!syntaxError)
{
// Its not really a file name, but GetExtension serves the purpose of getting the class name without
// the namespace prepended.
string tokenClass = t.ToString();
int pos = tokenClass.LastIndexOfAny(new char[] { '+', '.' });
tokenKey += ".";
tokenKey += tokenClass.Substring(pos + 1);
}
if (t is SyntaxErrorToken)
{
// Stop processing after the first syntax error because
// the order of tokens after this is an implementation detail and
// shouldn't be encoded into the unit tests.
syntaxError = true;
}
}
tokenKey = tokenKey.Replace("Token", "");
Console.WriteLine(tokenKey);
Assert.Equal(expectedSource, results);
Assert.Equal(expectedTokenKey, tokenKey);
Assert.Equal(expectedLastLineNumber, lastLine);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Diagnostics;
using System.Reflection.Metadata.Ecma335;
namespace System.Reflection.Metadata
{
struct AssemblyReference
{
private readonly MetadataReader reader;
// Workaround: JIT doesn't generate good code for nested structures, so use raw uint.
private readonly uint treatmentAndRowId;
private static readonly Version version_1_1_0_0 = new Version(1, 1, 0, 0);
private static readonly Version version_4_0_0_0 = new Version(4, 0, 0, 0);
internal AssemblyReference(MetadataReader reader, uint treatmentAndRowId)
{
DebugCorlib.Assert(reader != null);
DebugCorlib.Assert(treatmentAndRowId != 0);
// only virtual bit can be set in highest byte:
DebugCorlib.Assert((treatmentAndRowId & ~(TokenTypeIds.VirtualTokenMask | TokenTypeIds.RIDMask)) == 0);
this.reader = reader;
this.treatmentAndRowId = treatmentAndRowId;
}
private uint RowId
{
get { return treatmentAndRowId & TokenTypeIds.RIDMask; }
}
private bool IsVirtual
{
get { return (treatmentAndRowId & TokenTypeIds.VirtualTokenMask) != 0; }
}
public Version Version
{
get
{
if (IsVirtual)
{
return GetVirtualVersion();
}
// change mscorlib version:
if (RowId == reader.WinMDMscorlibRef)
{
return version_4_0_0_0;
}
return reader.AssemblyRefTable.GetVersion(RowId);
}
}
public AssemblyFlags Flags
{
get
{
if (IsVirtual)
{
return GetVirtualFlags();
}
return reader.AssemblyRefTable.GetFlags(RowId);
}
}
public StringHandle Name
{
get
{
if (IsVirtual)
{
return GetVirtualName();
}
return reader.AssemblyRefTable.GetName(RowId);
}
}
public StringHandle Culture
{
get
{
if (IsVirtual)
{
return GetVirtualCulture();
}
return reader.AssemblyRefTable.GetCulture(RowId);
}
}
public BlobHandle PublicKeyOrToken
{
get
{
if (IsVirtual)
{
return GetVirtualPublicKeyOrToken();
}
return reader.AssemblyRefTable.GetPublicKeyOrToken(RowId);
}
}
public BlobHandle HashValue
{
get
{
if (IsVirtual)
{
return GetVirtualHashValue();
}
return reader.AssemblyRefTable.GetHashValue(RowId);
}
}
public CustomAttributeHandleCollection GetCustomAttributes()
{
if (IsVirtual)
{
return GetVirtualCustomAttributes();
}
return new CustomAttributeHandleCollection(reader, AssemblyReferenceHandle.FromRowId(RowId));
}
#region Virtual Rows
private Version GetVirtualVersion()
{
switch ((AssemblyReferenceHandle.VirtualIndex)RowId)
{
case AssemblyReferenceHandle.VirtualIndex.System_Numerics_Vectors:
return version_1_1_0_0;
default:
return version_4_0_0_0;
}
}
private AssemblyFlags GetVirtualFlags()
{
// use flags from mscorlib ref (specifically PublicKey flag):
return reader.AssemblyRefTable.GetFlags(reader.WinMDMscorlibRef);
}
private StringHandle GetVirtualName()
{
return StringHandle.FromVirtualIndex(GetVirtualNameIndex((AssemblyReferenceHandle.VirtualIndex)RowId));
}
private StringHandle.VirtualIndex GetVirtualNameIndex(AssemblyReferenceHandle.VirtualIndex index)
{
switch (index)
{
case AssemblyReferenceHandle.VirtualIndex.System_ObjectModel:
return StringHandle.VirtualIndex.System_ObjectModel;
case AssemblyReferenceHandle.VirtualIndex.System_Runtime:
return StringHandle.VirtualIndex.System_Runtime;
case AssemblyReferenceHandle.VirtualIndex.System_Runtime_InteropServices_WindowsRuntime:
return StringHandle.VirtualIndex.System_Runtime_InteropServices_WindowsRuntime;
case AssemblyReferenceHandle.VirtualIndex.System_Runtime_WindowsRuntime:
return StringHandle.VirtualIndex.System_Runtime_WindowsRuntime;
case AssemblyReferenceHandle.VirtualIndex.System_Runtime_WindowsRuntime_UI_Xaml:
return StringHandle.VirtualIndex.System_Runtime_WindowsRuntime_UI_Xaml;
case AssemblyReferenceHandle.VirtualIndex.System_Numerics_Vectors:
return StringHandle.VirtualIndex.System_Numerics_Vectors;
}
DebugCorlib.Assert(false, "Unexpected virtual index value");
return 0;
}
private StringHandle GetVirtualCulture()
{
return default(StringHandle);
}
private BlobHandle GetVirtualPublicKeyOrToken()
{
switch ((AssemblyReferenceHandle.VirtualIndex)RowId)
{
case AssemblyReferenceHandle.VirtualIndex.System_Runtime_WindowsRuntime:
case AssemblyReferenceHandle.VirtualIndex.System_Runtime_WindowsRuntime_UI_Xaml:
// use key or token from mscorlib ref:
return reader.AssemblyRefTable.GetPublicKeyOrToken(reader.WinMDMscorlibRef);
default:
// use contract assembly key or token:
var hasFullKey = (reader.AssemblyRefTable.GetFlags(reader.WinMDMscorlibRef) & AssemblyFlags.PublicKey) != 0;
return BlobHandle.FromVirtualIndex(hasFullKey ? BlobHandle.VirtualIndex.ContractPublicKey : BlobHandle.VirtualIndex.ContractPublicKeyToken, 0);
}
}
private BlobHandle GetVirtualHashValue()
{
return default(BlobHandle);
}
private CustomAttributeHandleCollection GetVirtualCustomAttributes()
{
// return custom attributes applied on mscorlib ref
return new CustomAttributeHandleCollection(reader, AssemblyReferenceHandle.FromRowId(reader.WinMDMscorlibRef));
}
#endregion
}
}
| |
// The MIT License (MIT)
//
// Copyright (c) 2014-2016, Institute for Software & Systems Engineering
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
namespace SafetySharp.Compiler.Analyzers
{
using JetBrains.Annotations;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Utilities;
/// <summary>
/// Represents a diagnostic produced by a <see cref="Analyzer" />, providing information about errors and
/// warnings in a S# model.
/// </summary>
public class DiagnosticInfo
{
/// <summary>
/// The prefix that is used for all diagnostic identifiers.
/// </summary>
public const string Prefix = "SS";
/// <summary>
/// The category that is used for all diagnostics.
/// </summary>
public const string Category = "SafetySharp";
/// <summary>
/// Initializes a new instance.
/// </summary>
private DiagnosticInfo()
{
}
/// <summary>
/// Gets the descriptor for the diagnostic emitted by the analyzer.
/// </summary>
public DiagnosticDescriptor Descriptor { get; private set; }
/// <summary>
/// Gets the identifier of the diagnostic.
/// </summary>
public DiagnosticIdentifier Id { get; private set; }
/// <summary>
/// Describes the error diagnostic of the analyzer.
/// </summary>
/// <param name="identifier">The identifier of the analyzer's diagnostic.</param>
/// <param name="description">The description of the diagnostic.</param>
/// <param name="messageFormat">The message format of the diagnostic.</param>
public static DiagnosticInfo Error(DiagnosticIdentifier identifier, [NotNull] string description, [NotNull] string messageFormat)
{
return Initialize(identifier, description, messageFormat, DiagnosticSeverity.Error);
}
/// <summary>
/// Describes the error diagnostic of the analyzer.
/// </summary>
/// <param name="identifier">The identifier of the analyzer's diagnostic.</param>
/// <param name="description">The description of the diagnostic.</param>
/// <param name="messageFormat">The message format of the diagnostic.</param>
public static DiagnosticInfo Warning(DiagnosticIdentifier identifier, [NotNull] string description, [NotNull] string messageFormat)
{
return Initialize(identifier, description, messageFormat, DiagnosticSeverity.Warning);
}
/// <summary>
/// Describes the error diagnostic of the analyzer.
/// </summary>
/// <param name="identifier">The identifier of the analyzer's diagnostic.</param>
/// <param name="description">The description of the diagnostic.</param>
/// <param name="messageFormat">The message format of the diagnostic.</param>
/// <param name="severity">The severity of the diagnostic.</param>
private static DiagnosticInfo Initialize(DiagnosticIdentifier identifier, [NotNull] string description,
[NotNull] string messageFormat, DiagnosticSeverity severity)
{
Requires.NotNullOrWhitespace(description, nameof(description));
Requires.NotNullOrWhitespace(messageFormat, nameof(messageFormat));
Requires.InRange(severity, nameof(severity));
return new DiagnosticInfo
{
Descriptor = new DiagnosticDescriptor(Prefix + (int)identifier, description, messageFormat, Category, severity, true),
Id = identifier
};
}
/// <summary>
/// Emits a diagnostic for <paramref name="symbol" /> using the <paramref name="messageArgs" /> to format the
/// diagnostic message.
/// </summary>
/// <param name="context">The context in which the diagnostic should be emitted.</param>
/// <param name="symbol">The symbol node the diagnostic is emitted for.</param>
/// <param name="messageArgs">The arguments for formatting the diagnostic message.</param>
public void Emit(CompilationAnalysisContext context, [NotNull] ISymbol symbol, params object[] messageArgs)
{
context.ReportDiagnostic(CreateDiagnostic(symbol.Locations[0], messageArgs));
}
/// <summary>
/// Emits a diagnostic for <paramref name="syntaxNode" /> using the <paramref name="messageArgs" /> to format the
/// diagnostic message.
/// </summary>
/// <param name="context">The context in which the diagnostic should be emitted.</param>
/// <param name="syntaxNode">The syntax node the diagnostic is emitted for.</param>
/// <param name="messageArgs">The arguments for formatting the diagnostic message.</param>
public void Emit(SyntaxNodeAnalysisContext context, [NotNull] SyntaxNode syntaxNode, params object[] messageArgs)
{
context.ReportDiagnostic(CreateDiagnostic(syntaxNode.GetLocation(), messageArgs));
}
/// <summary>
/// Emits a diagnostic for <paramref name="syntaxNode" /> using the <paramref name="messageArgs" /> to format the
/// diagnostic message.
/// </summary>
/// <param name="context">The context in which the diagnostic should be emitted.</param>
/// <param name="syntaxNode">The syntax node the diagnostic is emitted for.</param>
/// <param name="messageArgs">The arguments for formatting the diagnostic message.</param>
public void Emit(SyntaxTreeAnalysisContext context, [NotNull] SyntaxNode syntaxNode, params object[] messageArgs)
{
context.ReportDiagnostic(CreateDiagnostic(syntaxNode.GetLocation(), messageArgs));
}
/// <summary>
/// Emits a diagnostic for <paramref name="syntaxToken" /> using the <paramref name="messageArgs" /> to format the
/// diagnostic message.
/// </summary>
/// <param name="context">The context in which the diagnostic should be emitted.</param>
/// <param name="syntaxToken">The syntax token the diagnostic is emitted for.</param>
/// <param name="messageArgs">The arguments for formatting the diagnostic message.</param>
public void Emit(SyntaxTreeAnalysisContext context, SyntaxToken syntaxToken, params object[] messageArgs)
{
context.ReportDiagnostic(CreateDiagnostic(syntaxToken.GetLocation(), messageArgs));
}
/// <summary>
/// Emits a diagnostic for <paramref name="syntaxNode" /> using the <paramref name="messageArgs" /> to format the
/// diagnostic message.
/// </summary>
/// <param name="context">The context in which the diagnostic should be emitted.</param>
/// <param name="syntaxNode">The syntax node the diagnostic is emitted for.</param>
/// <param name="messageArgs">The arguments for formatting the diagnostic message.</param>
public void Emit(SemanticModelAnalysisContext context, [NotNull] SyntaxNode syntaxNode, params object[] messageArgs)
{
context.ReportDiagnostic(CreateDiagnostic(syntaxNode.GetLocation(), messageArgs));
}
/// <summary>
/// Emits a diagnostic for <paramref name="syntaxToken" /> using the <paramref name="messageArgs" /> to format the
/// diagnostic message.
/// </summary>
/// <param name="context">The context in which the diagnostic should be emitted.</param>
/// <param name="syntaxToken">The syntax token the diagnostic is emitted for.</param>
/// <param name="messageArgs">The arguments for formatting the diagnostic message.</param>
public void Emit(SemanticModelAnalysisContext context, SyntaxToken syntaxToken, params object[] messageArgs)
{
context.ReportDiagnostic(CreateDiagnostic(syntaxToken.GetLocation(), messageArgs));
}
/// <summary>
/// Emits a diagnostic for <paramref name="location" /> using the <paramref name="messageArgs" /> to format the
/// diagnostic message.
/// </summary>
/// <param name="context">The context in which the diagnostic should be emitted.</param>
/// <param name="location">The location the diagnostic is emitted for.</param>
/// <param name="messageArgs">The arguments for formatting the diagnostic message.</param>
public void Emit(SemanticModelAnalysisContext context, [NotNull] Location location, params object[] messageArgs)
{
context.ReportDiagnostic(CreateDiagnostic(location, messageArgs));
}
/// <summary>
/// Emits a diagnostic for <paramref name="symbol" /> using the <paramref name="messageArgs" /> to format the diagnostic
/// message.
/// </summary>
/// <param name="context">The context in which the diagnostic should be emitted.</param>
/// <param name="symbol">The symbol the diagnostic is emitted for.</param>
/// <param name="messageArgs">The arguments for formatting the diagnostic message.</param>
public void Emit(SymbolAnalysisContext context, [NotNull] ISymbol symbol, params object[] messageArgs)
{
context.ReportDiagnostic(CreateDiagnostic(symbol.Locations[0], messageArgs));
}
/// <summary>
/// Creates a diagnostic for <paramref name="location" /> using the <paramref name="messageArgs" /> to format the
/// diagnostic message.
/// </summary>
/// <param name="location">The location the diagnostic is emitted for.</param>
/// <param name="messageArgs">The arguments for formatting the diagnostic message.</param>
public Diagnostic CreateDiagnostic([NotNull] Location location, params object[] messageArgs)
{
return Diagnostic.Create(Descriptor, location, messageArgs);
}
}
}
| |
//
// (C) Copyright 2003-2011 by Autodesk, Inc.
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
//
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.Xml;
using Autodesk.Revit;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
namespace Revit.SDK.Samples.AllViews.CS
{
/// <summary>
/// Implements the Revit add-in interface IExternalCommand
/// </summary>
[Autodesk.Revit.Attributes.Transaction(Autodesk.Revit.Attributes.TransactionMode.Manual)]
[Autodesk.Revit.Attributes.Regeneration(Autodesk.Revit.Attributes.RegenerationOption.Manual)]
[Autodesk.Revit.Attributes.Journaling(Autodesk.Revit.Attributes.JournalingMode.NoCommandData)]
public class Command : IExternalCommand
{
#region IExternalCommand Members Implementation
/// <summary>
/// Implement this method as an external command for Revit.
/// </summary>
/// <param name="commandData">An object that is passed to the external application
/// which contains data related to the command,
/// such as the application object and active view.</param>
/// <param name="message">A message that can be set by the external application
/// which will be displayed if a failure or cancellation is returned by
/// the external command.</param>
/// <param name="elements">A set of elements to which the external application
/// can add elements that are to be highlighted in case of failure or cancellation.</param>
/// <returns>Return the status of the external command.
/// A result of Succeeded means that the API external method functioned as expected.
/// Cancelled can be used to signify that the user cancelled the external operation
/// at some point. Failure should be returned if the application is unable to proceed with
/// the operation.</returns>
public Autodesk.Revit.UI.Result Execute(Autodesk.Revit.UI.ExternalCommandData commandData,
ref string message, Autodesk.Revit.DB.ElementSet elements)
{
Transaction newTran = null;
try
{
if (null == commandData)
{
throw new ArgumentNullException("commandData");
}
Document doc = commandData.Application.ActiveUIDocument.Document;
ViewsMgr view = new ViewsMgr(doc);
newTran = new Transaction(doc);
newTran.Start("AllViews_Sample");
AllViewsForm dlg = new AllViewsForm(view);
if (dlg.ShowDialog() == DialogResult.OK)
{
view.GenerateSheet(doc);
}
newTran.Commit();
return Autodesk.Revit.UI.Result.Succeeded;
}
catch (Exception e)
{
message = e.Message;
if ((newTran != null) && newTran.HasStarted() && !newTran.HasEnded())
newTran.RollBack();
return Autodesk.Revit.UI.Result.Failed;
}
}
#endregion IExternalCommand Members Implementation
}
/// <summary>
/// Generating a new sheet that has all the selected views placed in.
/// </summary>
public class ViewsMgr
{
private TreeNode m_allViewsNames = new TreeNode("Views (all)");
private ViewSet m_allViews = new ViewSet();
private ViewSet m_selectedViews = new ViewSet();
private FamilySymbol m_titleBlock;
private FamilySymbolSet m_allTitleBlocks = new FamilySymbolSet();
private ArrayList m_allTitleBlocksNames = new ArrayList();
private string m_sheetName;
private double m_rows;
private double TITLEBAR = 0.2;
private double GOLDENSECTION = 0.618;
/// <summary>
/// Tree node store all views' names.
/// </summary>
public TreeNode AllViewsNames
{
get
{
return m_allViewsNames;
}
}
/// <summary>
/// List of all title blocks' names.
/// </summary>
public ArrayList AllTitleBlocksNames
{
get
{
return m_allTitleBlocksNames;
}
}
/// <summary>
/// The selected sheet's name.
/// </summary>
public string SheetName
{
get
{
return m_sheetName;
}
set
{
m_sheetName = value;
}
}
/// <summary>
/// Constructor of views object.
/// </summary>
/// <param name="doc">the active document</param>
public ViewsMgr(Document doc)
{
GetAllViews(doc);
GetTitleBlocks(doc);
}
/// <summary>
/// Finds all the views in the active document.
/// </summary>
/// <param name="doc">the active document</param>
private void GetAllViews(Document doc)
{
FilteredElementCollector collector = new FilteredElementCollector(doc);
FilteredElementIterator itor = collector.OfClass(typeof(Autodesk.Revit.DB.View)).GetElementIterator();
itor.Reset();
while (itor.MoveNext())
{
Autodesk.Revit.DB.View view = itor.Current as Autodesk.Revit.DB.View;
// skip view templates because they're invisible in project browser
if (null == view || view.IsTemplate)
{
continue;
}
else
{
ElementType objType = doc.get_Element(view.GetTypeId()) as ElementType;
if (null == objType || objType.Name.Equals("Schedule")
|| objType.Name.Equals("Drawing Sheet"))
{
continue;
}
else
{
m_allViews.Insert(view);
AssortViews(view.Name, objType.Name);
}
}
}
}
/// <summary>
/// Assort all views for tree view displaying.
/// </summary>
/// <param name="view">The view assorting</param>
/// <param name="type">The type of view</param>
private void AssortViews(string view, string type)
{
foreach (TreeNode t in AllViewsNames.Nodes)
{
if (t.Tag.Equals(type))
{
t.Nodes.Add(new TreeNode(view));
return;
}
}
TreeNode categoryNode = new TreeNode(type);
categoryNode.Tag = type;
if (type.Equals("Building Elevation"))
{
categoryNode.Text = "Elevations [" + type + "]";
}
else
{
categoryNode.Text = type + "s";
}
categoryNode.Nodes.Add(new TreeNode(view));
AllViewsNames.Nodes.Add(categoryNode);
}
/// <summary>
/// Retrieve the checked view from tree view.
/// </summary>
public void SelectViews()
{
ArrayList names = new ArrayList();
foreach (TreeNode t in AllViewsNames.Nodes)
{
foreach (TreeNode n in t.Nodes)
{
if (n.Checked && 0 == n.Nodes.Count)
{
names.Add(n.Text);
}
}
}
foreach (Autodesk.Revit.DB.View v in m_allViews)
{
foreach (string s in names)
{
if (s.Equals(v.Name))
{
m_selectedViews.Insert(v);
break;
}
}
}
}
/// <summary>
/// Generate sheet in active document.
/// </summary>
/// <param name="doc">the currently active document</param>
public void GenerateSheet(Document doc)
{
if (null == doc)
{
throw new ArgumentNullException("doc");
}
if (0 == m_selectedViews.Size)
{
throw new InvalidOperationException("No view be selected, generate sheet be cancelled.");
}
ViewSheet sheet = doc.Create.NewViewSheet(m_titleBlock);
sheet.Name = SheetName;
PlaceViews(m_selectedViews, sheet);
}
/// <summary>
/// Retrieve the title block to be generate by its name.
/// </summary>
/// <param name="name">The title block's name</param>
public void ChooseTitleBlock(string name)
{
if (string.IsNullOrEmpty(name))
{
throw new ArgumentNullException("name");
}
foreach (FamilySymbol f in m_allTitleBlocks)
{
if (name.Equals(f.Name))
{
m_titleBlock = f;
return;
}
}
}
/// <summary>
/// Retrieve all available title blocks in the currently active document.
/// </summary>
/// <param name="doc">the currently active document</param>
private void GetTitleBlocks(Document doc)
{
m_allTitleBlocks = doc.TitleBlocks;
if (0 == m_allTitleBlocks.Size)
{
throw new InvalidOperationException("There is no title block to generate sheet.");
}
foreach (FamilySymbol f in m_allTitleBlocks)
{
AllTitleBlocksNames.Add(f.Name);
if (null == m_titleBlock)
{
m_titleBlock = f;
}
}
}
/// <summary>
/// Place all selected views on this sheet's appropriate location.
/// </summary>
/// <param name="views">all selected views</param>
/// <param name="sheet">all views located sheet</param>
private void PlaceViews(ViewSet views, ViewSheet sheet)
{
double xDistance = 0;
double yDistance = 0;
CalculateDistance(sheet.Outline, views.Size, ref xDistance, ref yDistance);
Autodesk.Revit.DB.UV origin = GetOffSet(sheet.Outline, xDistance, yDistance);
//Autodesk.Revit.DB.UV temp = new Autodesk.Revit.DB.UV (origin.U, origin.V);
double tempU = origin.U;
double tempV = origin.V;
int n = 1;
foreach (Autodesk.Revit.DB.View v in views)
{
Autodesk.Revit.DB.UV location = new Autodesk.Revit.DB.UV (tempU, tempV);
Autodesk.Revit.DB.View view = v;
Rescale(view, xDistance, yDistance);
try
{
sheet.AddView(view, location);
}
catch (ArgumentException /*ae*/)
{
throw new InvalidOperationException("The view '" + view.Name +
"' can't be added, it may have already been placed in another sheet.");
}
if (0 != n++ % m_rows)
{
tempU = tempU + xDistance * (1 - TITLEBAR);
}
else
{
tempU = origin.U;
tempV = tempV + yDistance;
}
}
}
/// <summary>
/// Retrieve the appropriate origin.
/// </summary>
/// <param name="bBox"></param>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns></returns>
private Autodesk.Revit.DB.UV GetOffSet(BoundingBoxUV bBox, double x, double y)
{
return new Autodesk.Revit.DB.UV(bBox.Min.U + x * GOLDENSECTION, bBox.Min.V + y * GOLDENSECTION);
}
/// <summary>
/// Calculate the appropriate distance between the views lay on the sheet.
/// </summary>
/// <param name="bBox">The outline of sheet.</param>
/// <param name="amount">Amount of views.</param>
/// <param name="x">Distance in x axis between each view</param>
/// <param name="y">Distance in y axis between each view</param>
private void CalculateDistance(BoundingBoxUV bBox, int amount, ref double x, ref double y)
{
double xLength = (bBox.Max.U - bBox.Min.U) * (1 - TITLEBAR);
double yLength = (bBox.Max.V - bBox.Min.V);
//calculate appropriate rows numbers.
double result = Math.Sqrt(amount);
while (0 < (result - (int)result))
{
amount = amount + 1;
result = Math.Sqrt(amount);
}
m_rows = result;
double area = xLength * yLength / amount;
//calculate appropriate distance between the views.
if (bBox.Max.U > bBox.Max.V)
{
x = Math.Sqrt(area / GOLDENSECTION);
y = GOLDENSECTION * x;
}
else
{
y = Math.Sqrt(area / GOLDENSECTION);
x = GOLDENSECTION * y;
}
}
/// <summary>
/// Rescale the view's Scale value for suitable.
/// </summary>
/// <param name="view">The view to be located on sheet.</param>
/// <param name="x">Distance in x axis between each view</param>
/// <param name="y">Distance in y axis between each view</param>
static private void Rescale(Autodesk.Revit.DB.View view, double x, double y)
{
double Rescale = 2;
Autodesk.Revit.DB.UV outline = new Autodesk.Revit.DB.UV (view.Outline.Max.U - view.Outline.Min.U,
view.Outline.Max.V - view.Outline.Min.V);
if (outline.U > outline.V)
{
Rescale = outline.U / x * Rescale;
}
else
{
Rescale = outline.V / y * Rescale;
}
if (1 != view.Scale && 0 != Rescale)
{
view.Scale = (int)(view.Scale * Rescale);
}
}
}
}
| |
using System;
using System.Collections;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Media;
using Avalon.Windows.Internal.Utility;
namespace Avalon.Windows.Controls
{
/// <summary>
/// Provides a host for <see cref="InlineModalDialog"/>s.
/// </summary>
[StyleTypedProperty(Property = "BlurrerStyle", StyleTargetType = typeof(Border))]
public class InlineModalDecorator : Decorator
{
#region Fields
private const int DefaultChildIndex = 1;
private const int BlurrerAnimationDurationMs = 500;
private readonly Grid _panel;
private readonly Border _blurrer;
private bool _hasChild;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="InlineModalDecorator"/> class.
/// </summary>
public InlineModalDecorator()
{
_panel = new Grid();
AddVisualChild(_panel);
AddLogicalChild(_panel);
_blurrer = new Border { Visibility = Visibility.Collapsed };
_blurrer.SetBinding(StyleProperty, new Binding { Source = this, Path = new PropertyPath(BlurrerStyleProperty) });
_panel.Children.Add(_blurrer);
}
#endregion
#region Properties
/// <summary>
/// Identifies the <see cref="Target"/> dependency property.
/// </summary>
public static readonly DependencyProperty TargetProperty = DependencyProperty.Register(
"Target", typeof(UIElement), typeof(InlineModalDecorator), new FrameworkPropertyMetadata(OnTargetChanged));
private static void OnTargetChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var oldValue = (UIElement)e.OldValue;
if (oldValue != null)
{
InlineModalDialog.ClearModalDecorator(oldValue);
}
var newValue = (UIElement)e.NewValue;
if (newValue != null)
{
InlineModalDialog.SetModalDecorator(newValue, (InlineModalDecorator)d);
}
}
/// <summary>
/// Gets or sets the dialog decorator target.
/// This element will be marked as the root element under which inline dialogs can be used.
/// </summary>
public UIElement Target
{
get { return (UIElement)GetValue(TargetProperty); }
set { SetValue(TargetProperty, value); }
}
/// <summary>
/// Gets the current modal count.
/// </summary>
/// <value>The modal count.</value>
public int ModalCount
{
get { return (int)GetValue(ModalCountProperty); }
private set { SetValue(ModalCountPropertyKey, value); }
}
private static readonly DependencyPropertyKey ModalCountPropertyKey =
DependencyProperty.RegisterReadOnly("ModalCount", typeof(int), typeof(InlineModalDecorator), new FrameworkPropertyMetadata(0));
/// <summary>
/// Identifies the <see cref="ModalCount"/> dependency property.
/// </summary>
public static readonly DependencyProperty ModalCountProperty = ModalCountPropertyKey.DependencyProperty;
/// <summary>
/// Gets or sets the blurrer style.
/// <remarks>
/// The blurrer is a <see cref="Border"/>.
/// </remarks>
/// </summary>
/// <value>The blurrer style.</value>
public Style BlurrerStyle
{
get { return (Style)GetValue(BlurrerStyleProperty); }
set { SetValue(BlurrerStyleProperty, value); }
}
/// <summary>
/// Identifies the <see cref="BlurrerStyle"/> dependency property.
/// </summary>
public static readonly DependencyProperty BlurrerStyleProperty =
DependencyProperty.Register("BlurrerStyle", typeof(Style), typeof(InlineModalDecorator), new FrameworkPropertyMetadata(GetDefaultBlurrerStyle()));
private static Style GetDefaultBlurrerStyle()
{
var style = new Style(typeof(Border));
style.Setters.Add(new Setter(Border.BackgroundProperty, Brushes.Black));
style.Setters.Add(new Setter(OpacityProperty, 0.2D));
style.Seal();
return style;
}
#endregion
#region Overrides
/// <summary>
/// Gets or sets the child element.
/// </summary>
public override UIElement Child
{
get
{
return _hasChild ? _panel.Children[DefaultChildIndex] : null;
}
set
{
if (_hasChild)
{
_panel.Children.RemoveAt(DefaultChildIndex);
}
if (value != null)
{
Panel.SetZIndex(value, -1);
_panel.Children.Insert(DefaultChildIndex, value);
_hasChild = true;
}
else
{
_hasChild = false;
}
}
}
/// <summary>
/// Gets the logical children.
/// </summary>
protected override IEnumerator LogicalChildren
{
get { yield return _panel; }
}
/// <summary>
/// Gets the visual children count.
/// </summary>
protected override int VisualChildrenCount
{
get { return 1; }
}
/// <summary>
/// Gets the visual child at the specified index.
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
protected override Visual GetVisualChild(int index)
{
if (index > 0)
{
throw new ArgumentOutOfRangeException("index");
}
return _panel;
}
/// <summary>
/// Measures the element.
/// </summary>
/// <param name="constraint"></param>
/// <returns></returns>
protected override Size MeasureOverride(Size constraint)
{
_panel.Measure(constraint);
return _panel.DesiredSize;
}
/// <summary>
/// Arranges the element.
/// </summary>
/// <param name="arrangeSize"></param>
/// <returns></returns>
protected override Size ArrangeOverride(Size arrangeSize)
{
_panel.Arrange(new Rect(new Point(), arrangeSize));
return _panel.RenderSize;
}
#endregion
#region Internal Methods
internal void AddModal(UIElement newElement)
{
AddModal(newElement, true);
}
internal void AddModal(UIElement newElement, bool showBlurrer)
{
int childCount = _panel.Children.Count;
if (childCount > 1)
{
UIElement child = PeekChild();
child.IsHitTestVisible = false;
}
if (childCount <= 2 && showBlurrer)
{
_blurrer.InvalidateArrange();
Animator.AnimatePropertyFromTo(_blurrer, OpacityProperty, 0, null, BlurrerAnimationDurationMs);
_blurrer.Visibility = Visibility.Visible;
}
_panel.Children.Add(CreateDecorator(newElement));
UpdateModalCount();
}
internal void RemoveModal(UIElement closingElement)
{
RemoveModal(closingElement, true);
}
internal void RemoveModal(UIElement closingElement, bool hideBlurrer)
{
if (_panel.Children.Count <= 1) return;
var decorator = PeekChild() as Decorator;
if (decorator == null) return;
var element = decorator.Child;
if (!ReferenceEquals(element, closingElement)) return;
_panel.Children.Remove(decorator);
int childCount = _panel.Children.Count;
if (childCount > 0)
{
var child = PeekChild();
child.IsHitTestVisible = true;
if (childCount <= 2 && hideBlurrer)
{
Animator.AnimatePropertyFromTo(_blurrer, OpacityProperty, null, 0, BlurrerAnimationDurationMs, HideBlurrer);
}
}
UpdateModalCount();
}
internal UIElement TopmostModal
{
get
{
var decorator = PeekChild() as Decorator;
return decorator != null ? decorator.Child : null;
}
}
#endregion
#region Private Methods
private static Decorator CreateDecorator(UIElement element)
{
var decorator = new Decorator
{
Child = element
};
KeyboardNavigation.SetTabNavigation(decorator, KeyboardNavigationMode.Cycle);
KeyboardNavigation.SetControlTabNavigation(decorator, KeyboardNavigationMode.Cycle);
KeyboardNavigation.SetDirectionalNavigation(decorator, KeyboardNavigationMode.Cycle);
return decorator;
}
private UIElement PeekChild()
{
return _panel.Children[_panel.Children.Count - 1];
}
private void UpdateModalCount()
{
ModalCount = _panel.Children.Count - 2;
}
private void HideBlurrer(object sender, EventArgs e)
{
_blurrer.Visibility = Visibility.Collapsed;
}
#endregion
}
}
| |
#define SQLITE_ASCII
#define SQLITE_DISABLE_LFS
#define SQLITE_ENABLE_OVERSIZE_CELL_CHECK
#define SQLITE_MUTEX_OMIT
#define SQLITE_OMIT_AUTHORIZATION
#define SQLITE_OMIT_DEPRECATED
#define SQLITE_OMIT_GET_TABLE
#define SQLITE_OMIT_INCRBLOB
#define SQLITE_OMIT_LOOKASIDE
#define SQLITE_OMIT_SHARED_CACHE
#define SQLITE_OMIT_UTF16
#define SQLITE_OMIT_WAL
#define SQLITE_OS_WIN
#define SQLITE_SYSTEM_MALLOC
#define VDBE_PROFILE_OFF
#define WINDOWS_MOBILE
#define NDEBUG
#define _MSC_VER
#define YYFALLBACK
using System.Diagnostics;
using System.Text;
using HANDLE = System.IntPtr;
using i64 = System.Int64;
using u32 = System.UInt32;
using sqlite3_int64 = System.Int64;
namespace Community.CsharpSqlite
{
public partial class Sqlite3
{
/*
** 2005 November 29
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
******************************************************************************
**
** This file contains OS interface code that is common to all
** architectures.
*************************************************************************
** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
** C#-SQLite is an independent reimplementation of the SQLite software library
**
** SQLITE_SOURCE_ID: 2010-12-07 20:14:09 a586a4deeb25330037a49df295b36aaf624d0f45
**
*************************************************************************
*/
//#define _SQLITE_OS_C_ 1
//#include "sqliteInt.h"
//#undef _SQLITE_OS_C_
/*
** The default SQLite sqlite3_vfs implementations do not allocate
** memory (actually, os_unix.c allocates a small amount of memory
** from within OsOpen()), but some third-party implementations may.
** So we test the effects of a malloc() failing and the sqlite3OsXXX()
** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
**
** The following functions are instrumented for malloc() failure
** testing:
**
** sqlite3OsOpen()
** sqlite3OsRead()
** sqlite3OsWrite()
** sqlite3OsSync()
** sqlite3OsLock()
**
*/
#if (SQLITE_TEST)
static int sqlite3_memdebug_vfs_oom_test = 1;
//#define DO_OS_MALLOC_TEST(x) \
//if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3IsMemJournal(x))) { \
// void *pTstAlloc = sqlite3Malloc(10); \
// if (!pTstAlloc) return SQLITE_IOERR_NOMEM; \
// sqlite3_free(pTstAlloc); \
//}
static void DO_OS_MALLOC_TEST( sqlite3_file x )
{
}
#else
//#define DO_OS_MALLOC_TEST(x)
static void DO_OS_MALLOC_TEST( sqlite3_file x ) { }
#endif
/*
** The following routines are convenience wrappers around methods
** of the sqlite3_file object. This is mostly just syntactic sugar. All
** of this would be completely automatic if SQLite were coded using
** C++ instead of plain old C.
*/
static int sqlite3OsClose( sqlite3_file pId )
{
int rc = SQLITE_OK;
if ( pId.pMethods != null )
{
rc = pId.pMethods.xClose( pId );
pId.pMethods = null;
}
return rc;
}
static int sqlite3OsRead( sqlite3_file id, byte[] pBuf, int amt, i64 offset )
{
DO_OS_MALLOC_TEST( id );
if ( pBuf == null )
pBuf = sqlite3Malloc( amt );
return id.pMethods.xRead( id, pBuf, amt, offset );
}
static int sqlite3OsWrite( sqlite3_file id, byte[] pBuf, int amt, i64 offset )
{
DO_OS_MALLOC_TEST( id );
return id.pMethods.xWrite( id, pBuf, amt, offset );
}
static int sqlite3OsTruncate( sqlite3_file id, i64 size )
{
return id.pMethods.xTruncate( id, size );
}
static int sqlite3OsSync( sqlite3_file id, int flags )
{
DO_OS_MALLOC_TEST( id );
return id.pMethods.xSync( id, flags );
}
static int sqlite3OsFileSize( sqlite3_file id, ref long pSize )
{
return id.pMethods.xFileSize( id, ref pSize );
}
static int sqlite3OsLock( sqlite3_file id, int lockType )
{
DO_OS_MALLOC_TEST( id );
return id.pMethods.xLock( id, lockType );
}
static int sqlite3OsUnlock( sqlite3_file id, int lockType )
{
return id.pMethods.xUnlock( id, lockType );
}
static int sqlite3OsCheckReservedLock( sqlite3_file id, ref int pResOut )
{
DO_OS_MALLOC_TEST( id );
return id.pMethods.xCheckReservedLock( id, ref pResOut );
}
static int sqlite3OsFileControl( sqlite3_file id, u32 op, ref sqlite3_int64 pArg )
{
return id.pMethods.xFileControl( id, (int)op, ref pArg );
}
static int sqlite3OsSectorSize( sqlite3_file id )
{
dxSectorSize xSectorSize = id.pMethods.xSectorSize;
return ( xSectorSize != null ? xSectorSize( id ) : SQLITE_DEFAULT_SECTOR_SIZE );
}
static int sqlite3OsDeviceCharacteristics( sqlite3_file id )
{
return id.pMethods.xDeviceCharacteristics( id );
}
static int sqlite3OsShmLock( sqlite3_file id, int offset, int n, int flags )
{
return id.pMethods.xShmLock( id, offset, n, flags );
}
static void sqlite3OsShmBarrier( sqlite3_file id )
{
id.pMethods.xShmBarrier( id );
}
static int sqlite3OsShmUnmap( sqlite3_file id, int deleteFlag )
{
return id.pMethods.xShmUnmap( id, deleteFlag );
}
static int sqlite3OsShmMap(
sqlite3_file id, /* Database file handle */
int iPage,
int pgsz,
int bExtend, /* True to extend file if necessary */
out object pp /* OUT: Pointer to mapping */
)
{
return id.pMethods.xShmMap( id, iPage, pgsz, bExtend, out pp );
}
/*
** The next group of routines are convenience wrappers around the
** VFS methods.
*/
static int sqlite3OsOpen(
sqlite3_vfs pVfs,
string zPath,
sqlite3_file pFile,
int flags,
ref int pFlagsOut
)
{
int rc;
DO_OS_MALLOC_TEST( null );
/* 0x87f3f is a mask of SQLITE_OPEN_ flags that are valid to be passed
** down into the VFS layer. Some SQLITE_OPEN_ flags (for example,
** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
** reaching the VFS. */
rc = pVfs.xOpen( pVfs, zPath, pFile, flags & 0x87f3f, out pFlagsOut );
Debug.Assert( rc == SQLITE_OK || pFile.pMethods == null );
return rc;
}
static int sqlite3OsDelete( sqlite3_vfs pVfs, string zPath, int dirSync )
{
return pVfs.xDelete( pVfs, zPath, dirSync );
}
static int sqlite3OsAccess( sqlite3_vfs pVfs, string zPath, int flags, ref int pResOut )
{
DO_OS_MALLOC_TEST( null );
return pVfs.xAccess( pVfs, zPath, flags, out pResOut );
}
static int sqlite3OsFullPathname(
sqlite3_vfs pVfs,
string zPath,
int nPathOut,
StringBuilder zPathOut
)
{
zPathOut.Length = 0;//zPathOut[0] = 0;
return pVfs.xFullPathname( pVfs, zPath, nPathOut, zPathOut );
}
#if !SQLITE_OMIT_LOAD_EXTENSION
static HANDLE sqlite3OsDlOpen( sqlite3_vfs pVfs, string zPath )
{
return pVfs.xDlOpen( pVfs, zPath );
}
static void sqlite3OsDlError( sqlite3_vfs pVfs, int nByte, string zBufOut )
{
pVfs.xDlError( pVfs, nByte, zBufOut );
}
static object sqlite3OsDlSym( sqlite3_vfs pVfs, HANDLE pHdle, ref string zSym )
{
return pVfs.xDlSym( pVfs, pHdle, zSym );
}
static void sqlite3OsDlClose( sqlite3_vfs pVfs, HANDLE pHandle )
{
pVfs.xDlClose( pVfs, pHandle );
}
#endif
static int sqlite3OsRandomness( sqlite3_vfs pVfs, int nByte, byte[] zBufOut )
{
return pVfs.xRandomness( pVfs, nByte, zBufOut );
}
static int sqlite3OsSleep( sqlite3_vfs pVfs, int nMicro )
{
return pVfs.xSleep( pVfs, nMicro );
}
static int sqlite3OsCurrentTimeInt64( sqlite3_vfs pVfs, ref sqlite3_int64 pTimeOut )
{
int rc;
/* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64()
** method to get the current date and time if that method is available
** (if iVersion is 2 or greater and the function pointer is not NULL) and
** will fall back to xCurrentTime() if xCurrentTimeInt64() is
** unavailable.
*/
if ( pVfs.iVersion >= 2 && pVfs.xCurrentTimeInt64 != null )
{
rc = pVfs.xCurrentTimeInt64( pVfs, ref pTimeOut );
}
else
{
double r = 0;
rc = pVfs.xCurrentTime( pVfs, ref r );
pTimeOut = (sqlite3_int64)( r * 86400000.0 );
}
return rc;
}
static int sqlite3OsOpenMalloc(
ref sqlite3_vfs pVfs,
string zFile,
ref sqlite3_file ppFile,
int flags,
ref int pOutFlags
)
{
int rc = SQLITE_NOMEM;
sqlite3_file pFile;
pFile = new sqlite3_file(); //sqlite3Malloc(ref pVfs.szOsFile);
if ( pFile != null )
{
rc = sqlite3OsOpen( pVfs, zFile, pFile, flags, ref pOutFlags );
if ( rc != SQLITE_OK )
{
pFile = null; // was sqlite3DbFree(db,ref pFile);
}
else
{
ppFile = pFile;
}
}
return rc;
}
static int sqlite3OsCloseFree( sqlite3_file pFile )
{
int rc = SQLITE_OK;
Debug.Assert( pFile != null );
rc = sqlite3OsClose( pFile );
//sqlite3_free( ref pFile );
return rc;
}
/*
** This function is a wrapper around the OS specific implementation of
** sqlite3_os_init(). The purpose of the wrapper is to provide the
** ability to simulate a malloc failure, so that the handling of an
** error in sqlite3_os_init() by the upper layers can be tested.
*/
static int sqlite3OsInit()
{
//void *p = sqlite3_malloc(10);
//if( p==null ) return SQLITE_NOMEM;
//sqlite3_free(ref p);
return sqlite3_os_init();
}
/*
** The list of all registered VFS implementations.
*/
static sqlite3_vfs vfsList;
//#define vfsList GLOBAL(sqlite3_vfs *, vfsList)
/*
** Locate a VFS by name. If no name is given, simply return the
** first VFS on the list.
*/
//static bool isInit = false;
static sqlite3_vfs sqlite3_vfs_find( string zVfs )
{
sqlite3_vfs pVfs = null;
#if SQLITE_THREADSAFE
sqlite3_mutex mutex;
#endif
#if !SQLITE_OMIT_AUTOINIT
int rc = sqlite3_initialize();
if ( rc != 0 )
return null;
#endif
#if SQLITE_THREADSAFE
mutex = sqlite3MutexAlloc( SQLITE_MUTEX_STATIC_MASTER );
#endif
sqlite3_mutex_enter( mutex );
for ( pVfs = vfsList; pVfs != null; pVfs = pVfs.pNext )
{
if ( zVfs == null || zVfs == "" )
break;
if ( zVfs == pVfs.zName )
break; //strcmp(zVfs, pVfs.zName) == null) break;
}
sqlite3_mutex_leave( mutex );
return pVfs;
}
/*
** Unlink a VFS from the linked list
*/
static void vfsUnlink( sqlite3_vfs pVfs )
{
Debug.Assert( sqlite3_mutex_held( sqlite3MutexAlloc( SQLITE_MUTEX_STATIC_MASTER ) ) );
if ( pVfs == null )
{
/* No-op */
}
else if ( vfsList == pVfs )
{
vfsList = pVfs.pNext;
}
else if ( vfsList != null )
{
sqlite3_vfs p = vfsList;
while ( p.pNext != null && p.pNext != pVfs )
{
p = p.pNext;
}
if ( p.pNext == pVfs )
{
p.pNext = pVfs.pNext;
}
}
}
/*
** Register a VFS with the system. It is harmless to register the same
** VFS multiple times. The new VFS becomes the default if makeDflt is
** true.
*/
static int sqlite3_vfs_register( sqlite3_vfs pVfs, int makeDflt )
{
sqlite3_mutex mutex;
#if !SQLITE_OMIT_AUTOINIT
int rc = sqlite3_initialize();
if ( rc != 0 )
return rc;
#endif
mutex = sqlite3MutexAlloc( SQLITE_MUTEX_STATIC_MASTER );
sqlite3_mutex_enter( mutex );
vfsUnlink( pVfs );
if ( makeDflt != 0 || vfsList == null )
{
pVfs.pNext = vfsList;
vfsList = pVfs;
}
else
{
pVfs.pNext = vfsList.pNext;
vfsList.pNext = pVfs;
}
Debug.Assert( vfsList != null );
sqlite3_mutex_leave( mutex );
return SQLITE_OK;
}
/*
** Unregister a VFS so that it is no longer accessible.
*/
static int sqlite3_vfs_unregister( sqlite3_vfs pVfs )
{
#if SQLITE_THREADSAFE
sqlite3_mutex mutex = sqlite3MutexAlloc( SQLITE_MUTEX_STATIC_MASTER );
#endif
sqlite3_mutex_enter( mutex );
vfsUnlink( pVfs );
sqlite3_mutex_leave( mutex );
return SQLITE_OK;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Core.TestFramework;
using NUnit.Framework;
namespace Azure.Storage.Test.Shared
{
/// <summary>
/// Defines service-agnostic tests for OpenRead() methods.
/// </summary>
public abstract class OpenReadTestBase<TServiceClient, TContainerClient, TResourceClient, TClientOptions, TRequestConditions, TEnvironment> : StorageTestBase<TEnvironment>
where TServiceClient : class
where TContainerClient : class
where TResourceClient : class
where TClientOptions : ClientOptions
where TEnvironment : StorageTestEnvironment, new()
{
public enum ModifyDataMode
{
None = 0,
Replace = 1,
Append = 2
};
private readonly string _generatedResourceNamePrefix;
public ClientBuilder<TServiceClient, TClientOptions> ClientBuilder { get; protected set; }
/// <summary>
/// Supplies service-agnostic access conditions for tests.
/// </summary>
public abstract AccessConditionConfigs Conditions { get; }
/// <summary>
/// Error code expected from the service when attempted to open read on a nonexistent blob.
/// Different services supply different error codes.
/// </summary>
protected abstract string OpenReadAsync_Error_Code { get; }
public OpenReadTestBase(
bool async,
string generatedResourceNamePrefix = default,
RecordedTestMode? mode = null)
: base(async, mode)
{
_generatedResourceNamePrefix = generatedResourceNamePrefix ?? "test-resource-";
}
#region Service-Specific Methods
/// <summary>
/// Gets a service-specific disposing container for use with tests in this class.
/// </summary>
/// <param name="service">Optionally specified service client to get container from.</param>
/// <param name="containerName">Optional container name specification.</param>
protected abstract Task<IDisposingContainer<TContainerClient>> GetDisposingContainerAsync(
TServiceClient service = default,
string containerName = default);
/// <summary>
/// Gets a new service-specific resource client from a given container, e.g. a BlobClient from a
/// BlobContainerClient or a DataLakeFileClient from a DataLakeFileSystemClient.
/// </summary>
/// <param name="container">Container to get resource from.</param>
/// <param name="resourceLength">Sets the resource size in bytes, for resources that require this upfront.</param>
/// <param name="createResource">Whether to call CreateAsync on the resource, if necessary.</param>
/// <param name="resourceName">Optional name for the resource.</param>
/// <param name="options">ClientOptions for the resource client.</param>
protected abstract TResourceClient GetResourceClient(
TContainerClient container,
string resourceName = default,
TClientOptions options = default);
/// <summary>
/// Uploads data to be used for an OpenRead test.
/// </summary>
/// <param name="client">Client to call upload on.</param>
/// <param name="data">Data to upload.</param>
protected abstract Task StageDataAsync(
TResourceClient client,
Stream data);
protected abstract Task ModifyDataAsync(
TResourceClient client,
Stream data,
ModifyDataMode mode);
/// <summary>
/// Calls the 1:1 download method for the given resource client.
/// </summary>
/// <param name="client">Client to call the download on.</param>
protected abstract Task<Stream> OpenReadAsync(
TResourceClient client,
int? bufferSize = default,
long position = default,
TRequestConditions conditions = default,
bool allowModifications = false);
protected abstract Task<string> SetupLeaseAsync(TResourceClient client, string leaseId, string garbageLeaseId);
protected abstract Task<string> GetMatchConditionAsync(TResourceClient client, string match);
protected abstract TRequestConditions BuildRequestConditions(AccessConditionParameters parameters, bool lease = true);
#endregion
protected string GetNewResourceName()
=> _generatedResourceNamePrefix + ClientBuilder.Recording.Random.NewGuid();
private string GetGarbageLeaseId()
=> ClientBuilder.Recording.Random.NewGuid().ToString();
[RecordedTest]
public async Task OpenReadAsync()
{
int size = Constants.KB;
await using IDisposingContainer<TContainerClient> disposingContainer = await GetDisposingContainerAsync();
// Arrange
var data = GetRandomBuffer(size);
TResourceClient client = GetResourceClient(disposingContainer.Container);
await StageDataAsync(client, new MemoryStream(data));
// Act
Stream outputStream = await OpenReadAsync(client);
byte[] outputBytes = new byte[size];
await outputStream.ReadAsync(outputBytes, 0, size);
// Assert
Assert.AreEqual(data.Length, outputStream.Length);
TestHelper.AssertSequenceEqual(data, outputBytes);
}
[RecordedTest]
public async Task OpenReadAsync_BufferSize()
{
int size = Constants.KB;
int bufferSize = size / 8;
await using IDisposingContainer<TContainerClient> disposingContainer = await GetDisposingContainerAsync();
// Arrange
var data = GetRandomBuffer(size);
TResourceClient client = GetResourceClient(disposingContainer.Container);
await StageDataAsync(client, new MemoryStream(data));
// Act
Stream outputStream = await OpenReadAsync(client, bufferSize: bufferSize);
byte[] outputBytes = new byte[size];
int downloadedBytes = 0;
while (downloadedBytes < size)
{
downloadedBytes += await outputStream.ReadAsync(outputBytes, downloadedBytes, size / 4);
}
// Assert
Assert.AreEqual(data.Length, outputStream.Length);
TestHelper.AssertSequenceEqual(data, outputBytes);
}
[RecordedTest]
public async Task OpenReadAsync_OffsetAndBufferSize()
{
int size = Constants.KB;
int bufferSize = size / 8;
int position = size / 2;
await using IDisposingContainer<TContainerClient> disposingContainer = await GetDisposingContainerAsync();
// Arrange
var data = GetRandomBuffer(size);
TResourceClient client = GetResourceClient(disposingContainer.Container);
await StageDataAsync(client, new MemoryStream(data));
byte[] expected = new byte[size];
Array.Copy(data, position, expected, position, size - position);
// Act
Stream outputStream = await OpenReadAsync(client, bufferSize: bufferSize, position: position);
byte[] outputBytes = new byte[size];
int downloadedBytes = position;
while (downloadedBytes < size)
{
downloadedBytes += await outputStream.ReadAsync(outputBytes, downloadedBytes, size / 4);
}
// Assert
Assert.AreEqual(data.Length, outputStream.Length);
TestHelper.AssertSequenceEqual(expected, outputBytes);
}
[RecordedTest]
public async Task OpenReadAsync_Error()
{
// Arrange
await using IDisposingContainer<TContainerClient> disposingContainer = await GetDisposingContainerAsync();
TResourceClient client = GetResourceClient(disposingContainer.Container);
// Act
await TestHelper.AssertExpectedExceptionAsync<RequestFailedException>(
OpenReadAsync(client),
e => Assert.AreEqual(OpenReadAsync_Error_Code, e.ErrorCode));
}
[RecordedTest]
public virtual async Task OpenReadAsync_AccessConditions()
{
// Arrange
int size = Constants.KB;
int bufferSize = size / 4;
var garbageLeaseId = GetGarbageLeaseId();
await using IDisposingContainer<TContainerClient> disposingContainer = await GetDisposingContainerAsync();
foreach (AccessConditionParameters parameters in Conditions.AccessConditions_Data)
{
var data = GetRandomBuffer(size);
TResourceClient client = GetResourceClient(disposingContainer.Container);
await StageDataAsync(client, new MemoryStream(data));
parameters.Match = await GetMatchConditionAsync(client, parameters.Match);
parameters.LeaseId = await SetupLeaseAsync(client, parameters.LeaseId, garbageLeaseId);
TRequestConditions conditions = BuildRequestConditions(
parameters: parameters,
lease: true);
// Act
Stream outputStream = await OpenReadAsync(client, bufferSize: bufferSize, conditions: conditions);
byte[] outputBytes = new byte[size];
int downloadedBytes = 0;
while (downloadedBytes < size)
{
downloadedBytes += await outputStream.ReadAsync(outputBytes, downloadedBytes, size / 4);
}
// Assert
Assert.AreEqual(data.Length, outputStream.Length);
TestHelper.AssertSequenceEqual(data, outputBytes);
}
}
[RecordedTest]
public virtual async Task OpenReadAsync_AccessConditionsFail()
{
// Arrange
int size = Constants.KB;
int bufferSize = size / 4;
var garbageLeaseId = GetGarbageLeaseId();
foreach (AccessConditionParameters parameters in Conditions.GetAccessConditionsFail_Data(garbageLeaseId))
{
await using IDisposingContainer<TContainerClient> disposingContainer = await GetDisposingContainerAsync();
var data = GetRandomBuffer(size);
TResourceClient client = GetResourceClient(disposingContainer.Container);
await StageDataAsync(client, new MemoryStream(data));
parameters.NoneMatch = await GetMatchConditionAsync(client, parameters.NoneMatch);
TRequestConditions conditions = BuildRequestConditions(parameters, lease: true);
// Act
await TestHelper.CatchAsync<Exception>(
async () =>
{
var _ = await OpenReadAsync(client, bufferSize: bufferSize, conditions: conditions);
});
}
}
[RecordedTest]
public async Task OpenReadAsync_StrangeOffsetsTest()
{
// Arrange
await using IDisposingContainer<TContainerClient> disposingContainer = await GetDisposingContainerAsync();
int size = Constants.KB;
int bufferSize = 157;
byte[] expectedData = GetRandomBuffer(size);
TResourceClient client = GetResourceClient(disposingContainer.Container);
await StageDataAsync(client, new MemoryStream(expectedData));
Stream outputStream = await OpenReadAsync(client, bufferSize: bufferSize);
byte[] actualData = new byte[size];
int offset = 0;
// Act
int count = 0;
int readBytes = -1;
while (readBytes != 0)
{
for (count = 6; count < 37; count += 6)
{
readBytes = await outputStream.ReadAsync(actualData, offset, count);
if (readBytes == 0)
{
break;
}
offset += readBytes;
}
}
// Assert
TestHelper.AssertSequenceEqual(expectedData, actualData);
}
[RecordedTest]
public virtual async Task OpenReadAsync_Modified()
{
int size = Constants.KB;
int bufferSize = size / 2;
await using IDisposingContainer<TContainerClient> disposingContainer = await GetDisposingContainerAsync();
// Arrange
var data = GetRandomBuffer(size);
TResourceClient client = GetResourceClient(disposingContainer.Container);
await StageDataAsync(client, new MemoryStream(data));
// Act
Stream outputStream = await OpenReadAsync(client, bufferSize: bufferSize);
byte[] outputBytes = new byte[size];
await outputStream.ReadAsync(outputBytes, 0, size / 2);
// Modify the blob.
await ModifyDataAsync(client, new MemoryStream(GetRandomBuffer(size)), ModifyDataMode.Replace);
// Assert
await AssertExpectedExceptionOpenReadModifiedAsync(outputStream.ReadAsync(outputBytes, size / 2, size / 2));
}
/// <summary>
/// For the test <see cref="OpenReadAsync_Modified"/>, different services surface different exception types
/// and we check fields in that exception to ensure they are as expected. This method allows service-specific
/// subclasses to specify how they check this expected error.
/// </summary>
/// <param name="readTask">Task to asynchronously read from the stream.</param>
/// <returns></returns>
public abstract Task AssertExpectedExceptionOpenReadModifiedAsync(Task readTask);
[RecordedTest]
public async Task OpenReadAsync_ModifiedAllowBlobModifications()
{
int size = Constants.KB;
await using IDisposingContainer<TContainerClient> disposingContainer = await GetDisposingContainerAsync();
// Arrange
byte[] data0 = GetRandomBuffer(size);
byte[] data1 = GetRandomBuffer(size);
byte[] expectedData = new byte[2 * size];
Array.Copy(data0, 0, expectedData, 0, size);
Array.Copy(data1, 0, expectedData, size, size);
TResourceClient client = GetResourceClient(disposingContainer.Container);
await StageDataAsync(client, new MemoryStream(data0));
// Act
Stream outputStream = await OpenReadAsync(client, allowModifications: true);
byte[] outputBytes = new byte[2 * size];
await outputStream.ReadAsync(outputBytes, 0, size);
// Modify the blob.
await ModifyDataAsync(client, new MemoryStream(data1), ModifyDataMode.Append);
await outputStream.ReadAsync(outputBytes, size, size);
// Assert
TestHelper.AssertSequenceEqual(expectedData, outputBytes);
}
[RecordedTest]
[Ignore("Don't want to record 1 GB of data.")]
public async Task OpenReadAsync_LargeData()
{
// Arrange
await using IDisposingContainer<TContainerClient> disposingContainer = await GetDisposingContainerAsync();
int length = 1 * Constants.GB;
byte[] expectedData = GetRandomBuffer(length);
TResourceClient client = GetResourceClient(disposingContainer.Container);
using Stream stream = new MemoryStream(expectedData);
await StageDataAsync(client, stream);
Stream outputStream = await OpenReadAsync(client);
int readSize = 8 * Constants.MB;
byte[] actualData = new byte[readSize];
int offset = 0;
// Act
for (int i = 0; i < length / readSize; i++)
{
int actualRead = await outputStream.ReadAsync(actualData, 0, readSize);
for (int j = 0; j < actualRead; j++)
{
// Assert
if (actualData[j] != expectedData[offset + j])
{
Assert.Fail($"Index {offset + j} does not match. Expected: {expectedData[offset + j]} Actual: {actualData[j]}");
}
}
offset += actualRead;
}
}
[RecordedTest]
public async Task OpenReadAsync_CopyReadStreamToAnotherStream()
{
// Arrange
await using IDisposingContainer<TContainerClient> disposingContainer = await GetDisposingContainerAsync();
long size = 4 * Constants.MB;
byte[] expectedData = GetRandomBuffer(size);
TResourceClient client = GetResourceClient(disposingContainer.Container);
await StageDataAsync(client, new MemoryStream(expectedData));
MemoryStream outputStream = new MemoryStream();
// Act
using Stream blobStream = await OpenReadAsync(client);
await blobStream.CopyToAsync(outputStream);
TestHelper.AssertSequenceEqual(expectedData, outputStream.ToArray());
}
[RecordedTest]
public async Task OpenReadAsync_InvalidParameterTests()
{
int size = Constants.KB;
await using IDisposingContainer<TContainerClient> disposingContainer = await GetDisposingContainerAsync();
// Arrange
var data = GetRandomBuffer(size);
TResourceClient client = GetResourceClient(disposingContainer.Container);
await StageDataAsync(client, new MemoryStream(data));
Stream stream = await OpenReadAsync(client);
// Act
await TestHelper.AssertExpectedExceptionAsync<ArgumentNullException>(
stream.ReadAsync(buffer: null, offset: 0, count: 10),
new ArgumentNullException("buffer", "buffer cannot be null."));
await TestHelper.AssertExpectedExceptionAsync<ArgumentOutOfRangeException>(
stream.ReadAsync(buffer: new byte[10], offset: -1, count: 10),
new ArgumentOutOfRangeException("offset", "offset cannot be less than 0."));
await TestHelper.AssertExpectedExceptionAsync<ArgumentOutOfRangeException>(
stream.ReadAsync(buffer: new byte[10], offset: 11, count: 10),
new ArgumentOutOfRangeException("offset", "offset cannot exceed buffer length."));
await TestHelper.AssertExpectedExceptionAsync<ArgumentOutOfRangeException>(
stream.ReadAsync(buffer: new byte[10], offset: 1, count: -1),
new ArgumentOutOfRangeException("count", "count cannot be less than 0."));
}
[RecordedTest]
public async Task OpenReadAsync_Seek_PositionUnchanged()
{
int size = Constants.KB;
await using IDisposingContainer<TContainerClient> disposingContainer = await GetDisposingContainerAsync();
// Arrange
var data = GetRandomBuffer(size);
TResourceClient client = GetResourceClient(disposingContainer.Container);
await StageDataAsync(client, new MemoryStream(data));
// Act
Stream outputStream = await OpenReadAsync(client);
byte[] outputBytes = new byte[size];
outputStream.Seek(0, SeekOrigin.Begin);
Assert.AreEqual(0, outputStream.Position);
await outputStream.ReadAsync(outputBytes, 0, size);
// Assert
Assert.AreEqual(data.Length, outputStream.Length);
TestHelper.AssertSequenceEqual(data, outputBytes);
}
[RecordedTest]
public async Task OpenReadAsync_Seek_NegativeNewPosition()
{
int size = Constants.KB;
await using IDisposingContainer<TContainerClient> disposingContainer = await GetDisposingContainerAsync();
// Arrange
var data = GetRandomBuffer(size);
TResourceClient client = GetResourceClient(disposingContainer.Container);
await StageDataAsync(client, new MemoryStream(data));
// Act
Stream outputStream = await OpenReadAsync(client);
TestHelper.AssertExpectedException<ArgumentException>(
() => outputStream.Seek(-10, SeekOrigin.Begin),
new ArgumentException("New offset cannot be less than 0. Value was -10", "offset"));
}
[RecordedTest]
[TestCase(true)]
[TestCase(false)]
public async Task OpenReadAsync_Seek_NewPositionGreaterThanResourceLength(bool allowModifications)
{
int size = Constants.KB;
await using IDisposingContainer<TContainerClient> disposingContainer = await GetDisposingContainerAsync();
// Arrange
var data = GetRandomBuffer(size);
TResourceClient client = GetResourceClient(disposingContainer.Container);
await StageDataAsync(client, new MemoryStream(data));
// Act
Stream outputStream = await OpenReadAsync(client, allowModifications: allowModifications);
TestHelper.AssertExpectedException<ArgumentException>(
() => outputStream.Seek(1025, SeekOrigin.Begin),
new ArgumentException("You cannot seek past the last known length of the underlying blob or file.", "offset"));
Assert.AreEqual(size, outputStream.Length);
}
[RecordedTest]
[TestCase(0, SeekOrigin.Begin)]
[TestCase(10, SeekOrigin.Begin)]
[TestCase(-10, SeekOrigin.Current)]
[TestCase(0, SeekOrigin.Current)]
[TestCase(10, SeekOrigin.Current)]
[TestCase(0, SeekOrigin.End)]
[TestCase(-10, SeekOrigin.End)]
public async Task OpenReadAsync_Seek_Position(long offset, SeekOrigin origin)
{
int size = Constants.KB;
await using IDisposingContainer<TContainerClient> disposingContainer = await GetDisposingContainerAsync();
// Arrange
var data = GetRandomBuffer(size);
TResourceClient client = GetResourceClient(disposingContainer.Container);
await StageDataAsync(client, new MemoryStream(data));
Stream outputStream = await OpenReadAsync(client);
int readBytes = 512;
await outputStream.ReadAsync(new byte[readBytes], 0, readBytes);
Assert.AreEqual(512, outputStream.Position);
// Act
outputStream.Seek(offset, origin);
// Assert
if (origin == SeekOrigin.Begin)
{
Assert.AreEqual(offset, outputStream.Position);
}
else if (origin == SeekOrigin.Current)
{
Assert.AreEqual(readBytes + offset, outputStream.Position);
}
else
{
Assert.AreEqual(size + offset, outputStream.Position);
}
Assert.AreEqual(size, outputStream.Length);
}
[RecordedTest]
// lower position within _buffer
[TestCase(-50)]
// higher position within _buffer
[TestCase(50)]
// lower position below _buffer
[TestCase(-100)]
// higher position above _buffer
[TestCase(100)]
public async Task OpenReadAsync_Seek(long offset)
{
int size = Constants.KB;
int bufferSize = 128;
int initalPosition = 450;
await using IDisposingContainer<TContainerClient> disposingContainer = await GetDisposingContainerAsync();
// Arrange
byte[] data = GetRandomBuffer(size);
byte[] expectedData = new byte[size - (initalPosition + offset)];
Array.Copy(data, initalPosition + offset, expectedData, 0, size - (initalPosition + offset));
TResourceClient client = GetResourceClient(disposingContainer.Container);
await StageDataAsync(client, new MemoryStream(data));
// Act
Stream openReadStream = await OpenReadAsync(client, bufferSize: bufferSize);
int readbytes = initalPosition;
while (readbytes > 0)
{
readbytes -= await openReadStream.ReadAsync(new byte[readbytes], 0, readbytes);
}
openReadStream.Seek(offset, SeekOrigin.Current);
using MemoryStream outputStream = new MemoryStream();
await openReadStream.CopyToAsync(outputStream);
// Assert
Assert.AreEqual(expectedData.Length, outputStream.ToArray().Length);
Assert.AreEqual(size, openReadStream.Length);
TestHelper.AssertSequenceEqual(expectedData, outputStream.ToArray());
}
[RecordedTest]
// lower position within _buffer
[TestCase(400)]
// higher positiuon within _buffer
[TestCase(500)]
// lower position below _buffer
[TestCase(250)]
// higher position above _buffer
[TestCase(550)]
public async Task OpenReadAsync_SetPosition(long position)
{
int size = Constants.KB;
int bufferSize = 128;
int initalPosition = 450;
await using IDisposingContainer<TContainerClient> disposingContainer = await GetDisposingContainerAsync();
// Arrange
byte[] data = GetRandomBuffer(size);
byte[] expectedData = new byte[size - position];
Array.Copy(data, position, expectedData, 0, size - position);
TResourceClient client = GetResourceClient(disposingContainer.Container);
await StageDataAsync(client, new MemoryStream(data));
// Act
Stream openReadStream = await OpenReadAsync(client, bufferSize: bufferSize);
int readbytes = initalPosition;
while (readbytes > 0)
{
readbytes -= await openReadStream.ReadAsync(new byte[readbytes], 0, readbytes);
}
openReadStream.Position = position;
using MemoryStream outputStream = new MemoryStream();
await openReadStream.CopyToAsync(outputStream);
// Assert
Assert.AreEqual(expectedData.Length, outputStream.ToArray().Length);
TestHelper.AssertSequenceEqual(expectedData, outputStream.ToArray());
}
}
}
| |
using System.Configuration;
using System.IO;
using System.Text;
namespace MetX.Standard.Archived.Web
{
/// <summary>A SecureHandler with XslHandler rendering and SecureUserProfile functionality built in.
/// <para>Events are fired automatically by ProcessRequest() as follows:</para>
/// <code>
/// Clear();
/// if (OnLoad()) {
/// if (PreBuild()) {
/// Begin("xlgDoc", RootAttributes);
/// if (LoadMemberProfile)
/// // Adds the appropriate memberProfile element. If no id or username is posted, the current user is used (SecureUserProfile = memberProfile attributes).
/// if (BuildXml()) {
/// Transform();
/// PostTransform();
/// }
/// }
/// }
/// </code>
/// <para>If PreBuild returns false, no intnernal xml string or xsl transformation will occur</para>
/// <para>If BuildXml returns false, no xsl transformation or PostBuild will occur</para>
/// </summary>
public class SecureXslHandler : SecureHandler
{
/// <summary>The SecureUserProfile automatically loaded prior to Page_Load firing.</summary>
public SecureUserProfile memberProfile;
/// <summary>The path to the .xsl file to render the XML against. If blank, the system uses the xsl file with the same name as the class (Default.xsl for Default.aspx for instance)</summary>
public string xsltPath = string.Empty;
/// <summary>When set, xsltPath is ignored and the xsl stylesheet contained in xsltContent is used to transform.</summary>
public StringBuilder xsltContent;
/// <summary>The value of the DebugState attribute to place in root element. Default value is pulled from the Web.config setting xlgSecurity.Debug</summary>
public string DebugState = string.Empty;
/// <summary>Setting this to true will load a memberProfile element below the SecureUserPage element based on the value of the request variable "id" or "username"</summary>
public bool LoadMemberProfile = false;
/// <summary>The additional attributes to add to the root xml element</summary>
public string RootAttributes = string.Empty;
/// <summary>If set, it allows for the virtualization of output normally written to Response. This allows pages to generate other pages. See BuildVirtualPage</summary>
public StringWriter VirtualOutput;
private StringBuilder sb;
private string RootName = string.Empty;
private string _OutputFormat;
private bool _AlreadyStarted;
/// <summary>The XSL transformation class with (MetX.xml)</summary>
public xml Transformer = new xml();
public void AddRootAttribute(string Name, string Value)
{
if (Value != null)
RootAttributes += " " + Name + "=\"" + xml.AttributeEncode(Value) + "\"";
}
public void AddRootAttribute(string VariableName)
{
RootAttributes += " " + VariableName + "=\"" + xml.AttributeEncode(V(VariableName)) + "\"";
}
/// <summary>Clears the internal xml string area</summary>
public void Clear()
{
sb = new StringBuilder();
}
/// <summary>Generates page output returning a stringbuilder of the output.</summary>
/// <param name="context">The HttpContext to build the page from</param>
/// <param name="TargetUserName">The user who the page should be targeted toward. Use this when you wish to not only generate another page, but you want to generate another page as if another user had viewed it (useful when sending emails).</param>
/// <returns>A StringBuilder containing the output from the page</returns>
public StringBuilder BuildVirtualPage(HttpContext context, string TargetUserName)
{
StringBuilder vsb = new StringBuilder();
VirtualOutput = new StringWriter(vsb);
Start(context, TargetUserName);
ProcessRequest();
VirtualOutput.Close();
VirtualOutput.Dispose();
vsb.Replace("&#160;", " ");
return vsb;
}
/// <summary>Primes the object for manual output. Only call this method when you wish to manually build your own output (pages building pages). BuildVirtualPage calls this method.</summary>
/// <param name="context">The HttpContenxt the page's output should be based on</param>
/// <param name="TargetUserName">The user who the page should be targeted toward. Use this when you wish to not only generate another page, but you want to generate another page as if another user had viewed it (useful when sending emails).</param>
public void Start(HttpContext context, string TargetUserName)
{
if (!_AlreadyStarted)
{
Clear();
if (context != null)
{
Context = context;
Server = context.Server;
Request = context.Request;
Response = context.Response;
Session = context.Session;
}
if (TargetUserName == null || TargetUserName.Length == 0)
Security.Start(context);
else
Security.Start(context, TargetUserName);
sb.AppendLine("<?xml version=\"1.0\"?>");
if (Request["xslfile"] != null && Request["xslfile"].Length > 0)
{
xsltPath = Request["xslfile"] + string.Empty;
if ((xsltPath.IndexOf(".xsl", 0) + 1) == 0)
xsltPath += ".xsl";
}
_AlreadyStarted = true;
}
}
/// <summary>Writes the beginning xlgDoc root element to the internal xml string with no attributes</summary>
public void Begin()
{
Begin("xlgDoc", string.Empty);
}
/// <summary>Writes the beginning root element to the internal xml string with no attributes</summary>
/// <param name="RootNodeName">The root element name</param>
public void Begin(string RootNodeName)
{
Begin(RootNodeName, string.Empty);
}
/// <summary>Writes the beginning root element to the internal xml string with attributes</summary>
/// <param name="RootNodeName">The root element name</param>
/// <param name="Attributes">The attributes to place in the root element</param>
public void Begin(string RootNodeName, string Attributes)
{
if (RootNodeName != null && RootNodeName.Length > 0)
{
RootName = RootNodeName.Replace("<", string.Empty).Replace(">", string.Empty).Replace("\"", string.Empty).Replace("'", string.Empty);
sb.Append("<" + RootName);
if (Attributes != null && Attributes.Length > 0)
{
sb.Append(" " + Attributes.Trim() + " ");
}
if (Request["debug"] != null && Request["debug"].Length > 0)
{
DebugState = Request["debug"];
}
else if (ConfigurationManager.AppSettings["xlgDoc.Debug"] == "True")
{
DebugState = ConfigurationManager.AppSettings["xlgDoc.Debug"];
}
string ProbableURL = Request.Url.AbsoluteUri; //Path & Request.ServerVariables("URL") & "?" & Request.QueryString.ToString
if (Request.QueryString.ToString().Length == 0)
ProbableURL += "?" + Request.Form.ToString();
string URLPath = Token.First(ProbableURL, "?");
URLPath = Token.Before(URLPath, Token.Count(URLPath, "/"), "/") + "/";
string ServerPath = Token.Before(Request.Url.AbsoluteUri, 4, "/") + "/";
string VDirPath = Token.Before(URLPath, 5, "/") + "/";
//ServerPath = Token.Before(ServerPath, Token.Count(ServerPath, "/") - 1, "/") + "/";
if ((ProbableURL.IndexOf("&format=", 0) + 1) > -1)
ProbableURL = ProbableURL.Replace("&format=" + OutputFormat, string.Empty);
if (ProbableURL.EndsWith("?"))
ProbableURL = ProbableURL.Substring(0, ProbableURL.Length - 1);
sb.AppendLine(" ServerPath=\"" + xml.AttributeEncode(ServerPath) + "\" URLPath=\"" + xml.AttributeEncode(URLPath) + "\" VDirPath=\"" + xml.AttributeEncode(VDirPath) + "\" ProbableURL=\"" + xml.AttributeEncode(ProbableURL) + "\" Format=\"" + OutputFormat + "\" Version=\"" + ConfigurationManager.AppSettings["xlgDoc.Version"] + "\" DebugState=\"" + xml.AttributeEncode(DebugState) + "\">");
sb.Append(Security.InnerXml);
}
}
/// <summary>Writes the closing element to the internal xml string using this.RootName</summary>
private void EndDocument()
{
if (RootName != null && RootName.Length > 0)
sb.Append("</" + RootName + ">");
}
/// <summary>Appends an xml string to the internal xml StringBuilder</summary>
/// <param name="sToAppend">The xml string to append (usually one or more well formed elements)</param>
public void Append(string sToAppend)
{
sb.Append(sToAppend);
}
/// <summary>Appends xml inside a StringBuilder to the internal xml StringBuilder</summary>
/// <param name="sToAppend">The xml StringBuilder to append (usually one or more well formed elements)</param>
public void Append(StringBuilder sToAppend)
{
sb.Append(sToAppend);
}
/// <summary>Outputs the internal xml string to the Response</summary>
public void RawXml()
{
Response.ContentType = "text/xml";
NoTransform();
}
/// <summary>Transforms the internal xml string with the supplied xslt path and filename</summary>
/// <param name="xsltPath">The path and filename to render the internal xml string against</param>
public void Transform(string xsltPath)
{
if (OutputFormat == "xml")
{
RawXml();
}
else
{
EndDocument();
WriteToOutput(Transformer.xslTransform(PageCache, sb, MassageXsltPath(xsltPath)));
}
}
/// <summary>Renders the internal xml string and outputs it to the Response object. Set OutputFormat (or passing in "format" on the request query string) will override rendering options.</summary>
public void Transform()
{
if (OutputFormat == "xml")
RawXml();
else if (OutputFormat == "excel")
TransformToExcelDownload();
else if (OutputFormat == "json")
{
EndDocument();
xsltContent = MetX.Web.Virtual.xsl.XmlToJson.xslStringBuilder;
Transformer.xlgUrn.SetVar("JsonVariableName", Worker.nzString(Request["variablename"], "xlgDoc"));
WriteToOutput(Transformer.xslTransform(PageCache, sb, MassageXsltPath(xsltPath), xsltContent));
//XmlDocument xmlDoc = new XmlDocument();
//xmlDoc.LoadXml(sb.ToString());
//string varName = Worker.nzString(Request["variablename"], "xlgDoc");
//sb = new StringBuilder();
//if (varName == "debug")
//{
// sb.AppendLine("<HTML><BODY><HEAD><SCRIPT language='javascript'>");
//}
//if (varName != "none")
// sb.Append("var " + varName + " = ");
//xml.ToJson(xmlDoc.DocumentElement, sb);
//if (varName != "none")
// sb.AppendLine(";");
//if (varName == "debug")
//{
// sb.AppendLine();
// sb.AppendLine("var content = document.getElementById('content');");
// sb.AppendLine("outputNode(debug.xlgDoc);");
// sb.AppendLine("function outputNode(node) {");
// sb.AppendLine(" content.innerHTML = 'node.ServerPath = ' + node.ServerPath;");
// sb.AppendLine("");
// sb.AppendLine("}");
// sb.AppendLine("</SCRIPT><BODY><div id='content'></div></BODY></HTML>");
//}
//WriteToOutput(sb);
}
else
{
EndDocument();
if (xsltPath == null || xsltPath.Length == 0)
WriteToOutput(Transformer.xslTransform(PageCache, sb, MassageXsltPath(Security.PageName), xsltContent));
else
WriteToOutput(Transformer.xslTransform(PageCache, sb, MassageXsltPath(xsltPath), xsltContent));
}
}
/// <summary>Renders the internal xml string as Excel 2003 readable HTML and redirects to the unsecured viewtempdatafile internal handler to allow downloading in Excel. File will be available for about 5 minutes from the temporary folder.</summary>
public void TransformToExcelDownload()
{
Response.Clear();
Response.Redirect("viewtempdatafile.aspx?f=excel&v=" + Path.GetFileName(sTransformToExcelDownload()));
}
/// <summary>Renders the internal xml string as Excel 2003 readable HTML and returns the results.</summary>
/// <returns>The render Excel 2003 readable HTML string</returns>
public string sTransformToExcelDownload()
{
string BatchNum = System.DateTime.Now.Year.ToString() + System.DateTime.Now.Month.ToString() + System.DateTime.Now.Day.ToString() + System.DateTime.Now.Hour.ToString() + System.DateTime.Now.Minute.ToString() + System.DateTime.Now.Second.ToString() + System.DateTime.Now.Millisecond.ToString() + System.Threading.Thread.CurrentThread.ManagedThreadId.ToString();
string xlsFilename = "s" + BatchNum + ".xls";
string tempDir = Server.MapPath(ConfigurationManager.AppSettings["xlgSecurity.TempDataFolder"]);
//if (!Directory.Exists(tempDir))
// Directory.CreateDirectory(tempDir);
string OutputFilename = tempDir + "\\" + xlsFilename;
//if (File.Exists(OutputFilename))
//{
// File.SetAttributes(OutputFilename, FileAttributes.Normal);
// File.Delete(OutputFilename);
//}
//StringBuilder FileContents = sTransform();
//StreamWriter sw = File.CreateText(OutputFilename);
//sw.WriteLine(FileContents);
//sw.Flush();
//sw.Close();
//sw.Dispose();
Session["vcontent"] = sTransform();
return OutputFilename;
}
/// <summary>Renders the internal xml string and returns the output. OutputFormat will not override this transformation.</summary>
/// <returns>The rendered output</returns>
public StringBuilder sTransform()
{
EndDocument();
if (xsltPath == null || xsltPath.Length == 0)
return Transformer.xslTransform(PageCache, sb, MassageXsltPath(Security.PageName), xsltContent);
else
return Transformer.xslTransform(PageCache, sb, MassageXsltPath(xsltPath), xsltContent);
}
/// <summary>Returns the contents of the internal xml string</summary>
/// <returns>The internal xml string contents</returns>
public string sRawXml()
{
string ReturnValue = null;
EndDocument();
ReturnValue = sb.ToString();
return ReturnValue;
}
/// <summary>Causes the internal xml string to be written to the output</summary>
public void NoTransform()
{
EndDocument();
WriteToOutput(sb);
}
/// <summary>Writes a string to the Response object.</summary>
/// <param name="ToWrite">The string to write</param>
private void WriteToOutput(ref string ToWrite)
{
if (VirtualOutput == null)
{
Response.Write(ToWrite);
}
else
{
VirtualOutput.Write(ToWrite);
}
}
/// <summary>Writes a string to the Response object.</summary>
/// <param name="ToWrite">The StringBuilder to write</param>
private void WriteToOutput(StringBuilder ToWrite)
{
if (VirtualOutput == null)
{
Response.Write(ToWrite);
}
else
{
VirtualOutput.Write(ToWrite);
}
}
/// <summary>The format to render the page as. If not set, it will be set to the Request variable "format"</summary>
public string OutputFormat
{
get
{
if (_OutputFormat == null || _OutputFormat.Length == 0)
_OutputFormat = Request["format"];
return _OutputFormat;
}
set
{
_OutputFormat = value;
}
}
/// <summary>Override to Append your own elements to the internal xml string prior to xsl transformation.
/// <para>NOTE: This function has no implementation except to return true</para>
/// </summary>
/// <returns>Returns true</returns>
public virtual bool BuildXml()
{
return true;
}
/// <summary>Override to handle situations that need to be handled before anything else is done.
/// <para>NOTE: This function has no implementation except to return true</para>
/// </summary>
/// <returns>Returns true</returns>
public virtual bool OnLoad()
{
return true;
}
/// <summary>Override to handle situations that need to be handled after everything else is done.
/// <para>NOTE: This function has no implementation</para>
/// </summary>
public virtual void OnFinish()
{
}
/// <summary>Override to handle situations (such as handling POST) that need to be handled before the xml string is begun. This is where RootAttributes would be set.
/// <para>NOTE: This function has no implementation except to return true</para>
/// </summary>
/// <returns>Returns true</returns>
public virtual bool PreBuild()
{
return true;
}
/// <summary>Occurs after transformation and before the Response is returned to the client.
/// <para>NOTE: This function has no implementation except to return true</para>
/// </summary>
/// <returns>Returns true</returns>
public virtual bool PostTransform()
{
return true;
}
/// <summary>This is the HttpHandler event that triggers the PreBuild, BuildXml, PostBuild events.</summary>
public override void ProcessRequest()
{
Clear();
if (OnLoad())
{
if (PreBuild())
{
Begin("xlgDoc", RootAttributes);
if (LoadMemberProfile)
{
string username = Request["username"];
string NotificationID = Request["NotificationID"];
if (NotificationID != null && NotificationID.Length > 0)
username = sql.RetrieveSingleStringValue("SELECT UserName FROM [User] WHERE UserID='" + NotificationID + "'", "xlgSecurity");
if (username == null || username.Length == 0)
{
memberProfile = Security;
}
else
{
memberProfile = new SecureUserProfile();
if (!memberProfile.Load(Security.ApplicationName, Security.PageName, username))
memberProfile = Security;
}
Append(memberProfile.InnerXml.Replace("SecureUserPage", "memberProfile"));
}
if (BuildXml())
{
Transform();
PostTransform();
}
}
}
OnFinish();
}
}
}
| |
/// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
using NUnit.Framework;
using System;
using Twilio.Converters;
using Twilio.TwiML.Voice;
namespace Twilio.Tests.TwiML
{
[TestFixture]
public class DialTest : TwilioTest
{
[Test]
public void TestEmptyElement()
{
var elem = new Dial();
Assert.AreEqual(
"<?xml version=\"1.0\" encoding=\"utf-8\"?>" + Environment.NewLine +
"<Dial></Dial>",
elem.ToString()
);
}
[Test]
public void TestElementWithParams()
{
var elem = new Dial(
"number",
new Uri("https://example.com"),
Twilio.Http.HttpMethod.Get,
1,
true,
1,
"caller_id",
Dial.RecordEnum.DoNotRecord,
Dial.TrimEnum.TrimSilence,
new Uri("https://example.com"),
Twilio.Http.HttpMethod.Get,
Promoter.ListOfOne(Dial.RecordingEventEnum.InProgress),
true,
Dial.RingToneEnum.At,
Dial.RecordingTrackEnum.Both,
true,
new Uri("https://example.com"),
Twilio.Http.HttpMethod.Get
);
Assert.AreEqual(
"<?xml version=\"1.0\" encoding=\"utf-8\"?>" + Environment.NewLine +
"<Dial action=\"https://example.com\" method=\"GET\" timeout=\"1\" hangupOnStar=\"true\" timeLimit=\"1\" callerId=\"caller_id\" record=\"do-not-record\" trim=\"trim-silence\" recordingStatusCallback=\"https://example.com\" recordingStatusCallbackMethod=\"GET\" recordingStatusCallbackEvent=\"in-progress\" answerOnBridge=\"true\" ringTone=\"at\" recordingTrack=\"both\" sequential=\"true\" referUrl=\"https://example.com\" referMethod=\"GET\">number</Dial>",
elem.ToString()
);
}
[Test]
public void TestElementWithExtraAttributes()
{
var elem = new Dial();
elem.SetOption("newParam1", "value");
elem.SetOption("newParam2", 1);
Assert.AreEqual(
"<?xml version=\"1.0\" encoding=\"utf-8\"?>" + Environment.NewLine +
"<Dial newParam1=\"value\" newParam2=\"1\"></Dial>",
elem.ToString()
);
}
[Test]
public void TestNestElement()
{
var elem = new Dial();
var child = new Client();
elem.Nest(child).Identity();
Assert.AreEqual(
"<?xml version=\"1.0\" encoding=\"utf-8\"?>" + Environment.NewLine +
"<Dial>" + Environment.NewLine +
" <Client>" + Environment.NewLine +
" <Identity></Identity>" + Environment.NewLine +
" </Client>" + Environment.NewLine +
"</Dial>",
elem.ToString()
);
}
[Test]
public void TestElementWithChildren()
{
var elem = new Dial();
elem.Client(
"identity",
new Uri("https://example.com"),
Twilio.Http.HttpMethod.Get,
Promoter.ListOfOne(Client.EventEnum.Initiated),
new Uri("https://example.com"),
Twilio.Http.HttpMethod.Get
);
elem.Conference(
"name",
true,
Conference.BeepEnum.True,
true,
true,
new Uri("https://example.com"),
Twilio.Http.HttpMethod.Get,
1,
Conference.RecordEnum.DoNotRecord,
Conference.RegionEnum.Us1,
"CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
Conference.TrimEnum.TrimSilence,
Promoter.ListOfOne(Conference.EventEnum.Start),
new Uri("https://example.com"),
Twilio.Http.HttpMethod.Get,
new Uri("https://example.com"),
Twilio.Http.HttpMethod.Get,
Promoter.ListOfOne(Conference.RecordingEventEnum.InProgress),
new Uri("https://example.com"),
Conference.JitterBufferSizeEnum.Large,
"participant_label"
);
elem.Number(
new Twilio.Types.PhoneNumber("+15017122661"),
"send_digits",
new Uri("https://example.com"),
Twilio.Http.HttpMethod.Get,
Promoter.ListOfOne(Number.EventEnum.Initiated),
new Uri("https://example.com"),
Twilio.Http.HttpMethod.Get,
"BYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
);
elem.Queue(
"name",
new Uri("https://example.com"),
Twilio.Http.HttpMethod.Get,
"reservation_sid",
"post_work_activity_sid"
);
elem.Sim("DEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
elem.Sip(
new Uri("https://example.com"),
"username",
"password",
new Uri("https://example.com"),
Twilio.Http.HttpMethod.Get,
Promoter.ListOfOne(Sip.EventEnum.Initiated),
new Uri("https://example.com"),
Twilio.Http.HttpMethod.Get
);
Assert.AreEqual(
"<?xml version=\"1.0\" encoding=\"utf-8\"?>" + Environment.NewLine +
"<Dial>" + Environment.NewLine +
" <Client url=\"https://example.com\" method=\"GET\" statusCallbackEvent=\"initiated\" statusCallback=\"https://example.com\" statusCallbackMethod=\"GET\">identity</Client>" + Environment.NewLine +
" <Conference muted=\"true\" beep=\"true\" startConferenceOnEnter=\"true\" endConferenceOnExit=\"true\" waitUrl=\"https://example.com\" waitMethod=\"GET\" maxParticipants=\"1\" record=\"do-not-record\" region=\"us1\" coach=\"CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\" trim=\"trim-silence\" statusCallbackEvent=\"start\" statusCallback=\"https://example.com\" statusCallbackMethod=\"GET\" recordingStatusCallback=\"https://example.com\" recordingStatusCallbackMethod=\"GET\" recordingStatusCallbackEvent=\"in-progress\" eventCallbackUrl=\"https://example.com\" jitterBufferSize=\"large\" participantLabel=\"participant_label\">name</Conference>" + Environment.NewLine +
" <Number sendDigits=\"send_digits\" url=\"https://example.com\" method=\"GET\" statusCallbackEvent=\"initiated\" statusCallback=\"https://example.com\" statusCallbackMethod=\"GET\" byoc=\"BYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\">+15017122661</Number>" + Environment.NewLine +
" <Queue url=\"https://example.com\" method=\"GET\" reservationSid=\"reservation_sid\" postWorkActivitySid=\"post_work_activity_sid\">name</Queue>" + Environment.NewLine +
" <Sim>DEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX</Sim>" + Environment.NewLine +
" <Sip username=\"username\" password=\"password\" url=\"https://example.com\" method=\"GET\" statusCallbackEvent=\"initiated\" statusCallback=\"https://example.com\" statusCallbackMethod=\"GET\">https://example.com</Sip>" + Environment.NewLine +
"</Dial>",
elem.ToString()
);
}
[Test]
public void TestElementWithTextNode()
{
var elem = new Dial();
elem.AddText("Here is the content");
Assert.AreEqual(
"<?xml version=\"1.0\" encoding=\"utf-8\"?>" + Environment.NewLine +
"<Dial>Here is the content</Dial>",
elem.ToString()
);
}
[Test]
public void TestAllowGenericChildNodes()
{
var elem = new Dial();
elem.AddChild("generic-tag").AddText("Content").SetOption("tag", true);
Assert.AreEqual(
"<?xml version=\"1.0\" encoding=\"utf-8\"?>" + Environment.NewLine +
"<Dial>" + Environment.NewLine +
" <generic-tag tag=\"True\">Content</generic-tag>" + Environment.NewLine +
"</Dial>",
elem.ToString()
);
}
[Test]
public void TestAllowGenericChildrenOfChildNodes()
{
var elem = new Dial();
var child = new Client();
elem.Nest(child).AddChild("generic-tag").SetOption("tag", true).AddText("Content");
Assert.AreEqual(
"<?xml version=\"1.0\" encoding=\"utf-8\"?>" + Environment.NewLine +
"<Dial>" + Environment.NewLine +
" <Client>" + Environment.NewLine +
" <generic-tag tag=\"True\">Content</generic-tag>" + Environment.NewLine +
" </Client>" + Environment.NewLine +
"</Dial>",
elem.ToString()
);
}
[Test]
public void TestMixedContent()
{
var elem = new Dial();
elem.AddText("before")
.AddChild("Child").AddText("content");
elem.AddText("after");
Assert.AreEqual(
"<?xml version=\"1.0\" encoding=\"utf-8\"?>" + Environment.NewLine +
"<Dial>before<Child>content</Child>after</Dial>",
elem.ToString()
);
}
}
}
| |
using System;
using System.Drawing;
using DotNet.Highcharts.Enums;
using DotNet.Highcharts.Attributes;
using DotNet.Highcharts.Helpers;
namespace DotNet.Highcharts.Options
{
/// <summary>
/// A box plot is a convenient way of depicting groups of data through their five-number summaries: the smallest observation (sample minimum), lower quartile (Q1), median (Q2), upper quartile (Q3), and largest observation (sample maximum).
/// </summary>
public class PlotOptionsBoxplot
{
/// <summary>
/// Allow this series' points to be selected by clicking on the markers, bars or pie slices.
/// Default: false
/// </summary>
public bool? AllowPointSelect { get; set; }
/// <summary>
/// The main color or the series. In line type series it applies to the line and the point markers unless otherwise specified. In bar type series it applies to the bars unless a color is specified per point. The default value is pulled from the <code>options.colors</code> array.
/// </summary>
public Color? Color { get; set; }
/// <summary>
/// When using automatic point colors pulled from the <code>options.colors</code> collection, this option determines whether the chart should receive one color per series or one color per point.
/// Default: false
/// </summary>
public bool? ColorByPoint { get; set; }
/// <summary>
/// A series specific or series type specific color set to apply instead of the global <a href='#colors'>colors</a> when <a href='#plotOptions.column.colorByPoint'>colorByPoint</a> is true.
/// </summary>
public Color[] Colors { get; set; }
/// <summary>
/// You can set the cursor to 'pointer' if you have click events attached to the series, to signal to the user that the points and lines can be clicked.
/// </summary>
public Cursors? Cursor { get; set; }
/// <summary>
/// Enable or disable the mouse tracking for a specific series. This includes point tooltips and click events on graphs and points. For large datasets it improves performance.
/// Default: true
/// </summary>
public bool? EnableMouseTracking { get; set; }
public PlotOptionsBoxplotEvents Events { get; set; }
/// <summary>
/// The fill color of the box.
/// Default: #FFFFFF
/// </summary>
[JsonFormatter(addPropertyName: true, useCurlyBracketsForObject: false)]
public BackColorOrGradient FillColor { get; set; }
/// <summary>
/// Padding between each value groups, in x axis units.
/// Default: 0.2
/// </summary>
public Number? GroupPadding { get; set; }
/// <summary>
/// Whether to group non-stacked columns or to let them render independent of each other. Non-grouped columns will be laid out individually and overlap each other.
/// Default: true
/// </summary>
public bool? Grouping { get; set; }
/// <summary>
/// An id for the series. This can be used after render time to get a pointer to the series object through <code>chart.get()</code>.
/// </summary>
public string Id { get; set; }
/// <summary>
/// The width of the line surrounding the box. If any of <a href='#plotOptions.boxplot.stemWidth'>stemWidth</a>, <a href='#plotOptions.boxplot.medianWidth'>medianWidth</a> or <a href='#plotOptions.boxplot.whiskerWidth'>whiskerWidth</a> are <code>null</code>, the lineWidth also applies to these lines.
/// Default: 1
/// </summary>
public Number? LineWidth { get; set; }
/// <summary>
/// The <a href='#series.id'>id</a> of another series to link to. Additionally, the value can be ':previous' to link to the previous series. When two series are linked, only the first one appears in the legend. Toggling the visibility of this also toggles the linked series.
/// </summary>
public string LinkedTo { get; set; }
/// <summary>
/// The color of the median line. If <code>null</code>, the general series color applies.
/// Default: null
/// </summary>
public Color? MedianColor { get; set; }
/// <summary>
/// The pixel width of the median line. If <code>null</code>, the <a href='#plotOptions.boxplot.lineWidth'>lineWidth</a> is used.
/// Default: 2
/// </summary>
public Number? MedianWidth { get; set; }
/// <summary>
/// The color for the parts of the graph or points that are below the <a href='#plotOptions.series.threshold'>threshold</a>.
/// Default: null
/// </summary>
public Color? NegativeColor { get; set; }
/// <summary>
/// Properties for each single point
/// </summary>
public PlotOptionsBoxplotPoint Point { get; set; }
/// <summary>
/// <p>If no x values are given for the points in a series, pointInterval defines the interval of the x values. For example, if a series contains one value every decade starting from year 0, set pointInterval to 10.</p>.
/// Default: 1
/// </summary>
public Number? PointInterval { get; set; }
/// <summary>
/// Padding between each column or bar, in x axis units.
/// Default: 0.1
/// </summary>
public Number? PointPadding { get; set; }
/// <summary>
/// <p>Possible values: null, 'on', 'between'.</p><p>In a column chart, when pointPlacement is 'on', the point will not create any padding of the X axis. In a polar column chart this means that the first column points directly north. If the pointPlacement is 'between', the columns will be laid out between ticks. This is useful for example for visualising an amount between two points in time or in a certain sector of a polar chart.</p><p>Defaults to <code>null</code> in cartesian charts, <code>'between'</code> in polar charts.
/// </summary>
public Placement? PointPlacement { get; set; }
/// <summary>
/// The X axis range that each point is valid for. This determines the width of the column. On a categorized axis, the range will be 1 by default (one category unit). On linear and datetime axes, the range will be computed as the distance between the two closest data points.
/// </summary>
public Number? PointRange { get; set; }
/// <summary>
/// If no x values are given for the points in a series, pointStart defines on what value to start. For example, if a series contains one yearly value starting from 1945, set pointStart to 1945.
/// Default: 0
/// </summary>
[JsonFormatter(addPropertyName: false, useCurlyBracketsForObject: false)]
public PointStart PointStart { get; set; }
/// <summary>
/// A pixel value specifying a fixed width for each column or bar. When <code>null</code>, the width is calculated from the <code>pointPadding</code> and <code>groupPadding</code>.
/// </summary>
public Number? PointWidth { get; set; }
/// <summary>
/// Whether to select the series initially. If <code>showCheckbox</code> is true, the checkbox next to the series name will be checked for a selected series.
/// Default: false
/// </summary>
public bool? Selected { get; set; }
/// <summary>
/// If true, a checkbox is displayed next to the legend item to allow selecting the series. The state of the checkbox is determined by the <code>selected</code> option.
/// Default: false
/// </summary>
public bool? ShowCheckbox { get; set; }
/// <summary>
/// Whether to display this particular series or series type in the legend.
/// Default: true
/// </summary>
public bool? ShowInLegend { get; set; }
/// <summary>
/// A wrapper object for all the series options in specific states.
/// </summary>
public PlotOptionsBoxplotStates States { get; set; }
/// <summary>
/// The color of the stem, the vertical line extending from the box to the whiskers. If <code>null</code>, the series color is used.
/// Default: null
/// </summary>
public Color? StemColor { get; set; }
/// <summary>
/// The dash style of the stem, the vertical line extending from the box to the whiskers.
/// Default: Solid
/// </summary>
public DashStyles? StemDashStyle { get; set; }
/// <summary>
/// The width of the stem, the vertical line extending from the box to the whiskers. If <code>null</code>, the width is inherited from the <a href='#plotOptions.boxplot.lineWidth'>lineWidth</a> option.
/// Default: null
/// </summary>
public Number? StemWidth { get; set; }
/// <summary>
/// Sticky tracking of mouse events. When true, the <code>mouseOut</code> event on a series isn't triggered until the mouse moves over another series, or out of the plot area. When false, the <code>mouseOut</code> event on a series is triggered when the mouse leaves the area around the series' graph or markers. This also implies the tooltip. When <code>stickyTracking</code> is false and <code>tooltip.shared</code> is false, the tooltip will be hidden when moving the mouse between series.
/// Default: true
/// </summary>
public bool? StickyTracking { get; set; }
/// <summary>
/// A configuration object for the tooltip rendering of each single series. Properties are inherited from <a href='#tooltip'>tooltip</a>, but only the following properties can be defined on a series level.
/// </summary>
public PlotOptionsBoxplotTooltip Tooltip { get; set; }
/// <summary>
/// When a series contains a data array that is longer than this, only one dimensional arrays of numbers, or two dimensional arrays with x and y values are allowed. Also, only the first point is tested, and the rest are assumed to be the same format. This saves expensive data checking and indexing in long series.
/// Default: 1000
/// </summary>
public Number? TurboThreshold { get; set; }
/// <summary>
/// Set the initial visibility of the series.
/// Default: true
/// </summary>
public bool? Visible { get; set; }
/// <summary>
/// The color of the whiskers, the horizontal lines marking low and high values. When <code>null</code>, the general series color is used.
/// Default: null
/// </summary>
public Color? WhiskerColor { get; set; }
/// <summary>
/// The length of the whiskers, the horizontal lines marking low and high values. It can be a numerical pixel value, or a percentage value of the box width. Set <code>0</code> to disable whiskers.
/// Default: 50%
/// </summary>
[JsonFormatter(addPropertyName: true, useCurlyBracketsForObject: false)]
public PercentageOrPixel WhiskerLength { get; set; }
/// <summary>
/// The line width of the whiskers, the horizontal lines marking low and high values. When <code>null</code>, the general <a href='#plotOptions.boxplot.lineWidth'>lineWidth</a> applies.
/// Default: 2
/// </summary>
public Number? WhiskerWidth { get; set; }
/// <summary>
/// Define the z index of the series.
/// </summary>
public Number? ZIndex { get; set; }
}
}
| |
using System;
using System.Collections.Generic;
using System.Data.Services.Common;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Runtime.Versioning;
namespace NuGet
{
[DataServiceKey("Id", "Version")]
[EntityPropertyMapping("LastUpdated", SyndicationItemProperty.Updated, SyndicationTextContentKind.Plaintext, keepInContent: false)]
[EntityPropertyMapping("Id", SyndicationItemProperty.Title, SyndicationTextContentKind.Plaintext, keepInContent: false)]
[EntityPropertyMapping("Authors", SyndicationItemProperty.AuthorName, SyndicationTextContentKind.Plaintext, keepInContent: false)]
[EntityPropertyMapping("Summary", SyndicationItemProperty.Summary, SyndicationTextContentKind.Plaintext, keepInContent: false)]
[CLSCompliant(false)]
public class DataServicePackage : IPackage
{
private IHashProvider _hashProvider;
private bool _usingMachineCache;
private string _licenseNames;
internal IPackage _package;
public string Id
{
get;
set;
}
public string Version
{
get;
set;
}
public string Title
{
get;
set;
}
public string Authors
{
get;
set;
}
public string Owners
{
get;
set;
}
public Uri IconUrl
{
get;
set;
}
public Uri LicenseUrl
{
get;
set;
}
public Uri ProjectUrl
{
get;
set;
}
public Uri ReportAbuseUrl
{
get;
set;
}
public Uri GalleryDetailsUrl
{
get;
set;
}
public string LicenseNames
{
get { return _licenseNames; }
set
{
_licenseNames = value;
LicenseNameCollection =
String.IsNullOrEmpty(value) ? new string[0] : value.Split(';').ToArray();
}
}
public ICollection<string> LicenseNameCollection { get; private set; }
public Uri LicenseReportUrl { get; set; }
public Uri DownloadUrl
{
get
{
return Context.GetReadStreamUri(this);
}
}
public bool Listed
{
get;
set;
}
public DateTimeOffset? Published
{
get;
set;
}
public DateTimeOffset LastUpdated
{
get;
set;
}
public int DownloadCount
{
get;
set;
}
public bool RequireLicenseAcceptance
{
get;
set;
}
public bool DevelopmentDependency
{
get;
set;
}
public string Description
{
get;
set;
}
public string Summary
{
get;
set;
}
public string ReleaseNotes
{
get;
set;
}
public string Language
{
get;
set;
}
public string Tags
{
get;
set;
}
public string Dependencies
{
get;
set;
}
public string PackageHash
{
get;
set;
}
public string PackageHashAlgorithm
{
get;
set;
}
public bool IsLatestVersion
{
get;
set;
}
public bool IsAbsoluteLatestVersion
{
get;
set;
}
public string Copyright
{
get;
set;
}
public string MinClientVersion
{
get;
set;
}
private string OldHash { get; set; }
private IPackage Package
{
get
{
EnsurePackage(MachineCache.Default);
return _package;
}
}
internal IDataServiceContext Context
{
get;
set;
}
internal PackageDownloader Downloader { get; set; }
internal IHashProvider HashProvider
{
get { return _hashProvider ?? new CryptoHashProvider(PackageHashAlgorithm); }
set { _hashProvider = value; }
}
bool IPackage.Listed
{
get
{
return Listed;
}
}
IEnumerable<string> IPackageMetadata.Authors
{
get
{
if (String.IsNullOrEmpty(Authors))
{
return Enumerable.Empty<string>();
}
return Authors.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
}
}
IEnumerable<string> IPackageMetadata.Owners
{
get
{
if (String.IsNullOrEmpty(Owners))
{
return Enumerable.Empty<string>();
}
return Owners.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
}
}
public IEnumerable<PackageDependencySet> DependencySets
{
get
{
if (String.IsNullOrEmpty(Dependencies))
{
return Enumerable.Empty<PackageDependencySet>();
}
return ParseDependencySet(Dependencies);
}
}
public ICollection<PackageReferenceSet> PackageAssemblyReferences
{
get
{
return Package.PackageAssemblyReferences;
}
}
SemanticVersion IPackageName.Version
{
get
{
if (Version != null)
{
return new SemanticVersion(Version);
}
return null;
}
}
Version IPackageMetadata.MinClientVersion
{
get
{
if (!String.IsNullOrEmpty(MinClientVersion))
{
return new Version(MinClientVersion);
}
return null;
}
}
public IEnumerable<IPackageAssemblyReference> AssemblyReferences
{
get
{
return Package.AssemblyReferences;
}
}
public IEnumerable<FrameworkAssemblyReference> FrameworkAssemblies
{
get
{
return Package.FrameworkAssemblies;
}
}
public virtual IEnumerable<FrameworkName> GetSupportedFrameworks()
{
return Package.GetSupportedFrameworks();
}
public IEnumerable<IPackageFile> GetFiles()
{
return Package.GetFiles();
}
public Stream GetStream()
{
return Package.GetStream();
}
public override string ToString()
{
return this.GetFullName();
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
internal void EnsurePackage(IPackageCacheRepository cacheRepository)
{
// OData caches instances of DataServicePackage while updating their property values. As a result,
// the ZipPackage that we downloaded may no longer be valid (as indicated by a newer hash).
// When using MachineCache, once we've verified that the hashes match (which happens the first time around),
// we'll simply verify the file exists between successive calls.
IPackageMetadata packageMetadata = this;
bool refreshPackage = _package == null ||
(_package is OptimizedZipPackage && !((OptimizedZipPackage)_package).IsValid) ||
!String.Equals(OldHash, PackageHash, StringComparison.OrdinalIgnoreCase) ||
(_usingMachineCache && !cacheRepository.Exists(Id, packageMetadata.Version));
if (refreshPackage &&
TryGetPackage(cacheRepository, packageMetadata, out _package) &&
_package.GetHash(HashProvider).Equals(PackageHash, StringComparison.OrdinalIgnoreCase))
{
OldHash = PackageHash;
// Reset the flag so that we no longer need to download the package since it exists and is valid.
refreshPackage = false;
// Make a note that the backing store for the ZipPackage is the machine cache.
_usingMachineCache = true;
}
if (refreshPackage)
{
// We either do not have a package available locally or they are invalid. Download the package from the server.
_usingMachineCache = cacheRepository.InvokeOnPackage(packageMetadata.Id, packageMetadata.Version,
(stream) => Downloader.DownloadPackage(DownloadUrl, this, stream)
);
if (_usingMachineCache)
{
_package = cacheRepository.FindPackage(packageMetadata.Id, packageMetadata.Version);
Debug.Assert(_package != null);
}
else
{
// this can happen when access to the %LocalAppData% directory is blocked, e.g. on Windows Azure Web Site build
using (var targetStream = new MemoryStream())
{
Downloader.DownloadPackage(DownloadUrl, this, targetStream);
targetStream.Seek(0, SeekOrigin.Begin);
_package = new ZipPackage(targetStream);
}
}
OldHash = PackageHash;
}
}
private static List<PackageDependencySet> ParseDependencySet(string value)
{
var dependencySets = new List<PackageDependencySet>();
var dependencies = value.Split('|').Select(ParseDependency).ToList();
// group the dependencies by target framework
var groups = dependencies.GroupBy(d => d.Item3);
dependencySets.AddRange(
groups.Select(g => new PackageDependencySet(
g.Key, // target framework
g.Where(pair => !String.IsNullOrEmpty(pair.Item1)) // the Id is empty when a group is empty.
.Select(pair => new PackageDependency(pair.Item1, pair.Item2))))); // dependencies by that target framework
return dependencySets;
}
/// <summary>
/// Parses a dependency from the feed in the format:
/// id or id:versionSpec, or id:versionSpec:targetFramework
/// </summary>
private static Tuple<string, IVersionSpec, FrameworkName> ParseDependency(string value)
{
if (String.IsNullOrWhiteSpace(value))
{
return null;
}
// IMPORTANT: Do not pass StringSplitOptions.RemoveEmptyEntries to this method, because it will break
// if the version spec is null, for in that case, the Dependencies string sent down is "<id>::<target framework>".
// We do want to preserve the second empty element after the split.
string[] tokens = value.Trim().Split(new[] { ':' });
if (tokens.Length == 0)
{
return null;
}
// Trim the id
string id = tokens[0].Trim();
IVersionSpec versionSpec = null;
if (tokens.Length > 1)
{
// Attempt to parse the version
VersionUtility.TryParseVersionSpec(tokens[1], out versionSpec);
}
var targetFramework = (tokens.Length > 2 && !String.IsNullOrEmpty(tokens[2]))
? VersionUtility.ParseFrameworkName(tokens[2])
: null;
return Tuple.Create(id, versionSpec, targetFramework);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "We want to return null if any error occurred while trying to find the package.")]
private static bool TryGetPackage(IPackageRepository repository, IPackageMetadata packageMetadata, out IPackage package)
{
try
{
package = repository.FindPackage(packageMetadata.Id, packageMetadata.Version);
}
catch
{
// If the package in the repository is corrupted then return null
package = null;
}
return package != null;
}
}
}
| |
// Copyright Naked Objects Group Ltd, 45 Station Road, Henley on Thames, UK, RG9 1AT
// 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.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using NakedFramework;
using NakedObjects;
namespace AdventureWorksModel {
[DisplayName("Sales Order")]
public class SalesOrderHeader : ICreditCardCreator {
#region Injected Servives
public IDomainObjectContainer Container { set; protected get; }
public ShoppingCartRepository ShoppingCartRepository { set; protected get; }
public ProductRepository ProductRepository { set; protected get; }
public SalesRepository SalesRepository { set; protected get; }
public PersonRepository PersonRepository { set; protected get; }
#endregion
#region Life Cycle Methods
public void Created() {
OrderDate = DateTime.Now.Date;
DueDate = DateTime.Now.Date.AddDays(7);
RevisionNumber = 1;
Status = 1;
SubTotal = 0;
TaxAmt = 0;
Freight = 0;
TotalDue = 0;
}
public void Updating() {
const byte increment = 1;
RevisionNumber += increment;
ModifiedDate = DateTime.Now;
}
public void Persisted() {
if (AddItemsFromCart) {
ShoppingCartRepository.AddAllItemsInCartToOrder(this);
AddItemsFromCart = false;
}
}
public void Persisting() {
rowguid = Guid.NewGuid();
ModifiedDate = DateTime.Now;
}
#endregion
[Disabled, NotPersisted, Hidden(WhenTo.OncePersisted)]
public bool AddItemsFromCart { get; set; }
#region Properties
#region ID
[NakedObjectsIgnore]
public virtual int SalesOrderID { get; set; }
#endregion
#region SalesOrderNumber
[Title]
[Disabled]
[MemberOrder(1)]
public virtual string SalesOrderNumber { get; set; }
#endregion
#region Status
//Properly, the Status property should be [Disabled], and modified only through
//appropriate actions such as Approve. It has been left modifiable here only
//to demonstrate the behaviour of Enum properties.
[MemberOrder(1.1), EnumDataType(typeof (OrderStatus))]
public virtual byte Status { get; set; }
public byte DefaultStatus() {
return (byte) OrderStatus.InProcess;
}
[NakedObjectsIgnore]
public virtual Boolean IsInProcess() {
return Status.Equals((byte) OrderStatus.InProcess);
}
[NakedObjectsIgnore]
public virtual Boolean IsApproved() {
return Status.Equals((byte) OrderStatus.Approved);
}
[NakedObjectsIgnore]
public virtual bool IsBackOrdered() {
return Status.Equals((byte) OrderStatus.BackOrdered);
}
[NakedObjectsIgnore]
public virtual bool IsRejected() {
return Status.Equals((byte) OrderStatus.Rejected);
}
[NakedObjectsIgnore]
public virtual bool IsShipped() {
return Status.Equals((byte) OrderStatus.Shipped);
}
[NakedObjectsIgnore]
public virtual bool IsCancelled() {
return Status.Equals((byte) OrderStatus.Cancelled);
}
#endregion
#region Customer
[NakedObjectsIgnore]
public virtual int CustomerID { get; set; }
[Disabled, MemberOrder(2)]
public virtual Customer Customer { get; set; }
#endregion
#region Contact
//[NakedObjectsIgnore]
//public virtual int ContactID { get; set; }
//private Contact _contact;
//[NakedObjectsIgnore]
//public virtual Contact Contact { get { return _contact; } set { _contact = value; } }
//internal void SetUpContact(Contact value) {
// Contact = value;
// storeContact = FindStoreContactForContact();
//}
//#region StoreContact Property
//private StoreContact storeContact;
//[MemberOrder(3)]
//public virtual StoreContact StoreContact {
// get { return storeContact; }
// set {
// if (value != null) {
// storeContact = value;
// Contact = value.Contact;
// }
// }
//}
//private StoreContact FindStoreContactForContact() {
// IQueryable<StoreContact> query = from obj in Container.Instances<StoreContact>()
// where obj.Contact.BusinessEntityID == Contact.BusinessEntityID && obj.Store.BusinessEntityID == Customer.Store.BusinessEntityID
// select obj;
// return query.FirstOrDefault();
//}
//public virtual bool HideStoreContact() {
// return Customer != null && Customer.IsIndividual();
//}
//[Executed(Where.Remotely)]
//public List<StoreContact> ChoicesStoreContact() {
// throw new NotImplementedException();
// //if (Customer != null && Customer.IsStore()) {
// // return new List<StoreContact>(((Store) Customer).Contacts);
// //}
// //return new List<StoreContact>();
//}
//#endregion
#endregion
#region BillingAddress
[NakedObjectsIgnore]
public virtual int BillingAddressID { get; set; }
[MemberOrder(4)]
public virtual Address BillingAddress { get; set; }
public List<Address> ChoicesBillingAddress() {
return PersonRepository.AddressesFor(Customer.BusinessEntity()).ToList();
}
#endregion
#region PurchaseOrderNumber
[Optionally, StringLength(25), MemberOrder(5)]
public virtual string PurchaseOrderNumber { get; set; }
#endregion
#region ShippingAddress
[NakedObjectsIgnore]
public virtual int ShippingAddressID { get; set; }
[MemberOrder(10)]
public virtual Address ShippingAddress { get; set; }
public List<Address> ChoicesShippingAddress() {
return ChoicesBillingAddress();
}
#endregion
#region ShipMethod
[NakedObjectsIgnore]
public virtual int ShipMethodID { get; set; }
[MemberOrder(11)]
public virtual ShipMethod ShipMethod { get; set; }
public ShipMethod DefaultShipMethod() {
return Container.Instances<ShipMethod>().FirstOrDefault();
}
#endregion
#region AccountNumber
[Optionally, StringLength(15), MemberOrder(12)]
public virtual string AccountNumber { get; set; }
#endregion
#region Dates
#region OrderDate
[Disabled]
[MemberOrder(20)]
public virtual DateTime OrderDate { get; set; }
#endregion
#region DueDate
[MemberOrder(21)]
public virtual DateTime DueDate { get; set; }
public string DisableDueDate() {
return DisableIfShipped();
}
public string ValidateDueDate(DateTime dueDate) {
if (dueDate.Date < OrderDate.Date) {
return "Due date cannot be before order date";
}
return null;
}
private string DisableIfShipped() {
if (IsShipped()) {
return "Order has been shipped";
}
return null;
}
#endregion
#region ShipDate
[Optionally]
[MemberOrder(22)]
[DataType(DataType.DateTime)][Mask("d")]//Just to prove that you can, if perverse enough, make something
//a dateTime and then mask it as a Date
[Range(-30, 0)]
public virtual DateTime? ShipDate { get; set; }
public string DisableShipDate() {
return DisableIfShipped();
}
public string ValidateShipDate(DateTime? shipDate) {
if (shipDate.HasValue && shipDate.Value.Date < OrderDate.Date) {
return "Ship date cannot be before order date";
}
return null;
}
#endregion
#endregion
#region Amounts
[Disabled]
[MemberOrder(31)]
[Mask("C")]
public virtual decimal SubTotal { get; set; }
[Disabled]
[MemberOrder(32)]
[Mask("C")]
public virtual decimal TaxAmt { get; set; }
[Disabled]
[MemberOrder(33)]
[Mask("C")]
public virtual decimal Freight { get; set; }
[Disabled]
[MemberOrder(34)]
[Mask("C")]
public virtual decimal TotalDue { get; set; }
public void Recalculate() {
SubTotal = Details.Sum(d => d.LineTotal);
TotalDue = SubTotal;
}
public virtual string DisableRecalculate()
{
if (!IsInProcess())
{
return "Can only recalculate an 'In Process' order";
}
return null;
}
#region CurrencyRate
[NakedObjectsIgnore]
public virtual int? CurrencyRateID { get; set; }
[Optionally]
[MemberOrder(35)]
[FindMenu]
public virtual CurrencyRate CurrencyRate { get; set; }
#endregion
#endregion
#region OnlineOrder
[Description("Order has been placed via the web")]
[Disabled]
[MemberOrder(41)]
[DisplayName("Online Order")]
public virtual bool OnlineOrder { get; set; }
#endregion
#region CreditCard
[NakedObjectsIgnore]
public virtual int? CreditCardID { get; set; }
[Optionally]
[MemberOrder(42)]
public virtual CreditCard CreditCard { get; set; }
#endregion
#region CreditCardApprovalCode
[Disabled]
[StringLength(15)]
[MemberOrder(43)]
public virtual string CreditCardApprovalCode { get; set; }
#endregion
#region RevisionNumber
[Disabled]
[MemberOrder(51)]
public virtual byte RevisionNumber { get; set; }
#endregion
#region Comment
[Optionally]
[MultiLine(NumberOfLines = 3, Width = 50)]
[MemberOrder(52)]
[Description("Free-form text")]
public virtual string Comment { get; set; }
public bool HideComment()
{
return Comment == null || Comment == "";
}
public void ClearComment()
{
this.Comment = null;
}
public void AddStandardComments(IEnumerable<string> comments) {
foreach (string comment in comments) {
Comment += comment + "\n";
}
}
public string[] Choices0AddStandardComments() {
return new[] {
"Payment on delivery",
"Leave parcel with neighbour",
"Leave parcel round back"
};
}
public string[] Default0AddStandardComments() {
return new[] {
"Payment on delivery",
"Leave parcel with neighbour"
};
}
//Action to demonstrate use of auto-complete that returns IEnumerable<string>
public void AddComment(string comment) {
Comment += comment + "\n";
}
[PageSize(10)]
public IEnumerable<string> AutoComplete0AddComment(
[DescribedAs("Auto-complete")] [MinLength(2)] string matching) {
return Choices0AddStandardComments().Where(c => c.ToLower().Contains(matching.ToLower()));
}
//Action to demonstrate use of auto-complete that returns IEnumerable<string>
public void AddComment2(string comment) {
Comment += comment + "\n";
}
[PageSize(10)]
public IList<string> AutoComplete0AddComment2(
[DescribedAs("Auto-complete")] [MinLength(2)] string matching) {
return Choices0AddStandardComments().Where(c => c.ToLower().Contains(matching.ToLower())).ToList();
}
public void AddMultiLineComment([MultiLine(NumberOfLines = 3)] string comment)
{
Comment += comment + "\n";
}
#endregion
#region SalesPerson
[NakedObjectsIgnore]
public virtual int? SalesPersonID { get; set; }
[Optionally]
[MemberOrder(61)]
public virtual SalesPerson SalesPerson { get; set; }
[PageSize(20)]
public IQueryable<SalesPerson> AutoCompleteSalesPerson([MinLength(2)] string name) {
return SalesRepository.FindSalesPersonByName(null, name);
}
#endregion
#region SalesTerritory
[NakedObjectsIgnore]
public virtual int? SalesTerritoryID { get; set; }
[Optionally]
[MemberOrder(62)]
public virtual SalesTerritory SalesTerritory { get; set; }
#endregion
#region ModifiedDate and rowguid
#region ModifiedDate
[MemberOrder(99)]
[Disabled]
[ConcurrencyCheck]
public virtual DateTime ModifiedDate { get; set; }
#endregion
#region rowguid
[NakedObjectsIgnore]
public virtual Guid rowguid { get; set; }
#endregion
#endregion
#endregion
#region Collections
#region Details
private ICollection<SalesOrderDetail> details = new List<SalesOrderDetail>();
[Disabled]
public virtual ICollection<SalesOrderDetail> Details {
get { return details; }
set { details = value; }
}
#endregion
#region Reasons
private ICollection<SalesOrderHeaderSalesReason> salesOrderHeaderSalesReason = new List<SalesOrderHeaderSalesReason>();
[Disabled]
[DisplayName("Reasons")]
public virtual ICollection<SalesOrderHeaderSalesReason> SalesOrderHeaderSalesReason {
get { return salesOrderHeaderSalesReason; }
set { salesOrderHeaderSalesReason = value; }
}
#endregion
#endregion
#region Actions
#region Add New Detail
[Description("Add a new line item to the order")]
#pragma warning disable 612,618
[MemberOrder(Sequence="2", Name ="Details")]
#pragma warning restore 612,618
public SalesOrderDetail AddNewDetail(Product product,
[DefaultValue((short) 1), Range(1, 999)] short quantity) {
int stock = product.NumberInStock();
if (stock < quantity) {
var t = Container.NewTitleBuilder();
t.Append("Current inventory of").Append(product).Append(" is").Append(stock);
Container.WarnUser(t.ToString());
}
var sod = Container.NewTransientInstance<SalesOrderDetail>();
sod.SalesOrderHeader = this;
sod.SalesOrderID = SalesOrderID;
sod.OrderQty = quantity;
sod.SpecialOfferProduct = product.BestSpecialOfferProduct(quantity);
sod.Recalculate();
return sod;
}
public virtual string DisableAddNewDetail() {
if (!IsInProcess()) {
return "Can only add to 'In Process' order";
}
return null;
}
[PageSize(20)]
public IQueryable<Product> AutoComplete0AddNewDetail([MinLength(2)] string name) {
return ProductRepository.FindProductByName(name);
}
#endregion
#region Add New Details
[Description("Add multiple line items to the order")]
[MultiLine()]
#pragma warning disable 612, 618
[MemberOrder(Sequence = "1", Name = "Details")]
#pragma warning restore 612,618
public void AddNewDetails(Product product,
[DefaultValue((short)1)] short quantity)
{
var detail = AddNewDetail(product, quantity);
Container.Persist(ref detail);
}
public virtual string DisableAddNewDetails()
{
return DisableAddNewDetail();
}
[PageSize(20)]
public IQueryable<Product> AutoComplete0AddNewDetails([MinLength(2)] string name)
{
return AutoComplete0AddNewDetail(name);
}
public string ValidateAddNewDetails(short quantity)
{
var rb = new ReasonBuilder();
rb.AppendOnCondition(quantity <= 0, "Must be > 0");
return rb.Reason;
}
#endregion
#region Remove Detail
public void RemoveDetail(SalesOrderDetail detailToRemove) {
if (Details.Contains(detailToRemove)) {
Details.Remove(detailToRemove);
}
}
public IEnumerable<SalesOrderDetail> Choices0RemoveDetail() {
return Details;
}
public SalesOrderDetail Default0RemoveDetail() {
return Details.FirstOrDefault();
}
[MemberOrder(3)]
public void RemoveDetails([ContributedAction] IEnumerable<SalesOrderDetail> details) {
foreach (SalesOrderDetail detail in details) {
if (Details.Contains(detail)) {
Details.Remove(detail);
}
}
}
#endregion
#region AdjustQuantities
[MemberOrder(4)]
public void AdjustQuantities([ContributedAction] IEnumerable<SalesOrderDetail> details, short newQuantity)
{
foreach (SalesOrderDetail detail in details)
{
detail.OrderQty = newQuantity;
}
}
public string ValidateAdjustQuantities(IEnumerable<SalesOrderDetail> details, short newQuantity)
{
var rb = new ReasonBuilder();
rb.AppendOnCondition(details.Count(d => d.OrderQty == newQuantity) == details.Count(),
"All selected details already have specified quantity");
return rb.Reason;
}
#endregion
#region CreateNewCreditCard
[NakedObjectsIgnore]
public void CreatedCardHasBeenSaved(CreditCard card) {
CreditCard = card;
}
#endregion
#region AddNewSalesReason
#pragma warning disable 618
[MemberOrder(Name= "SalesOrderHeaderSalesReason", Sequence = "1")]
#pragma warning restore 618
public void AddNewSalesReason(SalesReason reason) {
if (SalesOrderHeaderSalesReason.All(y => y.SalesReason != reason)) {
var link = Container.NewTransientInstance<SalesOrderHeaderSalesReason>();
link.SalesOrderHeader = this;
link.SalesReason = reason;
Container.Persist(ref link);
SalesOrderHeaderSalesReason.Add(link);
}
else {
Container.WarnUser(string.Format("{0} already exists in Sales Reasons", reason.Name));
}
}
public string ValidateAddNewSalesReason(SalesReason reason) {
return SalesOrderHeaderSalesReason.Any(y => y.SalesReason == reason) ? string.Format("{0} already exists in Sales Reasons", reason.Name) : null;
}
[MemberOrder(1)]
public void RemoveSalesReason(SalesOrderHeaderSalesReason reason)
{
this.SalesOrderHeaderSalesReason.Remove(reason);
Container.DisposeInstance(reason);
}
public IList<SalesOrderHeaderSalesReason> Choices0RemoveSalesReason()
{
return this.SalesOrderHeaderSalesReason.ToList();
}
[MemberOrder(2)]
public void AddNewSalesReasons(IEnumerable<SalesReason> reasons) {
foreach (SalesReason r in reasons) {
AddNewSalesReason(r);
}
}
public string ValidateAddNewSalesReasons(IEnumerable<SalesReason> reasons) {
return reasons.Select(ValidateAddNewSalesReason).Aggregate("", (s, t) => string.IsNullOrEmpty(s) ? t : s + ", " + t);
}
[MemberOrder(2)]
public void RemoveSalesReasons(
[ContributedAction] IEnumerable<SalesOrderHeaderSalesReason> salesOrderHeaderSalesReason)
{
foreach(var reason in salesOrderHeaderSalesReason)
{
this.RemoveSalesReason(reason);
}
}
// This is done with an enum in order to test enum parameter handling by the framework
public enum SalesReasonCategories {
Other,
Promotion,
Marketing
}
[MemberOrder(3)]
public void AddNewSalesReasonsByCategory(SalesReasonCategories reasonCategory) {
IQueryable<SalesReason> allReasons = Container.Instances<SalesReason>();
var catName = reasonCategory.ToString();
foreach (SalesReason salesReason in allReasons.Where(salesReason => salesReason.ReasonType == catName)) {
AddNewSalesReason(salesReason);
}
}
[MemberOrder(4)]
public void AddNewSalesReasonsByCategories(IEnumerable<SalesReasonCategories> reasonCategories) {
foreach (SalesReasonCategories rc in reasonCategories) {
AddNewSalesReasonsByCategory(rc);
}
}
// Use 'hide', 'dis', 'val', 'actdef', 'actcho' shortcuts to add supporting methods here.
#endregion
#region ApproveOrder
[MemberOrder(1)]
public void ApproveOrder() {
Status = (byte) OrderStatus.Approved;
}
public virtual bool HideApproveOrder() {
return !IsInProcess();
}
public virtual string DisableApproveOrder() {
var rb = new ReasonBuilder();
if (Details.Count == 0) {
rb.Append("Cannot approve orders with no Details");
}
return rb.Reason;
}
#endregion
#region MarkAsShipped
[Description("Indicate that the order has been shipped, specifying the date")]
[Hidden(WhenTo.Always)] //Testing that the complementary methods don't show up either
public void MarkAsShipped(DateTime shipDate) {
Status = (byte) OrderStatus.Shipped;
ShipDate = shipDate;
}
public virtual string ValidateMarkAsShipped(DateTime date) {
var rb = new ReasonBuilder();
if (date.Date > DateTime.Now.Date) {
rb.Append("Ship Date cannot be after Today");
}
return rb.Reason;
}
public virtual string DisableMarkAsShipped() {
if (!IsApproved()) {
return "Order must be Approved before shipping";
}
return null;
}
public virtual bool HideMarkAsShipped() {
return IsRejected() || IsShipped() || IsCancelled();
}
#endregion
#region CancelOrder
// return this for testing purposes
public SalesOrderHeader CancelOrder() {
Status = (byte) OrderStatus.Cancelled;
return this;
}
public virtual bool HideCancelOrder() {
return IsShipped() || IsCancelled();
}
#endregion
#endregion
}
public enum OrderStatus : byte {
InProcess = 1,
Approved = 2,
BackOrdered = 3,
Rejected = 4,
Shipped = 5,
Cancelled = 6
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="OleDbMetaDataFactory.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// <owner current="true" primary="true">[....]</owner>
// <owner current="true" primary="false">Mugunm</owner>
//
//------------------------------------------------------------------------------
namespace System.Data.OleDb{
using System;
using System.Data;
using System.IO;
using System.Collections;
using System.Data.ProviderBase;
using System.Data.Common;
using System.Diagnostics;
using System.Globalization;
using System.Text;
using System.Xml;
using System.Xml.Schema;
internal sealed class OleDbMetaDataFactory : DbMetaDataFactory{ // V1.2.3300
private struct SchemaRowsetName {
internal SchemaRowsetName(string schemaName, Guid schemaRowset) {
_schemaName = schemaName;
_schemaRowset = schemaRowset;
}
internal readonly string _schemaName;
internal readonly Guid _schemaRowset;
}
private const string _collectionName = "CollectionName";
private const string _populationMechanism = "PopulationMechanism";
private const string _prepareCollection = "PrepareCollection";
private readonly SchemaRowsetName[] _schemaMapping;
internal OleDbMetaDataFactory(Stream XMLStream,
string serverVersion,
string serverVersionNormalized,
SchemaSupport[] schemaSupport):
base(XMLStream, serverVersion, serverVersionNormalized) {
// set up the colletion mane schema rowset guid mapping
_schemaMapping = new SchemaRowsetName[] {
new SchemaRowsetName(DbMetaDataCollectionNames.DataTypes,OleDbSchemaGuid.Provider_Types),
new SchemaRowsetName(OleDbMetaDataCollectionNames.Catalogs,OleDbSchemaGuid.Catalogs),
new SchemaRowsetName(OleDbMetaDataCollectionNames.Collations,OleDbSchemaGuid.Collations),
new SchemaRowsetName(OleDbMetaDataCollectionNames.Columns,OleDbSchemaGuid.Columns),
new SchemaRowsetName(OleDbMetaDataCollectionNames.Indexes,OleDbSchemaGuid.Indexes),
new SchemaRowsetName(OleDbMetaDataCollectionNames.Procedures,OleDbSchemaGuid.Procedures),
new SchemaRowsetName(OleDbMetaDataCollectionNames.ProcedureColumns,OleDbSchemaGuid.Procedure_Columns),
new SchemaRowsetName(OleDbMetaDataCollectionNames.ProcedureParameters,OleDbSchemaGuid.Procedure_Parameters),
new SchemaRowsetName(OleDbMetaDataCollectionNames.Tables,OleDbSchemaGuid.Tables),
new SchemaRowsetName(OleDbMetaDataCollectionNames.Views,OleDbSchemaGuid.Views)};
// verify the existance of the table in the data set
DataTable metaDataCollectionsTable = CollectionDataSet.Tables[DbMetaDataCollectionNames.MetaDataCollections];
if (metaDataCollectionsTable == null){
throw ADP.UnableToBuildCollection(DbMetaDataCollectionNames.MetaDataCollections);
}
// copy the table filtering out any rows that don't apply to the current version of the provider
metaDataCollectionsTable = CloneAndFilterCollection(DbMetaDataCollectionNames.MetaDataCollections, null);
// verify the existance of the table in the data set
DataTable restrictionsTable = CollectionDataSet.Tables[DbMetaDataCollectionNames.Restrictions];
if (restrictionsTable != null){
// copy the table filtering out any rows that don't apply to the current version of the provider
restrictionsTable= CloneAndFilterCollection(DbMetaDataCollectionNames.Restrictions, null);
}
// need to filter out any of the collections where
// 1) it is populated using prepare collection
// 2) it is in the collection to schema rowset mapping above
// 3) the provider does not support the necessary schema rowset
DataColumn populationMechanism = metaDataCollectionsTable.Columns[_populationMechanism];
if ((null == populationMechanism) || (typeof(System.String) != populationMechanism.DataType)) {
throw ADP.InvalidXmlMissingColumn(DbMetaDataCollectionNames.MetaDataCollections,_populationMechanism);
}
DataColumn collectionName = metaDataCollectionsTable.Columns[_collectionName];
if ((null == collectionName) || (typeof(System.String) != collectionName.DataType)) {
throw ADP.InvalidXmlMissingColumn(DbMetaDataCollectionNames.MetaDataCollections,_collectionName);
}
DataColumn restrictionCollectionName = null;
if (restrictionsTable != null){
restrictionCollectionName = restrictionsTable.Columns[_collectionName];
if ((null == restrictionCollectionName) || (typeof(System.String) != restrictionCollectionName.DataType)) {
throw ADP.InvalidXmlMissingColumn(DbMetaDataCollectionNames.Restrictions,_collectionName);
}
}
foreach (DataRow collection in metaDataCollectionsTable.Rows){
string populationMechanismValue = collection[populationMechanism] as string;
if (ADP.IsEmpty(populationMechanismValue )) {
throw ADP.InvalidXmlInvalidValue(DbMetaDataCollectionNames.MetaDataCollections,_populationMechanism);
}
string collectionNameValue = collection[collectionName] as string;
if (ADP.IsEmpty(collectionNameValue)) {
throw ADP.InvalidXmlInvalidValue(DbMetaDataCollectionNames.MetaDataCollections,_collectionName);
}
if (populationMechanismValue == _prepareCollection) {
// is the collection in the mapping
int mapping = -1;
for (int i = 0; i < _schemaMapping.Length; i++){
if (_schemaMapping[i]._schemaName == collectionNameValue){
mapping = i;
break;
}
}
// no go on to the next collection
if (mapping == -1) {
continue;
}
// does the provider support the necessary schema rowset
bool isSchemaRowsetSupported = false;
if (schemaSupport != null){
for (int i = 0; i < schemaSupport.Length; i++){
if (_schemaMapping[mapping]._schemaRowset == schemaSupport[i]._schemaRowset){
isSchemaRowsetSupported = true;
break;
}
}
}
// if not delete the row from the table
if (isSchemaRowsetSupported == false){
// but first delete any related restrictions
if (restrictionsTable != null) {
foreach (DataRow restriction in restrictionsTable.Rows) {
string restrictionCollectionNameValue = restriction[restrictionCollectionName] as string;
if (ADP.IsEmpty(restrictionCollectionNameValue)) {
throw ADP.InvalidXmlInvalidValue(DbMetaDataCollectionNames.Restrictions,_collectionName);
}
if (collectionNameValue == restrictionCollectionNameValue) {
restriction.Delete();
}
}
restrictionsTable.AcceptChanges();
}
collection.Delete();
}
}
}
// replace the original table with the updated one
metaDataCollectionsTable.AcceptChanges();
CollectionDataSet.Tables.Remove(CollectionDataSet.Tables[DbMetaDataCollectionNames.MetaDataCollections]);
CollectionDataSet.Tables.Add(metaDataCollectionsTable);
if (restrictionsTable != null) {
CollectionDataSet.Tables.Remove(CollectionDataSet.Tables[DbMetaDataCollectionNames.Restrictions]);
CollectionDataSet.Tables.Add(restrictionsTable);
}
}
private String BuildRegularExpression(string invalidChars, string invalidStartingChars){
StringBuilder regularExpression = new StringBuilder("[^");
ADP.EscapeSpecialCharacters(invalidStartingChars,regularExpression);
regularExpression.Append("][^");
ADP.EscapeSpecialCharacters(invalidChars,regularExpression);
regularExpression.Append("]*");
return regularExpression.ToString();
}
private DataTable GetDataSourceInformationTable(OleDbConnection connection, OleDbConnectionInternal internalConnection){
// verify that the data source information table is in the data set
DataTable dataSourceInformationTable = CollectionDataSet.Tables[DbMetaDataCollectionNames.DataSourceInformation];
if (dataSourceInformationTable == null){
throw ADP.UnableToBuildCollection(DbMetaDataCollectionNames.DataSourceInformation);
}
// copy the table filtering out any rows that don't apply to tho current version of the prrovider
dataSourceInformationTable = CloneAndFilterCollection(DbMetaDataCollectionNames.DataSourceInformation, null);
// after filtering there better be just one row
if (dataSourceInformationTable.Rows.Count != 1){
throw ADP.IncorrectNumberOfDataSourceInformationRows();
}
DataRow dataSourceInformation = dataSourceInformationTable.Rows[0];
// update the identifier separator
string catalogSeparatorPattern = internalConnection.GetLiteralInfo(ODB.DBLITERAL_CATALOG_SEPARATOR);
string schemaSeparatorPattern = internalConnection.GetLiteralInfo(ODB.DBLITERAL_SCHEMA_SEPARATOR);
if (catalogSeparatorPattern != null) {
StringBuilder compositeSeparatorPattern = new StringBuilder();
StringBuilder patternEscaped = new StringBuilder();
ADP.EscapeSpecialCharacters(catalogSeparatorPattern,patternEscaped);
compositeSeparatorPattern.Append(patternEscaped.ToString());
if ((schemaSeparatorPattern != null) && (schemaSeparatorPattern != catalogSeparatorPattern)) {
compositeSeparatorPattern.Append("|");
patternEscaped.Length = 0;
ADP.EscapeSpecialCharacters(schemaSeparatorPattern,patternEscaped);
compositeSeparatorPattern.Append(patternEscaped.ToString());
}
dataSourceInformation[DbMetaDataColumnNames.CompositeIdentifierSeparatorPattern] = compositeSeparatorPattern.ToString();
}
else if (schemaSeparatorPattern != null){
StringBuilder patternEscaped = new StringBuilder();
ADP.EscapeSpecialCharacters(schemaSeparatorPattern, patternEscaped);
dataSourceInformation[DbMetaDataColumnNames.CompositeIdentifierSeparatorPattern] = patternEscaped.ToString();;
}
// update the DataSourceProductName
object property;
property = connection.GetDataSourcePropertyValue(OleDbPropertySetGuid.DataSourceInfo,ODB.DBPROP_DBMSNAME);
if (property != null) {
dataSourceInformation[DbMetaDataColumnNames.DataSourceProductName] = (string) property;
}
// update the server version strings
dataSourceInformation[DbMetaDataColumnNames.DataSourceProductVersion] = ServerVersion;
dataSourceInformation[DbMetaDataColumnNames.DataSourceProductVersionNormalized] = ServerVersionNormalized;
// values that are the same for all OLE DB Providers. See SQLBU 308529
dataSourceInformation[DbMetaDataColumnNames.ParameterMarkerFormat] = "?";
dataSourceInformation[DbMetaDataColumnNames.ParameterMarkerPattern] = "\\?";
dataSourceInformation[DbMetaDataColumnNames.ParameterNameMaxLength] = 0;
property = connection.GetDataSourcePropertyValue(OleDbPropertySetGuid.DataSourceInfo,ODB.DBPROP_GROUPBY);
GroupByBehavior groupByBehavior = GroupByBehavior.Unknown;
if (property != null) {
switch ((int)property) {
case ODB.DBPROPVAL_GB_CONTAINS_SELECT:
groupByBehavior = GroupByBehavior.MustContainAll;
break;
case ODB.DBPROPVAL_GB_EQUALS_SELECT:
groupByBehavior = GroupByBehavior.ExactMatch;
break;
case ODB.DBPROPVAL_GB_NO_RELATION:
groupByBehavior = GroupByBehavior.Unrelated;
break;
case ODB.DBPROPVAL_GB_NOT_SUPPORTED:
groupByBehavior = GroupByBehavior.NotSupported;
break;
}
}
dataSourceInformation[DbMetaDataColumnNames.GroupByBehavior] = groupByBehavior;
SetIdentifierCase(DbMetaDataColumnNames.IdentifierCase,ODB.DBPROP_IDENTIFIERCASE,dataSourceInformation, connection);
SetIdentifierCase(DbMetaDataColumnNames.QuotedIdentifierCase,ODB.DBPROP_QUOTEDIDENTIFIERCASE,dataSourceInformation, connection);
property = connection.GetDataSourcePropertyValue(OleDbPropertySetGuid.DataSourceInfo,ODB.DBPROP_ORDERBYCOLUNSINSELECT);
if (property != null) {
dataSourceInformation[DbMetaDataColumnNames.OrderByColumnsInSelect] = (bool) property;
}
DataTable infoLiterals = internalConnection.BuildInfoLiterals();
if (infoLiterals != null){
DataRow[] tableNameRow = infoLiterals.Select("Literal = " + ODB.DBLITERAL_TABLE_NAME.ToString(CultureInfo.InvariantCulture));
if (tableNameRow != null) {
object invalidCharsObject = tableNameRow[0]["InvalidChars"];
if (invalidCharsObject.GetType() == typeof(string)) {
string invalidChars = (string)invalidCharsObject;
object invalidStartingCharsObject = tableNameRow[0]["InvalidStartingChars"];
string invalidStartingChars;
if (invalidStartingCharsObject.GetType() == typeof(string)) {
invalidStartingChars = (string)invalidStartingCharsObject;
}
else {
invalidStartingChars = invalidChars;
}
dataSourceInformation[DbMetaDataColumnNames.IdentifierPattern] =
BuildRegularExpression(invalidChars,invalidStartingChars);
}
}
}
// build the QuotedIdentifierPattern using the quote prefix and suffix from the provider and
// assuming that the quote suffix is escaped via repetion (i.e " becomes "")
string quotePrefix;
string quoteSuffix;
connection.GetLiteralQuotes(ADP.GetSchema, out quotePrefix, out quoteSuffix);
if (quotePrefix != null){
// if the quote suffix is null assume that it is the same as the prefix (See OLEDB spec
// IDBInfo::GetLiteralInfo DBLITERAL_QUOTE_SUFFIX.)
if (quoteSuffix == null) {
quoteSuffix = quotePrefix;
}
// only know how to build the parttern if the suffix is 1 character
// in all other cases just leave the field null
if (quoteSuffix.Length == 1) {
StringBuilder scratchStringBuilder = new StringBuilder();
ADP.EscapeSpecialCharacters(quoteSuffix,scratchStringBuilder );
string escapedQuoteSuffixString = scratchStringBuilder.ToString();
scratchStringBuilder.Length = 0;
ADP.EscapeSpecialCharacters(quotePrefix, scratchStringBuilder);
scratchStringBuilder.Append("(([^");
scratchStringBuilder.Append(escapedQuoteSuffixString);
scratchStringBuilder.Append("]|");
scratchStringBuilder.Append(escapedQuoteSuffixString);
scratchStringBuilder.Append(escapedQuoteSuffixString);
scratchStringBuilder.Append(")*)");
scratchStringBuilder.Append(escapedQuoteSuffixString);
dataSourceInformation[DbMetaDataColumnNames.QuotedIdentifierPattern] = scratchStringBuilder.ToString();
}
}
dataSourceInformationTable.AcceptChanges();
return dataSourceInformationTable;
}
private DataTable GetDataTypesTable(OleDbConnection connection){
// verify the existance of the table in the data set
DataTable dataTypesTable = CollectionDataSet.Tables[DbMetaDataCollectionNames.DataTypes];
if (dataTypesTable == null){
throw ADP.UnableToBuildCollection(DbMetaDataCollectionNames.DataTypes);
}
// copy the table filtering out any rows that don't apply to tho current version of the prrovider
dataTypesTable = CloneAndFilterCollection(DbMetaDataCollectionNames.DataTypes, null);
DataTable providerTypesTable = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Provider_Types,null);
DataColumn[] targetColumns = new DataColumn[] {
dataTypesTable.Columns[DbMetaDataColumnNames.TypeName],
dataTypesTable.Columns[DbMetaDataColumnNames.ColumnSize],
dataTypesTable.Columns[DbMetaDataColumnNames.CreateParameters],
dataTypesTable.Columns[DbMetaDataColumnNames.IsAutoIncrementable],
dataTypesTable.Columns[DbMetaDataColumnNames.IsCaseSensitive],
dataTypesTable.Columns[DbMetaDataColumnNames.IsFixedLength],
dataTypesTable.Columns[DbMetaDataColumnNames.IsFixedPrecisionScale],
dataTypesTable.Columns[DbMetaDataColumnNames.IsLong],
dataTypesTable.Columns[DbMetaDataColumnNames.IsNullable],
dataTypesTable.Columns[DbMetaDataColumnNames.IsUnsigned],
dataTypesTable.Columns[DbMetaDataColumnNames.MaximumScale],
dataTypesTable.Columns[DbMetaDataColumnNames.MinimumScale],
dataTypesTable.Columns[DbMetaDataColumnNames.LiteralPrefix],
dataTypesTable.Columns[DbMetaDataColumnNames.LiteralSuffix],
dataTypesTable.Columns[OleDbMetaDataColumnNames.NativeDataType]};
DataColumn[] sourceColumns = new DataColumn[] {
providerTypesTable.Columns["TYPE_NAME"],
providerTypesTable.Columns["COLUMN_SIZE"],
providerTypesTable.Columns["CREATE_PARAMS"],
providerTypesTable.Columns["AUTO_UNIQUE_VALUE"],
providerTypesTable.Columns["CASE_SENSITIVE"],
providerTypesTable.Columns["IS_FIXEDLENGTH"],
providerTypesTable.Columns["FIXED_PREC_SCALE"],
providerTypesTable.Columns["IS_LONG"],
providerTypesTable.Columns["IS_NULLABLE"],
providerTypesTable.Columns["UNSIGNED_ATTRIBUTE"],
providerTypesTable.Columns["MAXIMUM_SCALE"],
providerTypesTable.Columns["MINIMUM_SCALE"],
providerTypesTable.Columns["LITERAL_PREFIX"],
providerTypesTable.Columns["LITERAL_SUFFIX"],
providerTypesTable.Columns["DATA_TYPE"]};
Debug.Assert(sourceColumns.Length == targetColumns.Length);
DataColumn isSearchable = dataTypesTable.Columns[DbMetaDataColumnNames.IsSearchable];
DataColumn isSearchableWithLike = dataTypesTable.Columns[DbMetaDataColumnNames.IsSearchableWithLike];
DataColumn providerDbType = dataTypesTable.Columns[DbMetaDataColumnNames.ProviderDbType];
DataColumn clrType = dataTypesTable.Columns[DbMetaDataColumnNames.DataType];
DataColumn isLong = dataTypesTable.Columns[DbMetaDataColumnNames.IsLong];
DataColumn isFixed = dataTypesTable.Columns[DbMetaDataColumnNames.IsFixedLength];
DataColumn sourceOleDbType = providerTypesTable.Columns["DATA_TYPE"];
DataColumn searchable = providerTypesTable.Columns["SEARCHABLE"];
foreach (DataRow sourceRow in providerTypesTable.Rows) {
DataRow newRow = dataTypesTable.NewRow();
for (int i = 0; i < sourceColumns.Length; i++) {
if ((sourceColumns[i] != null) && (targetColumns[i] != null)){
newRow[targetColumns[i]] = sourceRow[sourceColumns[i]];
}
}
short nativeDataType = (short) Convert.ChangeType(sourceRow[sourceOleDbType],typeof(short), CultureInfo.InvariantCulture);
NativeDBType nativeType = NativeDBType.FromDBType(nativeDataType,(bool)newRow[isLong], (bool)newRow[isFixed]);
newRow[clrType] = nativeType.dataType.FullName;
newRow[providerDbType] = nativeType.enumOleDbType;
// searchable has to be special cased becasue it is not an eaxct mapping
if ((isSearchable != null) && (isSearchableWithLike != null) && (searchable != null)) {
newRow[isSearchable] = DBNull.Value;
newRow[isSearchableWithLike] = DBNull.Value;
if ( DBNull.Value != sourceRow[searchable]){
Int64 searchableValue = (Int64)(sourceRow[searchable]);
switch (searchableValue){
case ODB.DB_UNSEARCHABLE:
newRow[isSearchable] = false;
newRow[isSearchableWithLike] = false;
break;
case ODB.DB_LIKE_ONLY:
newRow[isSearchable] = false;
newRow[isSearchableWithLike] = true;
break;
case ODB.DB_ALL_EXCEPT_LIKE:
newRow[isSearchable] = true;
newRow[isSearchableWithLike] = false;
break;
case ODB.DB_SEARCHABLE:
newRow[isSearchable] = true;
newRow[isSearchableWithLike] = true;
break;
}
}
}
dataTypesTable.Rows.Add(newRow);
}
dataTypesTable.AcceptChanges();
return dataTypesTable;
}
private DataTable GetReservedWordsTable(OleDbConnectionInternal internalConnection){
// verify the existance of the table in the data set
DataTable reservedWordsTable = CollectionDataSet.Tables[DbMetaDataCollectionNames.ReservedWords];
if (null == reservedWordsTable){
throw ADP.UnableToBuildCollection(DbMetaDataCollectionNames.ReservedWords);
}
// copy the table filtering out any rows that don't apply to tho current version of the prrovider
reservedWordsTable = CloneAndFilterCollection(DbMetaDataCollectionNames.ReservedWords, null);
DataColumn reservedWordColumn = reservedWordsTable.Columns[DbMetaDataColumnNames.ReservedWord];
if (null == reservedWordColumn){
throw ADP.UnableToBuildCollection(DbMetaDataCollectionNames.ReservedWords);
}
if (!internalConnection.AddInfoKeywordsToTable(reservedWordsTable, reservedWordColumn)){
throw ODB.IDBInfoNotSupported();
}
return reservedWordsTable;
}
protected override DataTable PrepareCollection(String collectionName, String[] restrictions, DbConnection connection){
OleDbConnection oleDbConnection = (OleDbConnection) connection;
OleDbConnectionInternal oleDbInternalConnection = (OleDbConnectionInternal) (oleDbConnection.InnerConnection);
DataTable resultTable = null;
if (collectionName == DbMetaDataCollectionNames.DataSourceInformation){
if (ADP.IsEmptyArray(restrictions) == false){
throw ADP.TooManyRestrictions(DbMetaDataCollectionNames.DataSourceInformation);
}
resultTable = GetDataSourceInformationTable(oleDbConnection, oleDbInternalConnection);
}
else if (collectionName == DbMetaDataCollectionNames.DataTypes){
if (ADP.IsEmptyArray(restrictions) == false){
throw ADP.TooManyRestrictions(DbMetaDataCollectionNames.DataTypes);
}
resultTable = GetDataTypesTable(oleDbConnection);
}
else if (collectionName == DbMetaDataCollectionNames.ReservedWords){
if (ADP.IsEmptyArray(restrictions) == false){
throw ADP.TooManyRestrictions(DbMetaDataCollectionNames.ReservedWords);
}
resultTable = GetReservedWordsTable(oleDbInternalConnection);
}
else {
for (int i=0; i < _schemaMapping.Length; i++){
if (_schemaMapping[i]._schemaName== collectionName) {
// need to special case the oledb schema rowset restrictions on columns that are not
// string tpyes
object[] mungedRestrictions = restrictions;;
if (restrictions != null){
//verify that there are not too many restrictions
DataTable metaDataCollectionsTable = CollectionDataSet.Tables[DbMetaDataCollectionNames.MetaDataCollections];
int numberOfSupportedRestictions = -1;
// prepare colletion is called with the exact collection name so
// we can do an exact string comparision here
foreach (DataRow row in metaDataCollectionsTable.Rows){
string candidateCollectionName = ((string)row[DbMetaDataColumnNames.CollectionName,DataRowVersion.Current]);
if (collectionName == candidateCollectionName) {
numberOfSupportedRestictions = (int)row[DbMetaDataColumnNames.NumberOfRestrictions];
if (numberOfSupportedRestictions < restrictions.Length){
throw ADP.TooManyRestrictions(collectionName);
}
break;
}
}
Debug.Assert(numberOfSupportedRestictions != -1, "PrepareCollection was called for an collection that is not supported.");
// the 4th restrictionon the indexes schema rowset(type) is an I2 - enum
const int indexRestrictionTypeSlot = 3;
if ((collectionName == OleDbMetaDataCollectionNames.Indexes) &&
(restrictions.Length >= indexRestrictionTypeSlot+1) &&
(restrictions[indexRestrictionTypeSlot] != null)){
mungedRestrictions = new object[restrictions.Length];
for (int j = 0; j <restrictions.Length; j++){
mungedRestrictions[j] = restrictions[j];
}
UInt16 indexTypeValue;
if ((restrictions[indexRestrictionTypeSlot] == "DBPROPVAL_IT_BTREE") ||
(restrictions[indexRestrictionTypeSlot] == "1")){
indexTypeValue = 1;
}
else if ((restrictions[indexRestrictionTypeSlot] == "DBPROPVAL_IT_HASH") ||
(restrictions[indexRestrictionTypeSlot] == "2")){
indexTypeValue = 2;
}
else if ((restrictions[indexRestrictionTypeSlot] == "DBPROPVAL_IT_CONTENT") ||
(restrictions[indexRestrictionTypeSlot] == "3")){
indexTypeValue = 3;
}
else if ((restrictions[indexRestrictionTypeSlot] == "DBPROPVAL_IT_OTHER") ||
(restrictions[indexRestrictionTypeSlot] == "4")){
indexTypeValue = 4;
}
else {
throw ADP.InvalidRestrictionValue(collectionName,"TYPE",restrictions[indexRestrictionTypeSlot]);
}
mungedRestrictions[indexRestrictionTypeSlot] = indexTypeValue;
}
// the 4th restrictionon the procedures schema rowset(type) is an I2 - enum
const int procedureRestrictionTypeSlot = 3;
if ((collectionName == OleDbMetaDataCollectionNames.Procedures) &&
(restrictions.Length >= procedureRestrictionTypeSlot+1) &&
(restrictions[procedureRestrictionTypeSlot] != null)){
mungedRestrictions = new object[restrictions.Length];
for (int j = 0; j <restrictions.Length; j++){
mungedRestrictions[j] = restrictions[j];
}
Int16 procedureTypeValue;
if ((restrictions[procedureRestrictionTypeSlot] == "DB_PT_UNKNOWN") ||
(restrictions[procedureRestrictionTypeSlot] == "1")){
procedureTypeValue = 1;
}
else if ((restrictions[procedureRestrictionTypeSlot] == "DB_PT_PROCEDURE")||
(restrictions[procedureRestrictionTypeSlot] == "2")){
procedureTypeValue = 2;
}
else if ((restrictions[procedureRestrictionTypeSlot] == "DB_PT_FUNCTION")||
(restrictions[procedureRestrictionTypeSlot] == "3")){
procedureTypeValue = 3;
}
else {
throw ADP.InvalidRestrictionValue(collectionName,"PROCEDURE_TYPE",restrictions[procedureRestrictionTypeSlot]);
}
mungedRestrictions[procedureRestrictionTypeSlot] = procedureTypeValue;
}
}
resultTable = oleDbConnection.GetOleDbSchemaTable((System.Guid)_schemaMapping[i]._schemaRowset,mungedRestrictions);
break;
}
}
}
if (resultTable == null){
throw ADP.UnableToBuildCollection(collectionName);
}
return resultTable;
}
private void SetIdentifierCase(string columnName, int propertyID, DataRow row, OleDbConnection connection) {
object property = connection.GetDataSourcePropertyValue(OleDbPropertySetGuid.DataSourceInfo,propertyID);
IdentifierCase identifierCase = IdentifierCase.Unknown;
if (property != null) {
int propertyValue = (int)property;
switch (propertyValue) {
case ODB.DBPROPVAL_IC_UPPER:
case ODB.DBPROPVAL_IC_LOWER:
case ODB.DBPROPVAL_IC_MIXED:
identifierCase = IdentifierCase.Insensitive;
break;
case ODB.DBPROPVAL_IC_SENSITIVE:
identifierCase = IdentifierCase.Sensitive;
break;
}
}
row[columnName] = identifierCase;
}
}
}
| |
/*
* Copyright (c) 2011..., Sergei Grichine
* 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 Sergei Grichine nor the
* names of contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY Sergei Grichine ''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 Sergei Grichine 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.
*
* this is a X11 (BSD Revised) license - you do not have to publish your changes,
* although doing so, donating and contributing is always appreciated
*/
//#define TRACEDEBUG
//#define TRACEDEBUGTICKS
#define TRACELOG
namespace TrackRoamer.Robotics.Services.TrackRoamerBrickPower
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Xml;
using System.Net;
using System.IO;
using Microsoft.Ccr.Core;
using Microsoft.Dss.Core;
using Microsoft.Dss.Core.Attributes;
using Microsoft.Dss.ServiceModel.Dssp;
using Microsoft.Dss.Core.DsspHttp;
using Microsoft.Dss.ServiceModel.DsspServiceBase;
using W3C.Soap;
using coord = Microsoft.Robotics.Services.Coordination;
using submgr = Microsoft.Dss.Services.SubscriptionManager;
using TrackRoamer.Robotics.Utility.LibSystem;
using TrackRoamer.Robotics.Hardware.LibRoboteqController;
/// <summary>
/// The TrackRoamer Power Brick Service
/// </summary>
// the boe control code uses a polling loop that blocks a thread
// The ActivationSettings attribute with Sharing == false makes the runtime dedicate a dispatcher thread pool just for this service.
// ExecutionUnitsPerDispatcher - Indicates the number of execution units allocated to the dispatcher
// ShareDispatcher - Inidicates whether multiple service instances can be pooled or not
[ActivationSettings(ShareDispatcher = false, ExecutionUnitsPerDispatcher = 2)]
[Contract(Contract.Identifier)]
[DisplayName("(User) TrackRoamer Power Brick")]
[Description("Provides access to the TrackRoamer Power Brick")]
public class TrackRoamerBrickPowerService : DsspServiceBase
{
private const string _configFile = ServicePaths.Store + "/TrackRoamer.PowerBrick.config.xml";
private const int DEFAULT_COM_PORT_NUMBER = 7; // normally 1
[InitialStatePartner(Optional = true, ServiceUri = _configFile)]
private TrackRoamerBrickPowerState _state = new TrackRoamerBrickPowerState();
[EmbeddedResource("TrackRoamer.Robotics.Services.TrackRoamerBrickPower.TrackRoamerBrickPower.xslt")]
string _transform = null;
[ServicePort("/trackroamerbrickpower", AllowMultipleInstances=false)]
private TrackRoamerBrickPowerOperations _mainPort = new TrackRoamerBrickPowerOperations();
[Partner("SubMgr", Contract = submgr.Contract.Identifier, CreationPolicy = PartnerCreationPolicy.CreateAlways)]
private submgr.SubscriptionManagerPort _subMgrPort = new submgr.SubscriptionManagerPort();
private Port<DateTime> _controlPort = new Port<DateTime>();
/// <summary>
/// A CCR port for receiving RoboteQ AX2850 data
/// </summary>
private RbtqDataPort _rbtqDataPort = new RbtqDataPort();
/// <summary>
/// Communicate with the RoboteQ AX2850 hardware
/// </summary>
private BrickConnection _brickConnection = null;
private Dictionary<Guid, Port<UpdateMotorSpeed>> _coordinationList = new Dictionary<Guid, Port<UpdateMotorSpeed>>();
private DateTime _initializationTime;
public TrackRoamerBrickPowerService(DsspServiceCreationPort creationPort) :
base(creationPort)
{
LogInfo("TrackRoamerBrickPowerService:TrackRoamerBrickPowerService() -- port: " + creationPort.ToString());
_initializationTime = DateTime.Now;
}
/// <summary>
/// used by Hardware Controller to log all trace messages into a common stream, which is a property of DsspServiceBase.
/// </summary>
/// <param name="str"></param>
public void LogInfoViaService(string str)
{
LogInfo(str);
}
protected override void Start()
{
LogInfo("TrackRoamerBrickPowerService:Start() _state=" + _state);
if (_state == null)
{
// we usually don't come here, as the state is already configured by file - TrackRoamer.TrackRoamerBrickPower.Bot.Config.xml
LogInfo("TrackRoamerBrickPowerService:Start(): _state == null - initializing...");
_state = new TrackRoamerBrickPowerState();
_state.PowerControllerConfig = new PowerControllerConfig();
_state.PowerControllerConfig.CommPort = DEFAULT_COM_PORT_NUMBER;
_state.Connected = false;
_state.FrameCounter = 0;
_state.Whiskers = new Whiskers();
_state.MotorSpeed = new MotorSpeed();
_state.MotorEncoder = new MotorEncoder();
_state.MotorEncoderSpeed = new MotorEncoderSpeed();
_state.TimeStamp = DateTime.Now;
SaveState(_state);
}
else
{
LogInfo("TrackRoamerBrickPowerService:Start(): _state is supplied by file: " + _configFile);
}
if (_state.PowerControllerConfig == null)
{
_state.PowerControllerConfig = new PowerControllerConfig();
}
_brickConnection = new BrickConnection(_state.PowerControllerConfig, _rbtqDataPort, this);
// wireup all event handlers to receive AX2850 data:
_brickConnection.onValueReceived_EncoderLeftAbsolute += new OnValueReceived(_brickConnection_onValueReceived_EncoderLeftAbsolute);
_brickConnection.onValueReceived_EncoderRightAbsolute += new OnValueReceived(_brickConnection_onValueReceived_EncoderRightAbsolute);
_brickConnection.onValueReceived_EncoderSpeed += new OnValueReceived(_brickConnection_onValueReceived_EncoderSpeed);
_brickConnection.onValueReceived_WhiskerLeft += new OnValueReceived(onWhiskerLeft);
_brickConnection.onValueReceived_WhiskerRight += new OnValueReceived(onWhiskerRight);
_brickConnection.onValueReceived_AnalogInputs += new OnValueReceived(_brickConnection_onValueReceived_AnalogInputs);
_brickConnection.onValueReceived_DigitalInputE += new OnValueReceived(_brickConnection_onValueReceived_DigitalInputE);
_brickConnection.onValueReceived_Voltage += new OnValueReceived(_brickConnection_onValueReceived_Voltage);
_brickConnection.onValueReceived_MotorPower += new OnValueReceived(_brickConnection_onValueReceived_MotorPower);
_brickConnection.onValueReceived_MotorAmps += new OnValueReceived(_brickConnection_onValueReceived_MotorAmps);
_brickConnection.onValueReceived_HeatsinkTemperature += new OnValueReceived(_brickConnection_onValueReceived_HeatsinkTemperature);
base.Start(); // start MainPortInterleave; wireup [ServiceHandler] methods
SpawnIterator(ConnectToPowerController);
MainPortInterleave.CombineWith(
Arbiter.Interleave(
new TeardownReceiverGroup(),
new ExclusiveReceiverGroup(
Arbiter.ReceiveWithIterator(true, _controlPort, ControlLoop),
Arbiter.Receive<Exception>(true, _rbtqDataPort, ExceptionHandler),
Arbiter.Receive<string>(true, _rbtqDataPort, MessageHandler)
),
new ConcurrentReceiverGroup()));
// kick off control loop interval:
_controlPort.Post(DateTime.UtcNow);
lastRateSnapshot = DateTime.Now.AddSeconds(frameRateWatchdogDelaySec); // delay frame rate watchdog
LogInfo("OK: TrackRoamerBrickPowerService:ControlLoop activated");
// display HTTP service Uri
LogInfo("TrackRoamerBrickPowerService: Service uri: ");
}
#region Handlers for other measured values coming from the controller
void _brickConnection_onValueReceived_AnalogInputs(object sender, MeasuredValuesEventArgs e)
{
_state.PowerControllerState.Analog_Input_1 = e.value1;
_state.PowerControllerState.Analog_Input_2 = e.value2;
_state.TimeStamp = DateTime.Now;
}
void _brickConnection_onValueReceived_DigitalInputE(object sender, MeasuredValuesEventArgs e)
{
_state.PowerControllerState.Digital_Input_E = e.value1;
_state.TimeStamp = DateTime.Now;
}
void _brickConnection_onValueReceived_Voltage(object sender, MeasuredValuesEventArgs e)
{
// the voltages come in as hex bytes 0...255, and then converted by formula:
// Measured Main Battery Volts = 55 * Read Value / 256
// Measured Internal Volts = 28.5 * Read Value / 256
// there isn't much precision here, so rounding it to 2 digits seems adequate.
_state.PowerControllerState.Main_Battery_Voltage = e.value1.HasValue ? Math.Round(e.value1.Value, 2) : (double?)null;
_state.PowerControllerState.Internal_Voltage = e.value2.HasValue ? Math.Round(e.value2.Value, 2) : (double?)null;
_state.TimeStamp = DateTime.Now;
}
void _brickConnection_onValueReceived_MotorPower(object sender, MeasuredValuesEventArgs e)
{
_state.PowerControllerState.Motor_Power_Left = e.value1;
_state.PowerControllerState.Motor_Power_Right = e.value2;
_state.TimeStamp = DateTime.Now;
}
void _brickConnection_onValueReceived_MotorAmps(object sender, MeasuredValuesEventArgs e)
{
// note: Amps behave almost like integers, no precision here and low current will read as 0
_state.PowerControllerState.Motor_Amps_Left = e.value1;
_state.PowerControllerState.Motor_Amps_Right = e.value2;
_state.TimeStamp = DateTime.Now;
}
void _brickConnection_onValueReceived_HeatsinkTemperature(object sender, MeasuredValuesEventArgs e)
{
_state.PowerControllerState.Heatsink_Temperature_Left = e.value1;
_state.PowerControllerState.Heatsink_Temperature_Right = e.value2;
_state.TimeStamp = DateTime.Now;
}
#endregion // Handlers for other measured values coming from the controller
/// <summary>
/// Handle Errors
/// </summary>
/// <param name="ex"></param>
private void ExceptionHandler(Exception ex)
{
LogError(ex.Message);
}
/// <summary>
/// Handle messages
/// </summary>
/// <param name="message"></param>
private void MessageHandler(string message)
{
LogInfo(message);
}
#region Power Controller Helpers
/// <summary>
/// An iterator to connect to a Power Controller.
/// If no configuration exists, search for the connection.
/// </summary>
private IEnumerator<ITask> ConnectToPowerController()
{
try
{
_state.Connected = false;
if (_state.PowerControllerConfig.CommPort != 0 && _state.PowerControllerConfig.BaudRate != 0)
{
_state.PowerControllerConfig.ConfigurationStatus = "Opening RoboteQ AX2850 on Port " + _state.PowerControllerConfig.CommPort.ToString();
_state.Connected = _brickConnection.Open(_state.PowerControllerConfig.CommPort, _state.PowerControllerConfig.BaudRate);
}
else
{
_state.PowerControllerConfig.ConfigurationStatus = "Searching for the RoboteQ AX2850 COM Port";
_state.Connected = _brickConnection.FindPowerController();
if (_state.Connected)
{
_state.PowerControllerConfig = _brickConnection.PowerControllerConfig;
_state.TimeStamp = DateTime.Now;
SaveState(_state);
}
}
}
catch (UnauthorizedAccessException ex)
{
LogError(ex);
}
catch (IOException ex)
{
LogError(ex);
}
catch (ArgumentOutOfRangeException ex)
{
LogError(ex);
}
catch (ArgumentException ex)
{
LogError(ex);
}
catch (InvalidOperationException ex)
{
LogError(ex);
}
if (!_state.Connected)
{
_state.PowerControllerConfig.ConfigurationStatus = "Not Connected";
LogInfo(LogGroups.Console, "The RoboteQ AX2850 is not detected.\r\n* To configure the RoboteQ AX2850, navigate to: ");
}
else
{
_state.PowerControllerConfig.ConfigurationStatus = "Connected";
}
_state.TimeStamp = DateTime.Now;
yield break;
}
#endregion // Power Controller Helpers
#region Event handlers - activated by controller, generate Notifications (updates - e.g. whiskers and Encoders)
void _brickConnection_onValueReceived_EncoderSpeed(object sender, MeasuredValuesEventArgs ev)
{
#if TRACEDEBUGTICKS
LogInfo("TrackRoamerBrickPowerService : received EncoderSpeed : left=" + ev.value1 + " right=" + ev.value2);
#endif // TRACEDEBUGTICKS
UpdateMotorEncoderSpeed ume = new UpdateMotorEncoderSpeed();
ume.Body.Timestamp = new DateTime(ev.timestamp);
ume.Body.LeftSpeed = ev.value1;
ume.Body.RightSpeed = ev.value2;
_state.MotorEncoderSpeed.LeftSpeed = ume.Body.LeftSpeed;
_state.MotorEncoderSpeed.RightSpeed = ume.Body.RightSpeed;
_state.MotorEncoderSpeed.Timestamp = ume.Body.Timestamp;
_state.TimeStamp = DateTime.Now;
base.SendNotification<UpdateMotorEncoderSpeed>(_subMgrPort, ume);
}
private void _brickConnection_onValueReceived_EncoderLeftAbsolute(object sender, MeasuredValuesEventArgs ev)
{
#if TRACEDEBUGTICKS
LogInfo("TrackRoamerBrickPowerService : received EncoderLeftAbsolute : " + ev.value1);
#endif // TRACEDEBUGTICKS
UpdateMotorEncoder ume = new UpdateMotorEncoder();
ume.Body.Timestamp = new DateTime(ev.timestamp);
ume.Body.LeftDistance = ev.value1;
ume.Body.HardwareIdentifier = 1; // 1 = Left
_state.MotorEncoder.LeftDistance = ume.Body.LeftDistance;
_state.MotorEncoder.Timestamp = ume.Body.Timestamp;
_state.TimeStamp = DateTime.Now;
base.SendNotification <UpdateMotorEncoder>(_subMgrPort, ume);
}
private void _brickConnection_onValueReceived_EncoderRightAbsolute(object sender, MeasuredValuesEventArgs ev)
{
#if TRACEDEBUGTICKS
LogInfo("TrackRoamerBrickPowerService : received EncoderRightAbsolute : " + ev.value1);
#endif // TRACEDEBUGTICKS
UpdateMotorEncoder ume = new UpdateMotorEncoder();
ume.Body.Timestamp = new DateTime(ev.timestamp);
ume.Body.RightDistance = ev.value1;
ume.Body.HardwareIdentifier = 2; // 2 = Right
_state.MotorEncoder.RightDistance = ume.Body.RightDistance;
_state.MotorEncoder.Timestamp = ume.Body.Timestamp;
_state.TimeStamp = DateTime.Now;
base.SendNotification <UpdateMotorEncoder>(_subMgrPort, ume);
}
/// <summary>
/// for bumper-type situations, we need to stop movement immediately, and then we can
/// let the events propagate to the higher level behavior, to cause backup movement for example.
/// </summary>
private void stopMotorsNow()
{
// If we are connected, send the speed to the robot
if (ensureHardwareController())
{
_brickConnection.SetSpeed(0.0d, 0.0d);
}
}
private void onWhiskerLeft(object sender, MeasuredValuesEventArgs ev)
{
LogInfo("TrackRoamerBrickPowerService : WhiskerLeft : " + ev.value1);
if (ev.value1 > 0 && (!_state.Whiskers.FrontWhiskerLeft.HasValue || !_state.Whiskers.FrontWhiskerLeft.Value))
{
// if this is a "whisker pressed" event, do emergency stop:
stopMotorsNow();
// Note: UpdateMotorSpeedHandler() will not set positive speed if whiskers are pressed.
}
_state.Whiskers.FrontWhiskerLeft = ev.value1 > 0;
_state.Whiskers.Timestamp = new DateTime(ev.timestamp);
_state.TimeStamp = DateTime.Now;
UpdateWhiskers uw = new UpdateWhiskers();
uw.Body.Timestamp = _state.Whiskers.Timestamp;
uw.Body.FrontWhiskerLeft = ev.value1 > 0;
base.SendNotification<UpdateWhiskers>(_subMgrPort, uw);
}
private void onWhiskerRight(object sender, MeasuredValuesEventArgs ev)
{
LogInfo("TrackRoamerBrickPowerService : WhiskerRight : " + ev.value1);
if (ev.value1 > 0 && (!_state.Whiskers.FrontWhiskerRight.HasValue || !_state.Whiskers.FrontWhiskerRight.Value))
{
// if this is a "whisker pressed" event, do emergency stop.
stopMotorsNow();
// Note: UpdateMotorSpeedHandler() will not set positive speed if whiskers are pressed.
}
_state.Whiskers.Timestamp = new DateTime(ev.timestamp);
_state.Whiskers.FrontWhiskerRight = ev.value1 > 0;
_state.TimeStamp = DateTime.Now;
UpdateWhiskers uw = new UpdateWhiskers();
uw.Body.Timestamp = _state.Whiskers.Timestamp;
uw.Body.FrontWhiskerRight = ev.value1 > 0;
base.SendNotification<UpdateWhiskers>(_subMgrPort, uw);
}
#endregion // Event handlers - activated by controller, generate Notifications (updates - e.g. whiskers and Encoders)
#region ControlLoop()
private const int rateCountIntervalSec = 5;
private long frameCounterLast = 0;
private long errorCounterLast = 0;
private const double frameRateWatchdogDelaySec = 10.0d;
private DateTime lastRateSnapshot = DateTime.Now.AddSeconds(frameRateWatchdogDelaySec); // frame rate watchdog
double delay;
private double ElapsedSecondsSinceStart { get { return (DateTime.Now - _initializationTime).TotalSeconds; } }
private IEnumerator<ITask> ControlLoop(DateTime timestamp)
{
// we come here real often (10ms)
//LogInfo("TrackRoamerBrickPowerService:ControlLoop()");
double startTime = ElapsedSecondsSinceStart;
delay = _state.PowerControllerConfig.Delay / 1000.0d; // sampling interval in seconds
try
{
DateTime now = DateTime.Now;
if (!ensureHardwareController())
{
// LogError(LogGroups.Console, "failed attempt to connect to the Power Brick controller");
_state.ConnectAttempts++;
_state.TimeStamp = now;
//yield break;
}
else
{
_state.ConnectAttempts = 0;
_state.TimeStamp = now;
}
if (!_brickConnection.HcConnected && _state.ConnectAttempts > 3)
{
// this is bad - complain and wait, we can't connect to AX2850
delay = 2.0d; // seconds
Close(true);
lastRateSnapshot = DateTime.Now.AddSeconds(frameRateWatchdogDelaySec); // delay frame rate watchdog
LogError(LogGroups.Console, "Can not connect to the Power Brick controller");
}
else
{
// normal operation - call controller loop and update state, then come back in 20ms
if (!_state.Dropping)
{
_brickConnection.ExecuteMain(); // this is where controller work is done, call it often
}
_state.Connected = _brickConnection.HcConnected;
long frameCounter = _brickConnection.frameCounter;
long errorCounter = _brickConnection.errorCounter;
_state.FrameCounter = frameCounter;
_state.ErrorCounter = errorCounter;
_state.TimeStamp = now;
if (now > lastRateSnapshot.AddSeconds(rateCountIntervalSec))
{
_state.FrameRate = (int)((frameCounter - this.frameCounterLast) / rateCountIntervalSec);
this.frameCounterLast = frameCounter;
_state.ErrorRate = (int)((errorCounter - this.errorCounterLast) / rateCountIntervalSec);
this.errorCounterLast = errorCounter;
_state.TimeStamp = now;
lastRateSnapshot = now;
// frame rate watchdog:
if (_state.FrameRate == 0) // should be around 80; if 0 - something is terribly wrong.
{
LogError(LogGroups.Console, "Frame rate watchdog: FrameRate is 0 - resetting Power Brick controller");
Close(true);
lastRateSnapshot = now.AddSeconds(frameRateWatchdogDelaySec); // delay frame rate watchdog
}
}
}
}
finally
{
_state.PowerControllerConfig.ConfigurationStatus = _brickConnection.StatusLabel;
// all times here are in seconds:
double endTime = ElapsedSecondsSinceStart;
double elapsed = endTime - startTime;
double remainderToNextSamplingTime = delay - elapsed;
if (remainderToNextSamplingTime <= 0.005d)
{
// schedule immediately
remainderToNextSamplingTime = 0.005d; // 5ms
}
if (this.ServicePhase == ServiceRuntimePhase.Started)
{
if(remainderToNextSamplingTime > 1.0d)
{
LogInfo("TrackRoamerBrickPowerService:ControlLoop() - sleeping seconds=" + remainderToNextSamplingTime);
}
// schedule next sampling interval
Activate(this.TimeoutPort(
TimeSpan.FromSeconds(remainderToNextSamplingTime)).Receive(
(dt) => _controlPort.Post(dt) // call ControlLoop again
)
);
}
}
yield break;
}
#endregion // ControlLoop()
#region Operation Port Handlers - Get, HttpGet, UpdateMotorSpeed etc.
[ServiceHandler(ServiceHandlerBehavior.Concurrent)]
public virtual IEnumerator<ITask> GetHandler(Get get)
{
get.ResponsePort.Post(_state);
yield break;
}
[ServiceHandler(ServiceHandlerBehavior.Concurrent)]
public virtual IEnumerator<ITask> HttpGetHandler(HttpGet httpGet)
{
httpGet.ResponsePort.Post(new HttpResponseType(
HttpStatusCode.OK,
_state,
_transform)
);
yield break;
}
/// <summary>
/// Replace Handler
/// </summary>
/// <param name="replace"></param>
/// <returns></returns>
[ServiceHandler(ServiceHandlerBehavior.Exclusive)]
public virtual IEnumerator<ITask> ReplaceHandler(Replace replace)
{
LogInfo("TrackRoamerBrickPowerService:ReplaceHandler()");
Close();
_state = replace.Body;
_state.Connected = false;
_state.Connected = ReConnect();
_state.TimeStamp = DateTime.Now;
replace.ResponsePort.Post(DefaultReplaceResponseType.Instance);
yield break;
}
/// <summary>
/// Subscribe Handler
/// </summary>
/// <param name="subscribe"></param>
/// <returns></returns>
[ServiceHandler(ServiceHandlerBehavior.Exclusive)]
public virtual IEnumerator<ITask> SubscribeHandler(Subscribe subscribe)
{
SubscribeRequestType request = subscribe.Body;
LogInfo("TrackRoamerBrickPowerService:SubscribeHandler() -- Subscribe request from: " + request.Subscriber);
yield return Arbiter.Choice(
SubscribeHelper(_subMgrPort, request, subscribe.ResponsePort),
delegate(SuccessResult success) { },
delegate(Exception ex)
{
LogError(ex);
throw ex;
}
);
//_subMgrPort.Post(new submgr.Submit(request.Subscriber, DsspActions.UpdateRequest, _state.MotorSpeed, null));
//_subMgrPort.Post(new submgr.Submit(request.Subscriber, DsspActions.UpdateRequest, _state.Whiskers, null));
yield break;
}
/*
/// <summary>
/// QueryConfig Handler
/// </summary>
/// <param name="query"></param>
/// <returns></returns>
[ServiceHandler(ServiceHandlerBehavior.Concurrent)]
public virtual IEnumerator<ITask> QueryConfigHandler(QueryConfig query)
{
LogInfo("TrackRoamerBrickPowerService:QueryConfigHandler()");
query.ResponsePort.Post(_state.PowerControllerConfig);
yield break;
}
*/
/// <summary>
/// QueryWhiskers Handler
/// </summary>
/// <param name="query"></param>
/// <returns></returns>
[ServiceHandler(ServiceHandlerBehavior.Concurrent)]
public virtual IEnumerator<ITask> QueryWhiskersHandler(QueryWhiskers query)
{
query.ResponsePort.Post(_state.Whiskers);
yield break;
}
/// <summary>
/// QueryMotorSpeed Handler
/// </summary>
/// <param name="query"></param>
/// <returns></returns>
[ServiceHandler(ServiceHandlerBehavior.Concurrent)]
public virtual IEnumerator<ITask> QueryMotorSpeedHandler(QueryMotorSpeed query)
{
LogInfo("TrackRoamerBrickPowerService:QueryMotorSpeedHandler()");
query.ResponsePort.Post(_state.MotorSpeed);
yield break;
}
/// <summary>
/// UpdateConfig Handler
/// </summary>
/// <param name="update"></param>
/// <returns></returns>
[ServiceHandler(ServiceHandlerBehavior.Exclusive)]
public virtual IEnumerator<ITask> UpdateConfigHandler(UpdateConfig update)
{
LogInfo("TrackRoamerBrickPowerService:UpdateConfigHandler()");
if (update.Body.CommPort >= 0)
{
_state.PowerControllerConfig.CommPort = update.Body.CommPort;
LogInfo(" SerialPort=" + _state.PowerControllerConfig.CommPort);
_state.Connected = ReConnect();
}
update.ResponsePort.Post(DefaultUpdateResponseType.Instance);
yield break;
}
public void SetCoordinatedMotors(UpdateMotorSpeed[] motors)
{
//LogInfo("TrackRoamerBrickPowerService:SetCoordinatedMotors()");
MotorSpeed motorSpeed = new MotorSpeed() { Timestamp = DateTime.Now };
// Default null which is ignored by the controller.
motorSpeed.LeftSpeed = null;
motorSpeed.RightSpeed = null;
// Combine the motor commands
foreach (UpdateMotorSpeed ms in motors)
{
if (ms.Body.LeftSpeed != null && ms.Body.LeftSpeed >= -1.0 && ms.Body.LeftSpeed <= 1.0)
motorSpeed.LeftSpeed = ms.Body.LeftSpeed;
if (ms.Body.RightSpeed != null && ms.Body.RightSpeed >= -1.0 && ms.Body.RightSpeed <= 1.0)
motorSpeed.RightSpeed = ms.Body.RightSpeed;
}
// Send a singe command to the controller:
UpdateMotorSpeed combinedRequest = new UpdateMotorSpeed(motorSpeed);
_mainPort.Post(combinedRequest);
Activate(Arbiter.Choice(combinedRequest.ResponsePort,
delegate(DefaultUpdateResponseType response)
{
// send responses back to the original motors
foreach (UpdateMotorSpeed ms in motors)
ms.ResponsePort.Post(DefaultUpdateResponseType.Instance);
},
delegate(Fault fault)
{
// send failure back to the original motors
foreach (UpdateMotorSpeed ms in motors)
ms.ResponsePort.Post(fault);
}));
}
/// <summary>
/// UpdateMotorSpeed Handler
/// </summary>
/// <param name="update"></param>
/// <returns></returns>
[ServiceHandler(ServiceHandlerBehavior.Exclusive)]
public virtual IEnumerator<ITask> UpdateMotorSpeedHandler(UpdateMotorSpeed update)
{
//LogInfo("TrackRoamerBrickPowerService:UpdateMotorSpeedHandler()");
coord.ActuatorCoordination coordination = update.GetHeader<coord.ActuatorCoordination>();
if (coordination != null && coordination.Count > 1)
{
if (!_coordinationList.ContainsKey(coordination.RequestId))
{
_coordinationList.Add(coordination.RequestId, new Port<UpdateMotorSpeed>());
Activate(
Arbiter.MultipleItemReceive<UpdateMotorSpeed>(
false,
_coordinationList[coordination.RequestId],
coordination.Count,
SetCoordinatedMotors));
}
_coordinationList[coordination.RequestId].Post(update);
yield break;
}
bool changed = ((update.Body.LeftSpeed >= 0 && _state.MotorSpeed.LeftSpeed != update.Body.LeftSpeed)
|| (update.Body.RightSpeed >= 0 && _state.MotorSpeed.RightSpeed != update.Body.RightSpeed));
if (update.Body.LeftSpeed != null)
{
if (update.Body.LeftSpeed >= -1.0 && update.Body.LeftSpeed <= 1.0)
{
//LogInfo("TrackRoamerBrickPowerService:UpdateMotorSpeedHandler - LeftSpeed=" + update.Body.LeftSpeed + " requested");
_state.MotorSpeed.LeftSpeed = update.Body.LeftSpeed;
}
else
{
LogInfo("Error: TrackRoamerBrickPowerService:UpdateMotorSpeedHandler - invalid LeftSpeed=" + update.Body.LeftSpeed + " requested, must be between -1.0 and +1.0");
}
}
if (update.Body.RightSpeed != null)
{
if (update.Body.RightSpeed >= -1.0 && update.Body.RightSpeed <= 1.0)
{
//LogInfo("TrackRoamerBrickPowerService:UpdateMotorSpeedHandler - RightSpeed=" + update.Body.RightSpeed + " requested");
_state.MotorSpeed.RightSpeed = update.Body.RightSpeed;
}
else
{
LogInfo("Error: TrackRoamerBrickPowerService:UpdateMotorSpeedHandler - invalid RightSpeed=" + update.Body.RightSpeed + " requested, must be between -1.0 and +1.0");
}
}
// If we are connected, send the speed to the robot wheels controller:
if (ensureHardwareController())
{
double? leftSpeed = _state.MotorSpeed.LeftSpeed;
double? rightSpeed = _state.MotorSpeed.RightSpeed;
Tracer.Trace("IP: TrackRoamerBrickPowerService:UpdateMotorSpeedHandler - speed L: " + leftSpeed + " R: " + rightSpeed);
// it will take time for upper layers to react on whiskers. We want to have some protection here, to avoid damage.
// Note: while moving forward the speeds are negative.
// cannot move forward if whiskers are pressed; replace it with backwards movement at half speed though:
if (leftSpeed < 0 && _state.Whiskers.FrontWhiskerLeft.GetValueOrDefault())
{
Tracer.Trace("Warning: TrackRoamerBrickPowerService:UpdateMotorSpeedHandler - left whisker pressed, speed " + leftSpeed + " reversed");
leftSpeed = -leftSpeed / 2;
}
if (rightSpeed < 0 && _state.Whiskers.FrontWhiskerRight.GetValueOrDefault())
{
Tracer.Trace("Warning: TrackRoamerBrickPowerService:UpdateMotorSpeedHandler - right whisker pressed, speed " + rightSpeed + " reversed");
rightSpeed = -rightSpeed / 2;
}
_brickConnection.SetSpeed(leftSpeed, rightSpeed);
}
// Send Notifications to subscribers
if (changed)
{
_subMgrPort.Post(new submgr.Submit(_state.MotorSpeed, DsspActions.UpdateRequest));
}
_state.TimeStamp = _state.MotorSpeed.Timestamp = DateTime.Now;
update.ResponsePort.Post(DefaultUpdateResponseType.Instance);
yield break;
}
/// <summary>
/// SetOutputC Handler
/// </summary>
/// <param name="update"></param>
/// <returns></returns>
[ServiceHandler(ServiceHandlerBehavior.Exclusive)]
public virtual IEnumerator<ITask> SetOutputCHandler(SetOutputC update)
{
// If we are connected, send the speed to the robot
if (ensureHardwareController())
{
_brickConnection.SetOutputC(update.Body);
_state.TimeStamp = DateTime.Now;
_state.OutputC = update.Body ? 1 : 0;
}
// Send Notifications to subscribers
_subMgrPort.Post(new submgr.Submit(update, DsspActions.UpdateRequest));
update.ResponsePort.Post(DefaultUpdateResponseType.Instance);
yield break;
}
/*
/// <summary>
/// UpdateWhiskers Handler
/// </summary>
/// <param name="update"></param>
/// <returns></returns>
[ServiceHandler(ServiceHandlerBehavior.Exclusive)]
public virtual IEnumerator<ITask> UpdateWhiskersHandler(UpdateWhiskers update)
{
_state.Whiskers.FrontWhiskerLeft = update.Body.FrontWhiskerLeft;
_state.Whiskers.FrontWhiskerRight = update.Body.FrontWhiskerRight;
_state.Whiskers.Timestamp = update.Body.Timestamp;
_state.TimeStamp = DateTime.Now;
// Send Notifications to subscribers
_subMgrPort.Post(new submgr.Submit(_state.Whiskers, DsspActions.UpdateRequest));
update.ResponsePort.Post(DefaultUpdateResponseType.Instance);
yield break;
}
/// <summary>
/// UpdateMotorEncoder Handler
/// </summary>
/// <param name="update"></param>
/// <returns></returns>
[ServiceHandler(ServiceHandlerBehavior.Exclusive)]
public virtual IEnumerator<ITask> UpdateEncoderHandler(UpdateMotorEncoder update)
{
//_state.MotorEncoder.HardwareIdentifier = update.Body.HardwareIdentifier;
_state.MotorEncoder.LeftDistance = update.Body.LeftDistance;
_state.MotorEncoder.RightDistance = update.Body.RightDistance;
_state.MotorEncoder.Timestamp = update.Body.Timestamp;
// Send Notifications to subscribers
_subMgrPort.Post(new submgr.Submit(_state.MotorEncoder, DsspActions.UpdateRequest));
update.ResponsePort.Post(DefaultUpdateResponseType.Instance);
yield break;
}
/// <summary>
/// UpdateMotorEncoderSpeed Handler
/// </summary>
/// <param name="update"></param>
/// <returns></returns>
[ServiceHandler(ServiceHandlerBehavior.Exclusive)]
public virtual IEnumerator<ITask> UpdateEncoderSpeedHandler(UpdateMotorEncoderSpeed update)
{
_state.MotorEncoderSpeed.LeftSpeed = update.Body.LeftSpeed;
_state.MotorEncoderSpeed.RightSpeed = update.Body.RightSpeed;
_state.MotorEncoder.Timestamp = update.Body.Timestamp;
// Send Notifications to subscribers
_subMgrPort.Post(new submgr.Submit(_state.MotorEncoderSpeed, DsspActions.UpdateRequest));
update.ResponsePort.Post(DefaultUpdateResponseType.Instance);
yield break;
}
*/
/// <summary>
/// ResetMotorEncoder Handler
/// </summary>
/// <param name="update"></param>
/// <returns></returns>
[ServiceHandler(ServiceHandlerBehavior.Exclusive)]
public virtual IEnumerator<ITask> ResetEncoderHandler(ResetMotorEncoder reset)
{
LogInfo("TrackRoamerBrickPowerService:ResetEncoderHandler() id=" + reset.Body.HardwareIdentifier);
switch(reset.Body.HardwareIdentifier)
{
case 1:
_brickConnection.ResetEncoderLeft();
_state.MotorEncoder.LeftDistance = 0.0d;
_state.TimeStamp = DateTime.Now;
break;
case 2:
_brickConnection.ResetEncoderRight();
_state.MotorEncoder.RightDistance = 0.0d;
_state.TimeStamp = DateTime.Now;
break;
}
// Send Notifications to subscribers
_subMgrPort.Post(new submgr.Submit(_state.MotorEncoder, DsspActions.ReplaceRequest));
reset.ResponsePort.Post(DefaultReplaceResponseType.Instance);
yield break;
}
[ServiceHandler(ServiceHandlerBehavior.Teardown)]
public virtual IEnumerator<ITask> DropHandler(DsspDefaultDrop drop)
{
LogInfo("TrackRoamerBrickPowerService:DropHandler()");
_state.Dropping = true; // makes sure the command loop is not calling controller
_brickConnection.Close();
base.DefaultDropHandler(drop);
yield break;
}
#endregion // Operation Port Handlers
#region Hardware Controller Connections
/// <summary>
/// Connect and update bot hardware controller with current speed settings
/// </summary>
private bool ReConnect()
{
LogInfo("TrackRoamerBrickPowerService:ReConnect()");
Tracer.Trace("TrackRoamerBrickPowerService:ReConnect()");
Close(true);
bool connected = ensureHardwareController();
if (connected)
{
if (_state.MotorSpeed != null
&& _state.MotorSpeed.LeftSpeed.HasValue && _state.MotorSpeed.RightSpeed.HasValue
&& _state.MotorSpeed.LeftSpeed != 0.0d || _state.MotorSpeed.RightSpeed != 0.0d)
{
_brickConnection.SetSpeed(_state.MotorSpeed.LeftSpeed, _state.MotorSpeed.RightSpeed);
}
else
{
_state.MotorSpeed.LeftSpeed = 0.0d;
_state.MotorSpeed.RightSpeed = 0.0d;
_state.MotorSpeed.Timestamp = DateTime.Now;
_brickConnection.SetSpeed(0.0d, 0.0d); // if in doubt, stop
}
}
return connected;
}
/// <summary>
/// Close the underlying connection to the Hardware Controller.
/// <remarks>Modifies _state</remarks>
/// </summary>
private void Close(bool forceIt = false)
{
LogInfo("TrackRoamerBrickPowerService:Close()");
if (_state.Connected || forceIt)
{
_brickConnection.Close();
_state.Connected = false;
_state.TimeStamp = DateTime.Now;
}
}
private bool? lastAnnouncedControllerState = null;
/// <summary>
/// Connect to the underlying hardware controller (RoboteQ). Set _state.Connected accordingly.
/// <remarks>Modifies _state</remarks>
/// </summary>
/// <returns>true if controller is online ready for commands. Same as _state.Connected</returns>
private bool ensureHardwareController()
{
_state.Connected = _brickConnection.HcConnected;
if (!_state.Connected)
{
//LogInfo("TrackRoamerBrickPowerService:ConnectToHardwareController() - connecting...");
string errorMessage = string.Empty;
_state.Connected = _brickConnection.ReConnect(out errorMessage);
_state.TimeStamp = DateTime.Now;
if (!_state.Connected)
{
if (!string.IsNullOrEmpty(errorMessage))
{
LogError(LogGroups.Console, errorMessage);
Talker.Say(10, "cannot initialize Power Brick on COM" + _state.PowerControllerConfig.CommPort);
}
else
{
if (!lastAnnouncedControllerState.HasValue || lastAnnouncedControllerState.Value)
{
lastAnnouncedControllerState = false;
Talker.Say(10, "power brick offline");
}
}
}
else
{
//_brickConnection.ResetEncoderLeft();
//_brickConnection.ResetEncoderRight();
_state.MotorEncoder.LeftDistance = 0.0d;
_state.MotorEncoder.RightDistance = 0.0d;
_state.MotorEncoderSpeed.LeftSpeed = 0.0d;
_state.MotorEncoderSpeed.RightSpeed = 0.0d;
_state.TimeStamp = _state.MotorEncoder.Timestamp = _state.MotorEncoderSpeed.Timestamp = DateTime.Now;
if (!lastAnnouncedControllerState.HasValue || !lastAnnouncedControllerState.Value)
{
lastAnnouncedControllerState = true;
Talker.Say(5, "power brick online");
delay = _state.PowerControllerConfig.Delay / 1000.0d; // sampling interval in seconds
}
}
}
return _state.Connected;
}
#endregion // Hardware Controller Connections
#if TRACEDEBUG
protected new void LogInfo(string str)
{
Tracer.Trace(str);
}
protected new void LogError(string str)
{
Tracer.Error(str);
}
#endif // TRACEDEBUG
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Net.Test.Common;
using System.Text;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
namespace System.Net.Http.Functional.Tests
{
using Configuration = System.Net.Test.Common.Configuration;
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "UAP HTTP stack doesn't support .Proxy property")]
public abstract class HttpClientHandler_Proxy_Test : HttpClientTestBase
{
private readonly ITestOutputHelper _output;
public HttpClientHandler_Proxy_Test(ITestOutputHelper output)
{
_output = output;
}
[OuterLoop("Uses external server")]
[Theory]
[InlineData(AuthenticationSchemes.Ntlm, true, false)]
[InlineData(AuthenticationSchemes.Negotiate, true, false)]
[InlineData(AuthenticationSchemes.Basic, false, false)]
[InlineData(AuthenticationSchemes.Basic, true, false)]
[InlineData(AuthenticationSchemes.Digest, false, false)]
[InlineData(AuthenticationSchemes.Digest, true, false)]
[InlineData(AuthenticationSchemes.Ntlm, false, false)]
[InlineData(AuthenticationSchemes.Negotiate, false, false)]
[InlineData(AuthenticationSchemes.Basic, false, true)]
[InlineData(AuthenticationSchemes.Basic, true, true)]
[InlineData(AuthenticationSchemes.Digest, false, true)]
[InlineData(AuthenticationSchemes.Digest, true, true)]
public async Task AuthProxy__ValidCreds_ProxySendsRequestToServer(
AuthenticationSchemes proxyAuthScheme,
bool secureServer,
bool proxyClosesConnectionAfterFirst407Response)
{
if (PlatformDetection.IsFedora && IsCurlHandler)
{
// CurlHandler seems unstable on Fedora26 and returns error
// "System.Net.Http.CurlException : Failure when receiving data from the peer".
return;
}
if (PlatformDetection.IsWindowsNanoServer && IsWinHttpHandler && proxyAuthScheme == AuthenticationSchemes.Digest)
{
// WinHTTP doesn't support Digest very well and is disabled on Nano.
return;
}
if (PlatformDetection.IsFullFramework &&
(proxyAuthScheme == AuthenticationSchemes.Negotiate || proxyAuthScheme == AuthenticationSchemes.Ntlm))
{
// Skip due to bug in .NET Framework with Windows auth and proxy tunneling.
return;
}
if (!PlatformDetection.IsWindows &&
(proxyAuthScheme == AuthenticationSchemes.Negotiate || proxyAuthScheme == AuthenticationSchemes.Ntlm))
{
// CI machines don't have GSSAPI module installed and will fail with error from
// System.Net.Security.NegotiateStreamPal.AcquireCredentialsHandle():
// "GSSAPI operation failed with error - An invalid status code was supplied
// Configuration file does not specify default realm)."
return;
}
if (IsCurlHandler && proxyAuthScheme != AuthenticationSchemes.Basic)
{
// Issue #27870 curl HttpHandler can only do basic auth to proxy.
return;
}
Uri serverUri = secureServer ? Configuration.Http.SecureRemoteEchoServer : Configuration.Http.RemoteEchoServer;
var options = new LoopbackProxyServer.Options
{ AuthenticationSchemes = proxyAuthScheme,
ConnectionCloseAfter407 = proxyClosesConnectionAfterFirst407Response
};
using (LoopbackProxyServer proxyServer = LoopbackProxyServer.Create(options))
{
using (HttpClientHandler handler = CreateHttpClientHandler())
using (var client = new HttpClient(handler))
{
handler.Proxy = new WebProxy(proxyServer.Uri);
handler.Proxy.Credentials = new NetworkCredential("username", "password");
using (HttpResponseMessage response = await client.GetAsync(serverUri))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
TestHelper.VerifyResponseBody(
await response.Content.ReadAsStringAsync(),
response.Content.Headers.ContentMD5,
false,
null);
}
}
}
}
[OuterLoop("Uses external server")]
[Theory]
[MemberData(nameof(CredentialsForProxy))]
public async Task Proxy_BypassFalse_GetRequestGoesThroughCustomProxy(ICredentials creds, bool wrapCredsInCache)
{
var options = new LoopbackProxyServer.Options
{ AuthenticationSchemes = creds != null ? AuthenticationSchemes.Basic : AuthenticationSchemes.None
};
using (LoopbackProxyServer proxyServer = LoopbackProxyServer.Create(options))
{
const string BasicAuth = "Basic";
if (wrapCredsInCache)
{
Assert.IsAssignableFrom<NetworkCredential>(creds);
var cache = new CredentialCache();
cache.Add(proxyServer.Uri, BasicAuth, (NetworkCredential)creds);
creds = cache;
}
using (HttpClientHandler handler = CreateHttpClientHandler())
using (var client = new HttpClient(handler))
{
handler.Proxy = new WebProxy(proxyServer.Uri) { Credentials = creds };
using (HttpResponseMessage response = await client.GetAsync(Configuration.Http.RemoteEchoServer))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
TestHelper.VerifyResponseBody(
await response.Content.ReadAsStringAsync(),
response.Content.Headers.ContentMD5,
false,
null);
if (options.AuthenticationSchemes != AuthenticationSchemes.None)
{
NetworkCredential nc = creds?.GetCredential(proxyServer.Uri, BasicAuth);
Assert.NotNull(nc);
string expectedAuth =
string.IsNullOrEmpty(nc.Domain) ? $"{nc.UserName}:{nc.Password}" :
$"{nc.Domain}\\{nc.UserName}:{nc.Password}";
_output.WriteLine($"expectedAuth={expectedAuth}");
string expectedAuthHash = Convert.ToBase64String(Encoding.UTF8.GetBytes(expectedAuth));
// Check last request to proxy server. CurlHandler will use pre-auth for Basic proxy auth,
// so there might only be 1 request received by the proxy server. Other handlers won't use
// pre-auth for proxy so there would be 2 requests.
int requestCount = proxyServer.Requests.Count;
_output.WriteLine($"proxyServer.Requests.Count={requestCount}");
Assert.Equal(BasicAuth, proxyServer.Requests[requestCount - 1].AuthorizationHeaderValueScheme);
Assert.Equal(expectedAuthHash, proxyServer.Requests[requestCount - 1].AuthorizationHeaderValueToken);
}
}
}
}
}
[OuterLoop("Uses external server")]
[Theory]
[MemberData(nameof(BypassedProxies))]
public async Task Proxy_BypassTrue_GetRequestDoesntGoesThroughCustomProxy(IWebProxy proxy)
{
HttpClientHandler handler = CreateHttpClientHandler();
handler.Proxy = proxy;
using (var client = new HttpClient(handler))
using (HttpResponseMessage response = await client.GetAsync(Configuration.Http.RemoteEchoServer))
{
TestHelper.VerifyResponseBody(
await response.Content.ReadAsStringAsync(),
response.Content.Headers.ContentMD5,
false,
null);
}
}
[OuterLoop("Uses external server")]
[Fact]
public async Task Proxy_HaveNoCredsAndUseAuthenticatedCustomProxy_ProxyAuthenticationRequiredStatusCode()
{
var options = new LoopbackProxyServer.Options { AuthenticationSchemes = AuthenticationSchemes.Basic };
using (LoopbackProxyServer proxyServer = LoopbackProxyServer.Create(options))
{
HttpClientHandler handler = CreateHttpClientHandler();
handler.Proxy = new WebProxy(proxyServer.Uri);
using (var client = new HttpClient(handler))
using (HttpResponseMessage response = await client.GetAsync(Configuration.Http.RemoteEchoServer))
{
Assert.Equal(HttpStatusCode.ProxyAuthenticationRequired, response.StatusCode);
}
}
}
[Fact]
public async Task Proxy_SslProxyUnsupported_Throws()
{
using (HttpClientHandler handler = CreateHttpClientHandler())
using (var client = new HttpClient(handler))
{
handler.Proxy = new WebProxy("https://" + Guid.NewGuid().ToString("N"));
Type expectedType = IsNetfxHandler || UseSocketsHttpHandler ?
typeof(NotSupportedException) :
typeof(HttpRequestException);
await Assert.ThrowsAsync(expectedType, () => client.GetAsync("http://" + Guid.NewGuid().ToString("N")));
}
}
[OuterLoop("Uses external server")]
[Fact]
public async Task Proxy_SendSecureRequestThruProxy_ConnectTunnelUsed()
{
if (PlatformDetection.IsFedora && IsCurlHandler)
{
// CurlHandler seems unstable on Fedora26 and returns error
// "System.Net.Http.CurlException : Failure when receiving data from the peer".
return;
}
using (LoopbackProxyServer proxyServer = LoopbackProxyServer.Create())
{
HttpClientHandler handler = CreateHttpClientHandler();
handler.Proxy = new WebProxy(proxyServer.Uri);
using (var client = new HttpClient(handler))
using (HttpResponseMessage response = await client.GetAsync(Configuration.Http.SecureRemoteEchoServer))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
_output.WriteLine($"Proxy request line: {proxyServer.Requests[0].RequestLine}");
Assert.Contains("CONNECT", proxyServer.Requests[0].RequestLine);
}
}
}
[ActiveIssue(23702, TargetFrameworkMonikers.NetFramework)]
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsNanoServer))]
public async Task ProxyAuth_Digest_Succeeds()
{
if (IsCurlHandler)
{
// Issue #27870 CurlHandler can only do basic auth to proxy.
return;
}
const string expectedUsername = "testusername";
const string expectedPassword = "testpassword";
const string authHeader = "Proxy-Authenticate: Digest realm=\"NetCore\", nonce=\"PwOnWgAAAAAAjnbW438AAJSQi1kAAAAA\", qop=\"auth\", stale=false\r\n";
LoopbackServer.Options options = new LoopbackServer.Options { IsProxy = true, Username = expectedUsername, Password = expectedPassword };
var proxyCreds = new NetworkCredential(expectedUsername, expectedPassword);
await LoopbackServer.CreateServerAsync(async (proxyServer, proxyUrl) =>
{
using (HttpClientHandler handler = CreateHttpClientHandler())
using (var client = new HttpClient(handler))
{
handler.Proxy = new WebProxy(proxyUrl) { Credentials = proxyCreds };
// URL does not matter. We will get response from "proxy" code below.
Task<HttpResponseMessage> clientTask = client.GetAsync($"http://notarealserver.com/");
// Send Digest challenge.
Task<List<string>> serverTask = proxyServer.AcceptConnectionSendResponseAndCloseAsync(HttpStatusCode.ProxyAuthenticationRequired, authHeader);
if (clientTask == await Task.WhenAny(clientTask, serverTask).TimeoutAfter(TestHelper.PassingTestTimeoutMilliseconds))
{
// Client task shouldn't have completed successfully; propagate failure.
Assert.NotEqual(TaskStatus.RanToCompletion, clientTask.Status);
await clientTask;
}
// Verify user & password.
serverTask = proxyServer.AcceptConnectionPerformAuthenticationAndCloseAsync("");
await TaskTimeoutExtensions.WhenAllOrAnyFailed(new Task[] { clientTask, serverTask }, TestHelper.PassingTestTimeoutMilliseconds);
Assert.Equal(HttpStatusCode.OK, clientTask.Result.StatusCode);
}
}, options);
}
private static IEnumerable<object[]> BypassedProxies()
{
yield return new object[] { null };
yield return new object[] { new UseSpecifiedUriWebProxy(new Uri($"http://{Guid.NewGuid().ToString().Substring(0, 15)}:12345"), bypass: true) };
}
private static IEnumerable<object[]> CredentialsForProxy()
{
yield return new object[] { null, false };
foreach (bool wrapCredsInCache in new[] { true, false })
{
yield return new object[] { new NetworkCredential("username", "password"), wrapCredsInCache };
yield return new object[] { new NetworkCredential("username", "password", "domain"), wrapCredsInCache };
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using Nini.Config;
using log4net;
using System;
using System.Reflection;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using System.Xml.Serialization;
using System.Collections.Generic;
using OpenSim.Server.Base;
using OpenSim.Services.Interfaces;
using OpenSim.Framework;
using OpenSim.Framework.ServiceAuth;
using OpenSim.Framework.Servers.HttpServer;
using OpenMetaverse;
namespace OpenSim.Server.Handlers.AgentPreferences
{
public class AgentPreferencesServerPostHandler : BaseStreamHandler
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private IAgentPreferencesService m_AgentPreferencesService;
public AgentPreferencesServerPostHandler(IAgentPreferencesService service, IServiceAuth auth) :
base("POST", "/agentprefs", auth)
{
m_AgentPreferencesService = service;
}
protected override byte[] ProcessRequest(string path, Stream requestData,
IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
{
StreamReader sr = new StreamReader(requestData);
string body = sr.ReadToEnd();
sr.Close();
body = body.Trim();
//m_log.DebugFormat("[XXX]: query String: {0}", body);
try
{
Dictionary<string, object> request =
ServerUtils.ParseQueryString(body);
if (!request.ContainsKey("METHOD"))
return FailureResult();
string method = request["METHOD"].ToString();
switch (method)
{
case "getagentprefs":
return GetAgentPrefs(request);
case "setagentprefs":
return SetAgentPrefs(request);
case "getagentlang":
return GetAgentLang(request);
}
m_log.DebugFormat("[AGENT PREFERENCES HANDLER]: unknown method request: {0}", method);
}
catch (Exception e)
{
m_log.DebugFormat("[AGENT PREFERENCES HANDLER]: Exception {0}", e);
}
return FailureResult();
}
byte[] GetAgentPrefs(Dictionary<string, object> request)
{
if (!request.ContainsKey("UserID"))
return FailureResult();
UUID userID;
if (!UUID.TryParse(request["UserID"].ToString(), out userID))
return FailureResult();
AgentPrefs prefs = m_AgentPreferencesService.GetAgentPreferences(userID);
Dictionary<string, object> result = new Dictionary<string, object>();
if (prefs != null)
result = prefs.ToKeyValuePairs();
string xmlString = ServerUtils.BuildXmlResponse(result);
return Util.UTF8NoBomEncoding.GetBytes(xmlString);
}
byte[] SetAgentPrefs(Dictionary<string, object> request)
{
if (!request.ContainsKey("PrincipalID") || !request.ContainsKey("AccessPrefs") || !request.ContainsKey("HoverHeight")
|| !request.ContainsKey("Language") || !request.ContainsKey("LanguageIsPublic") || !request.ContainsKey("PermEveryone")
|| !request.ContainsKey("PermGroup") || !request.ContainsKey("PermNextOwner"))
{
return FailureResult();
}
UUID userID;
if (!UUID.TryParse(request["PrincipalID"].ToString(), out userID))
return FailureResult();
AgentPrefs data = new AgentPrefs(userID);
data.AccessPrefs = request["AccessPrefs"].ToString();
data.HoverHeight = double.Parse(request["HoverHeight"].ToString());
data.Language = request["Language"].ToString();
data.LanguageIsPublic = bool.Parse(request["LanguageIsPublic"].ToString());
data.PermEveryone = int.Parse(request["PermEveryone"].ToString());
data.PermGroup = int.Parse(request["PermGroup"].ToString());
data.PermNextOwner = int.Parse(request["PermNextOwner"].ToString());
return m_AgentPreferencesService.StoreAgentPreferences(data) ? SuccessResult() : FailureResult();
}
byte[] GetAgentLang(Dictionary<string, object> request)
{
if (!request.ContainsKey("UserID"))
return FailureResult();
UUID userID;
if (!UUID.TryParse(request["UserID"].ToString(), out userID))
return FailureResult();
string lang = "en-us";
AgentPrefs prefs = m_AgentPreferencesService.GetAgentPreferences(userID);
if (prefs != null)
{
if (prefs.LanguageIsPublic)
lang = prefs.Language;
}
Dictionary<string, object> result = new Dictionary<string, object>();
result["Language"] = lang;
string xmlString = ServerUtils.BuildXmlResponse(result);
return Util.UTF8NoBomEncoding.GetBytes(xmlString);
}
private byte[] SuccessResult()
{
XmlDocument doc = new XmlDocument();
XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration,
"", "");
doc.AppendChild(xmlnode);
XmlElement rootElement = doc.CreateElement("", "ServerResponse",
"");
doc.AppendChild(rootElement);
XmlElement result = doc.CreateElement("", "result", "");
result.AppendChild(doc.CreateTextNode("Success"));
rootElement.AppendChild(result);
return Util.DocToBytes(doc);
}
private byte[] FailureResult()
{
XmlDocument doc = new XmlDocument();
XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration,
"", "");
doc.AppendChild(xmlnode);
XmlElement rootElement = doc.CreateElement("", "ServerResponse",
"");
doc.AppendChild(rootElement);
XmlElement result = doc.CreateElement("", "result", "");
result.AppendChild(doc.CreateTextNode("Failure"));
rootElement.AppendChild(result);
return Util.DocToBytes(doc);
}
}
}
| |
// 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.Globalization;
using System.IO;
using System.Net;
using System.Xml;
using OpenLiveWriter.Api;
using OpenLiveWriter.CoreServices;
using OpenLiveWriter.Extensibility.BlogClient;
using OpenLiveWriter.BlogClient.Providers;
using OpenLiveWriter.HtmlParser.Parser;
namespace OpenLiveWriter.BlogClient.Clients
{
public abstract class XmlRpcBlogClient : BlogClientBase, IBlogClient
{
public XmlRpcBlogClient(Uri postApiUrl, IBlogCredentialsAccessor credentials)
: base(credentials)
{
_postApiUrl = UrlHelper.SafeToAbsoluteUri(postApiUrl);
// configure client options
BlogClientOptions clientOptions = new BlogClientOptions();
ConfigureClientOptions(clientOptions);
_clientOptions = clientOptions;
}
public virtual bool IsSecure
{
get
{
return Options.SupportsHttps || (_postApiUrl ?? "").StartsWith("https://", StringComparison.OrdinalIgnoreCase);
}
}
public IBlogClientOptions Options
{
get
{
return _clientOptions;
}
}
/// <summary>
/// Enable external users of the class to completely replace
/// the client options
/// </summary>
/// <param name="newClientOptions"></param>
public void OverrideOptions(IBlogClientOptions newClientOptions)
{
_clientOptions = newClientOptions;
}
/// <summary>
/// Enable subclasses to change the default client options
/// </summary>
/// <param name="clientOptions"></param>
protected virtual void ConfigureClientOptions(BlogClientOptions clientOptions)
{
}
public abstract BlogInfo[] GetUsersBlogs();
public BlogInfo[] GetImageEndpoints()
{
throw new NotImplementedException();
}
public abstract BlogPostCategory[] GetCategories(string blogId);
public abstract BlogPostKeyword[] GetKeywords(string blogId);
public abstract BlogPost[] GetRecentPosts(string blogId, int maxPosts, bool includeCategories, DateTime? now);
public string NewPost(string blogId, BlogPost post, INewCategoryContext newCategoryContext, bool publish, out string etag, out XmlDocument remotePost)
{
etag = null;
remotePost = null;
return NewPost(blogId, post, newCategoryContext, publish);
}
public abstract string NewPost(string blogId, BlogPost post, INewCategoryContext newCategoryContext, bool publish);
public bool EditPost(string blogId, BlogPost post, INewCategoryContext newCategoryContext, bool publish, out string etag, out XmlDocument remotePost)
{
etag = null;
remotePost = null;
return EditPost(blogId, post, newCategoryContext, publish);
}
public abstract bool EditPost(string blogId, BlogPost post, INewCategoryContext newCategoryContext, bool publish);
public abstract BlogPost GetPost(string blogId, string postId);
public abstract void DeletePost(string blogId, string postId, bool publish);
public virtual BlogPost GetPage(string blogId, string pageId)
{
throw new BlogClientMethodUnsupportedException("GetPage");
}
public virtual PageInfo[] GetPageList(string blogId)
{
throw new BlogClientMethodUnsupportedException("GetPageList");
}
public virtual BlogPost[] GetPages(string blogId, int maxPages)
{
throw new BlogClientMethodUnsupportedException("GetPages");
}
public string NewPage(string blogId, BlogPost page, bool publish, out string etag, out XmlDocument remotePost)
{
etag = null;
remotePost = null;
return NewPage(blogId, page, publish);
}
protected virtual string NewPage(string blogId, BlogPost page, bool publish)
{
throw new BlogClientMethodUnsupportedException("NewPage");
}
public bool EditPage(string blogId, BlogPost page, bool publish, out string etag, out XmlDocument remotePost)
{
etag = null;
remotePost = null;
return EditPage(blogId, page, publish);
}
protected virtual bool EditPage(string blogId, BlogPost page, bool publish)
{
throw new BlogClientMethodUnsupportedException("EditPage");
}
public virtual void DeletePage(string blogId, string pageId)
{
throw new BlogClientMethodUnsupportedException("DeletePage");
}
public virtual AuthorInfo[] GetAuthors(string blogId)
{
throw new BlogClientMethodUnsupportedException("GetAuthors");
}
public abstract string DoBeforePublishUploadWork(IFileUploadContext uploadContext);
public virtual void DoAfterPublishUploadWork(IFileUploadContext uploadContext)
{
}
public virtual HttpWebResponse SendAuthenticatedHttpRequest(string requestUri, int timeoutMs, HttpRequestFilter filter)
{
return BlogClientHelper.SendAuthenticatedHttpRequest(requestUri, filter, CreateCredentialsFilter(requestUri));
}
protected virtual HttpRequestFilter CreateCredentialsFilter(string requestUri)
{
TransientCredentials tc = Login();
if (tc != null)
return HttpRequestCredentialsFilter.Create(tc.Username, tc.Password, requestUri, true);
else
return null;
}
public virtual bool? DoesFileNeedUpload(IFileUploadContext uploadContext)
{
return null;
}
/// <summary>
/// Hook that allows subclasses to augment the HttpWebRequest used to make XML-RPC requests.
/// </summary>
/// <param name="request"></param>
protected virtual void BeforeHttpRequest(HttpWebRequest request)
{
// WARNING: Derived classes do not currently make it a practice to call this method
// so don't count on the code executing if the method is overriden!
}
public virtual BlogPostCategory[] SuggestCategories(string blogId, string partialCategoryName)
{
throw new BlogClientMethodUnsupportedException("SuggestCategories");
}
public virtual string AddCategory(string blogId, BlogPostCategory category)
{
throw new BlogClientMethodUnsupportedException("AddCategory");
}
protected readonly string UserAgent = ApplicationEnvironment.UserAgent;
public string Username
{
get { return Login().Username; }
}
public string Password
{
get { return Login().Password; }
}
/// <summary>
/// Call a method and return the XML result. Will throw an exception of type BlogClientException
/// if an error occurs.
/// </summary>
/// <param name="postUrl"></param>
/// <param name="methodName"></param>
/// <param name="parameters"></param>
/// <returns></returns>
protected XmlNode CallMethod(string methodName, params XmlRpcValue[] parameters)
{
string url = _postApiUrl;
if (Options.SupportsHttps)
{
if (url.StartsWith("http://", StringComparison.OrdinalIgnoreCase))
url = "https://" + url.Substring("http://".Length);
}
try
{
// create an RpcClient
XmlRpcClient xmlRpcClient = new XmlRpcClient(url, ApplicationEnvironment.UserAgent, new HttpRequestFilter(BeforeHttpRequest), _clientOptions.CharacterSet);
// call the method
XmlRpcMethodResponse response = xmlRpcClient.CallMethod(methodName, parameters);
// if success, return the response
if (!response.FaultOccurred)
{
return response.Response;
}
else // throw error indicating problem
{
// prepare to throw exception
BlogClientException exception;
// allow underlying provider to return a more descriptive exception type
exception = ExceptionForFault(response.FaultCode, response.FaultString);
if (exception == null) // if it couldn't just go generic
exception = new BlogClientProviderException(response.FaultCode, response.FaultString);
// throw the exception
throw exception;
}
}
catch (IOException ex)
{
throw new BlogClientIOException("calling XML-RPC method " + methodName, ex);
}
catch (WebException ex)
{
HttpRequestHelper.LogException(ex);
// see if this was a 404 not found
switch (ex.Status)
{
case WebExceptionStatus.ProtocolError:
HttpWebResponse response = ex.Response as HttpWebResponse;
if (response != null && response.StatusCode == HttpStatusCode.NotFound)
throw new BlogClientPostUrlNotFoundException(url, ex.Message);
else if (response.StatusCode == HttpStatusCode.Unauthorized)
throw new BlogClientAuthenticationException(response.StatusCode.ToString(), ex.Message, ex);
else
throw new BlogClientHttpErrorException(url, string.Format(CultureInfo.InvariantCulture, "{0} {1}", (int)response.StatusCode, response.StatusDescription), ex);
default:
throw new BlogClientConnectionErrorException(url, ex.Message);
}
}
catch (XmlRpcClientInvalidResponseException ex)
{
throw new BlogClientInvalidServerResponseException(methodName, ex.Message, ex.Response);
}
}
protected abstract BlogClientProviderException ExceptionForFault(string faultCode, string faultString);
protected XmlRpcArray ArrayFromStrings(string[] strings)
{
ArrayList stringValues = new ArrayList();
foreach (string str in strings)
stringValues.Add(new XmlRpcString(str));
return new XmlRpcArray((XmlRpcValue[])stringValues.ToArray(typeof(XmlRpcValue)));
}
protected static string NodeText(XmlNode node)
{
if (node != null)
return node.InnerText.Trim();
else
return String.Empty;
}
/// <summary>
/// Parse a date returned from a weblog. Returns the parsed date as a UTC DateTime value.
/// If the date does not have a timezone designator then it will be presumed to be in the
/// local time zone of this PC. This method is virtual so that for weblogs that produce
/// undesignated date/time strings in some other timezone (like the timezone of the
/// hosting providor) subclasses can do whatever offset is appropriate.
/// </summary>
/// <param name="xmlNode"></param>
/// <returns></returns>
protected virtual DateTime ParseBlogDate(XmlNode xmlNode)
{
string date = NodeText(xmlNode);
if (date != String.Empty)
{
try
{
return ParseBlogDate(date);
}
catch (Exception ex)
{
Trace.Fail("Unexpected exception parsing date: " + date + " (" + ex.Message + ")");
return DateTime.MinValue;
}
}
else
{
return DateTime.MinValue;
}
}
/// <summary>
/// Overridable hook to allow custom handling of setting the post title (in plain text form).
/// This method is called when reading the post title out of an XML-RPC response. Most providers
/// represent the post title value as HTML, so the default implementation here unescapes the encoded HTML
/// back into plain text.
/// </summary>
/// <param name="post"></param>
/// <param name="blogPostTitle"></param>
protected void SetPostTitleFromXmlValue(BlogPost post, string blogPostTitle)
{
bool isHtml = (Options.ReturnsHtmlTitlesOnGet != SupportsFeature.Unknown)
? Options.ReturnsHtmlTitlesOnGet == SupportsFeature.Yes
: Options.RequiresHtmlTitles;
if (!isHtml)
post.Title = blogPostTitle;
else
post.Title = HtmlUtils.UnEscapeEntities(blogPostTitle, HtmlUtils.UnEscapeMode.Default);
}
/// <summary>
/// Overridable hook to allow custom handling of reading the post title for insertion into an XML-RPC request.
/// This method is called when reading the post title for insertion in an XML-RPC response. Most providers
/// represent the post title value as HTML, so the default implementation here escapes plain text post Title
/// into HTML format.
/// </summary>
/// <param name="post"></param>
/// <returns></returns>
protected string GetPostTitleForXmlValue(BlogPost post)
{
if (!this.Options.RequiresHtmlTitles)
return post.Title;
else
return HtmlUtils.EscapeEntities(post.Title);
}
/// <summary>
/// Convert a blog date to a UTC date/time
/// </summary>
/// <param name="date">w3c date-time</param>
/// <returns></returns>
private static DateTime ParseBlogDate(string date)
{
IFormatProvider culture = new CultureInfo("en-US", true);
DateTime dateTime;
try
{
dateTime = DateTime.ParseExact(date, DATE_FORMATS, culture, DateTimeStyles.AllowWhiteSpaces);
return DateTimeHelper.LocalToUtc(dateTime);
}
catch (Exception)
{
//Now try the W3C UTC date formats
//Since .NET doesn't realize the the 'Z' is an indicator of the GMT timezone,
//ParseExact will return the date exactly as parsed (no shift for GMT)
return DateTime.ParseExact(date, DATE_FORMATS_UTC, culture, DateTimeStyles.AllowWhiteSpaces);
}
}
private static readonly string[] DATE_FORMATS = new string[] { "yyyy'-'MM'-'dd'T'HH':'mm':'sszzz", "yyyyMMdd'T'HH':'mm':'ss", "yyyy-MM-ddTHH:mm:ss" };
private static readonly string[] DATE_FORMATS_UTC = new string[] { "yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'", "yyyy'-'MM'-'dd'T'HH':'mm'Z'", "yyyyMMdd'T'HH':'mm':'ss'Z'" };
private readonly string _postApiUrl;
private IBlogClientOptions _clientOptions;
}
}
| |
#region File Description
//-----------------------------------------------------------------------------
// InputReporterGame.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
#region Using Statements
using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
#endregion
namespace InputReporter
{
/// <summary>
/// Displays live input values for all connected controllers.
/// </summary>
partial class InputReporterGame : Microsoft.Xna.Framework.Game
{
#region Image Positions
private static readonly Vector2[] connectedControllerPositions = new Vector2[4]
{
new Vector2(606f, 60f),
new Vector2(656f, 60f),
new Vector2(606f, 110f),
new Vector2(656f, 110f),
};
private static readonly Vector2[] selectedControllerPositions = new Vector2[4]
{
new Vector2(594f, 36f),
new Vector2(686f, 36f),
new Vector2(594f, 137f),
new Vector2(686f, 137f),
};
#endregion
#region Text Positions
private static readonly Vector2 titlePosition =
new Vector2(180f, 73f);
private static readonly Vector2 typeCenterPosition =
new Vector2(660f, 270f);
private static readonly Vector2 descriptionColumn1Position =
new Vector2(65f, 135f);
private static readonly Vector2 valueColumn1Position =
new Vector2(220f, 135f);
private static readonly Vector2 descriptionColumn2Position =
new Vector2(310f, 135f);
private static readonly Vector2 valueColumn2Position =
new Vector2(472f, 135f);
private static readonly Vector2 deadZoneInstructionsPosition =
new Vector2(570f, 380f);
private static readonly Vector2 exitInstructionsPosition =
new Vector2(618f, 425f);
#endregion
#region Text Colors
private static readonly Color titleColor = new Color(60, 134, 11);
private static readonly Color typeColor = new Color(38, 108, 87);
private static readonly Color descriptionColor = new Color(33, 89, 15);
private static readonly Color valueColor = new Color(38, 108, 87);
private static readonly Color disabledColor = new Color(171, 171, 171);
private static readonly Color instructionsColor = new Color(127, 130, 127);
#endregion
#region ChargeSwitch Durations
private const float deadZoneChargeSwitchDuration = 2f;
private const float exitChargeSwitchDuration = 2f;
#endregion
#region Input Data
private int selectedPlayer;
private GamePadState[] gamePadStates = new GamePadState[4];
private GamePadCapabilities[] gamePadCapabilities = new GamePadCapabilities[4];
private KeyboardState lastKeyboardState;
#endregion
#region Dead Zone Data
private GamePadDeadZone deadZone = GamePadDeadZone.IndependentAxes;
public GamePadDeadZone DeadZone
{
get { return deadZone; }
set
{
deadZone = value;
deadZoneString = "(" + deadZone.ToString() + ")";
if (dataFont != null)
{
Vector2 deadZoneStringSize =
dataFont.MeasureString(deadZoneString);
deadZoneStringPosition = new Vector2(
(float)Math.Floor(deadZoneStringCenterPosition.X -
deadZoneStringSize.X / 2f),
(float)Math.Floor(deadZoneStringCenterPosition.Y -
deadZoneStringSize.Y / 2f));
}
}
}
private string deadZoneString;
private Vector2 deadZoneStringPosition;
private Vector2 deadZoneStringCenterPosition;
#endregion
#region ChargeSwitches
private ChargeSwitchExit exitSwitch =
new ChargeSwitchExit(exitChargeSwitchDuration);
private ChargeSwitchDeadZone deadZoneSwitch =
new ChargeSwitchDeadZone(deadZoneChargeSwitchDuration);
#endregion
#region Graphics Data
private GraphicsDeviceManager graphics;
private SpriteBatch spriteBatch;
private SpriteFont titleFont;
private SpriteFont dataFont;
private SpriteFont dataActiveFont;
private SpriteFont typeFont;
private SpriteFont instructionsFont;
private SpriteFont instructionsActiveFont;
private Texture2D backgroundTexture;
private Texture2D[] connectedControllerTextures = new Texture2D[4];
private Texture2D[] selectedControllerTextures = new Texture2D[4];
private float dataSpacing;
#endregion
#region Initialization
/// <summary>
/// Primary constructor.
/// </summary>
public InputReporterGame()
{
graphics = new GraphicsDeviceManager(this);
graphics.PreferredBackBufferWidth = 853;
graphics.PreferredBackBufferHeight = 480;
Content.RootDirectory = "Content";
exitSwitch.Fire += new ChargeSwitch.FireDelegate(exitSwitch_Fire);
deadZoneSwitch.Fire += new ChargeSwitch.FireDelegate(ToggleDeadZone);
}
/// <summary>
/// Allows the game to perform any initialization it needs to before starting
/// to run. This is where it can query for any required services and load any
/// non-graphic related content. Calling base.Initialize will enumerate through
/// any components and initialize them as well.
/// </summary>
protected override void Initialize()
{
selectedPlayer = 0;
exitSwitch.Reset(exitChargeSwitchDuration);
deadZoneSwitch.Reset(deadZoneChargeSwitchDuration);
base.Initialize();
DeadZone = GamePadDeadZone.IndependentAxes;
}
#endregion
#region Graphics Load/Unload
/// <summary>
/// Load your graphics content.
/// </summary>
/// <param name="loadAllContent">Which type of content to load.</param>
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(graphics.GraphicsDevice);
titleFont = Content.Load<SpriteFont>("Fonts\\TitleFont");
dataFont = Content.Load<SpriteFont>("Fonts\\DataFont");
dataActiveFont = Content.Load<SpriteFont>("Fonts\\DataActiveFont");
typeFont = Content.Load<SpriteFont>("Fonts\\TypeFont");
instructionsFont = Content.Load<SpriteFont>("Fonts\\InstructionsFont");
instructionsActiveFont =
Content.Load<SpriteFont>("Fonts\\InstructionsActiveFont");
dataSpacing = (float)Math.Floor(dataFont.LineSpacing * 1.3f);
deadZoneStringCenterPosition = new Vector2(687f,
(float)Math.Floor(deadZoneInstructionsPosition.Y +
dataFont.LineSpacing * 1.7f));
backgroundTexture = Content.Load<Texture2D>("Textures\\Background");
connectedControllerTextures[0] =
Content.Load<Texture2D>("Textures\\connected_controller1");
connectedControllerTextures[1] =
Content.Load<Texture2D>("Textures\\connected_controller2");
connectedControllerTextures[2] =
Content.Load<Texture2D>("Textures\\connected_controller3");
connectedControllerTextures[3] =
Content.Load<Texture2D>("Textures\\connected_controller4");
selectedControllerTextures[0] =
Content.Load<Texture2D>("Textures\\select_controller1");
selectedControllerTextures[1] =
Content.Load<Texture2D>("Textures\\select_controller2");
selectedControllerTextures[2] =
Content.Load<Texture2D>("Textures\\select_controller3");
selectedControllerTextures[3] =
Content.Load<Texture2D>("Textures\\select_controller4");
}
#endregion
#region Updating
/// <summary>
/// Allows the game to run logic such as updating the world,
/// checking for collisions, gathering input and playing audio.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Update(GameTime gameTime)
{
KeyboardState keyboardState = Keyboard.GetState();
if (keyboardState.IsKeyDown(Keys.Escape))
{
this.Exit();
}
if (keyboardState.IsKeyDown(Keys.Space) &&
!lastKeyboardState.IsKeyDown(Keys.Space))
{
ToggleDeadZone();
}
bool setSelectedPlayer = false; // give preference to earlier controllers
for (int i = 0; i < 4; i++)
{
gamePadStates[i] = GamePad.GetState((PlayerIndex)i, deadZone);
gamePadCapabilities[i] = GamePad.GetCapabilities((PlayerIndex)i);
if (!setSelectedPlayer && IsActiveGamePad(ref gamePadStates[i]))
{
selectedPlayer = i;
setSelectedPlayer = true;
}
}
deadZoneSwitch.Update(gameTime, ref gamePadStates[selectedPlayer]);
exitSwitch.Update(gameTime, ref gamePadStates[selectedPlayer]);
base.Update(gameTime);
lastKeyboardState = keyboardState;
}
/// <summary>
/// Determines if the provided GamePadState is "active".
/// </summary>
/// <param name="gamePadState">The GamePadState that is checked.</param>
/// <remarks>
/// "Active" currently means that at least one of the buttons is being pressed.
/// </remarks>
/// <returns>True if "active".</returns>
private static bool IsActiveGamePad(ref GamePadState gamePadState)
{
return (gamePadState.IsConnected &&
((gamePadState.Buttons.A == ButtonState.Pressed) ||
(gamePadState.Buttons.B == ButtonState.Pressed) ||
(gamePadState.Buttons.X == ButtonState.Pressed) ||
(gamePadState.Buttons.Y == ButtonState.Pressed) ||
(gamePadState.Buttons.Start == ButtonState.Pressed) ||
(gamePadState.Buttons.Back == ButtonState.Pressed) ||
(gamePadState.Buttons.LeftShoulder == ButtonState.Pressed) ||
(gamePadState.Buttons.RightShoulder == ButtonState.Pressed) ||
(gamePadState.Buttons.LeftStick == ButtonState.Pressed) ||
(gamePadState.Buttons.RightStick == ButtonState.Pressed) ||
(gamePadState.DPad.Up == ButtonState.Pressed) ||
(gamePadState.DPad.Left == ButtonState.Pressed) ||
(gamePadState.DPad.Right == ButtonState.Pressed) ||
(gamePadState.DPad.Down == ButtonState.Pressed)));
}
#endregion
#region Drawing
/// <summary>
/// This is called when the game should draw itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
graphics.GraphicsDevice.Clear(Color.Black);
base.Draw(gameTime);
spriteBatch.Begin();
// draw the background
spriteBatch.Draw(backgroundTexture, Vector2.Zero, Color.White);
// draw the connected-controller images
for (int i = 0; i < 4; i++)
{
if (gamePadStates[i].IsConnected)
{
spriteBatch.Draw(connectedControllerTextures[i],
connectedControllerPositions[i], Color.White);
}
}
// draw the selected-player texture (numeral)
spriteBatch.Draw(selectedControllerTextures[selectedPlayer],
selectedControllerPositions[selectedPlayer], Color.White);
// draw controller title
string text = InputReporterResources.Title +
((PlayerIndex)selectedPlayer).ToString();
spriteBatch.DrawString(titleFont, text, titlePosition,
titleColor);
// draw controller type
text = gamePadCapabilities[selectedPlayer].GamePadType.ToString();
Vector2 textSize = typeFont.MeasureString(text);
spriteBatch.DrawString(typeFont, text, new Vector2(
(float)Math.Floor(typeCenterPosition.X -
textSize.X / 2f),
(float)Math.Floor(typeCenterPosition.Y -
textSize.Y / 2f)),
typeColor);
// draw the data
DrawData(ref gamePadStates[selectedPlayer],
ref gamePadCapabilities[selectedPlayer]);
// draw the instructions
spriteBatch.DrawString(deadZoneSwitch.Active ? instructionsActiveFont :
instructionsFont, InputReporterResources.DeadZoneInstructions,
deadZoneInstructionsPosition, instructionsColor);
spriteBatch.DrawString(instructionsFont, deadZoneString,
deadZoneStringPosition, instructionsColor);
spriteBatch.DrawString(exitSwitch.Active ? instructionsActiveFont :
instructionsFont, InputReporterResources.ExitInstructions,
exitInstructionsPosition, instructionsColor);
spriteBatch.End();
}
/// <summary>
/// Draw all data for a set of GamePad data and capabilities.
/// </summary>
/// <param name="gamePadState">The GamePad data.</param>
/// <param name="gamePadCapabilities">The GamePad capabilities.</param>
/// <remarks>
/// The GamePad structures are passed by reference for speed. They are not
/// modified in this method.
/// </remarks>
private void DrawData(ref GamePadState gamePadState,
ref GamePadCapabilities gamePadCapabilities)
{
//
// Draw the first column of data
//
Vector2 descriptionPosition = descriptionColumn1Position;
Vector2 valuePosition = valueColumn1Position;
// draw left thumbstick data
DrawValue(InputReporterResources.LeftThumbstickX, ref descriptionPosition,
gamePadState.ThumbSticks.Left.X.ToString("0.000"), ref valuePosition,
gamePadCapabilities.HasLeftXThumbStick,
gamePadState.ThumbSticks.Left.X != 0f);
DrawValue(InputReporterResources.LeftThumbstickY, ref descriptionPosition,
gamePadState.ThumbSticks.Left.Y.ToString("0.000"), ref valuePosition,
gamePadCapabilities.HasLeftYThumbStick,
gamePadState.ThumbSticks.Left.Y != 0f);
// draw the right thumbstick data
DrawValue(InputReporterResources.RightThumbstickX, ref descriptionPosition,
gamePadState.ThumbSticks.Right.X.ToString("0.000"), ref valuePosition,
gamePadCapabilities.HasRightXThumbStick,
gamePadState.ThumbSticks.Right.X != 0f);
DrawValue(InputReporterResources.RightThumbstickY, ref descriptionPosition,
gamePadState.ThumbSticks.Right.Y.ToString("0.000"), ref valuePosition,
gamePadCapabilities.HasRightYThumbStick,
gamePadState.ThumbSticks.Right.Y != 0f);
descriptionPosition.Y += dataSpacing;
valuePosition.Y += dataSpacing;
// draw the trigger data
DrawValue(InputReporterResources.LeftTrigger, ref descriptionPosition,
gamePadState.Triggers.Left.ToString("0.000"), ref valuePosition,
gamePadCapabilities.HasLeftTrigger,
gamePadState.Triggers.Left != 0f);
DrawValue(InputReporterResources.RightTrigger, ref descriptionPosition,
gamePadState.Triggers.Right.ToString("0.000"), ref valuePosition,
gamePadCapabilities.HasRightTrigger,
gamePadState.Triggers.Right != 0f);
descriptionPosition.Y += dataSpacing;
valuePosition.Y += dataSpacing;
// draw the directional pad data
DrawValue(InputReporterResources.DPadUp, ref descriptionPosition,
(gamePadState.DPad.Up == ButtonState.Pressed ?
InputReporterResources.ButtonPressed :
InputReporterResources.ButtonReleased), ref valuePosition,
gamePadCapabilities.HasDPadUpButton,
gamePadState.DPad.Up == ButtonState.Pressed);
DrawValue(InputReporterResources.DPadDown, ref descriptionPosition,
(gamePadState.DPad.Down == ButtonState.Pressed ?
InputReporterResources.ButtonPressed :
InputReporterResources.ButtonReleased), ref valuePosition,
gamePadCapabilities.HasDPadDownButton,
gamePadState.DPad.Down == ButtonState.Pressed);
DrawValue(InputReporterResources.DPadLeft, ref descriptionPosition,
(gamePadState.DPad.Left == ButtonState.Pressed ?
InputReporterResources.ButtonPressed :
InputReporterResources.ButtonReleased), ref valuePosition,
gamePadCapabilities.HasDPadLeftButton,
gamePadState.DPad.Left == ButtonState.Pressed);
DrawValue(InputReporterResources.DPadRight, ref descriptionPosition,
(gamePadState.DPad.Right == ButtonState.Pressed ?
InputReporterResources.ButtonPressed :
InputReporterResources.ButtonReleased), ref valuePosition,
gamePadCapabilities.HasDPadRightButton,
gamePadState.DPad.Right == ButtonState.Pressed);
descriptionPosition.Y += dataSpacing;
valuePosition.Y += dataSpacing;
// draw the vibration data
if (gamePadCapabilities.HasLeftVibrationMotor)
{
if (gamePadCapabilities.HasRightVibrationMotor)
{
spriteBatch.DrawString(dataFont,
InputReporterResources.BothVibrationMotors, descriptionPosition,
descriptionColor);
}
else
{
spriteBatch.DrawString(dataFont,
InputReporterResources.LeftVibrationMotor, descriptionPosition,
descriptionColor);
}
}
else if (gamePadCapabilities.HasRightVibrationMotor)
{
spriteBatch.DrawString(dataFont,
InputReporterResources.RightVibrationMotor, descriptionPosition,
descriptionColor);
}
else
{
spriteBatch.DrawString(dataFont, InputReporterResources.NoVibration,
descriptionPosition, descriptionColor);
}
//
// Draw the second column of data
//
descriptionPosition = descriptionColumn2Position;
valuePosition = valueColumn2Position;
// draw the button data
DrawValue(InputReporterResources.A, ref descriptionPosition,
(gamePadState.Buttons.A == ButtonState.Pressed ?
InputReporterResources.ButtonPressed :
InputReporterResources.ButtonReleased), ref valuePosition,
gamePadCapabilities.HasAButton,
gamePadState.Buttons.A == ButtonState.Pressed);
DrawValue(InputReporterResources.B, ref descriptionPosition,
(gamePadState.Buttons.B == ButtonState.Pressed ?
InputReporterResources.ButtonPressed :
InputReporterResources.ButtonReleased), ref valuePosition,
gamePadCapabilities.HasBButton,
gamePadState.Buttons.B == ButtonState.Pressed);
DrawValue(InputReporterResources.X, ref descriptionPosition,
(gamePadState.Buttons.X == ButtonState.Pressed ?
InputReporterResources.ButtonPressed :
InputReporterResources.ButtonReleased), ref valuePosition,
gamePadCapabilities.HasXButton,
gamePadState.Buttons.X == ButtonState.Pressed);
DrawValue(InputReporterResources.Y, ref descriptionPosition,
(gamePadState.Buttons.Y == ButtonState.Pressed ?
InputReporterResources.ButtonPressed :
InputReporterResources.ButtonReleased), ref valuePosition,
gamePadCapabilities.HasYButton,
gamePadState.Buttons.Y == ButtonState.Pressed);
DrawValue(InputReporterResources.LeftShoulder, ref descriptionPosition,
(gamePadState.Buttons.LeftShoulder == ButtonState.Pressed ?
InputReporterResources.ButtonPressed :
InputReporterResources.ButtonReleased), ref valuePosition,
gamePadCapabilities.HasLeftShoulderButton,
gamePadState.Buttons.LeftShoulder == ButtonState.Pressed);
DrawValue(InputReporterResources.RightShoulder, ref descriptionPosition,
(gamePadState.Buttons.RightShoulder == ButtonState.Pressed ?
InputReporterResources.ButtonPressed :
InputReporterResources.ButtonReleased), ref valuePosition,
gamePadCapabilities.HasRightShoulderButton,
gamePadState.Buttons.RightShoulder == ButtonState.Pressed);
DrawValue(InputReporterResources.LeftStick, ref descriptionPosition,
(gamePadState.Buttons.LeftStick == ButtonState.Pressed ?
InputReporterResources.ButtonPressed :
InputReporterResources.ButtonReleased), ref valuePosition,
gamePadCapabilities.HasLeftStickButton,
gamePadState.Buttons.LeftStick == ButtonState.Pressed);
DrawValue(InputReporterResources.RightStick, ref descriptionPosition,
(gamePadState.Buttons.RightStick == ButtonState.Pressed ?
InputReporterResources.ButtonPressed :
InputReporterResources.ButtonReleased), ref valuePosition,
gamePadCapabilities.HasRightStickButton,
gamePadState.Buttons.RightStick == ButtonState.Pressed);
DrawValue(InputReporterResources.Start, ref descriptionPosition,
(gamePadState.Buttons.Start == ButtonState.Pressed ?
InputReporterResources.ButtonPressed :
InputReporterResources.ButtonReleased), ref valuePosition,
gamePadCapabilities.HasStartButton,
gamePadState.Buttons.Start == ButtonState.Pressed);
DrawValue(InputReporterResources.Back, ref descriptionPosition,
(gamePadState.Buttons.Back == ButtonState.Pressed ?
InputReporterResources.ButtonPressed :
InputReporterResources.ButtonReleased), ref valuePosition,
gamePadCapabilities.HasBackButton,
gamePadState.Buttons.Back == ButtonState.Pressed);
descriptionPosition.Y += dataSpacing;
valuePosition.Y += dataSpacing;
// draw the packet number data
DrawValue(InputReporterResources.PacketNumber, ref descriptionPosition,
gamePadState.PacketNumber.ToString(), ref valuePosition,
gamePadCapabilities.IsConnected, false);
}
/// <summary>
/// Draw a single description/value pair.
/// </summary>
/// <param name="description">The description of the value.</param>
/// <param name="descriptionPosition">The position of the description.</param>
/// <param name="value">The value itself.</param>
/// <param name="valuePosition">The position of the value.</param>
/// <param name="enabled">If true, the value type is supported.</param>
/// <param name="active">If true, the value type is active right now.</param>
/// <remarks>
/// The positions are modified by this function, moving down one line.
/// </remarks>
private void DrawValue(string description, ref Vector2 descriptionPosition,
string value, ref Vector2 valuePosition, bool enabled, bool active)
{
spriteBatch.DrawString(dataFont, description, descriptionPosition,
enabled ? descriptionColor : disabledColor);
descriptionPosition.Y += dataSpacing;
spriteBatch.DrawString(active ? dataActiveFont : dataFont,
value, valuePosition, enabled ? valueColor : disabledColor);
valuePosition.Y += dataSpacing;
}
#endregion
#region ChargeSwitch Event Handlers
/// <summary>
/// Handles the dead-zone ChargeSwitch fire event. Toggles dead zone types.
/// </summary>
private void ToggleDeadZone()
{
switch (DeadZone)
{
case GamePadDeadZone.IndependentAxes:
DeadZone = GamePadDeadZone.Circular;
break;
case GamePadDeadZone.Circular:
DeadZone = GamePadDeadZone.None;
break;
case GamePadDeadZone.None:
DeadZone = GamePadDeadZone.IndependentAxes;
break;
}
}
/// <summary>
/// Handles the exit ChargeSwitch fire event. Exits the application.
/// </summary>
private void exitSwitch_Fire()
{
this.Exit();
}
#endregion
#region Entry Point
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main()
{
using (InputReporterGame game = new InputReporterGame())
{
game.Run();
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using Abp.Application.Services;
using Abp.AspNetCore.Configuration;
using Abp.Extensions;
using Abp.MsDependencyInjection.Extensions;
using Abp.Reflection;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ApplicationModels;
using Microsoft.AspNetCore.Mvc.Internal;
using Microsoft.Extensions.DependencyInjection;
using System.Linq;
using Abp.Collections.Extensions;
using Abp.Web.Api.ProxyScripting.Generators;
using JetBrains.Annotations;
using Microsoft.AspNetCore.Mvc.ModelBinding;
namespace Abp.AspNetCore.Mvc.Conventions
{
public class AbpAppServiceConvention : IApplicationModelConvention
{
private readonly Lazy<AbpAspNetCoreConfiguration> _configuration;
public AbpAppServiceConvention(IServiceCollection services)
{
_configuration = new Lazy<AbpAspNetCoreConfiguration>(() =>
{
return services
.GetSingletonServiceOrNull<AbpBootstrapper>()
.IocManager
.Resolve<AbpAspNetCoreConfiguration>();
}, true);
}
public void Apply(ApplicationModel application)
{
foreach (var controller in application.Controllers)
{
var type = controller.ControllerType.AsType();
if (typeof(IApplicationService).IsAssignableFrom(type))
{
controller.ControllerName = controller.ControllerName.RemovePostFix(ApplicationService.CommonPostfixes);
var configuration = GetControllerSettingOrNull(controller.ControllerType.AsType());
ConfigureArea(controller, configuration);
ConfigureRemoteService(controller, configuration);
}
else
{
var remoteServiceAtt = ReflectionHelper.GetSingleAttributeOrDefault<RemoteServiceAttribute>(type);
if (remoteServiceAtt != null && remoteServiceAtt.IsEnabledFor(type))
{
var configuration = GetControllerSettingOrNull(controller.ControllerType.AsType());
ConfigureRemoteService(controller, configuration);
}
}
}
}
private void ConfigureArea(ControllerModel controller, [CanBeNull] AbpServiceControllerSetting configuration)
{
if (configuration == null)
{
return;
}
if (controller.RouteValues.ContainsKey("area"))
{
return;
}
controller.RouteValues["area"] = configuration.ModuleName;
}
private void ConfigureRemoteService(ControllerModel controller, [CanBeNull] AbpServiceControllerSetting configuration)
{
ConfigureApiExplorer(controller);
ConfigureSelector(controller, configuration);
ConfigureParameters(controller);
}
private void ConfigureParameters(ControllerModel controller)
{
foreach (var action in controller.Actions)
{
foreach (var prm in action.Parameters)
{
if (prm.BindingInfo != null)
{
continue;
}
if (!TypeHelper.IsPrimitiveExtendedIncludingNullable(prm.ParameterInfo.ParameterType))
{
if (CanUseFormBodyBinding(action))
{
prm.BindingInfo = BindingInfo.GetBindingInfo(new[] { new FromBodyAttribute() });
}
}
}
}
}
private static bool CanUseFormBodyBinding(ActionModel action)
{
foreach (var selector in action.Selectors)
{
if (selector.ActionConstraints == null)
{
continue;
}
foreach (var actionConstraint in selector.ActionConstraints)
{
var httpMethodActionConstraint = actionConstraint as HttpMethodActionConstraint;
if (httpMethodActionConstraint == null)
{
continue;
}
if (httpMethodActionConstraint.HttpMethods.All(hm => hm.IsIn("GET", "DELETE", "TRACE", "HEAD")))
{
return false;
}
}
}
return true;
}
private void ConfigureApiExplorer(ControllerModel controller)
{
if (controller.ApiExplorer.GroupName.IsNullOrEmpty())
{
controller.ApiExplorer.GroupName = controller.ControllerName;
}
if (controller.ApiExplorer.IsVisible == null)
{
controller.ApiExplorer.IsVisible = true;
}
foreach (var action in controller.Actions)
{
ConfigureApiExplorer(action);
}
}
private void ConfigureApiExplorer(ActionModel action)
{
if (action.ApiExplorer.IsVisible == null)
{
var remoteServiceAtt = ReflectionHelper.GetSingleAttributeOrDefault<RemoteServiceAttribute>(action.ActionMethod);
action.ApiExplorer.IsVisible = remoteServiceAtt?.IsEnabledFor(action.ActionMethod);
}
}
private void ConfigureSelector(ControllerModel controller, [CanBeNull] AbpServiceControllerSetting configuration)
{
RemoveEmptySelectors(controller.Selectors);
if (controller.Selectors.Any(selector => selector.AttributeRouteModel != null))
{
return;
}
var moduleName = GetModuleNameOrDefault(controller.ControllerType.AsType());
foreach (var action in controller.Actions)
{
ConfigureSelector(moduleName, controller.ControllerName, action, configuration);
}
}
private void ConfigureSelector(string moduleName, string controllerName, ActionModel action, [CanBeNull] AbpServiceControllerSetting configuration)
{
RemoveEmptySelectors(action.Selectors);
if (!action.Selectors.Any())
{
AddAbpServiceSelector(moduleName, controllerName, action, configuration);
}
else
{
NormalizeSelectorRoutes(moduleName, controllerName, action);
}
}
private void AddAbpServiceSelector(string moduleName, string controllerName, ActionModel action, [CanBeNull] AbpServiceControllerSetting configuration)
{
var abpServiceSelectorModel = new SelectorModel
{
AttributeRouteModel = CreateAbpServiceAttributeRouteModel(moduleName, controllerName, action)
};
var verb = configuration?.UseConventionalHttpVerbs == true
? ProxyScriptingHelper.GetConventionalVerbForMethodName(action.ActionName)
: ProxyScriptingHelper.DefaultHttpVerb;
abpServiceSelectorModel.ActionConstraints.Add(new HttpMethodActionConstraint(new[] { verb }));
action.Selectors.Add(abpServiceSelectorModel);
}
private static void NormalizeSelectorRoutes(string moduleName, string controllerName, ActionModel action)
{
foreach (var selector in action.Selectors)
{
if (selector.AttributeRouteModel == null)
{
selector.AttributeRouteModel = CreateAbpServiceAttributeRouteModel(
moduleName,
controllerName,
action
);
}
}
}
private string GetModuleNameOrDefault(Type controllerType)
{
return GetControllerSettingOrNull(controllerType)?.ModuleName ??
AbpServiceControllerSetting.DefaultServiceModuleName;
}
private AbpServiceControllerSetting GetControllerSettingOrNull(Type controllerType)
{
foreach (var controllerSetting in _configuration.Value.ServiceControllerSettings)
{
if (controllerSetting.Assembly == controllerType.Assembly)
{
return controllerSetting;
}
}
return null;
}
private static AttributeRouteModel CreateAbpServiceAttributeRouteModel(string moduleName, string controllerName, ActionModel action)
{
return new AttributeRouteModel(
new RouteAttribute(
$"api/services/{moduleName}/{controllerName}/{action.ActionName}"
)
);
}
private static void RemoveEmptySelectors(IList<SelectorModel> selectors)
{
selectors
.Where(IsEmptySelector)
.ToList()
.ForEach(s => selectors.Remove(s));
}
private static bool IsEmptySelector(SelectorModel selector)
{
return selector.AttributeRouteModel == null && selector.ActionConstraints.IsNullOrEmpty();
}
}
}
| |
// 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 Xunit;
namespace System.Linq.Expressions.Tests
{
public static class NullableArrayLengthTests
{
#region NullableBool tests
[Fact]
public static void CheckNullableBoolArrayLengthTest()
{
CheckNullableBoolArrayLengthExpression(GenerateNullableBoolArray(0));
CheckNullableBoolArrayLengthExpression(GenerateNullableBoolArray(1));
CheckNullableBoolArrayLengthExpression(GenerateNullableBoolArray(5));
}
[Fact]
public static void CheckExceptionNullableBoolArrayLengthTest()
{
CheckExceptionNullableBoolArrayLength(null);
}
#endregion
#region NullableByte tests
[Fact]
public static void CheckNullableByteArrayLengthTest()
{
CheckNullableByteArrayLengthExpression(GenerateNullableByteArray(0));
CheckNullableByteArrayLengthExpression(GenerateNullableByteArray(1));
CheckNullableByteArrayLengthExpression(GenerateNullableByteArray(5));
}
[Fact]
public static void CheckExceptionNullableByteArrayLengthTest()
{
CheckExceptionNullableByteArrayLength(null);
}
#endregion
#region NullableChar tests
[Fact]
public static void CheckNullableCharArrayLengthTest()
{
CheckNullableCharArrayLengthExpression(GenerateNullableCharArray(0));
CheckNullableCharArrayLengthExpression(GenerateNullableCharArray(1));
CheckNullableCharArrayLengthExpression(GenerateNullableCharArray(5));
}
[Fact]
public static void CheckExceptionNullableCharArrayLengthTest()
{
CheckExceptionNullableCharArrayLength(null);
}
#endregion
#region NullableDecimal tests
[Fact]
public static void CheckNullableDecimalArrayLengthTest()
{
CheckNullableDecimalArrayLengthExpression(GenerateNullableDecimalArray(0));
CheckNullableDecimalArrayLengthExpression(GenerateNullableDecimalArray(1));
CheckNullableDecimalArrayLengthExpression(GenerateNullableDecimalArray(5));
}
[Fact]
public static void CheckExceptionNullableDecimalArrayLengthTest()
{
CheckExceptionNullableDecimalArrayLength(null);
}
#endregion
#region NullableDouble tests
[Fact]
public static void CheckNullableDoubleArrayLengthTest()
{
CheckNullableDoubleArrayLengthExpression(GenerateNullableDoubleArray(0));
CheckNullableDoubleArrayLengthExpression(GenerateNullableDoubleArray(1));
CheckNullableDoubleArrayLengthExpression(GenerateNullableDoubleArray(5));
}
[Fact]
public static void CheckExceptionNullableDoubleArrayLengthTest()
{
CheckExceptionNullableDoubleArrayLength(null);
}
#endregion
#region NullableEnum tests
[Fact]
public static void CheckNullableEnumArrayLengthTest()
{
CheckNullableEnumArrayLengthExpression(GenerateNullableEnumArray(0));
CheckNullableEnumArrayLengthExpression(GenerateNullableEnumArray(1));
CheckNullableEnumArrayLengthExpression(GenerateNullableEnumArray(5));
}
[Fact]
public static void CheckExceptionNullableEnumArrayLengthTest()
{
CheckExceptionNullableEnumArrayLength(null);
}
#endregion
#region NullableEnumLong tests
[Fact]
public static void CheckNullableEnumLongArrayLengthTest()
{
CheckNullableEnumLongArrayLengthExpression(GenerateNullableEnumLongArray(0));
CheckNullableEnumLongArrayLengthExpression(GenerateNullableEnumLongArray(1));
CheckNullableEnumLongArrayLengthExpression(GenerateNullableEnumLongArray(5));
}
[Fact]
public static void CheckExceptionNullableEnumLongArrayLengthTest()
{
CheckExceptionNullableEnumLongArrayLength(null);
}
#endregion
#region NullableFloat tests
[Fact]
public static void CheckNullableFloatArrayLengthTest()
{
CheckNullableFloatArrayLengthExpression(GenerateNullableFloatArray(0));
CheckNullableFloatArrayLengthExpression(GenerateNullableFloatArray(1));
CheckNullableFloatArrayLengthExpression(GenerateNullableFloatArray(5));
}
[Fact]
public static void CheckExceptionNullableFloatArrayLengthTest()
{
CheckExceptionNullableFloatArrayLength(null);
}
#endregion
#region NullableInt tests
[Fact]
public static void CheckNullableIntArrayLengthTest()
{
CheckNullableIntArrayLengthExpression(GenerateNullableIntArray(0));
CheckNullableIntArrayLengthExpression(GenerateNullableIntArray(1));
CheckNullableIntArrayLengthExpression(GenerateNullableIntArray(5));
}
[Fact]
public static void CheckExceptionNullableIntArrayLengthTest()
{
CheckExceptionNullableIntArrayLength(null);
}
#endregion
#region NullableLong tests
[Fact]
public static void CheckNullableLongArrayLengthTest()
{
CheckNullableLongArrayLengthExpression(GenerateNullableLongArray(0));
CheckNullableLongArrayLengthExpression(GenerateNullableLongArray(1));
CheckNullableLongArrayLengthExpression(GenerateNullableLongArray(5));
}
[Fact]
public static void CheckExceptionNullableLongArrayLengthTest()
{
CheckExceptionNullableLongArrayLength(null);
}
#endregion
#region NullableSByte tests
[Fact]
public static void CheckNullableSByteArrayLengthTest()
{
CheckNullableSByteArrayLengthExpression(GenerateNullableSByteArray(0));
CheckNullableSByteArrayLengthExpression(GenerateNullableSByteArray(1));
CheckNullableSByteArrayLengthExpression(GenerateNullableSByteArray(5));
}
[Fact]
public static void CheckExceptionNullableSByteArrayLengthTest()
{
CheckExceptionNullableSByteArrayLength(null);
}
#endregion
#region NullableStruct tests
[Fact]
public static void CheckNullableStructArrayLengthTest()
{
CheckNullableStructArrayLengthExpression(GenerateNullableStructArray(0));
CheckNullableStructArrayLengthExpression(GenerateNullableStructArray(1));
CheckNullableStructArrayLengthExpression(GenerateNullableStructArray(5));
}
[Fact]
public static void CheckExceptionNullableStructArrayLengthTest()
{
CheckExceptionNullableStructArrayLength(null);
}
#endregion
#region NullableStructWithString tests
[Fact]
public static void CheckNullableStructWithStringArrayLengthTest()
{
CheckNullableStructWithStringArrayLengthExpression(GenerateNullableStructWithStringArray(0));
CheckNullableStructWithStringArrayLengthExpression(GenerateNullableStructWithStringArray(1));
CheckNullableStructWithStringArrayLengthExpression(GenerateNullableStructWithStringArray(5));
}
[Fact]
public static void CheckExceptionNullableStructWithStringArrayLengthTest()
{
CheckExceptionNullableStructWithStringArrayLength(null);
}
#endregion
#region NullableStructWithStringAndValue tests
[Fact]
public static void CheckNullableStructWithStringAndValueArrayLengthTest()
{
CheckNullableStructWithStringAndValueArrayLengthExpression(GenerateNullableStructWithStringAndValueArray(0));
CheckNullableStructWithStringAndValueArrayLengthExpression(GenerateNullableStructWithStringAndValueArray(1));
CheckNullableStructWithStringAndValueArrayLengthExpression(GenerateNullableStructWithStringAndValueArray(5));
}
[Fact]
public static void CheckExceptionNullableStructWithStringAndValueArrayLengthTest()
{
CheckExceptionNullableStructWithStringAndValueArrayLength(null);
}
#endregion
#region NullableStructWithTwoParameters tests
[Fact]
public static void CheckNullableStructWithTwoParametersArrayLengthTest()
{
CheckNullableStructWithTwoParametersArrayLengthExpression(GenerateNullableStructWithTwoParametersArray(0));
CheckNullableStructWithTwoParametersArrayLengthExpression(GenerateNullableStructWithTwoParametersArray(1));
CheckNullableStructWithTwoParametersArrayLengthExpression(GenerateNullableStructWithTwoParametersArray(5));
}
[Fact]
public static void CheckExceptionNullableStructWithTwoParametersArrayLengthTest()
{
CheckExceptionNullableStructWithTwoParametersArrayLength(null);
}
#endregion
#region NullableStructWithValue tests
[Fact]
public static void CheckNullableStructWithValueArrayLengthTest()
{
CheckNullableStructWithValueArrayLengthExpression(GenerateNullableStructWithValueArray(0));
CheckNullableStructWithValueArrayLengthExpression(GenerateNullableStructWithValueArray(1));
CheckNullableStructWithValueArrayLengthExpression(GenerateNullableStructWithValueArray(5));
}
[Fact]
public static void CheckExceptionNullableStructWithValueArrayLengthTest()
{
CheckExceptionNullableStructWithValueArrayLength(null);
}
#endregion
#region NullableShort tests
[Fact]
public static void CheckNullableShortArrayLengthTest()
{
CheckNullableShortArrayLengthExpression(GenerateNullableShortArray(0));
CheckNullableShortArrayLengthExpression(GenerateNullableShortArray(1));
CheckNullableShortArrayLengthExpression(GenerateNullableShortArray(5));
}
[Fact]
public static void CheckExceptionNullableShortArrayLengthTest()
{
CheckExceptionNullableShortArrayLength(null);
}
#endregion
#region NullableUInt tests
[Fact]
public static void CheckNullableUIntArrayLengthTest()
{
CheckNullableUIntArrayLengthExpression(GenerateNullableUIntArray(0));
CheckNullableUIntArrayLengthExpression(GenerateNullableUIntArray(1));
CheckNullableUIntArrayLengthExpression(GenerateNullableUIntArray(5));
}
[Fact]
public static void CheckExceptionNullableUIntArrayLengthTest()
{
CheckExceptionNullableUIntArrayLength(null);
}
#endregion
#region NullableULong tests
[Fact]
public static void CheckNullableULongArrayLengthTest()
{
CheckNullableULongArrayLengthExpression(GenerateNullableULongArray(0));
CheckNullableULongArrayLengthExpression(GenerateNullableULongArray(1));
CheckNullableULongArrayLengthExpression(GenerateNullableULongArray(5));
}
[Fact]
public static void CheckExceptionNullableULongArrayLengthTest()
{
CheckExceptionNullableULongArrayLength(null);
}
#endregion
#region NullableUShort tests
[Fact]
public static void CheckNullableUShortArrayLengthTest()
{
CheckNullableUShortArrayLengthExpression(GenerateNullableUShortArray(0));
CheckNullableUShortArrayLengthExpression(GenerateNullableUShortArray(1));
CheckNullableUShortArrayLengthExpression(GenerateNullableUShortArray(5));
}
[Fact]
public static void CheckExceptionNullableUShortArrayLengthTest()
{
CheckExceptionNullableUShortArrayLength(null);
}
#endregion
#region Generic tests
[Fact]
public static void CheckGenericNullableEnumWithStructRestrictionArrayLengthTest()
{
CheckGenericWithStructRestrictionArrayLengthTestHelper<E>();
}
[Fact]
public static void CheckExceptionGenericNullableEnumWithStructRestrictionArrayLengthTest()
{
CheckExceptionGenericWithStructRestrictionArrayLengthTestHelper<E>();
}
[Fact]
public static void CheckGenericNullableStructWithStructRestrictionArrayLengthTest()
{
CheckGenericWithStructRestrictionArrayLengthTestHelper<S>();
}
[Fact]
public static void CheckExceptionGenericNullableStructWithStructRestrictionArrayLengthTest()
{
CheckExceptionGenericWithStructRestrictionArrayLengthTestHelper<S>();
}
[Fact]
public static void CheckGenericNullableStructWithStringAndFieldWithStructRestrictionArrayLengthTest()
{
CheckGenericWithStructRestrictionArrayLengthTestHelper<Scs>();
}
[Fact]
public static void CheckExceptionGenericNullableStructWithStringAndFieldWithStructRestrictionArrayLengthTest()
{
CheckExceptionGenericWithStructRestrictionArrayLengthTestHelper<Scs>();
}
#endregion
#region Generic helpers
public static void CheckGenericWithStructRestrictionArrayLengthTestHelper<Ts>() where Ts : struct
{
CheckGenericWithStructRestrictionArrayLengthExpression<Ts>(GenerateGenericWithStructRestrictionArray<Ts>(0));
CheckGenericWithStructRestrictionArrayLengthExpression<Ts>(GenerateGenericWithStructRestrictionArray<Ts>(1));
CheckGenericWithStructRestrictionArrayLengthExpression<Ts>(GenerateGenericWithStructRestrictionArray<Ts>(5));
}
public static void CheckExceptionGenericWithStructRestrictionArrayLengthTestHelper<Ts>() where Ts : struct
{
CheckExceptionGenericWithStructRestrictionArrayLength<Ts>(null);
}
#endregion
#region Generate array
private static bool?[] GenerateNullableBoolArray(int size)
{
bool?[] array = new bool?[] { true, false };
bool?[] result = new bool?[size];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static byte?[] GenerateNullableByteArray(int size)
{
byte?[] array = new byte?[] { 0, 1, byte.MaxValue };
byte?[] result = new byte?[size];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static char?[] GenerateNullableCharArray(int size)
{
char?[] array = new char?[] { '\0', '\b', 'A', '\uffff' };
char?[] result = new char?[size];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static decimal?[] GenerateNullableDecimalArray(int size)
{
decimal?[] array = new decimal?[] { decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue };
decimal?[] result = new decimal?[size];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static double?[] GenerateNullableDoubleArray(int size)
{
double?[] array = new double?[] { 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN };
double?[] result = new double?[size];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static E?[] GenerateNullableEnumArray(int size)
{
E?[] array = new E?[] { (E)0, E.A, E.B, (E)int.MaxValue, (E)int.MinValue };
E?[] result = new E?[size];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static El?[] GenerateNullableEnumLongArray(int size)
{
El?[] array = new El?[] { (El)0, El.A, El.B, (El)long.MaxValue, (El)long.MinValue };
El?[] result = new El?[size];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static float?[] GenerateNullableFloatArray(int size)
{
float?[] array = new float?[] { 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN };
float?[] result = new float?[size];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static int?[] GenerateNullableIntArray(int size)
{
int?[] array = new int?[] { 0, 1, -1, int.MinValue, int.MaxValue };
int?[] result = new int?[size];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static long?[] GenerateNullableLongArray(int size)
{
long?[] array = new long?[] { 0, 1, -1, long.MinValue, long.MaxValue };
long?[] result = new long?[size];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static sbyte?[] GenerateNullableSByteArray(int size)
{
sbyte?[] array = new sbyte?[] { 0, 1, -1, sbyte.MinValue, sbyte.MaxValue };
sbyte?[] result = new sbyte?[size];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static S?[] GenerateNullableStructArray(int size)
{
S?[] array = new S?[] { default(S), new S() };
S?[] result = new S?[size];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static Sc?[] GenerateNullableStructWithStringArray(int size)
{
Sc?[] array = new Sc?[] { default(Sc), new Sc(), new Sc(null) };
Sc?[] result = new Sc?[size];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static Scs?[] GenerateNullableStructWithStringAndValueArray(int size)
{
Scs?[] array = new Scs?[] { default(Scs), new Scs(), new Scs(null, new S()) };
Scs?[] result = new Scs?[size];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static Sp?[] GenerateNullableStructWithTwoParametersArray(int size)
{
Sp?[] array = new Sp?[] { default(Sp), new Sp(), new Sp(5, 5.0) };
Sp?[] result = new Sp?[size];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static Ss?[] GenerateNullableStructWithValueArray(int size)
{
Ss?[] array = new Ss?[] { default(Ss), new Ss(), new Ss(new S()) };
Ss?[] result = new Ss?[size];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static short?[] GenerateNullableShortArray(int size)
{
short?[] array = new short?[] { 0, 1, -1, short.MinValue, short.MaxValue };
short?[] result = new short?[size];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static uint?[] GenerateNullableUIntArray(int size)
{
uint?[] array = new uint?[] { 0, 1, uint.MaxValue };
uint?[] result = new uint?[size];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static ulong?[] GenerateNullableULongArray(int size)
{
ulong?[] array = new ulong?[] { 0, 1, ulong.MaxValue };
ulong?[] result = new ulong?[size];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static ushort?[] GenerateNullableUShortArray(int size)
{
ushort?[] array = new ushort?[] { 0, 1, ushort.MaxValue };
ushort?[] result = new ushort?[size];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static Ts?[] GenerateGenericWithStructRestrictionArray<Ts>(int size) where Ts : struct
{
Ts?[] array = new Ts?[] { default(Ts), new Ts() };
Ts?[] result = new Ts?[size];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
#endregion
#region Check length expression
private static void CheckNullableBoolArrayLengthExpression(bool?[] array)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(bool?[]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile();
Assert.Equal(array.Length, f());
}
private static void CheckNullableByteArrayLengthExpression(byte?[] array)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(byte?[]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile();
Assert.Equal(array.Length, f());
}
private static void CheckNullableCharArrayLengthExpression(char?[] array)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(char?[]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile();
Assert.Equal(array.Length, f());
}
private static void CheckNullableDecimalArrayLengthExpression(decimal?[] array)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(decimal?[]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile();
Assert.Equal(array.Length, f());
}
private static void CheckNullableDoubleArrayLengthExpression(double?[] array)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(double?[]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile();
Assert.Equal(array.Length, f());
}
private static void CheckNullableEnumArrayLengthExpression(E?[] array)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(E?[]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile();
Assert.Equal(array.Length, f());
}
private static void CheckNullableEnumLongArrayLengthExpression(El?[] array)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(El?[]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile();
Assert.Equal(array.Length, f());
}
private static void CheckNullableFloatArrayLengthExpression(float?[] array)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(float?[]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile();
Assert.Equal(array.Length, f());
}
private static void CheckNullableIntArrayLengthExpression(int?[] array)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(int?[]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile();
Assert.Equal(array.Length, f());
}
private static void CheckNullableLongArrayLengthExpression(long?[] array)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(long?[]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile();
Assert.Equal(array.Length, f());
}
private static void CheckNullableSByteArrayLengthExpression(sbyte?[] array)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(sbyte?[]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile();
Assert.Equal(array.Length, f());
}
private static void CheckNullableStructArrayLengthExpression(S?[] array)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(S?[]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile();
Assert.Equal(array.Length, f());
}
private static void CheckNullableStructWithStringArrayLengthExpression(Sc?[] array)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(Sc?[]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile();
Assert.Equal(array.Length, f());
}
private static void CheckNullableStructWithStringAndValueArrayLengthExpression(Scs?[] array)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(Scs?[]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile();
Assert.Equal(array.Length, f());
}
private static void CheckNullableStructWithTwoParametersArrayLengthExpression(Sp?[] array)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(Sp?[]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile();
Assert.Equal(array.Length, f());
}
private static void CheckNullableStructWithValueArrayLengthExpression(Ss?[] array)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(Ss?[]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile();
Assert.Equal(array.Length, f());
}
private static void CheckNullableShortArrayLengthExpression(short?[] array)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(short?[]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile();
Assert.Equal(array.Length, f());
}
private static void CheckNullableUIntArrayLengthExpression(uint?[] array)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(uint?[]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile();
Assert.Equal(array.Length, f());
}
private static void CheckNullableULongArrayLengthExpression(ulong?[] array)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(ulong?[]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile();
Assert.Equal(array.Length, f());
}
private static void CheckNullableUShortArrayLengthExpression(ushort?[] array)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(ushort?[]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile();
Assert.Equal(array.Length, f());
}
private static void CheckGenericWithStructRestrictionArrayLengthExpression<Ts>(Ts?[] array) where Ts : struct
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(Ts?[]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile();
Assert.Equal(array.Length, f());
}
#endregion
#region Check exception array length
private static void CheckExceptionNullableBoolArrayLength(bool?[] array)
{
bool success = true;
try
{
CheckNullableBoolArrayLengthExpression(array); // expect to fail
success = false;
}
catch
{
}
Assert.True(success);
}
private static void CheckExceptionNullableByteArrayLength(byte?[] array)
{
bool success = true;
try
{
CheckNullableByteArrayLengthExpression(array); // expect to fail
success = false;
}
catch
{
}
Assert.True(success);
}
private static void CheckExceptionNullableCharArrayLength(char?[] array)
{
bool success = true;
try
{
CheckNullableCharArrayLengthExpression(array); // expect to fail
success = false;
}
catch
{
}
Assert.True(success);
}
private static void CheckExceptionNullableDecimalArrayLength(decimal?[] array)
{
bool success = true;
try
{
CheckNullableDecimalArrayLengthExpression(array); // expect to fail
success = false;
}
catch
{
}
Assert.True(success);
}
private static void CheckExceptionNullableDoubleArrayLength(double?[] array)
{
bool success = true;
try
{
CheckNullableDoubleArrayLengthExpression(array); // expect to fail
success = false;
}
catch
{
}
Assert.True(success);
}
private static void CheckExceptionNullableEnumArrayLength(E?[] array)
{
bool success = true;
try
{
CheckNullableEnumArrayLengthExpression(array); // expect to fail
success = false;
}
catch
{
}
Assert.True(success);
}
private static void CheckExceptionNullableEnumLongArrayLength(El?[] array)
{
bool success = true;
try
{
CheckNullableEnumLongArrayLengthExpression(array); // expect to fail
success = false;
}
catch
{
}
Assert.True(success);
}
private static void CheckExceptionNullableFloatArrayLength(float?[] array)
{
bool success = true;
try
{
CheckNullableFloatArrayLengthExpression(array); // expect to fail
success = false;
}
catch
{
}
Assert.True(success);
}
private static void CheckExceptionNullableIntArrayLength(int?[] array)
{
bool success = true;
try
{
CheckNullableIntArrayLengthExpression(array); // expect to fail
success = false;
}
catch
{
}
Assert.True(success);
}
private static void CheckExceptionNullableLongArrayLength(long?[] array)
{
bool success = true;
try
{
CheckNullableLongArrayLengthExpression(array); // expect to fail
success = false;
}
catch
{
}
Assert.True(success);
}
private static void CheckExceptionNullableSByteArrayLength(sbyte?[] array)
{
bool success = true;
try
{
CheckNullableSByteArrayLengthExpression(array); // expect to fail
success = false;
}
catch
{
}
Assert.True(success);
}
private static void CheckExceptionNullableStructArrayLength(S?[] array)
{
bool success = true;
try
{
CheckNullableStructArrayLengthExpression(array); // expect to fail
success = false;
}
catch
{
}
Assert.True(success);
}
private static void CheckExceptionNullableStructWithStringArrayLength(Sc?[] array)
{
bool success = true;
try
{
CheckNullableStructWithStringArrayLengthExpression(array); // expect to fail
success = false;
}
catch
{
}
Assert.True(success);
}
private static void CheckExceptionNullableStructWithStringAndValueArrayLength(Scs?[] array)
{
bool success = true;
try
{
CheckNullableStructWithStringAndValueArrayLengthExpression(array); // expect to fail
success = false;
}
catch
{
}
Assert.True(success);
}
private static void CheckExceptionNullableStructWithTwoParametersArrayLength(Sp?[] array)
{
bool success = true;
try
{
CheckNullableStructWithTwoParametersArrayLengthExpression(array); // expect to fail
success = false;
}
catch
{
}
Assert.True(success);
}
private static void CheckExceptionNullableStructWithValueArrayLength(Ss?[] array)
{
bool success = true;
try
{
CheckNullableStructWithValueArrayLengthExpression(array); // expect to fail
success = false;
}
catch
{
}
Assert.True(success);
}
private static void CheckExceptionNullableShortArrayLength(short?[] array)
{
bool success = true;
try
{
CheckNullableShortArrayLengthExpression(array); // expect to fail
success = false;
}
catch
{
}
Assert.True(success);
}
private static void CheckExceptionNullableUIntArrayLength(uint?[] array)
{
bool success = true;
try
{
CheckNullableUIntArrayLengthExpression(array); // expect to fail
success = false;
}
catch
{
}
Assert.True(success);
}
private static void CheckExceptionNullableULongArrayLength(ulong?[] array)
{
bool success = true;
try
{
CheckNullableULongArrayLengthExpression(array); // expect to fail
success = false;
}
catch
{
}
Assert.True(success);
}
private static void CheckExceptionNullableUShortArrayLength(ushort?[] array)
{
bool success = true;
try
{
CheckNullableUShortArrayLengthExpression(array); // expect to fail
success = false;
}
catch
{
}
Assert.True(success);
}
private static void CheckExceptionGenericWithStructRestrictionArrayLength<Ts>(Ts?[] array) where Ts : struct
{
bool success = true;
try
{
CheckGenericWithStructRestrictionArrayLengthExpression<Ts>(array); // expect to fail
success = false;
}
catch
{
}
Assert.True(success);
}
#endregion
}
}
| |
/*
* ******************************************************************************
* Copyright 2014-2017 Spectra Logic Corporation. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use
* this file except in compliance with the License. A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file.
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
* ****************************************************************************
*/
// This code is auto-generated, do not modify
using Ds3.Models;
using System;
using System.Net;
namespace Ds3.Calls
{
public class GetBucketHistorySpectraS3Request : Ds3Request
{
private string _bucketId;
public string BucketId
{
get { return _bucketId; }
set { WithBucketId(value); }
}
private bool? _lastPage;
public bool? LastPage
{
get { return _lastPage; }
set { WithLastPage(value); }
}
private long? _minSequenceNumber;
public long? MinSequenceNumber
{
get { return _minSequenceNumber; }
set { WithMinSequenceNumber(value); }
}
private int? _pageLength;
public int? PageLength
{
get { return _pageLength; }
set { WithPageLength(value); }
}
private int? _pageOffset;
public int? PageOffset
{
get { return _pageOffset; }
set { WithPageOffset(value); }
}
private string _pageStartMarker;
public string PageStartMarker
{
get { return _pageStartMarker; }
set { WithPageStartMarker(value); }
}
public GetBucketHistorySpectraS3Request WithBucketId(Guid? bucketId)
{
this._bucketId = bucketId.ToString();
if (bucketId != null)
{
this.QueryParams.Add("bucket_id", bucketId.ToString());
}
else
{
this.QueryParams.Remove("bucket_id");
}
return this;
}
public GetBucketHistorySpectraS3Request WithBucketId(string bucketId)
{
this._bucketId = bucketId;
if (bucketId != null)
{
this.QueryParams.Add("bucket_id", bucketId);
}
else
{
this.QueryParams.Remove("bucket_id");
}
return this;
}
public GetBucketHistorySpectraS3Request WithLastPage(bool? lastPage)
{
this._lastPage = lastPage;
if (lastPage != null)
{
this.QueryParams.Add("last_page", lastPage.ToString());
}
else
{
this.QueryParams.Remove("last_page");
}
return this;
}
public GetBucketHistorySpectraS3Request WithMinSequenceNumber(long? minSequenceNumber)
{
this._minSequenceNumber = minSequenceNumber;
if (minSequenceNumber != null)
{
this.QueryParams.Add("min_sequence_number", minSequenceNumber.ToString());
}
else
{
this.QueryParams.Remove("min_sequence_number");
}
return this;
}
public GetBucketHistorySpectraS3Request WithPageLength(int? pageLength)
{
this._pageLength = pageLength;
if (pageLength != null)
{
this.QueryParams.Add("page_length", pageLength.ToString());
}
else
{
this.QueryParams.Remove("page_length");
}
return this;
}
public GetBucketHistorySpectraS3Request WithPageOffset(int? pageOffset)
{
this._pageOffset = pageOffset;
if (pageOffset != null)
{
this.QueryParams.Add("page_offset", pageOffset.ToString());
}
else
{
this.QueryParams.Remove("page_offset");
}
return this;
}
public GetBucketHistorySpectraS3Request WithPageStartMarker(Guid? pageStartMarker)
{
this._pageStartMarker = pageStartMarker.ToString();
if (pageStartMarker != null)
{
this.QueryParams.Add("page_start_marker", pageStartMarker.ToString());
}
else
{
this.QueryParams.Remove("page_start_marker");
}
return this;
}
public GetBucketHistorySpectraS3Request WithPageStartMarker(string pageStartMarker)
{
this._pageStartMarker = pageStartMarker;
if (pageStartMarker != null)
{
this.QueryParams.Add("page_start_marker", pageStartMarker);
}
else
{
this.QueryParams.Remove("page_start_marker");
}
return this;
}
public GetBucketHistorySpectraS3Request()
{
}
internal override HttpVerb Verb
{
get
{
return HttpVerb.GET;
}
}
internal override string Path
{
get
{
return "/_rest_/bucket_history";
}
}
}
}
| |
namespace OpenTK.Platform.Windows
{
#pragma warning disable 3019
#pragma warning disable 1591
public enum ArbCreateContext
{
CoreProfileBit = 0x0001,
CompatibilityProfileBit = 0x0002,
DebugBit = 0x0001,
ForwardCompatibleBit = 0x0002,
MajorVersion = 0x2091,
MinorVersion = 0x2092,
LayerPlane = 0x2093,
ContextFlags = 0x2094,
ErrorInvalidVersion = 0x2095,
ProfileMask = 0x9126
}
public enum WGL_ARB_buffer_region
{
BackColorBufferBitArb = ((int)0x00000002),
StencilBufferBitArb = ((int)0x00000008),
FrontColorBufferBitArb = ((int)0x00000001),
DepthBufferBitArb = ((int)0x00000004),
}
public enum WGL_EXT_pixel_format
{
SupportGdiExt = ((int)0x200f),
TypeColorindexExt = ((int)0x202c),
AccelerationExt = ((int)0x2003),
GreenBitsExt = ((int)0x2017),
DrawToWindowExt = ((int)0x2001),
SwapCopyExt = ((int)0x2029),
DrawToBitmapExt = ((int)0x2002),
TransparentExt = ((int)0x200a),
SwapMethodExt = ((int)0x2007),
SwapLayerBuffersExt = ((int)0x2006),
PixelTypeExt = ((int)0x2013),
AlphaShiftExt = ((int)0x201c),
AccumRedBitsExt = ((int)0x201e),
FullAccelerationExt = ((int)0x2027),
SupportOpenglExt = ((int)0x2010),
BlueShiftExt = ((int)0x201a),
RedBitsExt = ((int)0x2015),
NoAccelerationExt = ((int)0x2025),
StereoExt = ((int)0x2012),
GreenShiftExt = ((int)0x2018),
BlueBitsExt = ((int)0x2019),
AlphaBitsExt = ((int)0x201b),
RedShiftExt = ((int)0x2016),
DepthBitsExt = ((int)0x2022),
TypeRgbaExt = ((int)0x202b),
GenericAccelerationExt = ((int)0x2026),
AccumAlphaBitsExt = ((int)0x2021),
AccumGreenBitsExt = ((int)0x201f),
TransparentValueExt = ((int)0x200b),
AccumBlueBitsExt = ((int)0x2020),
ShareDepthExt = ((int)0x200c),
ShareAccumExt = ((int)0x200e),
SwapExchangeExt = ((int)0x2028),
AccumBitsExt = ((int)0x201d),
NumberUnderlaysExt = ((int)0x2009),
StencilBitsExt = ((int)0x2023),
DoubleBufferExt = ((int)0x2011),
NeedPaletteExt = ((int)0x2004),
ColorBitsExt = ((int)0x2014),
SwapUndefinedExt = ((int)0x202a),
NeedSystemPaletteExt = ((int)0x2005),
NumberOverlaysExt = ((int)0x2008),
AuxBuffersExt = ((int)0x2024),
NumberPixelFormatsExt = ((int)0x2000),
ShareStencilExt = ((int)0x200d),
}
public enum WGL_ARB_pixel_format
{
ShareStencilArb = ((int)0x200d),
AccumBitsArb = ((int)0x201d),
NumberUnderlaysArb = ((int)0x2009),
StereoArb = ((int)0x2012),
MaxPbufferHeightArb = ((int)0x2030),
TypeRgbaArb = ((int)0x202b),
SupportGdiArb = ((int)0x200f),
NeedSystemPaletteArb = ((int)0x2005),
AlphaBitsArb = ((int)0x201b),
ShareDepthArb = ((int)0x200c),
SupportOpenglArb = ((int)0x2010),
ColorBitsArb = ((int)0x2014),
AccumRedBitsArb = ((int)0x201e),
MaxPbufferWidthArb = ((int)0x202f),
NumberOverlaysArb = ((int)0x2008),
MaxPbufferPixelsArb = ((int)0x202e),
NeedPaletteArb = ((int)0x2004),
RedShiftArb = ((int)0x2016),
AccelerationArb = ((int)0x2003),
GreenBitsArb = ((int)0x2017),
TransparentGreenValueArb = ((int)0x2038),
PixelTypeArb = ((int)0x2013),
AuxBuffersArb = ((int)0x2024),
DrawToWindowArb = ((int)0x2001),
RedBitsArb = ((int)0x2015),
NumberPixelFormatsArb = ((int)0x2000),
GenericAccelerationArb = ((int)0x2026),
BlueBitsArb = ((int)0x2019),
PbufferLargestArb = ((int)0x2033),
AccumAlphaBitsArb = ((int)0x2021),
TransparentArb = ((int)0x200a),
FullAccelerationArb = ((int)0x2027),
ShareAccumArb = ((int)0x200e),
SwapExchangeArb = ((int)0x2028),
SwapUndefinedArb = ((int)0x202a),
TransparentAlphaValueArb = ((int)0x203a),
PbufferHeightArb = ((int)0x2035),
TransparentBlueValueArb = ((int)0x2039),
SwapMethodArb = ((int)0x2007),
StencilBitsArb = ((int)0x2023),
DepthBitsArb = ((int)0x2022),
GreenShiftArb = ((int)0x2018),
TransparentRedValueArb = ((int)0x2037),
DoubleBufferArb = ((int)0x2011),
NoAccelerationArb = ((int)0x2025),
TypeColorindexArb = ((int)0x202c),
SwapLayerBuffersArb = ((int)0x2006),
AccumBlueBitsArb = ((int)0x2020),
DrawToPbufferArb = ((int)0x202d),
AccumGreenBitsArb = ((int)0x201f),
PbufferWidthArb = ((int)0x2034),
TransparentIndexValueArb = ((int)0x203b),
AlphaShiftArb = ((int)0x201c),
DrawToBitmapArb = ((int)0x2002),
BlueShiftArb = ((int)0x201a),
SwapCopyArb = ((int)0x2029),
}
public enum WGL_EXT_pbuffer
{
DrawToPbufferExt = ((int)0x202d),
PbufferLargestExt = ((int)0x2033),
OptimalPbufferWidthExt = ((int)0x2031),
MaxPbufferPixelsExt = ((int)0x202e),
MaxPbufferHeightExt = ((int)0x2030),
PbufferWidthExt = ((int)0x2034),
MaxPbufferWidthExt = ((int)0x202f),
OptimalPbufferHeightExt = ((int)0x2032),
PbufferHeightExt = ((int)0x2035),
}
public enum WGL_ARB_pbuffer
{
PbufferWidthArb = ((int)0x2034),
TransparentGreenValueArb = ((int)0x2038),
PbufferHeightArb = ((int)0x2035),
PbufferLostArb = ((int)0x2036),
DrawToPbufferArb = ((int)0x202d),
TransparentIndexValueArb = ((int)0x203b),
TransparentRedValueArb = ((int)0x2037),
MaxPbufferPixelsArb = ((int)0x202e),
TransparentAlphaValueArb = ((int)0x203a),
MaxPbufferWidthArb = ((int)0x202f),
MaxPbufferHeightArb = ((int)0x2030),
TransparentBlueValueArb = ((int)0x2039),
PbufferLargestArb = ((int)0x2033),
}
public enum WGL_EXT_depth_float
{
DepthFloatExt = ((int)0x2040),
}
public enum WGL_EXT_multisample
{
SampleBuffersExt = ((int)0x2041),
SamplesExt = ((int)0x2042),
}
public enum WGL_ARB_multisample
{
SampleBuffersArb = ((int)0x2041),
SamplesArb = ((int)0x2042),
}
public enum WGL_EXT_make_current_read
{
ErrorInvalidPixelTypeExt = ((int)0x2043),
}
public enum WGL_ARB_make_current_read
{
ErrorInvalidPixelTypeArb = ((int)0x2043),
ErrorIncompatibleDeviceContextsArb = ((int)0x2054),
}
public enum WGL_I3D_genlock
{
GenlockSourceMultiviewI3d = ((int)0x2044),
GenlockSourceEdgeBothI3d = ((int)0x204c),
GenlockSourceEdgeRisingI3d = ((int)0x204b),
GenlockSourceDigitalSyncI3d = ((int)0x2048),
GenlockSourceExtenalFieldI3d = ((int)0x2046),
GenlockSourceDigitalFieldI3d = ((int)0x2049),
GenlockSourceExtenalSyncI3d = ((int)0x2045),
GenlockSourceEdgeFallingI3d = ((int)0x204a),
GenlockSourceExtenalTtlI3d = ((int)0x2047),
}
public enum WGL_I3D_gamma
{
GammaExcludeDesktopI3d = ((int)0x204f),
GammaTableSizeI3d = ((int)0x204e),
}
public enum WGL_I3D_digital_video_control
{
DigitalVideoCursorAlphaFramebufferI3d = ((int)0x2050),
DigitalVideoGammaCorrectedI3d = ((int)0x2053),
DigitalVideoCursorAlphaValueI3d = ((int)0x2051),
DigitalVideoCursorIncludedI3d = ((int)0x2052),
}
public enum WGL_3DFX_multisample
{
SampleBuffers3dfx = ((int)0x2060),
Samples3dfx = ((int)0x2061),
}
public enum WGL_ARB_render_texture
{
TextureCubeMapPositiveXArb = ((int)0x207d),
TextureCubeMapPositiveYArb = ((int)0x207f),
Aux0Arb = ((int)0x2087),
Texture1dArb = ((int)0x2079),
Aux6Arb = ((int)0x208d),
TextureCubeMapArb = ((int)0x2078),
TextureFormatArb = ((int)0x2072),
BackRightArb = ((int)0x2086),
BindToTextureRgbArb = ((int)0x2070),
MipmapLevelArb = ((int)0x207b),
CubeMapFaceArb = ((int)0x207c),
TextureCubeMapNegativeXArb = ((int)0x207e),
Aux7Arb = ((int)0x208e),
Aux8Arb = ((int)0x208f),
MipmapTextureArb = ((int)0x2074),
NoTextureArb = ((int)0x2077),
Aux3Arb = ((int)0x208a),
Texture2DArb = ((int)0x207a),
Aux1Arb = ((int)0x2088),
TextureCubeMapPositiveZArb = ((int)0x2081),
BindToTextureRgbaArb = ((int)0x2071),
TextureCubeMapNegativeYArb = ((int)0x2080),
TextureRgbaArb = ((int)0x2076),
FrontRightArb = ((int)0x2084),
Aux5Arb = ((int)0x208c),
Aux4Arb = ((int)0x208b),
TextureTargetArb = ((int)0x2073),
FrontLeftArb = ((int)0x2083),
Aux9Arb = ((int)0x2090),
TextureRgbArb = ((int)0x2075),
BackLeftArb = ((int)0x2085),
TextureCubeMapNegativeZArb = ((int)0x2082),
Aux2Arb = ((int)0x2089),
}
public enum WGL_NV_render_texture_rectangle
{
BindToTextureRectangleRgbNv = ((int)0x20a0),
BindToTextureRectangleRgbaNv = ((int)0x20a1),
TextureRectangleNv = ((int)0x20a2),
}
public enum WGL_NV_render_depth_texture
{
DepthTextureFormatNv = ((int)0x20a5),
TextureDepthComponentNv = ((int)0x20a6),
BindToTextureDepthNv = ((int)0x20a3),
DepthComponentNv = ((int)0x20a7),
BindToTextureRectangleDepthNv = ((int)0x20a4),
}
public enum WGL_NV_float_buffer
{
BindToTextureRectangleFloatRNv = ((int)0x20b1),
TextureFloatRNv = ((int)0x20b5),
TextureFloatRgbNv = ((int)0x20b7),
TextureFloatRgNv = ((int)0x20b6),
TextureFloatRgbaNv = ((int)0x20b8),
BindToTextureRectangleFloatRgbaNv = ((int)0x20b4),
FloatComponentsNv = ((int)0x20b0),
BindToTextureRectangleFloatRgNv = ((int)0x20b2),
BindToTextureRectangleFloatRgbNv = ((int)0x20b3),
}
public enum WGL_ARB_pixel_format_float
{
TypeRgbaFloatArb = ((int)0x21a0),
}
public enum WGL_ATI_pixel_format_float
{
TypeRgbaFloatAti = ((int)0x21a0),
}
public enum WGL_font_type
{
FontLines = ((int)0),
}
public enum All
{
SwapCopyExt = ((int)0x2029),
BackColorBufferBitArb = ((int)0x00000002),
FullAccelerationArb = ((int)0x2027),
AccelerationExt = ((int)0x2003),
GenlockSourceMultiviewI3d = ((int)0x2044),
Aux3Arb = ((int)0x208a),
TextureCubeMapNegativeYArb = ((int)0x2080),
DoubleBufferArb = ((int)0x2011),
SwapUndefinedExt = ((int)0x202a),
SupportGdiArb = ((int)0x200f),
Aux2Arb = ((int)0x2089),
TextureCubeMapArb = ((int)0x2078),
SwapLayerBuffersExt = ((int)0x2006),
SwapCopyArb = ((int)0x2029),
ErrorIncompatibleDeviceContextsArb = ((int)0x2054),
TypeColorindexArb = ((int)0x202c),
DigitalVideoCursorIncludedI3d = ((int)0x2052),
NeedPaletteExt = ((int)0x2004),
RedBitsArb = ((int)0x2015),
TextureCubeMapNegativeXArb = ((int)0x207e),
SampleBuffersExt = ((int)0x2041),
GenericAccelerationExt = ((int)0x2026),
BindToTextureRectangleRgbaNv = ((int)0x20a1),
NoTextureArb = ((int)0x2077),
FrontColorBufferBitArb = ((int)0x00000001),
TransparentValueExt = ((int)0x200b),
AlphaBitsArb = ((int)0x201b),
RedBitsExt = ((int)0x2015),
PbufferHeightArb = ((int)0x2035),
BindToTextureRectangleFloatRgbaNv = ((int)0x20b4),
SampleBuffersArb = ((int)0x2041),
MipmapLevelArb = ((int)0x207b),
NeedSystemPaletteExt = ((int)0x2005),
Aux4Arb = ((int)0x208b),
TextureFormatArb = ((int)0x2072),
AccumBitsExt = ((int)0x201d),
AccumBlueBitsExt = ((int)0x2020),
BackLeftArb = ((int)0x2085),
AlphaBitsExt = ((int)0x201b),
StencilBitsArb = ((int)0x2023),
DrawToPbufferExt = ((int)0x202d),
FullAccelerationExt = ((int)0x2027),
ColorBitsExt = ((int)0x2014),
BindToTextureRectangleFloatRgNv = ((int)0x20b2),
DepthBufferBitArb = ((int)0x00000004),
BindToTextureRgbaArb = ((int)0x2071),
AccumGreenBitsArb = ((int)0x201f),
AccumBitsArb = ((int)0x201d),
TypeRgbaFloatArb = ((int)0x21a0),
NeedPaletteArb = ((int)0x2004),
ShareAccumArb = ((int)0x200e),
TransparentArb = ((int)0x200a),
ShareStencilArb = ((int)0x200d),
Aux5Arb = ((int)0x208c),
ImageBufferLockI3d = ((int)0x00000002),
TextureFloatRNv = ((int)0x20b5),
DepthComponentNv = ((int)0x20a7),
FloatComponentsNv = ((int)0x20b0),
TransparentGreenValueArb = ((int)0x2038),
GenlockSourceExtenalTtlI3d = ((int)0x2047),
NeedSystemPaletteArb = ((int)0x2005),
BlueBitsExt = ((int)0x2019),
GreenShiftExt = ((int)0x2018),
OptimalPbufferWidthExt = ((int)0x2031),
AuxBuffersExt = ((int)0x2024),
TypeRgbaFloatAti = ((int)0x21a0),
FrontRightArb = ((int)0x2084),
DepthBitsExt = ((int)0x2022),
GammaTableSizeI3d = ((int)0x204e),
AccumAlphaBitsArb = ((int)0x2021),
Aux0Arb = ((int)0x2087),
TransparentIndexValueArb = ((int)0x203b),
AccumGreenBitsExt = ((int)0x201f),
TransparentBlueValueArb = ((int)0x2039),
NoAccelerationArb = ((int)0x2025),
MaxPbufferPixelsArb = ((int)0x202e),
GammaExcludeDesktopI3d = ((int)0x204f),
MaxPbufferPixelsExt = ((int)0x202e),
AccumBlueBitsArb = ((int)0x2020),
SwapUndefinedArb = ((int)0x202a),
ShareDepthExt = ((int)0x200c),
GenlockSourceEdgeBothI3d = ((int)0x204c),
Samples3dfx = ((int)0x2061),
DoubleBufferExt = ((int)0x2011),
BindToTextureRectangleFloatRgbNv = ((int)0x20b3),
SwapMethodExt = ((int)0x2007),
ErrorInvalidPixelTypeArb = ((int)0x2043),
GreenShiftArb = ((int)0x2018),
TextureFloatRgbaNv = ((int)0x20b8),
Aux1Arb = ((int)0x2088),
GreenBitsArb = ((int)0x2017),
NumberPixelFormatsExt = ((int)0x2000),
NumberOverlaysExt = ((int)0x2008),
PixelTypeArb = ((int)0x2013),
SwapLayerBuffersArb = ((int)0x2006),
DrawToBitmapArb = ((int)0x2002),
NumberPixelFormatsArb = ((int)0x2000),
PbufferLostArb = ((int)0x2036),
Aux9Arb = ((int)0x2090),
TextureCubeMapPositiveZArb = ((int)0x2081),
MaxPbufferHeightArb = ((int)0x2030),
TransparentExt = ((int)0x200a),
PbufferLargestArb = ((int)0x2033),
SwapMethodArb = ((int)0x2007),
TextureRgbaArb = ((int)0x2076),
PbufferWidthExt = ((int)0x2034),
OptimalPbufferHeightExt = ((int)0x2032),
StencilBitsExt = ((int)0x2023),
ShareStencilExt = ((int)0x200d),
DepthFloatExt = ((int)0x2040),
BindToTextureRgbArb = ((int)0x2070),
BindToTextureRectangleRgbNv = ((int)0x20a0),
GenlockSourceDigitalSyncI3d = ((int)0x2048),
AccumAlphaBitsExt = ((int)0x2021),
GenlockSourceExtenalSyncI3d = ((int)0x2045),
RedShiftExt = ((int)0x2016),
GenlockSourceDigitalFieldI3d = ((int)0x2049),
FrontLeftArb = ((int)0x2083),
BlueShiftArb = ((int)0x201a),
PbufferWidthArb = ((int)0x2034),
CubeMapFaceArb = ((int)0x207c),
StencilBufferBitArb = ((int)0x00000008),
NumberOverlaysArb = ((int)0x2008),
SwapExchangeExt = ((int)0x2028),
BackRightArb = ((int)0x2086),
DepthTextureFormatNv = ((int)0x20a5),
TextureFloatRgNv = ((int)0x20b6),
Texture1dArb = ((int)0x2079),
DepthBitsArb = ((int)0x2022),
BindToTextureDepthNv = ((int)0x20a3),
DrawToWindowArb = ((int)0x2001),
TypeRgbaExt = ((int)0x202b),
DigitalVideoCursorAlphaValueI3d = ((int)0x2051),
ErrorInvalidPixelTypeExt = ((int)0x2043),
AccumRedBitsExt = ((int)0x201e),
GreenBitsExt = ((int)0x2017),
TypeRgbaArb = ((int)0x202b),
DigitalVideoCursorAlphaFramebufferI3d = ((int)0x2050),
AuxBuffersArb = ((int)0x2024),
AccumRedBitsArb = ((int)0x201e),
TextureFloatRgbNv = ((int)0x20b7),
TypeColorindexExt = ((int)0x202c),
TransparentAlphaValueArb = ((int)0x203a),
BlueShiftExt = ((int)0x201a),
RedShiftArb = ((int)0x2016),
PbufferHeightExt = ((int)0x2035),
GenlockSourceEdgeRisingI3d = ((int)0x204b),
Texture2DArb = ((int)0x207a),
NumberUnderlaysArb = ((int)0x2009),
NumberUnderlaysExt = ((int)0x2009),
DrawToBitmapExt = ((int)0x2002),
ShareDepthArb = ((int)0x200c),
TextureDepthComponentNv = ((int)0x20a6),
NoAccelerationExt = ((int)0x2025),
PixelTypeExt = ((int)0x2013),
SupportOpenglArb = ((int)0x2010),
TextureCubeMapPositiveYArb = ((int)0x207f),
DrawToWindowExt = ((int)0x2001),
PbufferLargestExt = ((int)0x2033),
DrawToPbufferArb = ((int)0x202d),
SupportOpenglExt = ((int)0x2010),
SampleBuffers3dfx = ((int)0x2060),
GenlockSourceExtenalFieldI3d = ((int)0x2046),
MaxPbufferHeightExt = ((int)0x2030),
SupportGdiExt = ((int)0x200f),
Aux7Arb = ((int)0x208e),
DigitalVideoGammaCorrectedI3d = ((int)0x2053),
ColorBitsArb = ((int)0x2014),
Aux6Arb = ((int)0x208d),
ShareAccumExt = ((int)0x200e),
StereoArb = ((int)0x2012),
TextureRgbArb = ((int)0x2075),
AccelerationArb = ((int)0x2003),
TextureCubeMapPositiveXArb = ((int)0x207d),
TransparentRedValueArb = ((int)0x2037),
BlueBitsArb = ((int)0x2019),
SwapExchangeArb = ((int)0x2028),
SamplesExt = ((int)0x2042),
AlphaShiftExt = ((int)0x201c),
SamplesArb = ((int)0x2042),
TextureTargetArb = ((int)0x2073),
BindToTextureRectangleDepthNv = ((int)0x20a4),
AlphaShiftArb = ((int)0x201c),
Aux8Arb = ((int)0x208f),
MaxPbufferWidthExt = ((int)0x202f),
GenlockSourceEdgeFallingI3d = ((int)0x204a),
StereoExt = ((int)0x2012),
MaxPbufferWidthArb = ((int)0x202f),
TextureRectangleNv = ((int)0x20a2),
ImageBufferMinAccessI3d = ((int)0x00000001),
TextureCubeMapNegativeZArb = ((int)0x2082),
MipmapTextureArb = ((int)0x2074),
GenericAccelerationArb = ((int)0x2026),
BindToTextureRectangleFloatRNv = ((int)0x20b1),
FontLines = ((int)0),
}
public enum WGL_ARB_extensions_string
{
}
public enum WGL_I3D_image_buffer
{
ImageBufferMinAccessI3d = ((int)0x00000001),
ImageBufferLockI3d = ((int)0x00000002),
}
public enum WGL_I3D_swap_frame_lock
{
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Timers;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using log4net;
using log4net.Appender;
using log4net.Core;
using log4net.Repository;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using OpenSim.Framework;
using OpenSim.Framework.Console;
using OpenSim.Framework.Monitoring;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using Timer=System.Timers.Timer;
using Nini.Config;
namespace OpenSim.Framework.Servers
{
/// <summary>
/// Common base for the main OpenSimServers (user, grid, inventory, region, etc)
/// </summary>
public abstract class BaseOpenSimServer : ServerBase
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// Used by tests to suppress Environment.Exit(0) so that post-run operations are possible.
/// </summary>
public bool SuppressExit { get; set; }
/// <summary>
/// This will control a periodic log printout of the current 'show stats' (if they are active) for this
/// server.
/// </summary>
private int m_periodDiagnosticTimerMS = 60 * 60 * 1000;
private Timer m_periodicDiagnosticsTimer = new Timer(60 * 60 * 1000);
/// <summary>
/// Random uuid for private data
/// </summary>
protected string m_osSecret = String.Empty;
protected BaseHttpServer m_httpServer;
public BaseHttpServer HttpServer
{
get { return m_httpServer; }
}
public BaseOpenSimServer() : base()
{
// Random uuid for private data
m_osSecret = UUID.Random().ToString();
}
private static bool m_NoVerifyCertChain = false;
private static bool m_NoVerifyCertHostname = false;
public static bool ValidateServerCertificate(
object sender,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors sslPolicyErrors)
{
if (m_NoVerifyCertChain)
sslPolicyErrors &= ~SslPolicyErrors.RemoteCertificateChainErrors;
if (m_NoVerifyCertHostname)
sslPolicyErrors &= ~SslPolicyErrors.RemoteCertificateNameMismatch;
if (sslPolicyErrors == SslPolicyErrors.None)
return true;
return false;
}
/// <summary>
/// Must be overriden by child classes for their own server specific startup behaviour.
/// </summary>
protected virtual void StartupSpecific()
{
StatsManager.SimExtraStats = new SimExtraStatsCollector();
RegisterCommonCommands();
RegisterCommonComponents(Config);
IConfig startupConfig = Config.Configs["Startup"];
m_NoVerifyCertChain = startupConfig.GetBoolean("NoVerifyCertChain", m_NoVerifyCertChain);
m_NoVerifyCertHostname = startupConfig.GetBoolean("NoVerifyCertHostname", m_NoVerifyCertHostname);
ServicePointManager.ServerCertificateValidationCallback = ValidateServerCertificate;
int logShowStatsSeconds = startupConfig.GetInt("LogShowStatsSeconds", m_periodDiagnosticTimerMS / 1000);
m_periodDiagnosticTimerMS = logShowStatsSeconds * 1000;
m_periodicDiagnosticsTimer.Elapsed += new ElapsedEventHandler(LogDiagnostics);
if (m_periodDiagnosticTimerMS != 0)
{
m_periodicDiagnosticsTimer.Interval = m_periodDiagnosticTimerMS;
m_periodicDiagnosticsTimer.Enabled = true;
}
}
protected override void ShutdownSpecific()
{
Watchdog.Enabled = false;
base.ShutdownSpecific();
MainServer.Stop();
Thread.Sleep(5000);
Util.StopThreadPool();
WorkManager.Stop();
Thread.Sleep(1000);
RemovePIDFile();
m_log.Info("[SHUTDOWN]: Shutdown processing on main thread complete. Exiting...");
if (!SuppressExit)
Environment.Exit(0);
}
/// <summary>
/// Provides a list of help topics that are available. Overriding classes should append their topics to the
/// information returned when the base method is called.
/// </summary>
///
/// <returns>
/// A list of strings that represent different help topics on which more information is available
/// </returns>
protected virtual List<string> GetHelpTopics() { return new List<string>(); }
/// <summary>
/// Print statistics to the logfile, if they are active
/// </summary>
protected void LogDiagnostics(object source, ElapsedEventArgs e)
{
StringBuilder sb = new StringBuilder("DIAGNOSTICS\n\n");
sb.Append(GetUptimeReport());
sb.Append(StatsManager.SimExtraStats.Report());
sb.Append(Environment.NewLine);
sb.Append(GetThreadsReport());
m_log.Debug(sb);
}
/// <summary>
/// Performs initialisation of the scene, such as loading configuration from disk.
/// </summary>
public virtual void Startup()
{
m_log.Info("[STARTUP]: Beginning startup processing");
m_log.Info("[STARTUP]: version: " + m_version + Environment.NewLine);
// clr version potentially is more confusing than helpful, since it doesn't tell us if we're running under Mono/MS .NET and
// the clr version number doesn't match the project version number under Mono.
//m_log.Info("[STARTUP]: Virtual machine runtime version: " + Environment.Version + Environment.NewLine);
m_log.InfoFormat(
"[STARTUP]: Operating system version: {0}, .NET platform {1}, {2}-bit\n",
Environment.OSVersion, Environment.OSVersion.Platform, Util.Is64BitProcess() ? "64" : "32");
try
{
StartupSpecific();
}
catch(Exception e)
{
m_log.Fatal("Fatal error: " + e.ToString());
Environment.Exit(1);
}
TimeSpan timeTaken = DateTime.Now - m_startuptime;
// MainConsole.Instance.OutputFormat(
// "PLEASE WAIT FOR LOGINS TO BE ENABLED ON REGIONS ONCE SCRIPTS HAVE STARTED. Non-script portion of startup took {0}m {1}s.",
// timeTaken.Minutes, timeTaken.Seconds);
}
public string osSecret
{
// Secret uuid for the simulator
get { return m_osSecret; }
}
public string StatReport(IOSHttpRequest httpRequest)
{
// If we catch a request for "callback", wrap the response in the value for jsonp
if (httpRequest.Query.ContainsKey("callback"))
{
return httpRequest.Query["callback"].ToString() + "(" + StatsManager.SimExtraStats.XReport((DateTime.Now - m_startuptime).ToString() , m_version) + ");";
}
else
{
return StatsManager.SimExtraStats.XReport((DateTime.Now - m_startuptime).ToString() , m_version);
}
}
}
}
| |
using SteamKit2;
using System.Collections.Generic;
using SteamTrade;
namespace SteamBot
{
public class SteamTradeDemoHandler : UserHandler
{
// NEW ------------------------------------------------------------------
private readonly GenericInventory mySteamInventory;
private readonly GenericInventory OtherSteamInventory;
private bool tested;
// ----------------------------------------------------------------------
public SteamTradeDemoHandler(Bot bot, SteamID sid) : base(bot, sid)
{
mySteamInventory = new GenericInventory(SteamWeb);
OtherSteamInventory = new GenericInventory(SteamWeb);
}
public override bool OnGroupAdd()
{
return false;
}
public override bool OnFriendAdd ()
{
return true;
}
public override void OnLoginCompleted() {}
public override void OnChatRoomMessage(SteamID chatID, SteamID sender, string message)
{
Log.Info(Bot.SteamFriends.GetFriendPersonaName(sender) + ": " + message);
base.OnChatRoomMessage(chatID, sender, message);
}
public override void OnFriendRemove () {}
public override void OnMessage (string message, EChatEntryType type)
{
SendChatMessage(Bot.ChatResponse);
}
public override bool OnTradeRequest()
{
return true;
}
public override void OnTradeError (string error)
{
SendChatMessage("Oh, there was an error: {0}.", error);
Bot.Log.Warn (error);
}
public override void OnTradeTimeout ()
{
SendChatMessage("Sorry, but you were AFK and the trade was canceled.");
Bot.Log.Info ("User was kicked because he was AFK.");
}
public override void OnTradeInit()
{
// NEW -------------------------------------------------------------------------------
List<long> contextId = new List<long>();
tested = false;
/*************************************************************************************
*
* SteamInventory AppId = 753
*
* Context Id Description
* 1 Gifts (Games), must be public on steam profile in order to work.
* 6 Trading Cards, Emoticons & Backgrounds.
*
************************************************************************************/
contextId.Add(1);
contextId.Add(6);
mySteamInventory.load(753, contextId, Bot.SteamClient.SteamID);
OtherSteamInventory.load(753, contextId, OtherSID);
if (!mySteamInventory.isLoaded | !OtherSteamInventory.isLoaded)
{
SendTradeMessage("Couldn't open an inventory, type 'errors' for more info.");
}
SendTradeMessage("Type 'test' to start.");
// -----------------------------------------------------------------------------------
}
public override void OnTradeAddItem (Schema.Item schemaItem, Inventory.Item inventoryItem) {
// USELESS DEBUG MESSAGES -------------------------------------------------------------------------------
SendTradeMessage("Object AppID: {0}", inventoryItem.AppId);
SendTradeMessage("Object ContextId: {0}", inventoryItem.ContextId);
switch (inventoryItem.AppId)
{
case 440:
SendTradeMessage("TF2 Item Added.");
SendTradeMessage("Name: {0}", schemaItem.Name);
SendTradeMessage("Quality: {0}", inventoryItem.Quality);
SendTradeMessage("Level: {0}", inventoryItem.Level);
SendTradeMessage("Craftable: {0}", (inventoryItem.IsNotCraftable ? "No" : "Yes"));
break;
case 753:
GenericInventory.ItemDescription tmpDescription = OtherSteamInventory.getDescription(inventoryItem.Id);
SendTradeMessage("Steam Inventory Item Added.");
SendTradeMessage("Type: {0}", tmpDescription.type);
SendTradeMessage("Marketable: {0}", (tmpDescription.marketable ? "Yes" : "No"));
break;
default:
SendTradeMessage("Unknown item");
break;
}
// ------------------------------------------------------------------------------------------------------
}
public override void OnTradeRemoveItem (Schema.Item schemaItem, Inventory.Item inventoryItem) {}
public override void OnTradeMessage (string message) {
switch (message.ToLower())
{
case "errors":
if (OtherSteamInventory.errors.Count > 0)
{
SendTradeMessage("User Errors:");
foreach (string error in OtherSteamInventory.errors)
{
SendTradeMessage(" * {0}", error);
}
}
if (mySteamInventory.errors.Count > 0)
{
SendTradeMessage("Bot Errors:");
foreach (string error in mySteamInventory.errors)
{
SendTradeMessage(" * {0}", error);
}
}
break;
case "test":
if (tested)
{
foreach (GenericInventory.Item item in mySteamInventory.items.Values)
{
Trade.RemoveItem(item);
}
}
else
{
SendTradeMessage("Items on my bp: {0}", mySteamInventory.items.Count);
foreach (GenericInventory.Item item in mySteamInventory.items.Values)
{
Trade.AddItem(item);
}
}
tested = !tested;
break;
case "remove":
foreach (var item in mySteamInventory.items)
{
Trade.RemoveItem(item.Value.assetid, item.Value.appid, item.Value.contextid);
}
break;
}
}
public override void OnTradeReady (bool ready)
{
//Because SetReady must use its own version, it's important
//we poll the trade to make sure everything is up-to-date.
Trade.Poll();
if (!ready)
{
Trade.SetReady (false);
}
else
{
if(Validate () | IsAdmin)
{
Trade.SetReady (true);
}
}
}
public override void OnTradeSuccess()
{
// Trade completed successfully
Log.Success("Trade Complete.");
}
public override void OnTradeAccept()
{
if (Validate() | IsAdmin)
{
//Even if it is successful, AcceptTrade can fail on
//trades with a lot of items so we use a try-catch
try {
Trade.AcceptTrade();
}
catch {
Log.Warn ("The trade might have failed, but we can't be sure.");
}
Log.Success ("Trade Complete!");
}
}
public bool Validate ()
{
List<string> errors = new List<string> ();
errors.Add("This demo is meant to show you how to handle SteamInventory Items. Trade cannot be completed, unless you're an Admin.");
// send the errors
if (errors.Count != 0)
SendTradeMessage("There were errors in your trade: ");
foreach (string error in errors)
{
SendTradeMessage(error);
}
return errors.Count == 0;
}
}
}
| |
using System;
using System.Collections.Generic;
using SharpDX;
namespace ModernMoleculeViewer.Model
{
/// <summary>
/// Represents a residue in a molecule.
/// </summary>
/// <remarks>
/// Sometimes referred to as an amino acid. Generates WPF content to display the
/// residue in cartoon mode as well as in the identifier strip at the
/// top of the screen. Aggregates all constituent atoms.
/// </remarks>
internal class Residue : HoverObject
{
/// <summary>
///
/// </summary>
internal enum SelectionType { None, Partial, Full };
private readonly Molecule _molecule;
private readonly string _residueName;
private readonly string _chainIdentifier;
private readonly int _residueSequenceNumber;
private readonly string _residueIdentifier;
private readonly Color _residueColor;
private Color _structureColor;
private Color _color;
private readonly List<Atom> _atoms;
private readonly List<ResidueStripItem> _residueStripItems;
private bool _isSheet;
private bool _isHelix;
private bool _isStructureStart;
private bool _isStructureEnd;
private Residue _previousResidue;
private Residue _nextResidue;
private Vector3? _cAlphaPosition;
private Vector3? _carbonylOxygenPosition;
private Chain _chain;
private Ribbon _ribbon;
private Cartoon _cartoon;
private ColorScheme _colorScheme;
private SelectionType _selection;
private SelectionType _showAsSelection;
private bool _updatingSelectionProperty;
/// <summary>
/// Creates a new <see cref="Residue" /> object.
/// </summary>
/// <param name="molecule">The molecule this residue belongs to.</param>
/// <param name="atom">An atom in the residue. This is needed to obtain residue properties
/// since there is no corresponding PDB file record.</param>
internal Residue(Molecule molecule, Atom atom)
{
_molecule = molecule;
_molecule.ShowCartoonChanged += MoleculeShowCartoonChanged;
_residueName = atom.ResidueName;
_chainIdentifier = atom.ChainIdentifier;
_residueSequenceNumber = atom.ResidueSequenceNumber;
_atoms = new List<Atom>();
_atoms.Add(atom);
_residueIdentifier = GetResidueIdentifier(_residueName);
_residueColor = GetResidueColor(_residueName);
_structureColor = _residueIdentifier != "O" ? Color.LightGray : Color.Red;
_colorScheme = ColorScheme.Structure;
_residueStripItems = new List<ResidueStripItem>();
foreach (char character in _residueIdentifier)
{
ResidueStripItem residueStripItem = new ResidueStripItem(character.ToString());
residueStripItem.Residue = this;
_residueStripItems.Add(residueStripItem);
}
UpdateColorView();
}
/// <summary>
/// Label used for atom tooltips.
/// </summary>
internal override string DisplayName
{
get
{
return "[" + _residueSequenceNumber + "] " + _residueName;
}
}
/// <summary>
/// The multi-character abbreviation for the residue. For chain-based amino acids, this is
/// a three letter code.
/// </summary>
internal string ResidueName { get { return _residueName; } }
/// <summary>
/// Alphanumeric chain identifier for the chain residue belongs to.
/// </summary>
internal string ChainIdentifier { get { return _chainIdentifier; } }
/// <summary>
/// Index number for this amino acid.
/// </summary>
internal int ResidueSequenceNumber { get { return _residueSequenceNumber; } }
/// <summary>
/// Shortened abbreviation for the residue. For chain-based amino acids, this is a single
/// letter.
/// </summary>
internal string ResidueIdentifier { get { return _residueIdentifier; } }
/// <summary>
/// The color used for this residue when using the residue-based coloring method.
/// </summary>
internal Color ResidueColor { get { return _residueColor; } }
/// <summary>
/// The constituent atoms.
/// </summary>
internal List<Atom> Atoms { get { return _atoms; } }
/// <summary>
/// Gets and sets a boolean value indicating if this residue is part of a sheet.
/// </summary>
internal bool IsSheet
{
get { return _isSheet; }
set { _isSheet = value; }
}
/// <summary>
/// Gets and sets a boolean value indicating if this residue is part of a helix.
/// </summary>
internal bool IsHelix
{
get { return _isHelix; }
set { _isHelix = value; }
}
/// <summary>
/// Gets and sets a boolean value indicating if this residue is the first residue in a
/// secondary structure.
/// </summary>
internal bool IsStructureStart
{
get { return _isStructureStart; }
set { _isStructureStart = value; }
}
/// <summary>
/// Gets and sets a boolean value indicating if this residue is the last residue in a
/// secondary structure.
/// </summary>
internal bool IsStructureEnd
{
get { return _isStructureEnd; }
set { _isStructureEnd = value; }
}
/// <summary>
/// Reference to the previous residue in the current chain.
/// </summary>
internal Residue PreviousResidue
{
get { return _previousResidue; }
set { _previousResidue = value; }
}
/// <summary>
/// Reference to the next residue in the current chain.
/// </summary>
internal Residue NextResidue
{
get { return _nextResidue; }
set { _nextResidue = value; }
}
/// <summary>
/// If residue belongs to a standard protein amino acid this will contain the 3D location
/// of the alpha carbon atom.
/// </summary>
internal Vector3? CAlphaPosition
{
get { return _cAlphaPosition; }
set { _cAlphaPosition = value; }
}
/// <summary>
/// If residue belongs to a standard protein amino acid this will contain the 3D location
/// of the carbonyl oxygen atom.
/// </summary>
internal Vector3? CarbonylOxygenPosition
{
get { return _carbonylOxygenPosition; }
set { _carbonylOxygenPosition = value; }
}
/// <summary>
/// The chain this residue belongs to.
/// </summary>
internal Chain Chain
{
get { return _chain; }
set { _chain = value; }
}
/// <summary>
/// Reference to the <see cref="Ribbon" /> object that calculates spline paths for this
/// residue.
/// </summary>
internal Ribbon Ribbon
{
get { return _ribbon; }
set { _ribbon = value; }
}
/// <summary>
/// The color to use for this residue when using the structure-based coloring method.
/// </summary>
internal Color StructureColor
{
get { return _structureColor; }
set
{
_structureColor = value;
UpdateColorView();
}
}
/// <summary>
/// All of the <see cref="ResidueStripItem" /> controls for this residue. For protein
/// amino acids, there is only one item in this list.
/// </summary>
internal List<ResidueStripItem> ResidueStripItems
{
get { return _residueStripItems; }
}
/// <summary>
/// Currently used coloring method.
/// </summary>
internal ColorScheme ColorScheme
{
get
{
return _colorScheme;
}
set
{
if (_colorScheme != value)
{
_colorScheme = value;
UpdateColorView();
}
}
}
public Color Color
{
get { return _color; }
}
/// <summary>
/// Gets and sets a <see cref="SelectionType" /> enumeration value indicating the current
/// selection state.
/// </summary>
internal SelectionType Selection
{
get
{
return _selection;
}
set
{
if (_selection != value)
{
_selection = value;
_showAsSelection = _selection;
UpdateView();
_updatingSelectionProperty = true;
foreach (Atom atom in _atoms)
{
if (_selection == SelectionType.None)
atom.IsSelected = false;
else if (_selection == SelectionType.Full)
atom.IsSelected = true;
}
_updatingSelectionProperty = false;
}
}
}
/// <summary>
/// Gets and sets a <see cref="SelectionType" /> enumeration value indicating if the
/// residue is rendered as selected. For certain operations such as rubber-banding a
/// residue might be rendered as though it were selected even though it's not.
/// </summary>
internal SelectionType ShowAsSelection
{
get
{
return _showAsSelection;
}
set
{
if (_showAsSelection != value)
{
_showAsSelection = value;
UpdateView();
_updatingSelectionProperty = true;
foreach (Atom atom in _atoms)
{
if (_showAsSelection == SelectionType.None)
atom.ShowAsSelected = false;
else if (_showAsSelection == SelectionType.Partial)
atom.ShowAsSelected = atom.IsSelected;
else if (_showAsSelection == SelectionType.Full)
atom.ShowAsSelected = true;
}
_updatingSelectionProperty = false;
}
}
}
public Cartoon Cartoon
{
get { return _cartoon; }
set { _cartoon = value; }
}
/// <summary>
/// Updates the selection state based on the selection states of the constituent atoms.
/// </summary>
internal void UpdateForAtomSelectionChange()
{
if (_updatingSelectionProperty) return;
bool dirty = false;
bool fullSelected = true;
bool partialSelected = false;
foreach (Atom atom in _atoms)
{
if (atom.IsSelected) partialSelected = true;
else fullSelected = false;
}
if (fullSelected && _selection != SelectionType.Full)
{
_selection = SelectionType.Full;
dirty = true;
}
else if (!fullSelected && partialSelected && _selection != SelectionType.Partial)
{
_selection = SelectionType.Partial;
dirty = true;
}
else if (!partialSelected && _selection != SelectionType.None)
{
_selection = SelectionType.None;
dirty = true;
}
bool fullShowAsSelected = true;
bool partialShowAsSelected = false;
foreach (Atom atom in _atoms)
{
if (atom.ShowAsSelected) partialShowAsSelected = true;
else fullShowAsSelected = false;
}
if (fullShowAsSelected && _showAsSelection != SelectionType.Full)
{
_showAsSelection = SelectionType.Full;
dirty = true;
}
else if (!fullShowAsSelected && partialShowAsSelected &&
_showAsSelection != SelectionType.Partial)
{
_showAsSelection = SelectionType.Partial;
dirty = true;
}
else if (!partialShowAsSelected && _showAsSelection != SelectionType.None)
{
_showAsSelection = SelectionType.None;
dirty = true;
}
if (dirty) UpdateView();
}
/* /// <summary>
/// Performs hit testing for this residue.
/// </summary>
/// <param name="rayHitTestResult">A 3D mesh hit test result from the WPF visual tree hit
/// testing framework</param>
/// <returns>True if the mesh hit belongs to this residue, otherwise false.</returns>
internal virtual bool HoverHitTest(RayMeshGeometry3DHitTestResult rayHitTestResult)
{
if (cartoon != null)
return cartoon.HoverHitTest(rayHitTestResult);
else
return false;
}*/
/// <summary>
/// Determines if a particular residue name refers to an amino acid.
/// </summary>
/// <param name="residueName">A multi-character residue abbreviation.</param>
/// <returns>True if and only if the residue name refers to an amino acid.</returns>
internal static bool IsAminoName(string residueName)
{
if (residueName == "ALA") return true;
else if (residueName == "ARG") return true;
else if (residueName == "ASP") return true;
else if (residueName == "CYS") return true;
else if (residueName == "GLN") return true;
else if (residueName == "GLU") return true;
else if (residueName == "GLY") return true;
else if (residueName == "HIS") return true;
else if (residueName == "ILE") return true;
else if (residueName == "LEU") return true;
else if (residueName == "LYS") return true;
else if (residueName == "MET") return true;
else if (residueName == "PHE") return true;
else if (residueName == "PRO") return true;
else if (residueName == "SER") return true;
else if (residueName == "THR") return true;
else if (residueName == "TRP") return true;
else if (residueName == "TYR") return true;
else if (residueName == "VAL") return true;
else if (residueName == "ASN") return true;
else return false;
}
/// <summary>
/// Updates the 3D model to depict the correct hovered state.
/// </summary>
protected override void OnIsHoveredChanged()
{
UpdateView();
}
/// <summary>
/// Static method to obtain the single character abbreviation of an amino acid.
/// </summary>
/// <param name="residueName">A multi-character residue abbreviation.</param>
/// <returns>A single character abbreviation if one is available, othewise return the input
/// abbreviation.</returns>
private static string GetResidueIdentifier(string residueName)
{
if (residueName == "HOH") return "O";
else if (residueName == "ALA") return "A";
else if (residueName == "ARG") return "R";
else if (residueName == "ASP") return "D";
else if (residueName == "CYS") return "C";
else if (residueName == "GLN") return "Q";
else if (residueName == "GLU") return "E";
else if (residueName == "GLY") return "G";
else if (residueName == "HIS") return "H";
else if (residueName == "ILE") return "I";
else if (residueName == "LEU") return "L";
else if (residueName == "LYS") return "K";
else if (residueName == "MET") return "M";
else if (residueName == "PHE") return "F";
else if (residueName == "PRO") return "P";
else if (residueName == "SER") return "S";
else if (residueName == "THR") return "T";
else if (residueName == "TRP") return "W";
else if (residueName == "TYR") return "Y";
else if (residueName == "VAL") return "V";
else if (residueName == "ASN") return "N";
else return residueName;
}
/// <summary>
/// Selects a color based on the residue type.
/// </summary>
/// <param name="residueName">A multi-character residue abbreviation.</param>
/// <returns>A color for the residue.</returns>
private static Color GetResidueColor(string residueName)
{
if (residueName == "HOH") return Color.Red;
else if (residueName == "ALA") return new Color(199, 199, 199);
else if (residueName == "ARG") return new Color(229, 10, 10);
else if (residueName == "CYS") return new Color(229, 229, 0);
else if (residueName == "GLN") return new Color(0, 229, 229);
else if (residueName == "GLU") return new Color(229, 10, 10);
else if (residueName == "GLY") return new Color(234, 234, 234);
else if (residueName == "HIS") return new Color(130, 130, 209);
else if (residueName == "ILE") return new Color(15, 130, 15);
else if (residueName == "LEU") return new Color(15, 130, 15);
else if (residueName == "LYS") return new Color(20, 90, 255);
else if (residueName == "MET") return new Color(229, 229, 0);
else if (residueName == "PHE") return new Color(50, 50, 169);
else if (residueName == "PRO") return new Color(219, 149, 130);
else if (residueName == "SER") return new Color(249, 149, 0);
else if (residueName == "THR") return new Color(249, 149, 0);
else if (residueName == "TRP") return new Color(179, 90, 179);
else if (residueName == "TYR") return new Color(50, 50, 169);
else if (residueName == "VAL") return new Color(15, 130, 15);
else if (residueName == "ASN") return new Color(0, 229, 229);
else return Color.Green;
}
/// <summary>
/// Toggles visibility of 3D model components based on the
/// <see cref="Molecule.ShowCartoon" /> property.
/// </summary>
/// <param name="sender">The molecule.</param>
/// <param name="e">Empty event args.</param>
private void MoleculeShowCartoonChanged(object sender, EventArgs e)
{
/*if (_ribbon != null)
{
if (_molecule.ShowCartoon && _cartoon == null)
{
_cartoon = new Cartoon(this, _color, TODO);
}
}*/
}
/// <summary>
/// Selects the material color for this residue based on the coloring method.
/// </summary>
private void UpdateColorView()
{
if (_colorScheme == ColorScheme.Structure)
_color = _structureColor;
else if (_colorScheme == ColorScheme.Atom && _residueIdentifier == "O")
_color = Color.Red;
else if (_colorScheme == ColorScheme.Atom)
_color = Color.LightGray;
else if (_colorScheme == ColorScheme.Residue)
_color = _residueColor;
else if (_colorScheme == ColorScheme.Chain && _chain != null)
_color = _chain.ChainColor;
else if (_colorScheme == ColorScheme.Temperature)
_color = Atom.GetAverageTemperateColor(_atoms);
else
_color = Color.LightGray;
UpdateView();
}
/// <summary>
/// Updates the material color for this atom based on the coloring method and the current
/// hover state.
/// </summary>
private void UpdateView()
{
/* Color actualColor = _color;
if (IsHovered)
{
byte r = (byte)(_color.R + (255 - _color.R) / 2);
byte g = (byte)(_color.G + (255 - _color.G) / 2);
byte b = (byte)(_color.B + (255 - _color.B) / 2);
if (r == g && g == b) r = g = b = 255;
actualColor = new Color(r, g, b);
}
SolidColorBrush foreground = new SolidColorBrush(actualColor);
SolidColorBrush background = Brushes.Transparent;
if (_showAsSelection == SelectionType.Partial)
{
foreground = new SolidColorBrush(actualColor);
background = new SolidColorBrush(
Color.FromArgb(96, actualColor.R, actualColor.G, actualColor.B));
}
else if (_showAsSelection == SelectionType.Full)
{
foreground = Brushes.Black;
background = new SolidColorBrush(actualColor);
}
foreach (ResidueStripItem residueStripItem in _residueStripItems)
{
residueStripItem.Label.Foreground = foreground;
residueStripItem.Label.Background = background;
}
if (cartoon != null)
cartoon.Color = actualColor;*/
}
}
}
| |
// 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.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Formatting.Rules;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Rename;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Simplification;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.ExternalElements;
using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements;
using Microsoft.VisualStudio.LanguageServices.Implementation.Interop;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;
using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Editor.OptionsExtensionMethods;
using Roslyn.Utilities;
using Microsoft.CodeAnalysis.GeneratedCodeRecognition;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel
{
internal abstract partial class AbstractCodeModelService : ICodeModelService
{
private readonly ConditionalWeakTable<SyntaxTree, IBidirectionalMap<SyntaxNodeKey, SyntaxNode>> _treeToNodeKeyMaps =
new ConditionalWeakTable<SyntaxTree, IBidirectionalMap<SyntaxNodeKey, SyntaxNode>>();
protected readonly ISyntaxFactsService SyntaxFactsService;
private readonly IEditorOptionsFactoryService _editorOptionsFactoryService;
private readonly AbstractNodeNameGenerator _nodeNameGenerator;
private readonly AbstractNodeLocator _nodeLocator;
private readonly AbstractCodeModelEventCollector _eventCollector;
private readonly IEnumerable<IRefactorNotifyService> _refactorNotifyServices;
private readonly IFormattingRule _lineAdjustmentFormattingRule;
private readonly IFormattingRule _endRegionFormattingRule;
protected AbstractCodeModelService(
HostLanguageServices languageServiceProvider,
IEditorOptionsFactoryService editorOptionsFactoryService,
IEnumerable<IRefactorNotifyService> refactorNotifyServices,
IFormattingRule lineAdjustmentFormattingRule,
IFormattingRule endRegionFormattingRule)
{
Debug.Assert(languageServiceProvider != null);
Debug.Assert(editorOptionsFactoryService != null);
this.SyntaxFactsService = languageServiceProvider.GetService<ISyntaxFactsService>();
_editorOptionsFactoryService = editorOptionsFactoryService;
_lineAdjustmentFormattingRule = lineAdjustmentFormattingRule;
_endRegionFormattingRule = endRegionFormattingRule;
_refactorNotifyServices = refactorNotifyServices;
_nodeNameGenerator = CreateNodeNameGenerator();
_nodeLocator = CreateNodeLocator();
_eventCollector = CreateCodeModelEventCollector();
}
protected string GetNewLineCharacter(SourceText text)
{
return _editorOptionsFactoryService.GetEditorOptions(text).GetNewLineCharacter();
}
protected int GetTabSize(SourceText text)
{
var snapshot = text.FindCorrespondingEditorTextSnapshot();
return GetTabSize(snapshot);
}
protected int GetTabSize(ITextSnapshot snapshot)
{
if (snapshot == null)
{
throw new ArgumentNullException("snapshot");
}
var textBuffer = snapshot.TextBuffer;
return _editorOptionsFactoryService.GetOptions(textBuffer).GetTabSize();
}
protected SyntaxToken GetTokenWithoutAnnotation(SyntaxToken current, Func<SyntaxToken, SyntaxToken> nextTokenGetter)
{
while (current.ContainsAnnotations)
{
current = nextTokenGetter(current);
}
return current;
}
protected TextSpan GetEncompassingSpan(SyntaxNode root, SyntaxToken startToken, SyntaxToken endToken)
{
var startPosition = startToken.SpanStart;
var endPosition = endToken.RawKind == 0 ? root.Span.End : endToken.Span.End;
return TextSpan.FromBounds(startPosition, endPosition);
}
private IBidirectionalMap<SyntaxNodeKey, SyntaxNode> BuildNodeKeyMap(SyntaxTree syntaxTree)
{
var nameOrdinalMap = new Dictionary<string, int>();
var nodeKeyMap = BidirectionalMap<SyntaxNodeKey, SyntaxNode>.Empty;
foreach (var node in GetFlattenedMemberNodes(syntaxTree))
{
var name = _nodeNameGenerator.GenerateName(node);
int ordinal;
if (!nameOrdinalMap.TryGetValue(name, out ordinal))
{
ordinal = 0;
}
nameOrdinalMap[name] = ++ordinal;
var key = new SyntaxNodeKey(name, ordinal);
nodeKeyMap = nodeKeyMap.Add(key, node);
}
return nodeKeyMap;
}
private IBidirectionalMap<SyntaxNodeKey, SyntaxNode> GetNodeKeyMap(SyntaxTree syntaxTree)
{
return _treeToNodeKeyMaps.GetValue(syntaxTree, BuildNodeKeyMap);
}
public SyntaxNodeKey GetNodeKey(SyntaxNode node)
{
var nodeKey = TryGetNodeKey(node);
if (nodeKey.IsEmpty)
{
throw new ArgumentException();
}
return nodeKey;
}
public SyntaxNodeKey TryGetNodeKey(SyntaxNode node)
{
var nodeKeyMap = GetNodeKeyMap(node.SyntaxTree);
SyntaxNodeKey nodeKey;
if (!nodeKeyMap.TryGetKey(node, out nodeKey))
{
return SyntaxNodeKey.Empty;
}
return nodeKey;
}
public SyntaxNode LookupNode(SyntaxNodeKey nodeKey, SyntaxTree syntaxTree)
{
var nodeKeyMap = GetNodeKeyMap(syntaxTree);
SyntaxNode node;
if (!nodeKeyMap.TryGetValue(nodeKey, out node))
{
throw new ArgumentException();
}
return node;
}
public bool TryLookupNode(SyntaxNodeKey nodeKey, SyntaxTree syntaxTree, out SyntaxNode node)
{
var nodeKeyMap = GetNodeKeyMap(syntaxTree);
return nodeKeyMap.TryGetValue(nodeKey, out node);
}
public abstract bool MatchesScope(SyntaxNode node, EnvDTE.vsCMElement scope);
public abstract IEnumerable<SyntaxNode> GetOptionNodes(SyntaxNode parent);
public abstract IEnumerable<SyntaxNode> GetImportNodes(SyntaxNode parent);
public abstract IEnumerable<SyntaxNode> GetAttributeNodes(SyntaxNode parent);
public abstract IEnumerable<SyntaxNode> GetAttributeArgumentNodes(SyntaxNode parent);
public abstract IEnumerable<SyntaxNode> GetInheritsNodes(SyntaxNode parent);
public abstract IEnumerable<SyntaxNode> GetImplementsNodes(SyntaxNode parent);
public abstract IEnumerable<SyntaxNode> GetParameterNodes(SyntaxNode parent);
protected IEnumerable<SyntaxNode> GetFlattenedMemberNodes(SyntaxTree syntaxTree)
{
return GetMemberNodes(syntaxTree.GetRoot(), includeSelf: true, recursive: true, logicalFields: true, onlySupportedNodes: true);
}
protected IEnumerable<SyntaxNode> GetLogicalMemberNodes(SyntaxNode container)
{
return GetMemberNodes(container, includeSelf: false, recursive: false, logicalFields: true, onlySupportedNodes: false);
}
public IEnumerable<SyntaxNode> GetLogicalSupportedMemberNodes(SyntaxNode container)
{
return GetMemberNodes(container, includeSelf: false, recursive: false, logicalFields: true, onlySupportedNodes: true);
}
/// <summary>
/// Retrieves the members of a specified <paramref name="container"/> node. The members that are
/// returned can be controlled by passing various parameters.
/// </summary>
/// <param name="container">The <see cref="SyntaxNode"/> from which to retrieve members.</param>
/// <param name="includeSelf">If true, the container is returned as well.</param>
/// <param name="recursive">If true, members are recursed to return descendent members as well
/// as immediate children. For example, a namespace would return the namespaces and types within.
/// However, if <paramref name="recursive"/> is true, members with the namespaces and types would
/// also be returned.</param>
/// <param name="logicalFields">If true, field declarations are broken into their respective declarators.
/// For example, the field "int x, y" would return two declarators, one for x and one for y in place
/// of the field.</param>
/// <param name="onlySupportedNodes">If true, only members supported by Code Model are returned.</param>
public abstract IEnumerable<SyntaxNode> GetMemberNodes(SyntaxNode container, bool includeSelf, bool recursive, bool logicalFields, bool onlySupportedNodes);
public abstract string Language { get; }
public abstract string AssemblyAttributeString { get; }
public EnvDTE.CodeElement CreateExternalCodeElement(CodeModelState state, ProjectId projectId, ISymbol symbol)
{
switch (symbol.Kind)
{
case SymbolKind.Event:
return (EnvDTE.CodeElement)ExternalCodeEvent.Create(state, projectId, (IEventSymbol)symbol);
case SymbolKind.Field:
return (EnvDTE.CodeElement)ExternalCodeVariable.Create(state, projectId, (IFieldSymbol)symbol);
case SymbolKind.Method:
return (EnvDTE.CodeElement)ExternalCodeFunction.Create(state, projectId, (IMethodSymbol)symbol);
case SymbolKind.Namespace:
return (EnvDTE.CodeElement)ExternalCodeNamespace.Create(state, projectId, (INamespaceSymbol)symbol);
case SymbolKind.NamedType:
var namedType = (INamedTypeSymbol)symbol;
switch (namedType.TypeKind)
{
case TypeKind.Class:
case TypeKind.Module:
return (EnvDTE.CodeElement)ExternalCodeClass.Create(state, projectId, namedType);
case TypeKind.Delegate:
return (EnvDTE.CodeElement)ExternalCodeDelegate.Create(state, projectId, namedType);
case TypeKind.Enum:
return (EnvDTE.CodeElement)ExternalCodeEnum.Create(state, projectId, namedType);
case TypeKind.Interface:
return (EnvDTE.CodeElement)ExternalCodeInterface.Create(state, projectId, namedType);
case TypeKind.Struct:
return (EnvDTE.CodeElement)ExternalCodeStruct.Create(state, projectId, namedType);
default:
throw Exceptions.ThrowEFail();
}
case SymbolKind.Property:
return (EnvDTE.CodeElement)ExternalCodeProperty.Create(state, projectId, (IPropertySymbol)symbol);
default:
throw Exceptions.ThrowEFail();
}
}
/// <summary>
/// Do not use this method directly! Instead, go through <see cref="FileCodeModel.CreateCodeElement{T}(SyntaxNode)"/>
/// </summary>
public abstract EnvDTE.CodeElement CreateInternalCodeElement(
CodeModelState state,
FileCodeModel fileCodeModel,
SyntaxNode node);
public EnvDTE.CodeElement CreateCodeType(CodeModelState state, ProjectId projectId, ITypeSymbol typeSymbol)
{
if (typeSymbol.TypeKind == TypeKind.Pointer ||
typeSymbol.TypeKind == TypeKind.TypeParameter ||
typeSymbol.TypeKind == TypeKind.Submission)
{
throw Exceptions.ThrowEFail();
}
if (typeSymbol.TypeKind == TypeKind.Error ||
typeSymbol.TypeKind == TypeKind.Unknown)
{
return ExternalCodeUnknown.Create(state, projectId, typeSymbol);
}
var project = state.Workspace.CurrentSolution.GetProject(projectId);
if (project == null)
{
throw Exceptions.ThrowEFail();
}
if (typeSymbol.TypeKind == TypeKind.Dynamic)
{
var obj = project.GetCompilationAsync().Result.GetSpecialType(SpecialType.System_Object);
return (EnvDTE.CodeElement)ExternalCodeClass.Create(state, projectId, obj);
}
EnvDTE.CodeElement element;
if (TryGetElementFromSource(state, project, typeSymbol, out element))
{
return element;
}
EnvDTE.vsCMElement elementKind = GetElementKind(typeSymbol);
switch (elementKind)
{
case EnvDTE.vsCMElement.vsCMElementClass:
case EnvDTE.vsCMElement.vsCMElementModule:
return (EnvDTE.CodeElement)ExternalCodeClass.Create(state, projectId, typeSymbol);
case EnvDTE.vsCMElement.vsCMElementInterface:
return (EnvDTE.CodeElement)ExternalCodeInterface.Create(state, projectId, typeSymbol);
case EnvDTE.vsCMElement.vsCMElementDelegate:
return (EnvDTE.CodeElement)ExternalCodeDelegate.Create(state, projectId, typeSymbol);
case EnvDTE.vsCMElement.vsCMElementEnum:
return (EnvDTE.CodeElement)ExternalCodeEnum.Create(state, projectId, typeSymbol);
case EnvDTE.vsCMElement.vsCMElementStruct:
return (EnvDTE.CodeElement)ExternalCodeStruct.Create(state, projectId, typeSymbol);
default:
Debug.Fail("Unsupported element kind: " + elementKind);
throw Exceptions.ThrowEInvalidArg();
}
}
public abstract EnvDTE.CodeTypeRef CreateCodeTypeRef(CodeModelState state, ProjectId projectId, object type);
public abstract EnvDTE.vsCMTypeRef GetTypeKindForCodeTypeRef(ITypeSymbol typeSymbol);
public abstract string GetAsFullNameForCodeTypeRef(ITypeSymbol typeSymbol);
public abstract string GetAsStringForCodeTypeRef(ITypeSymbol typeSymbol);
public abstract bool IsParameterNode(SyntaxNode node);
public abstract bool IsAttributeNode(SyntaxNode node);
public abstract bool IsAttributeArgumentNode(SyntaxNode node);
public abstract bool IsOptionNode(SyntaxNode node);
public abstract bool IsImportNode(SyntaxNode node);
public ISymbol ResolveSymbol(Workspace workspace, ProjectId projectId, SymbolKey symbolId)
{
var project = workspace.CurrentSolution.GetProject(projectId);
if (project == null)
{
throw Exceptions.ThrowEFail();
}
return symbolId.Resolve(project.GetCompilationAsync().Result).Symbol;
}
protected EnvDTE.CodeFunction CreateInternalCodeAccessorFunction(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node)
{
SyntaxNode parentNode = node
.Ancestors()
.FirstOrDefault(n => TryGetNodeKey(n) != SyntaxNodeKey.Empty);
if (parentNode == null)
{
throw new InvalidOperationException();
}
var parent = fileCodeModel.CreateCodeElement<EnvDTE.CodeElement>(parentNode);
var parentObj = ComAggregate.GetManagedObject<AbstractCodeMember>(parent);
var accessorKind = GetAccessorKind(node);
return CodeAccessorFunction.Create(state, parentObj, accessorKind);
}
protected EnvDTE.CodeAttribute CreateInternalCodeAttribute(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node)
{
var parentNode = GetEffectiveParentForAttribute(node);
AbstractCodeElement parentObject;
if (IsParameterNode(parentNode))
{
var parentElement = fileCodeModel.CreateCodeElement<EnvDTE.CodeElement>(parentNode);
parentObject = ComAggregate.GetManagedObject<AbstractCodeElement>(parentElement);
}
else
{
var nodeKey = parentNode.AncestorsAndSelf()
.Select(n => TryGetNodeKey(n))
.FirstOrDefault(nk => nk != SyntaxNodeKey.Empty);
if (nodeKey == SyntaxNodeKey.Empty)
{
// This is an assembly-level attribute.
parentNode = fileCodeModel.GetSyntaxRoot();
parentObject = null;
}
else
{
parentNode = fileCodeModel.LookupNode(nodeKey);
var parentElement = fileCodeModel.CreateCodeElement<EnvDTE.CodeElement>(parentNode);
parentObject = ComAggregate.GetManagedObject<AbstractCodeElement>(parentElement);
}
}
string name;
int ordinal;
GetAttributeNameAndOrdinal(parentNode, node, out name, out ordinal);
return CodeAttribute.Create(state, fileCodeModel, parentObject, name, ordinal);
}
protected EnvDTE80.CodeImport CreateInternalCodeImport(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node)
{
SyntaxNode parentNode;
string name;
GetImportParentAndName(node, out parentNode, out name);
AbstractCodeElement parentObj = null;
if (parentNode != null)
{
var parent = fileCodeModel.CreateCodeElement<EnvDTE.CodeElement>(parentNode);
parentObj = ComAggregate.GetManagedObject<AbstractCodeElement>(parent);
}
return CodeImport.Create(state, fileCodeModel, parentObj, name);
}
protected EnvDTE.CodeParameter CreateInternalCodeParameter(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node)
{
SyntaxNode parentNode = node
.Ancestors()
.FirstOrDefault(n => TryGetNodeKey(n) != SyntaxNodeKey.Empty);
if (parentNode == null)
{
throw new InvalidOperationException();
}
string name = GetParameterName(node);
var parent = fileCodeModel.CreateCodeElement<EnvDTE.CodeElement>(parentNode);
var parentObj = ComAggregate.GetManagedObject<AbstractCodeMember>(parent);
return CodeParameter.Create(state, parentObj, name);
}
protected EnvDTE80.CodeElement2 CreateInternalCodeOptionStatement(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node)
{
string name;
int ordinal;
GetOptionNameAndOrdinal(node.Parent, node, out name, out ordinal);
return CodeOptionsStatement.Create(state, fileCodeModel, name, ordinal);
}
protected EnvDTE80.CodeElement2 CreateInternalCodeInheritsStatement(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node)
{
SyntaxNode parentNode = node
.Ancestors()
.FirstOrDefault(n => TryGetNodeKey(n) != SyntaxNodeKey.Empty);
if (parentNode == null)
{
throw new InvalidOperationException();
}
string namespaceName;
int ordinal;
GetInheritsNamespaceAndOrdinal(parentNode, node, out namespaceName, out ordinal);
var parent = fileCodeModel.CreateCodeElement<EnvDTE.CodeElement>(parentNode);
var parentObj = ComAggregate.GetManagedObject<AbstractCodeMember>(parent);
return CodeInheritsStatement.Create(state, parentObj, namespaceName, ordinal);
}
protected EnvDTE80.CodeElement2 CreateInternalCodeImplementsStatement(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node)
{
SyntaxNode parentNode = node
.Ancestors()
.FirstOrDefault(n => TryGetNodeKey(n) != SyntaxNodeKey.Empty);
if (parentNode == null)
{
throw new InvalidOperationException();
}
string namespaceName;
int ordinal;
GetImplementsNamespaceAndOrdinal(parentNode, node, out namespaceName, out ordinal);
var parent = fileCodeModel.CreateCodeElement<EnvDTE.CodeElement>(parentNode);
var parentObj = ComAggregate.GetManagedObject<AbstractCodeMember>(parent);
return CodeImplementsStatement.Create(state, parentObj, namespaceName, ordinal);
}
protected EnvDTE80.CodeAttributeArgument CreateInternalCodeAttributeArgument(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node)
{
SyntaxNode attributeNode;
int index;
GetAttributeArgumentParentAndIndex(node, out attributeNode, out index);
var codeAttribute = CreateInternalCodeAttribute(state, fileCodeModel, attributeNode);
var codeAttributeObj = ComAggregate.GetManagedObject<CodeAttribute>(codeAttribute);
return CodeAttributeArgument.Create(state, codeAttributeObj, index);
}
public abstract EnvDTE.CodeElement CreateUnknownCodeElement(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node);
public abstract EnvDTE.CodeElement CreateUnknownRootNamespaceCodeElement(CodeModelState state, FileCodeModel fileCodeModel);
public abstract string GetUnescapedName(string name);
public abstract string GetName(SyntaxNode node);
public abstract SyntaxNode GetNodeWithName(SyntaxNode node);
public abstract SyntaxNode SetName(SyntaxNode node, string name);
public abstract string GetFullName(SyntaxNode node, SemanticModel semanticModel);
public abstract string GetFullName(ISymbol symbol);
public abstract string GetFullyQualifiedName(string name, int position, SemanticModel semanticModel);
public void Rename(ISymbol symbol, string newName, Solution solution)
{
// TODO: (tomescht) make this testable through unit tests.
// Right now we have to go through the project system to find all
// the outstanding CodeElements which might be affected by the
// rename. This is silly. This functionality should be moved down
// into the service layer.
var workspace = solution.Workspace as VisualStudioWorkspaceImpl;
if (workspace == null)
{
throw Exceptions.ThrowEFail();
}
// Save the node keys.
var nodeKeyValidation = new NodeKeyValidation();
foreach (var project in workspace.ProjectTracker.Projects)
{
nodeKeyValidation.AddProject(project);
}
var optionSet = workspace.Services.GetService<IOptionService>().GetOptions();
// Rename symbol.
var newSolution = Renamer.RenameSymbolAsync(solution, symbol, newName, optionSet).WaitAndGetResult(CancellationToken.None);
var changedDocuments = newSolution.GetChangedDocuments(solution);
// Notify third parties of the coming rename operation and let exceptions propagate out
_refactorNotifyServices.TryOnBeforeGlobalSymbolRenamed(workspace, changedDocuments, symbol, newName, throwOnFailure: true);
// Update the workspace.
if (!workspace.TryApplyChanges(newSolution))
{
throw Exceptions.ThrowEFail();
}
// Notify third parties of the completed rename operation and let exceptions propagate out
_refactorNotifyServices.TryOnAfterGlobalSymbolRenamed(workspace, changedDocuments, symbol, newName, throwOnFailure: true);
RenameTrackingDismisser.DismissRenameTracking(workspace, changedDocuments);
// Update the node keys.
nodeKeyValidation.RestoreKeys();
}
public VirtualTreePoint? GetStartPoint(SyntaxNode node, EnvDTE.vsCMPart? part)
{
return _nodeLocator.GetStartPoint(node, part);
}
public VirtualTreePoint? GetEndPoint(SyntaxNode node, EnvDTE.vsCMPart? part)
{
return _nodeLocator.GetEndPoint(node, part);
}
public abstract EnvDTE.vsCMAccess GetAccess(ISymbol symbol);
public abstract EnvDTE.vsCMAccess GetAccess(SyntaxNode node);
public abstract SyntaxNode GetNodeWithModifiers(SyntaxNode node);
public abstract SyntaxNode GetNodeWithType(SyntaxNode node);
public abstract SyntaxNode GetNodeWithInitializer(SyntaxNode node);
public abstract SyntaxNode SetAccess(SyntaxNode node, EnvDTE.vsCMAccess access);
public abstract EnvDTE.vsCMElement GetElementKind(SyntaxNode node);
protected EnvDTE.vsCMElement GetElementKind(ITypeSymbol typeSymbol)
{
switch (typeSymbol.TypeKind)
{
case TypeKind.Array:
case TypeKind.Class:
return EnvDTE.vsCMElement.vsCMElementClass;
case TypeKind.Interface:
return EnvDTE.vsCMElement.vsCMElementInterface;
case TypeKind.Struct:
return EnvDTE.vsCMElement.vsCMElementStruct;
case TypeKind.Enum:
return EnvDTE.vsCMElement.vsCMElementEnum;
case TypeKind.Delegate:
return EnvDTE.vsCMElement.vsCMElementDelegate;
case TypeKind.Module:
return EnvDTE.vsCMElement.vsCMElementModule;
default:
Debug.Fail("Unexpected TypeKind: " + typeSymbol.TypeKind);
throw Exceptions.ThrowEInvalidArg();
}
}
protected bool TryGetElementFromSource(CodeModelState state, Project project, ITypeSymbol typeSymbol, out EnvDTE.CodeElement element)
{
element = null;
if (!typeSymbol.IsDefinition)
{
return false;
}
// Here's the strategy for determine what source file we'd try to return an element from.
// 1. Prefer source files that we don't heuristically flag as generated code.
// 2. If all of the source files are generated code, pick the first one.
var generatedCodeRecognitionService = project.Solution.Workspace.Services.GetService<IGeneratedCodeRecognitionService>();
Compilation compilation = null;
Tuple<DocumentId, Location> generatedCode = null;
DocumentId chosenDocumentId = null;
Location chosenLocation = null;
foreach (var location in typeSymbol.Locations)
{
if (location.IsInSource)
{
compilation = compilation ?? project.GetCompilationAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None);
if (compilation.ContainsSyntaxTree(location.SourceTree))
{
var document = project.GetDocument(location.SourceTree);
if (generatedCodeRecognitionService?.IsGeneratedCode(document) == false)
{
chosenLocation = location;
chosenDocumentId = document.Id;
break;
}
else
{
generatedCode = generatedCode ?? Tuple.Create(document.Id, location);
}
}
}
}
if (chosenDocumentId == null && generatedCode != null)
{
chosenDocumentId = generatedCode.Item1;
chosenLocation = generatedCode.Item2;
}
if (chosenDocumentId != null)
{
var fileCodeModel = state.Workspace.GetFileCodeModel(chosenDocumentId);
if (fileCodeModel != null)
{
var underlyingFileCodeModel = ComAggregate.GetManagedObject<FileCodeModel>(fileCodeModel);
element = underlyingFileCodeModel.CodeElementFromPosition(chosenLocation.SourceSpan.Start, GetElementKind(typeSymbol));
return element != null;
}
}
return false;
}
public abstract bool IsAccessorNode(SyntaxNode node);
public abstract MethodKind GetAccessorKind(SyntaxNode node);
public abstract bool TryGetAccessorNode(SyntaxNode parentNode, MethodKind kind, out SyntaxNode accessorNode);
public abstract bool TryGetParameterNode(SyntaxNode parentNode, string name, out SyntaxNode parameterNode);
public abstract bool TryGetImportNode(SyntaxNode parentNode, string dottedName, out SyntaxNode importNode);
public abstract bool TryGetOptionNode(SyntaxNode parentNode, string name, int ordinal, out SyntaxNode optionNode);
public abstract bool TryGetInheritsNode(SyntaxNode parentNode, string name, int ordinal, out SyntaxNode inheritsNode);
public abstract bool TryGetImplementsNode(SyntaxNode parentNode, string name, int ordinal, out SyntaxNode implementsNode);
public abstract bool TryGetAttributeNode(SyntaxNode parentNode, string name, int ordinal, out SyntaxNode attributeNode);
public abstract bool TryGetAttributeArgumentNode(SyntaxNode attributeNode, int index, out SyntaxNode attributeArgumentNode);
public abstract void GetOptionNameAndOrdinal(SyntaxNode parentNode, SyntaxNode optionNode, out string name, out int ordinal);
public abstract void GetInheritsNamespaceAndOrdinal(SyntaxNode inheritsNode, SyntaxNode optionNode, out string namespaceName, out int ordinal);
public abstract void GetImplementsNamespaceAndOrdinal(SyntaxNode implementsNode, SyntaxNode optionNode, out string namespaceName, out int ordinal);
public abstract void GetAttributeNameAndOrdinal(SyntaxNode parentNode, SyntaxNode attributeNode, out string name, out int ordinal);
public abstract SyntaxNode GetAttributeTargetNode(SyntaxNode attributeNode);
public abstract string GetAttributeTarget(SyntaxNode attributeNode);
public abstract string GetAttributeValue(SyntaxNode attributeNode);
public abstract SyntaxNode SetAttributeTarget(SyntaxNode attributeNode, string value);
public abstract SyntaxNode SetAttributeValue(SyntaxNode attributeNode, string value);
public abstract SyntaxNode GetNodeWithAttributes(SyntaxNode node);
public abstract SyntaxNode GetEffectiveParentForAttribute(SyntaxNode node);
public abstract SyntaxNode CreateAttributeNode(string name, string value, string target = null);
public abstract void GetAttributeArgumentParentAndIndex(SyntaxNode attributeArgumentNode, out SyntaxNode attributeNode, out int index);
public abstract SyntaxNode CreateAttributeArgumentNode(string name, string value);
public abstract string GetAttributeArgumentValue(SyntaxNode attributeArgumentNode);
public abstract string GetImportAlias(SyntaxNode node);
public abstract string GetImportNamespaceOrType(SyntaxNode node);
public abstract void GetImportParentAndName(SyntaxNode importNode, out SyntaxNode namespaceNode, out string name);
public abstract SyntaxNode CreateImportNode(string name, string alias = null);
public abstract string GetParameterName(SyntaxNode node);
public virtual string GetParameterFullName(SyntaxNode node)
{
return GetParameterName(node);
}
public abstract EnvDTE80.vsCMParameterKind GetParameterKind(SyntaxNode node);
public abstract SyntaxNode SetParameterKind(SyntaxNode node, EnvDTE80.vsCMParameterKind kind);
public abstract SyntaxNode CreateParameterNode(string name, string type);
public abstract EnvDTE.vsCMFunction ValidateFunctionKind(SyntaxNode containerNode, EnvDTE.vsCMFunction kind, string name);
public abstract bool SupportsEventThrower { get; }
public abstract bool GetCanOverride(SyntaxNode memberNode);
public abstract SyntaxNode SetCanOverride(SyntaxNode memberNode, bool value);
public abstract EnvDTE80.vsCMClassKind GetClassKind(SyntaxNode typeNode, INamedTypeSymbol typeSymbol);
public abstract SyntaxNode SetClassKind(SyntaxNode typeNode, EnvDTE80.vsCMClassKind kind);
public abstract string GetComment(SyntaxNode node);
public abstract SyntaxNode SetComment(SyntaxNode node, string value);
public abstract EnvDTE80.vsCMConstKind GetConstKind(SyntaxNode variableNode);
public abstract SyntaxNode SetConstKind(SyntaxNode variableNode, EnvDTE80.vsCMConstKind kind);
public abstract EnvDTE80.vsCMDataTypeKind GetDataTypeKind(SyntaxNode typeNode, INamedTypeSymbol symbol);
public abstract SyntaxNode SetDataTypeKind(SyntaxNode typeNode, EnvDTE80.vsCMDataTypeKind kind);
public abstract string GetDocComment(SyntaxNode node);
public abstract SyntaxNode SetDocComment(SyntaxNode node, string value);
public abstract EnvDTE.vsCMFunction GetFunctionKind(IMethodSymbol symbol);
public abstract EnvDTE80.vsCMInheritanceKind GetInheritanceKind(SyntaxNode typeNode, INamedTypeSymbol typeSymbol);
public abstract SyntaxNode SetInheritanceKind(SyntaxNode typeNode, EnvDTE80.vsCMInheritanceKind kind);
public abstract bool GetIsAbstract(SyntaxNode memberNode, ISymbol symbol);
public abstract SyntaxNode SetIsAbstract(SyntaxNode memberNode, bool value);
public abstract bool GetIsConstant(SyntaxNode variableNode);
public abstract SyntaxNode SetIsConstant(SyntaxNode variableNode, bool value);
public abstract bool GetIsDefault(SyntaxNode propertyNode);
public abstract SyntaxNode SetIsDefault(SyntaxNode propertyNode, bool value);
public abstract bool GetIsGeneric(SyntaxNode memberNode);
public abstract bool GetIsPropertyStyleEvent(SyntaxNode eventNode);
public abstract bool GetIsShared(SyntaxNode memberNode, ISymbol symbol);
public abstract SyntaxNode SetIsShared(SyntaxNode memberNode, bool value);
public abstract bool GetMustImplement(SyntaxNode memberNode);
public abstract SyntaxNode SetMustImplement(SyntaxNode memberNode, bool value);
public abstract EnvDTE80.vsCMOverrideKind GetOverrideKind(SyntaxNode memberNode);
public abstract SyntaxNode SetOverrideKind(SyntaxNode memberNode, EnvDTE80.vsCMOverrideKind kind);
public abstract EnvDTE80.vsCMPropertyKind GetReadWrite(SyntaxNode memberNode);
public abstract SyntaxNode SetType(SyntaxNode node, ITypeSymbol typeSymbol);
public abstract Document Delete(Document document, SyntaxNode node);
public abstract string GetMethodXml(SyntaxNode node, SemanticModel semanticModel);
public abstract string GetInitExpression(SyntaxNode node);
public abstract SyntaxNode AddInitExpression(SyntaxNode node, string value);
public abstract CodeGenerationDestination GetDestination(SyntaxNode containerNode);
protected abstract Accessibility GetDefaultAccessibility(SymbolKind targetSymbolKind, CodeGenerationDestination destination);
public Accessibility GetAccessibility(EnvDTE.vsCMAccess access, SymbolKind targetSymbolKind, CodeGenerationDestination destination = CodeGenerationDestination.Unspecified)
{
// Note: Some EnvDTE.vsCMAccess members aren't "bitwise-mutually-exclusive"
// Specifically, vsCMAccessProjectOrProtected (12) is a combination of vsCMAccessProject (4) and vsCMAccessProtected (8)
// We therefore check for this first.
if ((access & EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected) == EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected)
{
return Accessibility.ProtectedOrInternal;
}
else if ((access & EnvDTE.vsCMAccess.vsCMAccessPrivate) != 0)
{
return Accessibility.Private;
}
else if ((access & EnvDTE.vsCMAccess.vsCMAccessProject) != 0)
{
return Accessibility.Internal;
}
else if ((access & EnvDTE.vsCMAccess.vsCMAccessProtected) != 0)
{
return Accessibility.Protected;
}
else if ((access & EnvDTE.vsCMAccess.vsCMAccessPublic) != 0)
{
return Accessibility.Public;
}
else if ((access & EnvDTE.vsCMAccess.vsCMAccessDefault) != 0)
{
return GetDefaultAccessibility(targetSymbolKind, destination);
}
else
{
throw new ArgumentException(ServicesVSResources.InvalidAccess, "access");
}
}
public bool GetWithEvents(EnvDTE.vsCMAccess access)
{
return (access & EnvDTE.vsCMAccess.vsCMAccessWithEvents) != 0;
}
protected SpecialType GetSpecialType(EnvDTE.vsCMTypeRef type)
{
// TODO(DustinCa): Verify this list against VB
switch (type)
{
case EnvDTE.vsCMTypeRef.vsCMTypeRefBool:
return SpecialType.System_Boolean;
case EnvDTE.vsCMTypeRef.vsCMTypeRefByte:
return SpecialType.System_Byte;
case EnvDTE.vsCMTypeRef.vsCMTypeRefChar:
return SpecialType.System_Char;
case EnvDTE.vsCMTypeRef.vsCMTypeRefDecimal:
return SpecialType.System_Decimal;
case EnvDTE.vsCMTypeRef.vsCMTypeRefDouble:
return SpecialType.System_Double;
case EnvDTE.vsCMTypeRef.vsCMTypeRefFloat:
return SpecialType.System_Single;
case EnvDTE.vsCMTypeRef.vsCMTypeRefInt:
return SpecialType.System_Int32;
case EnvDTE.vsCMTypeRef.vsCMTypeRefLong:
return SpecialType.System_Int64;
case EnvDTE.vsCMTypeRef.vsCMTypeRefObject:
return SpecialType.System_Object;
case EnvDTE.vsCMTypeRef.vsCMTypeRefShort:
return SpecialType.System_Int16;
case EnvDTE.vsCMTypeRef.vsCMTypeRefString:
return SpecialType.System_String;
case EnvDTE.vsCMTypeRef.vsCMTypeRefVoid:
return SpecialType.System_Void;
default:
// TODO: Support vsCMTypeRef2? It doesn't appear that Dev10 C# does...
throw new ArgumentException();
}
}
private ITypeSymbol GetSpecialType(EnvDTE.vsCMTypeRef type, Compilation compilation)
{
return compilation.GetSpecialType(GetSpecialType(type));
}
protected abstract ITypeSymbol GetTypeSymbolFromPartialName(string partialName, SemanticModel semanticModel, int position);
public abstract ITypeSymbol GetTypeSymbolFromFullName(string fullName, Compilation compilation);
public ITypeSymbol GetTypeSymbol(object type, SemanticModel semanticModel, int position)
{
if (type is EnvDTE.CodeTypeRef)
{
return GetTypeSymbolFromPartialName(((EnvDTE.CodeTypeRef)type).AsString, semanticModel, position);
}
else if (type is EnvDTE.CodeType)
{
return GetTypeSymbolFromFullName(((EnvDTE.CodeType)type).FullName, semanticModel.Compilation);
}
ITypeSymbol typeSymbol;
if (type is EnvDTE.vsCMTypeRef || type is int)
{
typeSymbol = GetSpecialType((EnvDTE.vsCMTypeRef)type, semanticModel.Compilation);
}
else if (type is string)
{
typeSymbol = GetTypeSymbolFromPartialName((string)type, semanticModel, position);
}
else
{
throw new InvalidOperationException();
}
if (typeSymbol == null)
{
throw new ArgumentException();
}
return typeSymbol;
}
public abstract SyntaxNode CreateReturnDefaultValueStatement(ITypeSymbol type);
protected abstract int GetAttributeIndexInContainer(
SyntaxNode containerNode,
Func<SyntaxNode, bool> predicate);
/// <summary>
/// The position argument is a VARIANT which may be an EnvDTE.CodeElement, an int or a string
/// representing the name of a member. This function translates the argument and returns the
/// 1-based position of the specified attribute.
/// </summary>
public int PositionVariantToAttributeInsertionIndex(object position, SyntaxNode containerNode, FileCodeModel fileCodeModel)
{
return PositionVariantToInsertionIndex(
position,
containerNode,
fileCodeModel,
GetAttributeIndexInContainer,
GetAttributeNodes);
}
protected abstract int GetAttributeArgumentIndexInContainer(
SyntaxNode containerNode,
Func<SyntaxNode, bool> predicate);
public int PositionVariantToAttributeArgumentInsertionIndex(object position, SyntaxNode containerNode, FileCodeModel fileCodeModel)
{
return PositionVariantToInsertionIndex(
position,
containerNode,
fileCodeModel,
GetAttributeArgumentIndexInContainer,
GetAttributeArgumentNodes);
}
protected abstract int GetImportIndexInContainer(
SyntaxNode containerNode,
Func<SyntaxNode, bool> predicate);
public int PositionVariantToImportInsertionIndex(object position, SyntaxNode containerNode, FileCodeModel fileCodeModel)
{
return PositionVariantToInsertionIndex(
position,
containerNode,
fileCodeModel,
GetImportIndexInContainer,
GetImportNodes);
}
protected abstract int GetParameterIndexInContainer(
SyntaxNode containerNode,
Func<SyntaxNode, bool> predicate);
public int PositionVariantToParameterInsertionIndex(object position, SyntaxNode containerNode, FileCodeModel fileCodeModel)
{
return PositionVariantToInsertionIndex(
position,
containerNode,
fileCodeModel,
GetParameterIndexInContainer,
GetParameterNodes);
}
/// <summary>
/// Finds the index of the first child within the container for which <paramref name="predicate"/> returns true.
/// Note that the result is a 1-based as that is what code model expects. Returns -1 if no match is found.
/// </summary>
protected abstract int GetMemberIndexInContainer(
SyntaxNode containerNode,
Func<SyntaxNode, bool> predicate);
/// <summary>
/// The position argument is a VARIANT which may be an EnvDTE.CodeElement, an int or a string
/// representing the name of a member. This function translates the argument and returns the
/// 1-based position of the specified member.
/// </summary>
public int PositionVariantToMemberInsertionIndex(object position, SyntaxNode containerNode, FileCodeModel fileCodeModel)
{
return PositionVariantToInsertionIndex(
position,
containerNode,
fileCodeModel,
GetMemberIndexInContainer,
n => GetMemberNodes(n, includeSelf: false, recursive: false, logicalFields: false, onlySupportedNodes: false));
}
private int PositionVariantToInsertionIndex(
object position,
SyntaxNode containerNode,
FileCodeModel fileCodeModel,
Func<SyntaxNode, Func<SyntaxNode, bool>, int> getIndexInContainer,
Func<SyntaxNode, IEnumerable<SyntaxNode>> getChildNodes)
{
int result;
if (position is int)
{
result = (int)position;
}
else if (position is EnvDTE.CodeElement)
{
var codeElement = ComAggregate.TryGetManagedObject<AbstractCodeElement>(position);
if (codeElement == null || codeElement.FileCodeModel != fileCodeModel)
{
throw Exceptions.ThrowEInvalidArg();
}
var positionNode = codeElement.LookupNode();
if (positionNode == null)
{
throw Exceptions.ThrowEFail();
}
result = getIndexInContainer(containerNode, child => child == positionNode);
}
else if (position is string)
{
var name = (string)position;
result = getIndexInContainer(containerNode, child => GetName(child) == name);
}
else if (position == null || position == Type.Missing)
{
result = 0;
}
else
{
// Nothing we can handle...
throw Exceptions.ThrowEInvalidArg();
}
// -1 means to insert at the end, so we'll return the last child.
return result == -1
? getChildNodes(containerNode).ToArray().Length
: result;
}
protected abstract SyntaxNode GetFieldFromVariableNode(SyntaxNode variableNode);
protected abstract SyntaxNode GetVariableFromFieldNode(SyntaxNode fieldNode);
protected abstract SyntaxNode GetAttributeFromAttributeDeclarationNode(SyntaxNode attributeDeclarationNode);
protected void GetNodesAroundInsertionIndex<TSyntaxNode>(
TSyntaxNode containerNode,
int childIndexToInsertAfter,
out TSyntaxNode insertBeforeNode,
out TSyntaxNode insertAfterNode)
where TSyntaxNode : SyntaxNode
{
var childNodes = GetLogicalMemberNodes(containerNode).ToArray();
// Note: childIndexToInsertAfter is 1-based but can be 0, meaning insert before any other members.
// If it isn't 0, it means to insert the member node *after* the node at the 1-based index.
Debug.Assert(childIndexToInsertAfter >= 0 && childIndexToInsertAfter <= childNodes.Length);
// Initialize the nodes that we'll insert the new member before and after.
insertBeforeNode = null;
insertAfterNode = null;
if (childIndexToInsertAfter == 0)
{
if (childNodes.Length > 0)
{
insertBeforeNode = (TSyntaxNode)childNodes[0];
}
}
else
{
insertAfterNode = (TSyntaxNode)childNodes[childIndexToInsertAfter - 1];
if (childIndexToInsertAfter < childNodes.Length)
{
insertBeforeNode = (TSyntaxNode)childNodes[childIndexToInsertAfter];
}
}
if (insertBeforeNode != null)
{
insertBeforeNode = (TSyntaxNode)GetFieldFromVariableNode(insertBeforeNode);
}
if (insertAfterNode != null)
{
insertAfterNode = (TSyntaxNode)GetFieldFromVariableNode(insertAfterNode);
}
}
private int GetMemberInsertionIndex(SyntaxNode container, int insertionIndex)
{
var childNodes = GetLogicalMemberNodes(container).ToArray();
// Note: childIndexToInsertAfter is 1-based but can be 0, meaning insert before any other members.
// If it isn't 0, it means to insert the member node *after* the node at the 1-based index.
Debug.Assert(insertionIndex >= 0 && insertionIndex <= childNodes.Length);
if (insertionIndex == 0)
{
return 0;
}
else
{
var nodeAtIndex = GetFieldFromVariableNode(childNodes[insertionIndex - 1]);
return GetMemberNodes(container, includeSelf: false, recursive: false, logicalFields: false, onlySupportedNodes: false).ToList().IndexOf(nodeAtIndex) + 1;
}
}
private int GetAttributeArgumentInsertionIndex(SyntaxNode container, int insertionIndex)
{
return insertionIndex;
}
private int GetAttributeInsertionIndex(SyntaxNode container, int insertionIndex)
{
return insertionIndex;
}
private int GetImportInsertionIndex(SyntaxNode container, int insertionIndex)
{
return insertionIndex;
}
private int GetParameterInsertionIndex(SyntaxNode container, int insertionIndex)
{
return insertionIndex;
}
protected abstract bool IsCodeModelNode(SyntaxNode node);
protected abstract TextSpan GetSpanToFormat(SyntaxNode root, TextSpan span);
protected abstract SyntaxNode InsertMemberNodeIntoContainer(int index, SyntaxNode member, SyntaxNode container);
protected abstract SyntaxNode InsertAttributeArgumentIntoContainer(int index, SyntaxNode attributeArgument, SyntaxNode container);
protected abstract SyntaxNode InsertAttributeListIntoContainer(int index, SyntaxNode attribute, SyntaxNode container);
protected abstract SyntaxNode InsertImportIntoContainer(int index, SyntaxNode import, SyntaxNode container);
protected abstract SyntaxNode InsertParameterIntoContainer(int index, SyntaxNode parameter, SyntaxNode container);
private Document FormatAnnotatedNode(Document document, SyntaxAnnotation annotation, IEnumerable<IFormattingRule> additionalRules, CancellationToken cancellationToken)
{
var root = document.GetSyntaxRootAsync(cancellationToken).WaitAndGetResult(cancellationToken);
var annotatedNode = root.GetAnnotatedNodesAndTokens(annotation).Single().AsNode();
var formattingSpan = GetSpanToFormat(root, annotatedNode.FullSpan);
var formattingRules = Formatter.GetDefaultFormattingRules(document);
if (additionalRules != null)
{
formattingRules = additionalRules.Concat(formattingRules);
}
return Formatter.FormatAsync(
document,
new TextSpan[] { formattingSpan },
options: null,
rules: formattingRules,
cancellationToken: cancellationToken).WaitAndGetResult(cancellationToken);
}
private SyntaxNode InsertNode(
Document document,
bool batchMode,
int insertionIndex,
SyntaxNode containerNode,
SyntaxNode node,
Func<int, SyntaxNode, SyntaxNode, SyntaxNode> insertNodeIntoContainer,
CancellationToken cancellationToken,
out Document newDocument)
{
var root = document.GetSyntaxRootAsync(cancellationToken).WaitAndGetResult(cancellationToken);
// Annotate the member we're inserting so we can get back to it.
var annotation = new SyntaxAnnotation();
var gen = SyntaxGenerator.GetGenerator(document);
node = node.WithAdditionalAnnotations(annotation);
if (gen.GetDeclarationKind(node) != DeclarationKind.NamespaceImport)
{
// REVIEW: how simplifier ever worked for code model? nobody added simplifier.Annotation before?
node = node.WithAdditionalAnnotations(Simplifier.Annotation);
}
var newContainerNode = insertNodeIntoContainer(insertionIndex, node, containerNode);
var newRoot = root.ReplaceNode(containerNode, newContainerNode);
document = document.WithSyntaxRoot(newRoot);
if (!batchMode)
{
document = Simplifier.ReduceAsync(document, annotation, optionSet: null, cancellationToken: cancellationToken).WaitAndGetResult(cancellationToken);
}
document = FormatAnnotatedNode(document, annotation, new[] { _lineAdjustmentFormattingRule, _endRegionFormattingRule }, cancellationToken);
// out param
newDocument = document;
// new node
return document
.GetSyntaxRootAsync(cancellationToken).WaitAndGetResult(cancellationToken)
.GetAnnotatedNodesAndTokens(annotation)
.Single()
.AsNode();
}
/// <summary>
/// Override to determine whether <param name="newNode"/> adds a method body to <param name="node"/>.
/// This is used to determine whether a blank line should be added inside the body when formatting.
/// </summary>
protected abstract bool AddBlankLineToMethodBody(SyntaxNode node, SyntaxNode newNode);
public Document UpdateNode(
Document document,
SyntaxNode node,
SyntaxNode newNode,
CancellationToken cancellationToken)
{
// Annotate the member we're inserting so we can get back to it.
var annotation = new SyntaxAnnotation();
// REVIEW: how simplifier ever worked for code model? nobody added simplifier.Annotation before?
var annotatedNode = newNode.WithAdditionalAnnotations(annotation, Simplifier.Annotation);
var oldRoot = document.GetSyntaxRootAsync(cancellationToken).WaitAndGetResult(cancellationToken);
var newRoot = oldRoot.ReplaceNode(node, annotatedNode);
document = document.WithSyntaxRoot(newRoot);
var additionalRules = AddBlankLineToMethodBody(node, newNode)
? SpecializedCollections.SingletonEnumerable(_lineAdjustmentFormattingRule)
: null;
document = FormatAnnotatedNode(document, annotation, additionalRules, cancellationToken);
return document;
}
public SyntaxNode InsertAttribute(
Document document,
bool batchMode,
int insertionIndex,
SyntaxNode containerNode,
SyntaxNode attributeNode,
CancellationToken cancellationToken,
out Document newDocument)
{
var finalNode = InsertNode(
document,
batchMode,
GetAttributeInsertionIndex(containerNode, insertionIndex),
containerNode,
attributeNode,
InsertAttributeListIntoContainer,
cancellationToken,
out newDocument);
return GetAttributeFromAttributeDeclarationNode(finalNode);
}
public SyntaxNode InsertAttributeArgument(
Document document,
bool batchMode,
int insertionIndex,
SyntaxNode containerNode,
SyntaxNode attributeArgumentNode,
CancellationToken cancellationToken,
out Document newDocument)
{
var finalNode = InsertNode(
document,
batchMode,
GetAttributeArgumentInsertionIndex(containerNode, insertionIndex),
containerNode,
attributeArgumentNode,
InsertAttributeArgumentIntoContainer,
cancellationToken,
out newDocument);
return finalNode;
}
public SyntaxNode InsertImport(
Document document,
bool batchMode,
int insertionIndex,
SyntaxNode containerNode,
SyntaxNode importNode,
CancellationToken cancellationToken,
out Document newDocument)
{
var finalNode = InsertNode(
document,
batchMode,
GetImportInsertionIndex(containerNode, insertionIndex),
containerNode,
importNode,
InsertImportIntoContainer,
cancellationToken,
out newDocument);
return finalNode;
}
public SyntaxNode InsertParameter(
Document document,
bool batchMode,
int insertionIndex,
SyntaxNode containerNode,
SyntaxNode parameterNode,
CancellationToken cancellationToken,
out Document newDocument)
{
var finalNode = InsertNode(
document,
batchMode,
GetParameterInsertionIndex(containerNode, insertionIndex),
containerNode,
parameterNode,
InsertParameterIntoContainer,
cancellationToken,
out newDocument);
return finalNode;
}
public SyntaxNode InsertMember(
Document document,
bool batchMode,
int insertionIndex,
SyntaxNode containerNode,
SyntaxNode memberNode,
CancellationToken cancellationToken,
out Document newDocument)
{
var finalNode = InsertNode(
document,
batchMode,
GetMemberInsertionIndex(containerNode, insertionIndex),
containerNode,
memberNode,
InsertMemberNodeIntoContainer,
cancellationToken,
out newDocument);
return GetVariableFromFieldNode(finalNode);
}
public Queue<CodeModelEvent> CollectCodeModelEvents(SyntaxTree oldTree, SyntaxTree newTree)
{
return _eventCollector.Collect(oldTree, newTree);
}
public abstract bool IsNamespace(SyntaxNode node);
public abstract bool IsType(SyntaxNode node);
public virtual IList<string> GetHandledEventNames(SyntaxNode method, SemanticModel semanticModel)
{
// descendents may override (particularly VB).
return SpecializedCollections.EmptyList<string>();
}
public virtual bool HandlesEvent(string eventName, SyntaxNode method, SemanticModel semanticModel)
{
// descendents may override (particularly VB).
return false;
}
public virtual Document AddHandlesClause(Document document, string eventName, SyntaxNode method, CancellationToken cancellationToken)
{
// descendents may override (particularly VB).
return document;
}
public virtual Document RemoveHandlesClause(Document document, string eventName, SyntaxNode method, CancellationToken cancellationToken)
{
// descendents may override (particularly VB).
return document;
}
public abstract string[] GetFunctionExtenderNames();
public abstract object GetFunctionExtender(string name, SyntaxNode node, ISymbol symbol);
public abstract string[] GetPropertyExtenderNames();
public abstract object GetPropertyExtender(string name, SyntaxNode node, ISymbol symbol);
public abstract string[] GetExternalTypeExtenderNames();
public abstract object GetExternalTypeExtender(string name, string externalLocation);
public abstract string[] GetTypeExtenderNames();
public abstract object GetTypeExtender(string name, AbstractCodeType codeType);
public abstract bool IsValidBaseType(SyntaxNode node, ITypeSymbol typeSymbol);
public abstract SyntaxNode AddBase(SyntaxNode node, ITypeSymbol typeSymbol, SemanticModel semanticModel, int? position);
public abstract SyntaxNode RemoveBase(SyntaxNode node, ITypeSymbol typeSymbol, SemanticModel semanticModel);
public abstract bool IsValidInterfaceType(SyntaxNode node, ITypeSymbol typeSymbol);
public abstract SyntaxNode AddImplementedInterface(SyntaxNode node, ITypeSymbol typeSymbol, SemanticModel semanticModel, int? position);
public abstract SyntaxNode RemoveImplementedInterface(SyntaxNode node, ITypeSymbol typeSymbol, SemanticModel semanticModel);
public abstract string GetPrototype(SyntaxNode node, ISymbol symbol, PrototypeFlags flags);
public virtual void AttachFormatTrackingToBuffer(ITextBuffer buffer)
{
// can be override by languages if needed
}
public virtual void DetachFormatTrackingToBuffer(ITextBuffer buffer)
{
// can be override by languages if needed
}
public virtual void EnsureBufferFormatted(ITextBuffer buffer)
{
// can be override by languages if needed
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace ThoughtWorks.VisualStudio
{
internal class Mapi
{
internal bool AddRecipientTo(string email)
{
return AddRecipient(email, HowTo.MAPI_TO);
}
internal bool AddRecipientCc(string email)
{
return AddRecipient(email, HowTo.MAPI_TO);
}
internal bool AddRecipientBcc(string email)
{
return AddRecipient(email, HowTo.MAPI_TO);
}
internal void AddAttachment(string strAttachmentFileName)
{
m_attachments.Add(strAttachmentFileName);
}
internal int SendMailPopup(string strSubject, string strBody)
{
return SendMail(strSubject, strBody, MAPI_LOGON_UI | MAPI_DIALOG);
}
internal int SendMailDirect(string strSubject, string strBody)
{
return SendMail(strSubject, strBody, MAPI_LOGON_UI);
}
[SuppressMessage("Microsoft.Globalization", "CA2101:SpecifyMarshalingForPInvokeStringArguments",
MessageId = "MapiMessage.subject"),
SuppressMessage("Microsoft.Globalization", "CA2101:SpecifyMarshalingForPInvokeStringArguments",
MessageId = "MapiMessage.noteText"),
SuppressMessage("Microsoft.Globalization", "CA2101:SpecifyMarshalingForPInvokeStringArguments",
MessageId = "MapiMessage.messageType"),
SuppressMessage("Microsoft.Globalization", "CA2101:SpecifyMarshalingForPInvokeStringArguments",
MessageId = "MapiMessage.dateReceived"),
SuppressMessage("Microsoft.Globalization", "CA2101:SpecifyMarshalingForPInvokeStringArguments",
MessageId = "MapiMessage.conversationID"),
SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass"), DllImport("MAPI32.DLL")]
private static extern int MAPISendMail(IntPtr sess, IntPtr hwnd, MapiMessage message, int flg, int rsv);
[SuppressMessage("Microsoft.Globalization", "CA1300:SpecifyMessageBoxOptions"),
SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "MAPISendMail"),
SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters",
MessageId = "System.Windows.Forms.MessageBox.Show(System.String,System.String)")]
private int SendMail(string strSubject, string strBody, int how)
{
var msg = new MapiMessage();
msg.subject = strSubject;
msg.noteText = strBody;
msg.recips = GetRecipients(out msg.recipCount);
msg.files = GetAttachments(out msg.fileCount);
m_lastError = MAPISendMail(new IntPtr(0), new IntPtr(0), msg, how, 0);
if (m_lastError > 1)
MessageBox.Show("MAPISendMail failed! " + GetLastError(), "MAPISendMail");
Cleanup(ref msg);
return m_lastError;
}
private bool AddRecipient(string email, HowTo howTo)
{
var recipient = new MapiRecipDesc();
recipient.recipClass = (int) howTo;
recipient.name = email;
m_recipients.Add(recipient);
return true;
}
private IntPtr GetRecipients(out int recipCount)
{
recipCount = 0;
if (m_recipients.Count == 0)
return IntPtr.Zero;
int size = Marshal.SizeOf(typeof (MapiRecipDesc));
IntPtr intPtr = Marshal.AllocHGlobal(m_recipients.Count*size);
var ptr = (int) intPtr;
foreach (MapiRecipDesc mapiDesc in m_recipients)
{
Marshal.StructureToPtr(mapiDesc, (IntPtr) ptr, false);
ptr += size;
}
recipCount = m_recipients.Count;
return intPtr;
}
private IntPtr GetAttachments(out int fileCount)
{
fileCount = 0;
if (m_attachments == null)
return IntPtr.Zero;
if ((m_attachments.Count <= 0) || (m_attachments.Count > maxAttachments))
return IntPtr.Zero;
int size = Marshal.SizeOf(typeof (MapiFileDesc));
IntPtr intPtr = Marshal.AllocHGlobal(m_attachments.Count*size);
var mapiFileDesc = new MapiFileDesc();
mapiFileDesc.position = -1;
var ptr = (int) intPtr;
foreach (string strAttachment in m_attachments)
{
mapiFileDesc.name = Path.GetFileName(strAttachment);
mapiFileDesc.path = strAttachment;
Marshal.StructureToPtr(mapiFileDesc, (IntPtr) ptr, false);
ptr += size;
}
fileCount = m_attachments.Count;
return intPtr;
}
private void Cleanup(ref MapiMessage msg)
{
int size = Marshal.SizeOf(typeof (MapiRecipDesc));
int ptr = 0;
if (msg.recips != IntPtr.Zero)
{
ptr = (int) msg.recips;
for (int i = 0; i < msg.recipCount; i++)
{
Marshal.DestroyStructure((IntPtr) ptr, typeof (MapiRecipDesc));
ptr += size;
}
Marshal.FreeHGlobal(msg.recips);
}
if (msg.files != IntPtr.Zero)
{
size = Marshal.SizeOf(typeof (MapiFileDesc));
ptr = (int) msg.files;
for (int i = 0; i < msg.fileCount; i++)
{
Marshal.DestroyStructure((IntPtr) ptr, typeof (MapiFileDesc));
ptr += size;
}
Marshal.FreeHGlobal(msg.files);
}
m_recipients.Clear();
m_attachments.Clear();
m_lastError = 0;
}
[SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.Int32.ToString"
)]
internal string GetLastError()
{
if (m_lastError <= 26)
return errors[m_lastError];
return "MAPI error [" + m_lastError.ToString() + "]";
}
private readonly string[] errors = new[]
{
"OK [0]", "User abort [1]", "General MAPI failure [2]",
"MAPI login failure [3]",
"Disk full [4]", "Insufficient memory [5]", "Access denied [6]",
"-unknown- [7]",
"Too many sessions [8]", "Too many files were specified [9]",
"Too many recipients were specified [10]",
"A specified attachment was not found [11]",
"Attachment open failure [12]", "Attachment write failure [13]",
"Unknown recipient [14]", "Bad recipient type [15]",
"No messages [16]", "Invalid message [17]", "Text too large [18]",
"Invalid session [19]",
"Type not supported [20]",
"A recipient was specified ambiguously [21]", "Message in use [22]",
"Network failure [23]",
"Invalid edit fields [24]", "Invalid recipients [25]",
"Not supported [26]"
};
private readonly List<MapiRecipDesc> m_recipients = new List<MapiRecipDesc>();
private readonly List<string> m_attachments = new List<string>();
private int m_lastError;
private const int MAPI_LOGON_UI = 0x00000001;
private const int MAPI_DIALOG = 0x00000008;
private const int maxAttachments = 20;
private enum HowTo
{
MAPI_ORIG = 0,
MAPI_TO,
MAPI_CC,
MAPI_BCC
};
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
internal class MapiMessage
{
internal int reserved;
internal string subject;
internal string noteText;
internal string messageType;
internal string dateReceived;
internal string conversationID;
internal int flags;
internal IntPtr originator;
internal int recipCount;
internal IntPtr recips;
internal int fileCount;
internal IntPtr files;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
internal class MapiFileDesc
{
internal int reserved;
internal int flags;
internal int position;
internal string path;
internal string name;
internal IntPtr type;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
internal class MapiRecipDesc
{
internal int reserved;
internal int recipClass;
internal string name;
internal string address;
internal int eIDSize;
internal IntPtr entryID;
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using OpenMetaverse;
using log4net;
using Nini.Config;
using System.Reflection;
using OpenSim.Services.Base;
using OpenSim.Services.Interfaces;
using OpenSim.Data;
using OpenSim.Framework;
namespace OpenSim.Services.InventoryService
{
public class XInventoryService : ServiceBase, IInventoryService
{
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
protected IXInventoryData m_Database;
protected bool m_AllowDelete = true;
protected string m_ConfigName = "InventoryService";
public XInventoryService(IConfigSource config)
: this(config, "InventoryService")
{
}
public XInventoryService(IConfigSource config, string configName) : base(config)
{
if (configName != string.Empty)
m_ConfigName = configName;
string dllName = String.Empty;
string connString = String.Empty;
//string realm = "Inventory"; // OSG version doesn't use this
//
// Try reading the [InventoryService] section first, if it exists
//
IConfig authConfig = config.Configs[m_ConfigName];
if (authConfig != null)
{
dllName = authConfig.GetString("StorageProvider", dllName);
connString = authConfig.GetString("ConnectionString", connString);
m_AllowDelete = authConfig.GetBoolean("AllowDelete", true);
// realm = authConfig.GetString("Realm", realm);
}
//
// Try reading the [DatabaseService] section, if it exists
//
IConfig dbConfig = config.Configs["DatabaseService"];
if (dbConfig != null)
{
if (dllName == String.Empty)
dllName = dbConfig.GetString("StorageProvider", String.Empty);
if (connString == String.Empty)
connString = dbConfig.GetString("ConnectionString", String.Empty);
}
//
// We tried, but this doesn't exist. We can't proceed.
//
if (dllName == String.Empty)
throw new Exception("No StorageProvider configured");
m_Database = LoadPlugin<IXInventoryData>(dllName,
new Object[] {connString, String.Empty});
if (m_Database == null)
throw new Exception("Could not find a storage interface in the given module");
}
public virtual bool CreateUserInventory(UUID principalID)
{
// This is braindeaad. We can't ever communicate that we fixed
// an existing inventory. Well, just return root folder status,
// but check sanity anyway.
//
bool result = false;
InventoryFolderBase rootFolder = GetRootFolder(principalID);
if (rootFolder == null)
{
rootFolder = ConvertToOpenSim(CreateFolder(principalID, UUID.Zero, (int)AssetType.RootFolder, "My Inventory"));
result = true;
}
XInventoryFolder[] sysFolders = GetSystemFolders(principalID, rootFolder.ID);
if (!Array.Exists(sysFolders, delegate (XInventoryFolder f) { if (f.type == (int)AssetType.Animation) return true; return false; }))
CreateFolder(principalID, rootFolder.ID, (int)AssetType.Animation, "Animations");
if (!Array.Exists(sysFolders, delegate (XInventoryFolder f) { if (f.type == (int)AssetType.Bodypart) return true; return false; }))
CreateFolder(principalID, rootFolder.ID, (int)AssetType.Bodypart, "Body Parts");
if (!Array.Exists(sysFolders, delegate (XInventoryFolder f) { if (f.type == (int)AssetType.CallingCard) return true; return false; }))
CreateFolder(principalID, rootFolder.ID, (int)AssetType.CallingCard, "Calling Cards");
if (!Array.Exists(sysFolders, delegate (XInventoryFolder f) { if (f.type == (int)AssetType.Clothing) return true; return false; }))
CreateFolder(principalID, rootFolder.ID, (int)AssetType.Clothing, "Clothing");
if (!Array.Exists(sysFolders, delegate (XInventoryFolder f) { if (f.type == (int)AssetType.Gesture) return true; return false; }))
CreateFolder(principalID, rootFolder.ID, (int)AssetType.Gesture, "Gestures");
if (!Array.Exists(sysFolders, delegate (XInventoryFolder f) { if (f.type == (int)AssetType.Landmark) return true; return false; }))
CreateFolder(principalID, rootFolder.ID, (int)AssetType.Landmark, "Landmarks");
if (!Array.Exists(sysFolders, delegate (XInventoryFolder f) { if (f.type == (int)AssetType.LostAndFoundFolder) return true; return false; }))
CreateFolder(principalID, rootFolder.ID, (int)AssetType.LostAndFoundFolder, "Lost And Found");
if (!Array.Exists(sysFolders, delegate (XInventoryFolder f) { if (f.type == (int)AssetType.Notecard) return true; return false; }))
CreateFolder(principalID, rootFolder.ID, (int)AssetType.Notecard, "Notecards");
if (!Array.Exists(sysFolders, delegate (XInventoryFolder f) { if (f.type == (int)AssetType.Object) return true; return false; }))
CreateFolder(principalID, rootFolder.ID, (int)AssetType.Object, "Objects");
if (!Array.Exists(sysFolders, delegate (XInventoryFolder f) { if (f.type == (int)AssetType.SnapshotFolder) return true; return false; }))
CreateFolder(principalID, rootFolder.ID, (int)AssetType.SnapshotFolder, "Photo Album");
if (!Array.Exists(sysFolders, delegate (XInventoryFolder f) { if (f.type == (int)AssetType.LSLText) return true; return false; }))
CreateFolder(principalID, rootFolder.ID, (int)AssetType.LSLText, "Scripts");
if (!Array.Exists(sysFolders, delegate (XInventoryFolder f) { if (f.type == (int)AssetType.Sound) return true; return false; }))
CreateFolder(principalID, rootFolder.ID, (int)AssetType.Sound, "Sounds");
if (!Array.Exists(sysFolders, delegate (XInventoryFolder f) { if (f.type == (int)AssetType.Texture) return true; return false; }))
CreateFolder(principalID, rootFolder.ID, (int)AssetType.Texture, "Textures");
if (!Array.Exists(sysFolders, delegate (XInventoryFolder f) { if (f.type == (int)AssetType.TrashFolder) return true; return false; }))
CreateFolder(principalID, rootFolder.ID, (int)AssetType.TrashFolder, "Trash");
return result;
}
protected XInventoryFolder CreateFolder(UUID principalID, UUID parentID, int type, string name)
{
XInventoryFolder newFolder = new XInventoryFolder();
newFolder.folderName = name;
newFolder.type = type;
newFolder.version = 1;
newFolder.folderID = UUID.Random();
newFolder.agentID = principalID;
newFolder.parentFolderID = parentID;
m_Database.StoreFolder(newFolder);
return newFolder;
}
protected virtual XInventoryFolder[] GetSystemFolders(UUID principalID, UUID rootID)
{
// m_log.DebugFormat("[XINVENTORY SERVICE]: Getting system folders for {0}", principalID);
XInventoryFolder[] allFolders = m_Database.GetFolders(
new string[] { "agentID", "parentFolderID" },
new string[] { principalID.ToString(), rootID.ToString() });
XInventoryFolder[] sysFolders = Array.FindAll(
allFolders,
delegate (XInventoryFolder f)
{
if (f.type > 0)
return true;
return false;
});
// m_log.DebugFormat(
// "[XINVENTORY SERVICE]: Found {0} system folders for {1}", sysFolders.Length, principalID);
return sysFolders;
}
public virtual List<InventoryFolderBase> GetInventorySkeleton(UUID principalID)
{
XInventoryFolder[] allFolders = m_Database.GetFolders(
new string[] { "agentID" },
new string[] { principalID.ToString() });
if (allFolders.Length == 0)
return null;
List<InventoryFolderBase> folders = new List<InventoryFolderBase>();
foreach (XInventoryFolder x in allFolders)
{
//m_log.DebugFormat("[XINVENTORY SERVICE]: Adding folder {0} to skeleton", x.folderName);
folders.Add(ConvertToOpenSim(x));
}
return folders;
}
public virtual InventoryFolderBase GetRootFolder(UUID principalID)
{
XInventoryFolder[] folders = m_Database.GetFolders(
new string[] { "agentID", "parentFolderID"},
new string[] { principalID.ToString(), UUID.Zero.ToString() });
if (folders.Length == 0)
return null;
XInventoryFolder root = null;
foreach (XInventoryFolder folder in folders)
{
if (folder.folderName == "My Inventory")
{
root = folder;
break;
}
}
if (root == null) // oops
root = folders[0];
return ConvertToOpenSim(root);
}
public virtual InventoryFolderBase GetFolderForType(UUID principalID, AssetType type)
{
// m_log.DebugFormat("[XINVENTORY SERVICE]: Getting folder type {0} for user {1}", type, principalID);
InventoryFolderBase rootFolder = GetRootFolder(principalID);
if (rootFolder == null)
{
m_log.WarnFormat(
"[XINVENTORY]: Found no root folder for {0} in GetFolderForType() when looking for {1}",
principalID, type);
return null;
}
return GetSystemFolderForType(rootFolder, type);
}
private InventoryFolderBase GetSystemFolderForType(InventoryFolderBase rootFolder, AssetType type)
{
// m_log.DebugFormat("[XINVENTORY SERVICE]: Getting folder type {0} for user {1}", type, principalID);
if (type == AssetType.RootFolder)
return rootFolder;
XInventoryFolder[] folders = m_Database.GetFolders(
new string[] { "agentID", "parentFolderID", "type"},
new string[] { rootFolder.Owner.ToString(), rootFolder.ID.ToString(), ((int)type).ToString() });
if (folders.Length == 0)
{
// m_log.WarnFormat("[XINVENTORY SERVICE]: Found no folder for type {0} for user {1}", type, principalID);
return null;
}
// m_log.DebugFormat(
// "[XINVENTORY SERVICE]: Found folder {0} {1} for type {2} for user {3}",
// folders[0].folderName, folders[0].folderID, type, principalID);
return ConvertToOpenSim(folders[0]);
}
public virtual InventoryCollection GetFolderContent(UUID principalID, UUID folderID)
{
// This method doesn't receive a valud principal id from the
// connector. So we disregard the principal and look
// by ID.
//
//m_log.DebugFormat("[XINVENTORY SERVICE]: Fetch contents for folder {0}", folderID.ToString());
InventoryCollection inventory = new InventoryCollection();
inventory.UserID = principalID;
inventory.Folders = new List<InventoryFolderBase>();
inventory.Items = new List<InventoryItemBase>();
XInventoryFolder[] folders = m_Database.GetFolders(
new string[] { "parentFolderID"},
new string[] { folderID.ToString() });
foreach (XInventoryFolder x in folders)
{
//m_log.DebugFormat("[XINVENTORY]: Adding folder {0} to response", x.folderName);
inventory.Folders.Add(ConvertToOpenSim(x));
}
XInventoryItem[] items = m_Database.GetItems(
new string[] { "parentFolderID"},
new string[] { folderID.ToString() });
foreach (XInventoryItem i in items)
{
//m_log.DebugFormat("[XINVENTORY]: Adding item {0} to response", i.inventoryName);
inventory.Items.Add(ConvertToOpenSim(i));
}
return inventory;
}
public virtual List<InventoryItemBase> GetFolderItems(UUID principalID, UUID folderID)
{
// m_log.DebugFormat("[XINVENTORY]: Fetch items for folder {0}", folderID);
// Since we probably don't get a valid principal here, either ...
//
List<InventoryItemBase> invItems = new List<InventoryItemBase>();
XInventoryItem[] items = m_Database.GetItems(
new string[] { "parentFolderID" },
new string[] { folderID.ToString() });
foreach (XInventoryItem i in items)
invItems.Add(ConvertToOpenSim(i));
return invItems;
}
public virtual bool AddFolder(InventoryFolderBase folder)
{
// m_log.DebugFormat("[XINVENTORY]: Add folder {0} type {1} in parent {2}", folder.Name, folder.Type, folder.ParentID);
InventoryFolderBase check = GetFolder(folder);
if (check != null)
return false;
if (folder.Type != (short)AssetType.Folder && folder.Type != (short)AssetType.Unknown)
{
InventoryFolderBase rootFolder = GetRootFolder(folder.Owner);
if (rootFolder == null)
{
m_log.WarnFormat(
"[XINVENTORY]: Found no root folder for {0} in AddFolder() when looking for {1}",
folder.Owner, folder.Type);
return false;
}
// Check we're not trying to add this as a system folder.
if (folder.ParentID == rootFolder.ID)
{
InventoryFolderBase existingSystemFolder
= GetSystemFolderForType(rootFolder, (AssetType)folder.Type);
if (existingSystemFolder != null)
{
m_log.WarnFormat(
"[XINVENTORY]: System folder of type {0} already exists when tried to add {1} to {2} for {3}",
folder.Type, folder.Name, folder.ParentID, folder.Owner);
return false;
}
}
}
XInventoryFolder xFolder = ConvertFromOpenSim(folder);
return m_Database.StoreFolder(xFolder);
}
public virtual bool UpdateFolder(InventoryFolderBase folder)
{
// m_log.DebugFormat("[XINVENTORY]: Update folder {0} {1} ({2})", folder.Name, folder.Type, folder.ID);
XInventoryFolder xFolder = ConvertFromOpenSim(folder);
InventoryFolderBase check = GetFolder(folder);
if (check == null)
return AddFolder(folder);
if ((check.Type != (short)AssetType.Unknown || xFolder.type != (short)AssetType.Unknown)
&& (check.Type != (short)AssetType.OutfitFolder || xFolder.type != (short)AssetType.OutfitFolder))
{
if (xFolder.version < check.Version)
{
// m_log.DebugFormat("[XINVENTORY]: {0} < {1} can't do", xFolder.version, check.Version);
return false;
}
check.Version = (ushort)xFolder.version;
xFolder = ConvertFromOpenSim(check);
// m_log.DebugFormat(
// "[XINVENTORY]: Storing version only update to system folder {0} {1} {2}",
// xFolder.folderName, xFolder.version, xFolder.type);
return m_Database.StoreFolder(xFolder);
}
if (xFolder.version < check.Version)
xFolder.version = check.Version;
xFolder.folderID = check.ID;
return m_Database.StoreFolder(xFolder);
}
public virtual bool MoveFolder(InventoryFolderBase folder)
{
return m_Database.MoveFolder(folder.ID.ToString(), folder.ParentID.ToString());
}
// We don't check the principal's ID here
//
public virtual bool DeleteFolders(UUID principalID, List<UUID> folderIDs)
{
return DeleteFolders(principalID, folderIDs, true);
}
public virtual bool DeleteFolders(UUID principalID, List<UUID> folderIDs, bool onlyIfTrash)
{
if (!m_AllowDelete)
return false;
// Ignore principal ID, it's bogus at connector level
//
foreach (UUID id in folderIDs)
{
if (onlyIfTrash && !ParentIsTrash(id))
continue;
//m_log.InfoFormat("[XINVENTORY SERVICE]: Delete folder {0}", id);
InventoryFolderBase f = new InventoryFolderBase();
f.ID = id;
PurgeFolder(f, onlyIfTrash);
m_Database.DeleteFolders("folderID", id.ToString());
}
return true;
}
public virtual bool PurgeFolder(InventoryFolderBase folder)
{
return PurgeFolder(folder, true);
}
public virtual bool PurgeFolder(InventoryFolderBase folder, bool onlyIfTrash)
{
if (!m_AllowDelete)
return false;
if (onlyIfTrash && !ParentIsTrash(folder.ID))
return false;
XInventoryFolder[] subFolders = m_Database.GetFolders(
new string[] { "parentFolderID" },
new string[] { folder.ID.ToString() });
foreach (XInventoryFolder x in subFolders)
{
PurgeFolder(ConvertToOpenSim(x), onlyIfTrash);
m_Database.DeleteFolders("folderID", x.folderID.ToString());
}
m_Database.DeleteItems("parentFolderID", folder.ID.ToString());
return true;
}
public virtual bool AddItem(InventoryItemBase item)
{
// m_log.DebugFormat(
// "[XINVENTORY SERVICE]: Adding item {0} {1} to folder {2} for {3}", item.Name, item.ID, item.Folder, item.Owner);
return m_Database.StoreItem(ConvertFromOpenSim(item));
}
public virtual bool UpdateItem(InventoryItemBase item)
{
if (!m_AllowDelete)
if (item.AssetType == (sbyte)AssetType.Link || item.AssetType == (sbyte)AssetType.LinkFolder)
return false;
// m_log.InfoFormat(
// "[XINVENTORY SERVICE]: Updating item {0} {1} in folder {2}", item.Name, item.ID, item.Folder);
InventoryItemBase retrievedItem = GetItem(item);
if (retrievedItem == null)
{
m_log.WarnFormat(
"[XINVENTORY SERVICE]: Tried to update item {0} {1}, owner {2} but no existing item found.",
item.Name, item.ID, item.Owner);
return false;
}
// Do not allow invariants to change. Changes to folder ID occur in MoveItems()
if (retrievedItem.InvType != item.InvType
|| retrievedItem.AssetType != item.AssetType
|| retrievedItem.Folder != item.Folder
|| retrievedItem.CreatorIdentification != item.CreatorIdentification
|| retrievedItem.Owner != item.Owner)
{
m_log.WarnFormat(
"[XINVENTORY SERVICE]: Caller to UpdateItem() for {0} {1} tried to alter property(s) that should be invariant, (InvType, AssetType, Folder, CreatorIdentification, Owner), existing ({2}, {3}, {4}, {5}, {6}), update ({7}, {8}, {9}, {10}, {11})",
retrievedItem.Name,
retrievedItem.ID,
retrievedItem.InvType,
retrievedItem.AssetType,
retrievedItem.Folder,
retrievedItem.CreatorIdentification,
retrievedItem.Owner,
item.InvType,
item.AssetType,
item.Folder,
item.CreatorIdentification,
item.Owner);
item.InvType = retrievedItem.InvType;
item.AssetType = retrievedItem.AssetType;
item.Folder = retrievedItem.Folder;
item.CreatorIdentification = retrievedItem.CreatorIdentification;
item.Owner = retrievedItem.Owner;
}
return m_Database.StoreItem(ConvertFromOpenSim(item));
}
public virtual bool MoveItems(UUID principalID, List<InventoryItemBase> items)
{
// Principal is b0rked. *sigh*
//
foreach (InventoryItemBase i in items)
{
m_Database.MoveItem(i.ID.ToString(), i.Folder.ToString());
}
return true;
}
public virtual bool DeleteItems(UUID principalID, List<UUID> itemIDs)
{
if (!m_AllowDelete)
{
// We must still allow links and links to folders to be deleted, otherwise they will build up
// in the player's inventory until they can no longer log in. Deletions of links due to code bugs or
// similar is inconvenient but on a par with accidental movement of items. The original item is never
// touched.
foreach (UUID id in itemIDs)
{
if (!m_Database.DeleteItems(
new string[] { "inventoryID", "assetType" },
new string[] { id.ToString(), ((sbyte)AssetType.Link).ToString() }))
{
m_Database.DeleteItems(
new string[] { "inventoryID", "assetType" },
new string[] { id.ToString(), ((sbyte)AssetType.LinkFolder).ToString() });
}
}
}
else
{
// Just use the ID... *facepalms*
//
foreach (UUID id in itemIDs)
m_Database.DeleteItems("inventoryID", id.ToString());
}
return true;
}
public virtual InventoryItemBase GetItem(InventoryItemBase item)
{
XInventoryItem[] items = m_Database.GetItems(
new string[] { "inventoryID" },
new string[] { item.ID.ToString() });
if (items.Length == 0)
return null;
return ConvertToOpenSim(items[0]);
}
public virtual InventoryFolderBase GetFolder(InventoryFolderBase folder)
{
XInventoryFolder[] folders = m_Database.GetFolders(
new string[] { "folderID"},
new string[] { folder.ID.ToString() });
if (folders.Length == 0)
return null;
return ConvertToOpenSim(folders[0]);
}
public virtual List<InventoryItemBase> GetActiveGestures(UUID principalID)
{
XInventoryItem[] items = m_Database.GetActiveGestures(principalID);
if (items.Length == 0)
return new List<InventoryItemBase>();
List<InventoryItemBase> ret = new List<InventoryItemBase>();
foreach (XInventoryItem x in items)
ret.Add(ConvertToOpenSim(x));
return ret;
}
public virtual int GetAssetPermissions(UUID principalID, UUID assetID)
{
return m_Database.GetAssetPermissions(principalID, assetID);
}
public virtual InventoryCollection GetUserInventory(UUID userID)
{
InventoryCollection userInventory = new InventoryCollection();
userInventory.UserID = userID;
userInventory.Folders = new List<InventoryFolderBase>();
userInventory.Items = new List<InventoryItemBase>();
List<InventoryFolderBase> skel = GetInventorySkeleton(userID);
if (skel != null)
{
foreach (InventoryFolderBase f in skel)
{
InventoryCollection c = GetFolderContent(userID, f.ID);
if (c != null && c.Items != null && c.Items.Count > 0)
userInventory.Items.AddRange(c.Items);
if (c != null && c.Folders != null && c.Folders.Count > 0)
userInventory.Folders.AddRange(c.Folders);
}
}
m_log.DebugFormat("[XINVENTORY SERVICE]: GetUserInventory for user {0} returning {1} folders and {2} items",
userID, userInventory.Folders.Count, userInventory.Items.Count);
return userInventory;
}
public void GetUserInventory(UUID userID, InventoryReceiptCallback callback)
{
}
// Unused.
//
public bool HasInventoryForUser(UUID userID)
{
return false;
}
// CM Helpers
//
protected InventoryFolderBase ConvertToOpenSim(XInventoryFolder folder)
{
InventoryFolderBase newFolder = new InventoryFolderBase();
newFolder.ParentID = folder.parentFolderID;
newFolder.Type = (short)folder.type;
// Viewer can't understand anything that's not in it's LLFolderType enum
if (newFolder.Type == 100)
newFolder.Type = -1;
newFolder.Version = (ushort)folder.version;
newFolder.Name = folder.folderName;
newFolder.Owner = folder.agentID;
newFolder.ID = folder.folderID;
return newFolder;
}
protected XInventoryFolder ConvertFromOpenSim(InventoryFolderBase folder)
{
XInventoryFolder newFolder = new XInventoryFolder();
newFolder.parentFolderID = folder.ParentID;
newFolder.type = (int)folder.Type;
newFolder.version = (int)folder.Version;
newFolder.folderName = folder.Name;
newFolder.agentID = folder.Owner;
newFolder.folderID = folder.ID;
return newFolder;
}
protected InventoryItemBase ConvertToOpenSim(XInventoryItem item)
{
InventoryItemBase newItem = new InventoryItemBase();
newItem.AssetID = item.assetID;
newItem.AssetType = item.assetType;
newItem.Name = item.inventoryName;
newItem.Owner = item.avatarID;
newItem.ID = item.inventoryID;
newItem.InvType = item.invType;
newItem.Folder = item.parentFolderID;
newItem.CreatorIdentification = item.creatorID;
newItem.Description = item.inventoryDescription;
newItem.NextPermissions = (uint)item.inventoryNextPermissions;
newItem.CurrentPermissions = (uint)item.inventoryCurrentPermissions;
newItem.BasePermissions = (uint)item.inventoryBasePermissions;
newItem.EveryOnePermissions = (uint)item.inventoryEveryOnePermissions;
newItem.GroupPermissions = (uint)item.inventoryGroupPermissions;
newItem.GroupID = item.groupID;
if (item.groupOwned == 0)
newItem.GroupOwned = false;
else
newItem.GroupOwned = true;
newItem.SalePrice = item.salePrice;
newItem.SaleType = (byte)item.saleType;
newItem.Flags = (uint)item.flags;
newItem.CreationDate = item.creationDate;
return newItem;
}
protected XInventoryItem ConvertFromOpenSim(InventoryItemBase item)
{
XInventoryItem newItem = new XInventoryItem();
newItem.assetID = item.AssetID;
newItem.assetType = item.AssetType;
newItem.inventoryName = item.Name;
newItem.avatarID = item.Owner;
newItem.inventoryID = item.ID;
newItem.invType = item.InvType;
newItem.parentFolderID = item.Folder;
newItem.creatorID = item.CreatorIdentification;
newItem.inventoryDescription = item.Description;
newItem.inventoryNextPermissions = (int)item.NextPermissions;
newItem.inventoryCurrentPermissions = (int)item.CurrentPermissions;
newItem.inventoryBasePermissions = (int)item.BasePermissions;
newItem.inventoryEveryOnePermissions = (int)item.EveryOnePermissions;
newItem.inventoryGroupPermissions = (int)item.GroupPermissions;
newItem.groupID = item.GroupID;
if (item.GroupOwned)
newItem.groupOwned = 1;
else
newItem.groupOwned = 0;
newItem.salePrice = item.SalePrice;
newItem.saleType = (int)item.SaleType;
newItem.flags = (int)item.Flags;
newItem.creationDate = item.CreationDate;
return newItem;
}
private bool ParentIsTrash(UUID folderID)
{
XInventoryFolder[] folder = m_Database.GetFolders(new string[] {"folderID"}, new string[] {folderID.ToString()});
if (folder.Length < 1)
return false;
if (folder[0].type == (int)AssetType.TrashFolder)
return true;
UUID parentFolder = folder[0].parentFolderID;
while (parentFolder != UUID.Zero)
{
XInventoryFolder[] parent = m_Database.GetFolders(new string[] {"folderID"}, new string[] {parentFolder.ToString()});
if (parent.Length < 1)
return false;
if (parent[0].type == (int)AssetType.TrashFolder)
return true;
if (parent[0].type == (int)AssetType.RootFolder)
return false;
parentFolder = parent[0].parentFolderID;
}
return false;
}
}
}
| |
/*
* Copyright (c) 2010-2015 Pivotal Software, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you
* may not use this file except in compliance with the License. You
* may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License. See accompanying
* LICENSE file.
*/
namespace AdoNetTest.WIN
{
partial class formRunner
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.menuStrip1 = new System.Windows.Forms.MenuStrip();
this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripConfigFile = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.listBoxMsg = new System.Windows.Forms.ListBox();
this.buttonStart = new System.Windows.Forms.Button();
this.buttonStop = new System.Windows.Forms.Button();
this.radioButtonRunOnce = new System.Windows.Forms.RadioButton();
this.radioButtonRunContinuous = new System.Windows.Forms.RadioButton();
this.button1 = new System.Windows.Forms.Button();
this.comboBox1 = new System.Windows.Forms.ComboBox();
this.label1 = new System.Windows.Forms.Label();
this.menuStrip1.SuspendLayout();
this.SuspendLayout();
//
// menuStrip1
//
this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.fileToolStripMenuItem});
this.menuStrip1.Location = new System.Drawing.Point(0, 0);
this.menuStrip1.Name = "menuStrip1";
this.menuStrip1.Size = new System.Drawing.Size(717, 24);
this.menuStrip1.TabIndex = 0;
this.menuStrip1.Text = "menuStrip1";
//
// fileToolStripMenuItem
//
this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.toolStripConfigFile,
this.toolStripSeparator1,
this.exitToolStripMenuItem});
this.fileToolStripMenuItem.Name = "fileToolStripMenuItem";
this.fileToolStripMenuItem.Size = new System.Drawing.Size(35, 20);
this.fileToolStripMenuItem.Text = "File";
//
// toolStripConfigFile
//
this.toolStripConfigFile.Name = "toolStripConfigFile";
this.toolStripConfigFile.Size = new System.Drawing.Size(135, 22);
this.toolStripConfigFile.Text = "Config File";
this.toolStripConfigFile.Click += new System.EventHandler(this.toolStripConfigFile_Click);
//
// toolStripSeparator1
//
this.toolStripSeparator1.Name = "toolStripSeparator1";
this.toolStripSeparator1.Size = new System.Drawing.Size(132, 6);
//
// exitToolStripMenuItem
//
this.exitToolStripMenuItem.Name = "exitToolStripMenuItem";
this.exitToolStripMenuItem.Size = new System.Drawing.Size(135, 22);
this.exitToolStripMenuItem.Text = "Exit";
//
// listBoxMsg
//
this.listBoxMsg.Dock = System.Windows.Forms.DockStyle.Bottom;
this.listBoxMsg.FormattingEnabled = true;
this.listBoxMsg.Location = new System.Drawing.Point(0, 114);
this.listBoxMsg.Name = "listBoxMsg";
this.listBoxMsg.Size = new System.Drawing.Size(717, 459);
this.listBoxMsg.TabIndex = 6;
//
// buttonStart
//
this.buttonStart.Location = new System.Drawing.Point(531, 27);
this.buttonStart.Name = "buttonStart";
this.buttonStart.Size = new System.Drawing.Size(75, 23);
this.buttonStart.TabIndex = 2;
this.buttonStart.Text = "Start";
this.buttonStart.UseVisualStyleBackColor = true;
this.buttonStart.Click += new System.EventHandler(this.buttonStart_Click);
//
// buttonStop
//
this.buttonStop.Location = new System.Drawing.Point(612, 27);
this.buttonStop.Name = "buttonStop";
this.buttonStop.Size = new System.Drawing.Size(75, 23);
this.buttonStop.TabIndex = 3;
this.buttonStop.Text = "Stop";
this.buttonStop.UseVisualStyleBackColor = true;
this.buttonStop.Click += new System.EventHandler(this.buttonStop_Click);
//
// radioButtonRunOnce
//
this.radioButtonRunOnce.AutoSize = true;
this.radioButtonRunOnce.Checked = true;
this.radioButtonRunOnce.Location = new System.Drawing.Point(275, 30);
this.radioButtonRunOnce.Name = "radioButtonRunOnce";
this.radioButtonRunOnce.Size = new System.Drawing.Size(74, 17);
this.radioButtonRunOnce.TabIndex = 4;
this.radioButtonRunOnce.TabStop = true;
this.radioButtonRunOnce.Text = "Run Once";
this.radioButtonRunOnce.UseVisualStyleBackColor = true;
this.radioButtonRunOnce.CheckedChanged += new System.EventHandler(this.radioButtonRunOnce_CheckedChanged);
//
// radioButtonRunContinuous
//
this.radioButtonRunContinuous.AutoSize = true;
this.radioButtonRunContinuous.Location = new System.Drawing.Point(365, 30);
this.radioButtonRunContinuous.Name = "radioButtonRunContinuous";
this.radioButtonRunContinuous.Size = new System.Drawing.Size(108, 17);
this.radioButtonRunContinuous.TabIndex = 5;
this.radioButtonRunContinuous.Text = "Run Continuously";
this.radioButtonRunContinuous.UseVisualStyleBackColor = true;
this.radioButtonRunContinuous.CheckedChanged += new System.EventHandler(this.radioButtonRunContinuous_CheckedChanged);
//
// button1
//
this.button1.Location = new System.Drawing.Point(533, 66);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(72, 27);
this.button1.TabIndex = 8;
this.button1.Text = "Run it";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// comboBox1
//
this.comboBox1.FormattingEnabled = true;
this.comboBox1.Location = new System.Drawing.Point(83, 66);
this.comboBox1.MaxDropDownItems = 25;
this.comboBox1.Name = "comboBox1";
this.comboBox1.Size = new System.Drawing.Size(428, 21);
this.comboBox1.Sorted = true;
this.comboBox1.TabIndex = 9;
this.comboBox1.SelectedIndexChanged += new System.EventHandler(this.comboBox1_SelectedIndexChanged);
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(17, 70);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(60, 13);
this.label1.TabIndex = 10;
this.label1.Text = "Test name:";
//
// formRunner
//
this.ClientSize = new System.Drawing.Size(717, 573);
this.Controls.Add(this.label1);
this.Controls.Add(this.comboBox1);
this.Controls.Add(this.button1);
this.Controls.Add(this.radioButtonRunContinuous);
this.Controls.Add(this.radioButtonRunOnce);
this.Controls.Add(this.listBoxMsg);
this.Controls.Add(this.buttonStop);
this.Controls.Add(this.buttonStart);
this.Controls.Add(this.menuStrip1);
this.MainMenuStrip = this.menuStrip1;
this.MaximumSize = new System.Drawing.Size(725, 600);
this.MinimumSize = new System.Drawing.Size(725, 600);
this.Name = "formRunner";
this.Text = "AdoNetTest Runner";
this.Load += new System.EventHandler(this.formRunner_Load);
this.menuStrip1.ResumeLayout(false);
this.menuStrip1.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.MenuStrip menuStrip1;
private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem toolStripConfigFile;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator1;
private System.Windows.Forms.ListBox listBoxMsg;
private System.Windows.Forms.Button buttonStart;
private System.Windows.Forms.Button buttonStop;
private System.Windows.Forms.RadioButton radioButtonRunOnce;
private System.Windows.Forms.RadioButton radioButtonRunContinuous;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.ComboBox comboBox1;
private System.Windows.Forms.Label label1;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using Xunit;
namespace System.Runtime.Serialization.Formatters.Tests
{
public partial class BinaryFormatterTests : RemoteExecutorTestBase
{
[Theory]
[MemberData(nameof(BasicObjectsRoundtrip_MemberData))]
public void ValidateBasicObjectsRoundtrip(object obj, FormatterAssemblyStyle assemblyFormat, TypeFilterLevel filterLevel, FormatterTypeStyle typeFormat)
{
object clone = FormatterClone(obj, null, assemblyFormat, filterLevel, typeFormat);
if (!ReferenceEquals(obj, string.Empty)) // "" is interned and will roundtrip as the same object
{
Assert.NotSame(obj, clone);
}
CheckForAnyEquals(obj, clone);
}
// Used for updating blobs in BinaryFormatterTestData.cs
//[Fact]
public void UpdateBlobs()
{
string testDataFilePath = GetTestDataFilePath();
IEnumerable<object[]> coreTypeRecords = GetCoreTypeRecords();
string[] coreTypeBlobs = GetCoreTypeBlobs(coreTypeRecords, FormatterAssemblyStyle.Full).ToArray();
var (numberOfBlobs, numberOfFoundBlobs, numberOfUpdatedBlobs) = UpdateCoreTypeBlobs(testDataFilePath, coreTypeBlobs);
Console.WriteLine($"{numberOfBlobs} existing blobs" +
$"{Environment.NewLine}{numberOfFoundBlobs} found blobs with regex search" +
$"{Environment.NewLine}{numberOfUpdatedBlobs} updated blobs with regex replace");
}
[Theory]
[MemberData(nameof(SerializableObjects_MemberData))]
public void ValidateAgainstBlobs(object obj, string[] blobs)
{
if (obj == null)
{
throw new ArgumentNullException("The serializable object must not be null", nameof(obj));
}
if (blobs == null || blobs.Length == 0)
{
throw new ArgumentOutOfRangeException($"Type {obj} has no blobs to deserialize and test equality against. Blob: " +
SerializeObjectToBlob(obj, FormatterAssemblyStyle.Full));
}
SanityCheckBlob(obj, blobs);
foreach (string blob in blobs)
{
CheckForAnyEquals(obj, DeserializeBlobToObject(blob, FormatterAssemblyStyle.Simple));
CheckForAnyEquals(obj, DeserializeBlobToObject(blob, FormatterAssemblyStyle.Full));
}
}
[Fact]
public void ArraySegmentDefaultCtor()
{
// This is workaround for Xunit bug which tries to pretty print test case name and enumerate this object.
// When inner array is not initialized it throws an exception when this happens.
object obj = new ArraySegment<int>();
string corefxBlob = "AAEAAAD/////AQAAAAAAAAAEAQAAAHJTeXN0ZW0uQXJyYXlTZWdtZW50YDFbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0DAAAABl9hcnJheQdfb2Zmc2V0Bl9jb3VudAcAAAgICAoAAAAAAAAAAAs=";
string netfxBlob = "AAEAAAD/////AQAAAAAAAAAEAQAAAHJTeXN0ZW0uQXJyYXlTZWdtZW50YDFbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0DAAAABl9hcnJheQdfb2Zmc2V0Bl9jb3VudAcAAAgICAoAAAAAAAAAAAs=";
CheckForAnyEquals(obj, DeserializeBlobToObject(corefxBlob, FormatterAssemblyStyle.Full));
CheckForAnyEquals(obj, DeserializeBlobToObject(netfxBlob, FormatterAssemblyStyle.Full));
}
[Fact]
public void ValidateDeserializationOfObjectWithDifferentAssemblyVersion()
{
// To generate this properly, change AssemblyVersion to a value which is unlikely to happen in production and generate base64(serialized-data)
// For this test 9.98.7.987 is being used
var obj = new SomeType() { SomeField = 7 };
string serializedObj = @"AAEAAAD/////AQAAAAAAAAAMAgAAAHNTeXN0ZW0uUnVudGltZS5TZXJpYWxpemF0aW9uLkZvcm1hdHRlcnMuVGVzdHMsIFZlcnNpb249OS45OC43Ljk4NywgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj05ZDc3Y2M3YWQzOWI2OGViBQEAAAA2U3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLlNvbWVUeXBlAQAAAAlTb21lRmllbGQACAIAAAAHAAAACw==";
var deserialized = (SomeType)DeserializeBlobToObject(serializedObj, FormatterAssemblyStyle.Simple);
Assert.Equal(obj, deserialized);
}
[Fact]
public void ValidateDeserializationOfObjectWithGenericTypeWhichGenericArgumentHasDifferentAssemblyVersion()
{
// To generate this properly, change AssemblyVersion to a value which is unlikely to happen in production and generate base64(serialized-data)
// For this test 9.98.7.987 is being used
var obj = new GenericTypeWithArg<SomeType>() { Test = new SomeType() { SomeField = 9 } };
string serializedObj = @"AAEAAAD/////AQAAAAAAAAAMAgAAAHNTeXN0ZW0uUnVudGltZS5TZXJpYWxpemF0aW9uLkZvcm1hdHRlcnMuVGVzdHMsIFZlcnNpb249OS45OC43Ljk4NywgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj05ZDc3Y2M3YWQzOWI2OGViBQEAAADxAVN5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cy5HZW5lcmljVHlwZVdpdGhBcmdgMVtbU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLlNvbWVUeXBlLCBTeXN0ZW0uUnVudGltZS5TZXJpYWxpemF0aW9uLkZvcm1hdHRlcnMuVGVzdHMsIFZlcnNpb249OS45OC43Ljk4NywgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj05ZDc3Y2M3YWQzOWI2OGViXV0BAAAABFRlc3QENlN5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cy5Tb21lVHlwZQIAAAACAAAACQMAAAAFAwAAADZTeXN0ZW0uUnVudGltZS5TZXJpYWxpemF0aW9uLkZvcm1hdHRlcnMuVGVzdHMuU29tZVR5cGUBAAAACVNvbWVGaWVsZAAIAgAAAAkAAAAL";
var deserialized = (GenericTypeWithArg<SomeType>)DeserializeBlobToObject(serializedObj, FormatterAssemblyStyle.Simple);
Assert.Equal(obj, deserialized);
}
[Theory]
[MemberData(nameof(SerializableEqualityComparers_MemberData))]
public void ValidateEqualityComparersAgainstBlobs(object obj, string[] blobs)
{
if (obj == null)
{
throw new ArgumentNullException("The serializable object must not be null", nameof(obj));
}
if (blobs == null || blobs.Length == 0)
{
throw new ArgumentOutOfRangeException($"Type {obj} has no blobs to deserialize and test equality against. Blob: " +
SerializeObjectToBlob(obj, FormatterAssemblyStyle.Full));
}
SanityCheckBlob(obj, blobs);
foreach (string blob in blobs)
{
ValidateEqualityComparer(DeserializeBlobToObject(blob, FormatterAssemblyStyle.Simple));
ValidateEqualityComparer(DeserializeBlobToObject(blob, FormatterAssemblyStyle.Full));
}
}
[Fact]
public void RoundtripManyObjectsInOneStream()
{
object[][] objects = SerializableObjects_MemberData().ToArray();
var s = new MemoryStream();
var f = new BinaryFormatter();
foreach (object[] obj in objects)
{
f.Serialize(s, obj[0]);
}
s.Position = 0;
foreach (object[] obj in objects)
{
object clone = f.Deserialize(s);
CheckForAnyEquals(obj[0], clone);
}
}
[Fact]
public void SameObjectRepeatedInArray()
{
object o = new object();
object[] arr = new[] { o, o, o, o, o };
object[] result = FormatterClone(arr);
Assert.Equal(arr.Length, result.Length);
Assert.NotSame(arr, result);
Assert.NotSame(arr[0], result[0]);
for (int i = 1; i < result.Length; i++)
{
Assert.Same(result[0], result[i]);
}
}
[Theory]
[MemberData(nameof(SerializableExceptions_MemberData))]
public void Roundtrip_Exceptions(Exception expected)
{
BinaryFormatterHelpers.AssertRoundtrips(expected);
}
[Theory]
[MemberData(nameof(NonSerializableTypes_MemberData))]
public void ValidateNonSerializableTypes(object obj, FormatterAssemblyStyle assemblyFormat, TypeFilterLevel filterLevel, FormatterTypeStyle typeFormat)
{
var f = new BinaryFormatter()
{
AssemblyFormat = assemblyFormat,
FilterLevel = filterLevel,
TypeFormat = typeFormat
};
using (var s = new MemoryStream())
{
Assert.Throws<SerializationException>(() => f.Serialize(s, obj));
}
}
[Fact]
public void SerializeNonSerializableTypeWithSurrogate()
{
var p = new NonSerializablePair<int, string>() { Value1 = 1, Value2 = "2" };
Assert.False(p.GetType().IsSerializable);
Assert.Throws<SerializationException>(() => FormatterClone(p));
NonSerializablePair<int, string> result = FormatterClone(p, new NonSerializablePairSurrogate());
Assert.NotSame(p, result);
Assert.Equal(p.Value1, result.Value1);
Assert.Equal(p.Value2, result.Value2);
}
[Fact]
public void SerializationEvents_FireAsExpected()
{
var f = new BinaryFormatter();
var obj = new IncrementCountsDuringRoundtrip(null);
Assert.Equal(0, obj.IncrementedDuringOnSerializingMethod);
Assert.Equal(0, obj.IncrementedDuringOnSerializedMethod);
Assert.Equal(0, obj.IncrementedDuringOnDeserializingMethod);
Assert.Equal(0, obj.IncrementedDuringOnDeserializedMethod);
using (var s = new MemoryStream())
{
f.Serialize(s, obj);
s.Position = 0;
Assert.Equal(1, obj.IncrementedDuringOnSerializingMethod);
Assert.Equal(1, obj.IncrementedDuringOnSerializedMethod);
Assert.Equal(0, obj.IncrementedDuringOnDeserializingMethod);
Assert.Equal(0, obj.IncrementedDuringOnDeserializedMethod);
var result = (IncrementCountsDuringRoundtrip)f.Deserialize(s);
Assert.Equal(1, obj.IncrementedDuringOnSerializingMethod);
Assert.Equal(1, obj.IncrementedDuringOnSerializedMethod);
Assert.Equal(0, obj.IncrementedDuringOnDeserializingMethod);
Assert.Equal(0, obj.IncrementedDuringOnDeserializedMethod);
Assert.Equal(1, result.IncrementedDuringOnSerializingMethod);
Assert.Equal(0, result.IncrementedDuringOnSerializedMethod);
Assert.Equal(1, result.IncrementedDuringOnDeserializingMethod);
Assert.Equal(1, result.IncrementedDuringOnDeserializedMethod);
}
}
[Fact]
public void SerializationEvents_DerivedTypeWithEvents_FireAsExpected()
{
var f = new BinaryFormatter();
var obj = new DerivedIncrementCountsDuringRoundtrip(null);
Assert.Equal(0, obj.IncrementedDuringOnSerializingMethod);
Assert.Equal(0, obj.IncrementedDuringOnSerializedMethod);
Assert.Equal(0, obj.IncrementedDuringOnDeserializingMethod);
Assert.Equal(0, obj.IncrementedDuringOnDeserializedMethod);
Assert.Equal(0, obj.DerivedIncrementedDuringOnSerializingMethod);
Assert.Equal(0, obj.DerivedIncrementedDuringOnSerializedMethod);
Assert.Equal(0, obj.DerivedIncrementedDuringOnDeserializingMethod);
Assert.Equal(0, obj.DerivedIncrementedDuringOnDeserializedMethod);
using (var s = new MemoryStream())
{
f.Serialize(s, obj);
s.Position = 0;
Assert.Equal(1, obj.IncrementedDuringOnSerializingMethod);
Assert.Equal(1, obj.IncrementedDuringOnSerializedMethod);
Assert.Equal(0, obj.IncrementedDuringOnDeserializingMethod);
Assert.Equal(0, obj.IncrementedDuringOnDeserializedMethod);
Assert.Equal(1, obj.DerivedIncrementedDuringOnSerializingMethod);
Assert.Equal(1, obj.DerivedIncrementedDuringOnSerializedMethod);
Assert.Equal(0, obj.DerivedIncrementedDuringOnDeserializingMethod);
Assert.Equal(0, obj.DerivedIncrementedDuringOnDeserializedMethod);
var result = (DerivedIncrementCountsDuringRoundtrip)f.Deserialize(s);
Assert.Equal(1, obj.IncrementedDuringOnSerializingMethod);
Assert.Equal(1, obj.IncrementedDuringOnSerializedMethod);
Assert.Equal(0, obj.IncrementedDuringOnDeserializingMethod);
Assert.Equal(0, obj.IncrementedDuringOnDeserializedMethod);
Assert.Equal(1, obj.DerivedIncrementedDuringOnSerializingMethod);
Assert.Equal(1, obj.DerivedIncrementedDuringOnSerializedMethod);
Assert.Equal(0, obj.DerivedIncrementedDuringOnDeserializingMethod);
Assert.Equal(0, obj.DerivedIncrementedDuringOnDeserializedMethod);
Assert.Equal(1, result.IncrementedDuringOnSerializingMethod);
Assert.Equal(0, result.IncrementedDuringOnSerializedMethod);
Assert.Equal(1, result.IncrementedDuringOnDeserializingMethod);
Assert.Equal(1, result.IncrementedDuringOnDeserializedMethod);
Assert.Equal(1, result.DerivedIncrementedDuringOnSerializingMethod);
Assert.Equal(0, result.DerivedIncrementedDuringOnSerializedMethod);
Assert.Equal(1, result.DerivedIncrementedDuringOnDeserializingMethod);
Assert.Equal(1, result.DerivedIncrementedDuringOnDeserializedMethod);
}
}
[Fact]
public void Properties_Roundtrip()
{
var f = new BinaryFormatter();
Assert.Null(f.Binder);
var binder = new DelegateBinder();
f.Binder = binder;
Assert.Same(binder, f.Binder);
Assert.NotNull(f.Context);
Assert.Null(f.Context.Context);
Assert.Equal(StreamingContextStates.All, f.Context.State);
var context = new StreamingContext(StreamingContextStates.Clone);
f.Context = context;
Assert.Equal(StreamingContextStates.Clone, f.Context.State);
Assert.Null(f.SurrogateSelector);
var selector = new SurrogateSelector();
f.SurrogateSelector = selector;
Assert.Same(selector, f.SurrogateSelector);
Assert.Equal(FormatterAssemblyStyle.Simple, f.AssemblyFormat);
f.AssemblyFormat = FormatterAssemblyStyle.Full;
Assert.Equal(FormatterAssemblyStyle.Full, f.AssemblyFormat);
Assert.Equal(TypeFilterLevel.Full, f.FilterLevel);
f.FilterLevel = TypeFilterLevel.Low;
Assert.Equal(TypeFilterLevel.Low, f.FilterLevel);
Assert.Equal(FormatterTypeStyle.TypesAlways, f.TypeFormat);
f.TypeFormat = FormatterTypeStyle.XsdString;
Assert.Equal(FormatterTypeStyle.XsdString, f.TypeFormat);
}
[Fact]
public void SerializeDeserialize_InvalidArguments_ThrowsException()
{
var f = new BinaryFormatter();
AssertExtensions.Throws<ArgumentNullException>("serializationStream", () => f.Serialize(null, new object()));
AssertExtensions.Throws<ArgumentNullException>("serializationStream", () => f.Deserialize(null));
Assert.Throws<SerializationException>(() => f.Deserialize(new MemoryStream())); // seekable, 0-length
}
[Theory]
[InlineData(FormatterAssemblyStyle.Simple, false)]
[InlineData(FormatterAssemblyStyle.Full, true)]
public void MissingField_FailsWithAppropriateStyle(FormatterAssemblyStyle style, bool exceptionExpected)
{
var f = new BinaryFormatter();
var s = new MemoryStream();
f.Serialize(s, new Version1ClassWithoutField());
s.Position = 0;
f = new BinaryFormatter() { AssemblyFormat = style };
f.Binder = new DelegateBinder { BindToTypeDelegate = (_, __) => typeof(Version2ClassWithoutOptionalField) };
if (exceptionExpected)
{
Assert.Throws<SerializationException>(() => f.Deserialize(s));
}
else
{
var result = (Version2ClassWithoutOptionalField)f.Deserialize(s);
Assert.NotNull(result);
Assert.Equal(null, result.Value);
}
}
[Theory]
[InlineData(FormatterAssemblyStyle.Simple)]
[InlineData(FormatterAssemblyStyle.Full)]
public void OptionalField_Missing_Success(FormatterAssemblyStyle style)
{
var f = new BinaryFormatter();
var s = new MemoryStream();
f.Serialize(s, new Version1ClassWithoutField());
s.Position = 0;
f = new BinaryFormatter() { AssemblyFormat = style };
f.Binder = new DelegateBinder { BindToTypeDelegate = (_, __) => typeof(Version2ClassWithOptionalField) };
var result = (Version2ClassWithOptionalField)f.Deserialize(s);
Assert.NotNull(result);
Assert.Equal(null, result.Value);
}
[Fact]
public void ObjectReference_RealObjectSerialized()
{
var obj = new ObjRefReturnsObj { Real = 42 };
object real = FormatterClone<object>(obj);
Assert.Equal(42, real);
}
// Test is disabled becaues it can cause improbable memory allocations leading to interminable paging.
// We're keeping the code because it could be useful to a dev making local changes to binary formatter code.
//[OuterLoop]
//[Theory]
//[MemberData(nameof(FuzzInputs_MemberData))]
public void Deserialize_FuzzInput(object obj, Random rand)
{
// Get the serialized data for the object
byte[] data = SerializeObjectToRaw(obj, FormatterAssemblyStyle.Simple);
// Make some "random" changes to it
for (int i = 1; i < rand.Next(1, 100); i++)
{
data[rand.Next(data.Length)] = (byte)rand.Next(256);
}
// Try to deserialize that.
try
{
DeserializeRawToObject(data, FormatterAssemblyStyle.Simple);
// Since there's no checksum, it's possible we changed data that didn't corrupt the instance
}
catch (ArgumentOutOfRangeException) { }
catch (ArrayTypeMismatchException) { }
catch (DecoderFallbackException) { }
catch (FormatException) { }
catch (IndexOutOfRangeException) { }
catch (InvalidCastException) { }
catch (OutOfMemoryException) { }
catch (OverflowException) { }
catch (NullReferenceException) { }
catch (SerializationException) { }
catch (TargetInvocationException) { }
catch (ArgumentException) { }
catch (FileLoadException) { }
}
[Fact]
public void Deserialize_EndOfStream_ThrowsException()
{
var f = new BinaryFormatter();
var s = new MemoryStream();
f.Serialize(s, 1024);
for (long i = s.Length - 1; i >= 0; i--)
{
s.Position = 0;
var data = new byte[i];
Assert.Equal(data.Length, s.Read(data, 0, data.Length));
Assert.Throws<SerializationException>(() => f.Deserialize(new MemoryStream(data)));
}
}
[Theory]
[MemberData(nameof(CrossProcessObjects_MemberData))]
public void Roundtrip_CrossProcess(object obj)
{
string outputPath = GetTestFilePath();
string inputPath = GetTestFilePath();
// Serialize out to a file
using (FileStream fs = File.OpenWrite(outputPath))
{
new BinaryFormatter().Serialize(fs, obj);
}
// In another process, deserialize from that file and serialize to another
RemoteInvoke((remoteInput, remoteOutput) =>
{
Assert.False(File.Exists(remoteOutput));
using (FileStream input = File.OpenRead(remoteInput))
using (FileStream output = File.OpenWrite(remoteOutput))
{
var b = new BinaryFormatter();
b.Serialize(output, b.Deserialize(input));
return SuccessExitCode;
}
}, outputPath, inputPath).Dispose();
// Deserialize what the other process serialized and compare it to the original
using (FileStream fs = File.OpenRead(inputPath))
{
object deserialized = new BinaryFormatter().Deserialize(fs);
Assert.Equal(obj, deserialized);
}
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, ".NET Framework fails when serializing arrays with non-zero lower bounds")]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "UAPAOT does not support non-zero lower bounds")]
public void Roundtrip_ArrayContainingArrayAtNonZeroLowerBound()
{
FormatterClone(Array.CreateInstance(typeof(uint[]), new[] { 5 }, new[] { 1 }));
}
}
}
| |
/*
* Created by SharpDevelop.
* User: Anthony.Mason
* Date: 5/8/2007
* Time: 8:14 AM
*
*/
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Configuration;
using LibUSBLauncher;
namespace SharpLauncher
{
/// <summary>
/// Form to change the settings in the application.
/// </summary>
public partial class SettingsForm : BaseForm
{
#region Private Data
private Configuration config = null;
private bool _cameraSettingsChanged = false;
#endregion
#region Constructor
/// <summary>
/// Construcor.
/// </summary>
/// <param name="conf">The configuration file passed in from the main form.</param>
public SettingsForm(Configuration conf)
{
InitializeComponent();
config = conf;
this.Refresh();
}
#endregion
#region Event Handlers
/// <summary>
/// Called when the Refresh Rate text box value changes
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void txtRefreshRate_TextChanged(object sender, EventArgs e)
{
int num;
try
{
num = Convert.ToInt32(this.txtRefreshRate.Text);
this.errorProvider1.SetError(this.txtRefreshRate,"");
}
catch(Exception e1)
{
num = 20;
this.errorProvider1.SetError(this.txtRefreshRate,"This is not a valid value");
Log.Instance.Out(e1);
}
config.AppSettings.Settings[Constants.Settings.WEBCAM_REFRESH_RATE].Value = num.ToString();
_cameraSettingsChanged = true;
}
/// <summary>
/// Called when the Prime After Fire checkbox is clicked or unclicked
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void ChkPrimeCheckedChanged(object sender, EventArgs e)
{
config.AppSettings.Settings[Constants.Settings.PRIME_AIRTANK].Value = this.chkPrime.Checked ? "Y" : "N";
}
/// <summary>
/// Called when the camera height text box value changes
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void TxtCamWidthTextChanged(object sender, EventArgs e)
{
try
{
int x = Convert.ToInt32(this.txtCamWidth.Text);
}
catch(Exception e1)
{
Log.Instance.Out(e1);
this.errorProvider1.SetError(this.txtCamWidth,"Camera Width must be a valid number");
return;
}
config.AppSettings.Settings[Constants.Settings.CAMERA_WIDTH].Value = this.txtCamWidth.Text;
_cameraSettingsChanged = true;
}
/// <summary>
/// Called when the camera height text boxes value changes
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void TxtCamHeightTextChanged(object sender, EventArgs e)
{
try
{
int x = Convert.ToInt32(this.txtCamHeight.Text);
}
catch(Exception e1)
{
Log.Instance.Out(e1);
this.errorProvider1.SetError(this.txtCamWidth,"Camera Height must be a valid number");
return;
}
config.AppSettings.Settings[Constants.Settings.CAMERA_HEIGHT].Value = this.txtCamHeight.Text;
_cameraSettingsChanged = true;
}
/// <summary>
/// Called when the Default button is clicked
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void BtnDefaultClick(object sender, EventArgs e)
{
this.resetToDefault();
this.Refresh();
}
/// <summary>
/// Called when Ok is clicked.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void BtnOKClick(object sender, EventArgs e)
{
this.Close();
}
#endregion
#region Overrides
/// <summary>
/// Refreshes the form and sets loads the settings from file.
/// </summary>
public override void Refresh()
{
string rocketReset,refreshRate,primeTank,camWidth,camHeight, candidShots, candidShotsMS;
rocketReset = config.AppSettings.Settings[Constants.Settings.RESET_LAUNCHER_ON_START].Value;
refreshRate = config.AppSettings.Settings[Constants.Settings.WEBCAM_REFRESH_RATE].Value;
primeTank = config.AppSettings.Settings[Constants.Settings.PRIME_AIRTANK].Value;
camWidth = config.AppSettings.Settings[Constants.Settings.CAMERA_WIDTH].Value;
camHeight = config.AppSettings.Settings[Constants.Settings.CAMERA_HEIGHT].Value;
candidShots = config.AppSettings.Settings[Constants.Settings.CANDID_SHOTS].Value;
candidShotsMS = config.AppSettings.Settings[Constants.Settings.CANDID_SHOTS_TIMING].Value;
this.txtRefreshRate.Text = refreshRate;
this.fillCheckBox(primeTank,this.chkPrime);
this.txtCamWidth.Text = camWidth;
this.txtCamHeight.Text = camHeight;
this.txtCandidShots.Text = candidShots;
this.txtCandidShotsMS.Text = candidShotsMS;
}
#endregion
#region Properties
/// <summary>
/// Tells the main form whether or not to refresh the camera's image
/// </summary>
public bool CameraSettingsChanged
{
get { return _cameraSettingsChanged; }
}
#endregion
#region Utility Functions
/// <summary>
/// This is used to make it easier to set checkboxes based on the setting result
/// </summary>
/// <param name="setting"></param>
/// <param name="box"></param>
private void fillCheckBox(string setting, CheckBox box)
{
if(setting == null || setting == "" || setting == "N")
box.Checked = false;
else
box.Checked = true;
}
/// <summary>
/// Resets all settings back to their default value as defined in Constants.Settings struct.
/// </summary>
private void resetToDefault()
{
config.AppSettings.Settings[Constants.Settings.CAMERA_HEIGHT].Value = Constants.Defaults.CAMERA_HEIGHT;
config.AppSettings.Settings[Constants.Settings.CAMERA_WIDTH].Value = Constants.Defaults.CAMERA_WIDTH;
config.AppSettings.Settings[Constants.Settings.IMAGE_NUMBER].Value = Constants.Defaults.IMAGE_NUMBER;
config.AppSettings.Settings[Constants.Settings.PRIME_AIRTANK].Value = Constants.Defaults.PRIME_AIRTANK;
config.AppSettings.Settings[Constants.Settings.RESET_LAUNCHER_ON_START].Value = Constants.Defaults.RESET_LAUNCHER_ON_START;
config.AppSettings.Settings[Constants.Settings.WEBCAM_ON_START].Value = Constants.Defaults.WEBCAM_ON_START;
config.AppSettings.Settings[Constants.Settings.WEBCAM_REFRESH_RATE].Value = Constants.Defaults.WEBCAM_REFRESH_RATE;
config.AppSettings.Settings[Constants.Settings.CANDID_SHOTS].Value = Constants.Defaults.CANDID_SHOTS;
config.AppSettings.Settings[Constants.Settings.CANDID_SHOTS_TIMING].Value = Constants.Defaults.CANDID_SHOTS_TIMING;
}
#endregion
void TxtCandidShotsTextChanged(object sender, EventArgs e)
{
if(!checkValidNumberRange(this.txtCandidShots.Text,0,20))
{
this.errorProvider1.SetError(this.txtCandidShots,"Must be a valid number between 0 and 20");
return;
}
else
{
this.errorProvider1.SetError(this.txtCandidShots,"");
config.AppSettings.Settings[Constants.Settings.CANDID_SHOTS].Value = this.txtCandidShots.Text;
}
}
void TxtCandidShotsMSTextChanged(object sender, EventArgs e)
{
if(!checkValidNumberRange(this.txtCandidShotsMS.Text,100,5000))
{
this.errorProvider1.SetError(this.txtCandidShotsMS,"Must be a valid number between 100 and 5000");
return;
}
else
{
this.errorProvider1.SetError(this.txtCandidShotsMS,"");
config.AppSettings.Settings[Constants.Settings.CANDID_SHOTS_TIMING].Value = this.txtCandidShotsMS.Text;
}
}
/// <summary>
/// Checks to see if a string is a valid integer, and that it is between the range specified by low and high (inclusive)
/// </summary>
/// <param name="number"></param>
/// <param name="low"></param>
/// <param name="high"></param>
/// <returns></returns>
private bool checkValidNumberRange(string number,int low, int high)
{
int num = 0;
try
{
num = Convert.ToInt32(number);
}
catch(Exception e)
{
Log.Instance.Out(e);
return false;
}
if(num < low || num > high)
return false;
return true;
}
}
}
| |
// Copyright 2015 XLGAMES Inc.
//
// Distributed under the MIT License (See
// accompanying file "LICENSE" or the website
// http://www.opensource.org/licenses/mit-license.php)
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Sce.Atf;
using Sce.Atf.Adaptation;
using Sce.Atf.Applications;
using Sce.Atf.Controls;
using Sce.Atf.Controls.Adaptable;
#pragma warning disable 0649 // Field '...' is never assigned to, and will always have its default value null
namespace MaterialTool
{
[Export(typeof(IDocumentClient))]
[Export(typeof(Editor))]
[Export(typeof(IInitializable))]
[PartCreationPolicy(CreationPolicy.Shared)]
public class Editor : IDocumentClient, IControlHostClient, IInitializable
{
[ImportingConstructor]
public Editor(
IControlHostService controlHostService,
ICommandService commandService,
IContextRegistry contextRegistry,
IDocumentRegistry documentRegistry,
IDocumentService documentService,
LayerLister layerLister)
{
m_controlHostService = controlHostService;
m_commandService = commandService;
m_contextRegistry = contextRegistry;
m_documentRegistry = documentRegistry;
m_documentService = documentService;
m_layerLister = layerLister;
// string initialDirectory = Path.Combine(Directory.GetCurrentDirectory(), "..\\..\\..\\..\\components\\wws_atf\\Samples\\CircuitEditor\\data");
// EditorInfo.InitialDirectory = initialDirectory;
}
private IControlHostService m_controlHostService;
private ICommandService m_commandService;
private IContextRegistry m_contextRegistry;
private IDocumentRegistry m_documentRegistry;
private IDocumentService m_documentService;
private LayerLister m_layerLister;
[Import(AllowDefault = true)]
private IStatusService m_statusService = null;
[Import(AllowDefault = true)]
private ISettingsService m_settingsService = null;
[Import]
private IFileDialogService m_fileDialogService = null;
[ImportMany]
private IEnumerable<Lazy<IContextMenuCommandProvider>> m_contextMenuCommandProviders = null;
// scripting related members
[Import(AllowDefault = true)]
private ScriptingService m_scriptingService = null;
#region IInitializable
void IInitializable.Initialize()
{
if (m_scriptingService != null)
{
// load this assembly into script domain.
m_scriptingService.LoadAssembly(GetType().Assembly);
m_scriptingService.ImportAllTypes("CircuitEditorSample");
m_scriptingService.ImportAllTypes("Sce.Atf.Controls.Adaptable.Graphs");
m_scriptingService.SetVariable("editor", this);
m_scriptingService.SetVariable("layerLister", m_layerLister);
m_contextRegistry.ActiveContextChanged += delegate
{
var editingContext = m_contextRegistry.GetActiveContext<DiagramEditingContext>();
var viewContext = m_contextRegistry.GetActiveContext<Controls.ViewingContext>();
IHistoryContext hist = m_contextRegistry.GetActiveContext<IHistoryContext>();
m_scriptingService.SetVariable("editingContext", editingContext);
m_scriptingService.SetVariable("view", viewContext);
m_scriptingService.SetVariable("hist", hist);
};
// attach tweakable bridge for accessing console variables
m_scriptingService.SetVariable("cv", new GUILayer.TweakableBridge());
}
if (m_settingsService != null)
{
// var settings = new[]
// {
// new BoundPropertyDescriptor(typeof (CircuitDefaultStyle),
// () => CircuitDefaultStyle.EdgeStyle,
// "Wire Style".Localize(), "Circuit Editor".Localize(),
// "Default Edge Style".Localize()),
// };
// m_settingsService.RegisterUserSettings("Circuit Editor", settings);
// m_settingsService.RegisterSettings(this, settings);
}
// We need to make sure there is a material set to the active
// material context... If there is none, we must create a new
// untitled material, and set that...
if (_activeMaterialContext.MaterialName == null)
_activeMaterialContext.MaterialName = GUILayer.RawMaterial.CreateUntitled().Initializer;
}
#endregion
#region IDocumentClient Members
public DocumentClientInfo Info { get { return EditorInfo; } }
public static DocumentClientInfo EditorInfo =
new DocumentClientInfo(
"Shader Graph".Localize(),
new string[] { ".tech", ".sh", ".hlsl", ".txt" },
null, null, false)
{ DefaultExtension = ".tech" };
public bool CanOpen(Uri uri) { return EditorInfo.IsCompatibleUri(uri); }
public IDocument Open(Uri uri)
{
var underlyingDoc = _exportProvider.GetExport<NodeEditorCore.IDiagramDocument>().Value;
underlyingDoc.ViewModel = new HyperGraph.GraphModel();
underlyingDoc.ViewModel.CompatibilityStrategy = _nodeFactory.CreateCompatibilityStrategy();
underlyingDoc.GraphContext = new ShaderPatcherLayer.NodeGraphContext();
// When creating a new document, we'll pass through here with a file that
// doesn't exist... So let's check if we need to load it now...
if (File.Exists(uri.LocalPath))
underlyingDoc.Load(uri);
underlyingDoc.GraphContext.DefaultsMaterial = _activeMaterialContext.MaterialName;
underlyingDoc.GraphContext.PreviewModelFile = "game/model/galleon/galleon.dae";
var doc = new DiagramDocument(underlyingDoc, uri) { NodeFactory = _nodeFactory };
var control = _exportProvider.GetExport<Controls.IDiagramControl>().Value;
control.SetContext(doc);
// Create a control for the new document, and register it!
_controlRegistry.RegisterControl(
doc, control.As<Control>(),
new ControlInfo(Path.GetFileName(uri.LocalPath), uri.LocalPath, StandardControlGroup.Center) { IsDocument = true },
this);
return doc;
}
public void Show(IDocument document)
{
// Our viewing context is independent of the document... we would need to search through all of the
// controls to find one that is open to this document...?
var ctrl = _controlRegistry.DiagramControls.Where(x => x.Key == document).FirstOrDefault();
if (ctrl.Key == document)
m_controlHostService.Show(ctrl.Value.First);
}
public void Save(IDocument document, Uri uri)
{
var doc = (DiagramDocument)document;
doc.UnderlyingDocument.Save(uri);
doc.Uri = uri;
}
public void Close(IDocument document)
{
m_documentRegistry.Remove(document);
}
#endregion
#region IControlHostClient Members
public void Activate(Control control)
{
AdaptableControl adaptableControl = (AdaptableControl)control;
var context = adaptableControl.ContextAs<Controls.AdaptableSet>();
if (context != null)
{
m_contextRegistry.ActiveContext = context;
var circuitDocument = context.As<DiagramDocument>();
if (circuitDocument != null)
m_documentRegistry.ActiveDocument = circuitDocument;
}
}
public void Deactivate(Control control) {}
public bool Close(Control control)
{
var adaptableControl = (AdaptableControl)control;
bool closed = true;
var doc = adaptableControl.ContextAs<DiagramDocument>();
if (doc != null)
{
closed = m_documentService.Close(doc);
if (closed)
Close(doc);
}
else
{
// We don't care if the control was already unregistered. 'closed' should be true.
_controlRegistry.UnregisterControl(control);
}
return closed;
}
#endregion
/// <summary>
/// Gets and sets a string to be used as the initial directory for the open/save dialog box
/// regardless of whatever directory the user may have previously navigated to. The default
/// value is null. Set to null to cancel this behavior.</summary>
public string InitialDirectory
{
get { return m_fileDialogService.ForcedInitialDirectory; }
set { m_fileDialogService.ForcedInitialDirectory = value; }
}
private void control_HoverStarted(object sender, HoverEventArgs<object, object> e)
{
_hoverForm = GetHoverForm(e);
}
private HoverBase GetHoverForm(HoverEventArgs<object, object> e)
{
HoverBase result = CreateHoverForm(e);
if (result != null)
{
Point p = Control.MousePosition;
result.Location = new Point(p.X - (result.Width + 12), p.Y + 12);
result.ShowWithoutFocus();
}
return result;
}
// create hover form for module or connection
private HoverBase CreateHoverForm(HoverEventArgs<object, object> e)
{
// StringBuilder sb = new StringBuilder();
//
// var hoverItem = e.Object;
// var hoverPart = e.Part;
//
// if (e.SubPart.Is<GroupPin>())
// {
// sb.Append(e.SubPart.Cast<GroupPin>().Name);
// CircuitUtil.GetDomNodeName(e.SubPart.Cast<DomNode>());
// }
// else if (e.SubObject.Is<DomNode>())
// {
// CircuitUtil.GetDomNodeName(e.SubObject.Cast<DomNode>());
// }
// else if (hoverPart.Is<GroupPin>())
// {
// sb.Append(hoverPart.Cast<GroupPin>().Name);
// CircuitUtil.GetDomNodeName(hoverPart.Cast<DomNode>());
// }
// else if (hoverItem.Is<DomNode>())
// {
// CircuitUtil.GetDomNodeName(hoverItem.Cast<DomNode>());
// }
//
// HoverBase result = null;
// if (sb.Length > 0) // remove trailing '\n'
// {
// //sb.Length = sb.Length - 1;
// result = new HoverLabel(sb.ToString());
// }
//
// return result;
return null;
}
private void control_HoverStopped(object sender, EventArgs e)
{
if (_hoverForm != null)
{
_hoverForm.Controls.Clear();
_hoverForm.Close();
_hoverForm.Dispose();
}
}
[Import]
private DiagramControlRegistry _controlRegistry = null;
private HoverBase _hoverForm;
[Import]
private ExportProvider _exportProvider;
[Import]
private NodeEditorCore.IShaderFragmentNodeCreator _nodeFactory;
[Import]
private ControlsLibraryExt.Material.ActiveMaterialContext _activeMaterialContext;
}
}
| |
/********************************************************************
The Multiverse Platform is made available under the MIT License.
Copyright (c) 2012 The Multiverse Foundation
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify,
merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
OR OTHER DEALINGS IN THE SOFTWARE.
*********************************************************************/
namespace AssetImporter
{
partial class Importer
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Importer));
this.assetNameTextBox = new System.Windows.Forms.TextBox();
this.assetTypeComboBox = new System.Windows.Forms.ComboBox();
this.openSourceFileDialog = new System.Windows.Forms.OpenFileDialog();
this.statusStrip = new System.Windows.Forms.StatusStrip();
this.repositoryLabel = new System.Windows.Forms.ToolStripStatusLabel();
this.openAssetDialog = new System.Windows.Forms.OpenFileDialog();
this.saveAssetDialog = new System.Windows.Forms.SaveFileDialog();
this.categoryPanel = new System.Windows.Forms.Panel();
this.categoryComboBox = new System.Windows.Forms.ComboBox();
this.label3 = new System.Windows.Forms.Label();
this.menuStrip1 = new System.Windows.Forms.MenuStrip();
this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.newAssetToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.openAssetToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.saveAssetToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.saveAssetAsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.designateRepositoryToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.helpToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.launchOnlineHelpMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.submitFeedbackMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.releaseNotesMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.aboutAssetImporterToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStrip1 = new System.Windows.Forms.ToolStrip();
this.newAssetToolStripButton = new System.Windows.Forms.ToolStripButton();
this.openAssetToolStripButton = new System.Windows.Forms.ToolStripButton();
this.saveAssetToolStripButton = new System.Windows.Forms.ToolStripButton();
this.designateRepositoryToolStripButton = new System.Windows.Forms.ToolStripButton();
this.filesLabel = new System.Windows.Forms.Label();
this.filesListBox = new System.Windows.Forms.ListBox();
this.label4 = new System.Windows.Forms.Label();
this.trashPictureBox = new System.Windows.Forms.PictureBox();
this.descriptionLabel = new System.Windows.Forms.Label();
this.descriptionTextBox = new System.Windows.Forms.TextBox();
this.label6 = new System.Windows.Forms.Label();
this.label7 = new System.Windows.Forms.Label();
this.propertyEditorButton = new System.Windows.Forms.Button();
this.statusStrip.SuspendLayout();
this.categoryPanel.SuspendLayout();
this.menuStrip1.SuspendLayout();
this.toolStrip1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.trashPictureBox)).BeginInit();
this.SuspendLayout();
//
// assetNameTextBox
//
this.assetNameTextBox.Location = new System.Drawing.Point(111, 133);
this.assetNameTextBox.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.assetNameTextBox.Name = "assetNameTextBox";
this.assetNameTextBox.Size = new System.Drawing.Size(409, 22);
this.assetNameTextBox.TabIndex = 6;
this.assetNameTextBox.TextChanged += new System.EventHandler(this.assetNameTextBox_TextChanged);
//
// assetTypeComboBox
//
this.assetTypeComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.assetTypeComboBox.FormattingEnabled = true;
this.assetTypeComboBox.Location = new System.Drawing.Point(111, 97);
this.assetTypeComboBox.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.assetTypeComboBox.Name = "assetTypeComboBox";
this.assetTypeComboBox.Size = new System.Drawing.Size(199, 24);
this.assetTypeComboBox.TabIndex = 8;
this.assetTypeComboBox.SelectedIndexChanged += new System.EventHandler(this.assetTypeComboBox_SelectedIndexChanged);
//
// statusStrip
//
this.statusStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.repositoryLabel});
this.statusStrip.Location = new System.Drawing.Point(0, 675);
this.statusStrip.Name = "statusStrip";
this.statusStrip.Padding = new System.Windows.Forms.Padding(1, 0, 19, 0);
this.statusStrip.Size = new System.Drawing.Size(1084, 22);
this.statusStrip.TabIndex = 9;
//
// repositoryLabel
//
this.repositoryLabel.Name = "repositoryLabel";
this.repositoryLabel.Size = new System.Drawing.Size(0, 17);
//
// openAssetDialog
//
this.openAssetDialog.DefaultExt = "asset";
this.openAssetDialog.Filter = "Asset Files (*.asset)|*.asset|All Files (*.*)|*.*";
//
// saveAssetDialog
//
this.saveAssetDialog.Filter = "Asset Files (*.asset)|*.asset|All Files (*.*)|*.*";
//
// categoryPanel
//
this.categoryPanel.Controls.Add(this.categoryComboBox);
this.categoryPanel.Controls.Add(this.label3);
this.categoryPanel.Location = new System.Drawing.Point(708, 73);
this.categoryPanel.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.categoryPanel.Name = "categoryPanel";
this.categoryPanel.Size = new System.Drawing.Size(273, 48);
this.categoryPanel.TabIndex = 14;
//
// categoryComboBox
//
this.categoryComboBox.FormattingEnabled = true;
this.categoryComboBox.Location = new System.Drawing.Point(76, 11);
this.categoryComboBox.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.categoryComboBox.Name = "categoryComboBox";
this.categoryComboBox.Size = new System.Drawing.Size(188, 24);
this.categoryComboBox.TabIndex = 1;
this.categoryComboBox.SelectedIndexChanged += new System.EventHandler(this.categoryComboBox_SelectedIndexChanged);
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(4, 15);
this.label3.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(69, 17);
this.label3.TabIndex = 0;
this.label3.Text = "Category:";
//
// menuStrip1
//
this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.fileToolStripMenuItem,
this.helpToolStripMenuItem});
this.menuStrip1.Location = new System.Drawing.Point(0, 0);
this.menuStrip1.Name = "menuStrip1";
this.menuStrip1.Padding = new System.Windows.Forms.Padding(8, 2, 0, 2);
this.menuStrip1.Size = new System.Drawing.Size(1084, 26);
this.menuStrip1.TabIndex = 15;
this.menuStrip1.Text = "menuStrip1";
//
// fileToolStripMenuItem
//
this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.newAssetToolStripMenuItem,
this.openAssetToolStripMenuItem,
this.saveAssetToolStripMenuItem,
this.saveAssetAsToolStripMenuItem,
this.designateRepositoryToolStripMenuItem,
this.exitToolStripMenuItem});
this.fileToolStripMenuItem.Name = "fileToolStripMenuItem";
this.fileToolStripMenuItem.Size = new System.Drawing.Size(40, 22);
this.fileToolStripMenuItem.Text = "&File";
//
// newAssetToolStripMenuItem
//
this.newAssetToolStripMenuItem.Name = "newAssetToolStripMenuItem";
this.newAssetToolStripMenuItem.Size = new System.Drawing.Size(243, 22);
this.newAssetToolStripMenuItem.Text = "&New Asset";
this.newAssetToolStripMenuItem.Click += new System.EventHandler(this.newAssetToolStripMenuItem_Click);
//
// openAssetToolStripMenuItem
//
this.openAssetToolStripMenuItem.Name = "openAssetToolStripMenuItem";
this.openAssetToolStripMenuItem.Size = new System.Drawing.Size(243, 22);
this.openAssetToolStripMenuItem.Text = "&Open Asset...";
this.openAssetToolStripMenuItem.Click += new System.EventHandler(this.openAssetToolStripMenuItem_Click);
//
// saveAssetToolStripMenuItem
//
this.saveAssetToolStripMenuItem.Name = "saveAssetToolStripMenuItem";
this.saveAssetToolStripMenuItem.Size = new System.Drawing.Size(243, 22);
this.saveAssetToolStripMenuItem.Text = "&Save Asset";
this.saveAssetToolStripMenuItem.Click += new System.EventHandler(this.saveAssetToolStripMenuItem_Click);
//
// saveAssetAsToolStripMenuItem
//
this.saveAssetAsToolStripMenuItem.Name = "saveAssetAsToolStripMenuItem";
this.saveAssetAsToolStripMenuItem.Size = new System.Drawing.Size(243, 22);
this.saveAssetAsToolStripMenuItem.Text = "Save Asset &As...";
this.saveAssetAsToolStripMenuItem.Click += new System.EventHandler(this.saveAssetAsToolStripMenuItem_Click);
//
// designateRepositoryToolStripMenuItem
//
this.designateRepositoryToolStripMenuItem.Name = "designateRepositoryToolStripMenuItem";
this.designateRepositoryToolStripMenuItem.Size = new System.Drawing.Size(243, 22);
this.designateRepositoryToolStripMenuItem.Text = "&Designate Repository...";
this.designateRepositoryToolStripMenuItem.Click += new System.EventHandler(this.designateRepositoryToolStripMenuItem_Click);
//
// exitToolStripMenuItem
//
this.exitToolStripMenuItem.Name = "exitToolStripMenuItem";
this.exitToolStripMenuItem.Size = new System.Drawing.Size(243, 22);
this.exitToolStripMenuItem.Text = "&Exit";
this.exitToolStripMenuItem.Click += new System.EventHandler(this.exitToolStripMenuItem_Click);
//
// helpToolStripMenuItem
//
this.helpToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.launchOnlineHelpMenuItem,
this.submitFeedbackMenuItem,
this.releaseNotesMenuItem,
this.aboutAssetImporterToolStripMenuItem});
this.helpToolStripMenuItem.Name = "helpToolStripMenuItem";
this.helpToolStripMenuItem.Size = new System.Drawing.Size(48, 22);
this.helpToolStripMenuItem.Text = "&Help";
//
// launchOnlineHelpMenuItem
//
this.launchOnlineHelpMenuItem.Name = "launchOnlineHelpMenuItem";
this.launchOnlineHelpMenuItem.Size = new System.Drawing.Size(263, 22);
this.launchOnlineHelpMenuItem.Text = "Launch Online Help";
this.launchOnlineHelpMenuItem.Click += new System.EventHandler(this.launchOnlineHelpMenuItem_Clicked);
//
// submitFeedbackMenuItem
//
this.submitFeedbackMenuItem.Name = "submitFeedbackMenuItem";
this.submitFeedbackMenuItem.Size = new System.Drawing.Size(263, 22);
this.submitFeedbackMenuItem.Text = "Submit Feedback or a Bug";
this.submitFeedbackMenuItem.Click += new System.EventHandler(this.submitFeedbackMenuItem_Clicked);
//
// releaseNotesMenuItem
//
this.releaseNotesMenuItem.Name = "releaseNotesMenuItem";
this.releaseNotesMenuItem.Size = new System.Drawing.Size(263, 22);
this.releaseNotesMenuItem.Text = "Release Notes";
this.releaseNotesMenuItem.Click += new System.EventHandler(this.releaseNotesMenuItem_Clicked);
//
// aboutAssetImporterToolStripMenuItem
//
this.aboutAssetImporterToolStripMenuItem.Name = "aboutAssetImporterToolStripMenuItem";
this.aboutAssetImporterToolStripMenuItem.Size = new System.Drawing.Size(263, 22);
this.aboutAssetImporterToolStripMenuItem.Text = "&About Asset Importer...";
this.aboutAssetImporterToolStripMenuItem.Click += new System.EventHandler(this.aboutAssetImporterToolStripMenuItem_Click);
//
// toolStrip1
//
this.toolStrip1.ImageScalingSize = new System.Drawing.Size(36, 32);
this.toolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.newAssetToolStripButton,
this.openAssetToolStripButton,
this.saveAssetToolStripButton,
this.designateRepositoryToolStripButton});
this.toolStrip1.Location = new System.Drawing.Point(0, 26);
this.toolStrip1.Name = "toolStrip1";
this.toolStrip1.Size = new System.Drawing.Size(1084, 39);
this.toolStrip1.TabIndex = 16;
this.toolStrip1.Text = "toolStrip1";
//
// newAssetToolStripButton
//
this.newAssetToolStripButton.AutoSize = false;
this.newAssetToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.newAssetToolStripButton.Image = ((System.Drawing.Image)(resources.GetObject("newAssetToolStripButton.Image")));
this.newAssetToolStripButton.ImageAlign = System.Drawing.ContentAlignment.TopCenter;
this.newAssetToolStripButton.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this.newAssetToolStripButton.ImageTransparentColor = System.Drawing.SystemColors.Control;
this.newAssetToolStripButton.Name = "newAssetToolStripButton";
this.newAssetToolStripButton.Size = new System.Drawing.Size(38, 35);
this.newAssetToolStripButton.Text = "New";
this.newAssetToolStripButton.TextAlign = System.Drawing.ContentAlignment.BottomCenter;
this.newAssetToolStripButton.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageAboveText;
this.newAssetToolStripButton.ToolTipText = "Create New Asset";
this.newAssetToolStripButton.Click += new System.EventHandler(this.newAssetToolStripButton_Click);
//
// openAssetToolStripButton
//
this.openAssetToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.openAssetToolStripButton.Image = ((System.Drawing.Image)(resources.GetObject("openAssetToolStripButton.Image")));
this.openAssetToolStripButton.ImageAlign = System.Drawing.ContentAlignment.TopCenter;
this.openAssetToolStripButton.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this.openAssetToolStripButton.ImageTransparentColor = System.Drawing.SystemColors.ControlLight;
this.openAssetToolStripButton.Name = "openAssetToolStripButton";
this.openAssetToolStripButton.Size = new System.Drawing.Size(38, 36);
this.openAssetToolStripButton.Text = "Open";
this.openAssetToolStripButton.TextAlign = System.Drawing.ContentAlignment.BottomCenter;
this.openAssetToolStripButton.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageAboveText;
this.openAssetToolStripButton.ToolTipText = "Open Asset";
this.openAssetToolStripButton.Click += new System.EventHandler(this.openAssetToolStripButton_Click);
//
// saveAssetToolStripButton
//
this.saveAssetToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.saveAssetToolStripButton.Image = ((System.Drawing.Image)(resources.GetObject("saveAssetToolStripButton.Image")));
this.saveAssetToolStripButton.ImageAlign = System.Drawing.ContentAlignment.TopCenter;
this.saveAssetToolStripButton.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this.saveAssetToolStripButton.ImageTransparentColor = System.Drawing.SystemColors.ControlLight;
this.saveAssetToolStripButton.Name = "saveAssetToolStripButton";
this.saveAssetToolStripButton.Size = new System.Drawing.Size(36, 36);
this.saveAssetToolStripButton.Text = "Save";
this.saveAssetToolStripButton.TextAlign = System.Drawing.ContentAlignment.BottomCenter;
this.saveAssetToolStripButton.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageAboveText;
this.saveAssetToolStripButton.ToolTipText = "Save Asset";
this.saveAssetToolStripButton.Click += new System.EventHandler(this.saveAssetToolStripButton_Click);
//
// designateRepositoryToolStripButton
//
this.designateRepositoryToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.designateRepositoryToolStripButton.Image = ((System.Drawing.Image)(resources.GetObject("designateRepositoryToolStripButton.Image")));
this.designateRepositoryToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.designateRepositoryToolStripButton.Name = "designateRepositoryToolStripButton";
this.designateRepositoryToolStripButton.Size = new System.Drawing.Size(40, 36);
this.designateRepositoryToolStripButton.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageAboveText;
this.designateRepositoryToolStripButton.ToolTipText = "Designate Asset Repository Directory";
this.designateRepositoryToolStripButton.Visible = false;
this.designateRepositoryToolStripButton.Click += new System.EventHandler(this.designateRepositoryToolStripButton_Click);
//
// filesLabel
//
this.filesLabel.Location = new System.Drawing.Point(17, 190);
this.filesLabel.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.filesLabel.Name = "filesLabel";
this.filesLabel.Size = new System.Drawing.Size(290, 35);
this.filesLabel.TabIndex = 17;
this.filesLabel.Text = "Files";
//
// filesListBox
//
this.filesListBox.FormattingEnabled = true;
this.filesListBox.ItemHeight = 16;
this.filesListBox.Location = new System.Drawing.Point(20, 255);
this.filesListBox.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.filesListBox.Name = "filesListBox";
this.filesListBox.SelectionMode = System.Windows.Forms.SelectionMode.MultiExtended;
this.filesListBox.Size = new System.Drawing.Size(287, 404);
this.filesListBox.TabIndex = 18;
this.filesListBox.MouseUp += new System.Windows.Forms.MouseEventHandler(this.anyListBox_MouseUp);
this.filesListBox.MouseMove += new System.Windows.Forms.MouseEventHandler(this.anyListBox_MouseMove);
this.filesListBox.MouseDown += new System.Windows.Forms.MouseEventHandler(this.anyListBox_MouseDown);
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(17, 228);
this.label4.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(295, 17);
this.label4.TabIndex = 19;
this.label4.Text = "(Drag and drop onto listboxes and text boxes)";
//
// trashPictureBox
//
this.trashPictureBox.AllowDrop = true;
this.trashPictureBox.Image = global::AssetImporter.Properties.Resources.image4;
this.trashPictureBox.Location = new System.Drawing.Point(1007, 69);
this.trashPictureBox.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.trashPictureBox.Name = "trashPictureBox";
this.trashPictureBox.Size = new System.Drawing.Size(53, 84);
this.trashPictureBox.TabIndex = 20;
this.trashPictureBox.TabStop = false;
this.trashPictureBox.DragOver += new System.Windows.Forms.DragEventHandler(this.trashPictureBox_DragOver);
this.trashPictureBox.DragDrop += new System.Windows.Forms.DragEventHandler(this.trashPictureBox_DragDrop);
//
// descriptionLabel
//
this.descriptionLabel.AutoSize = true;
this.descriptionLabel.Location = new System.Drawing.Point(337, 639);
this.descriptionLabel.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.descriptionLabel.Name = "descriptionLabel";
this.descriptionLabel.Size = new System.Drawing.Size(150, 17);
this.descriptionLabel.TabIndex = 21;
this.descriptionLabel.Text = "Description (Optional):";
//
// descriptionTextBox
//
this.descriptionTextBox.Location = new System.Drawing.Point(491, 635);
this.descriptionTextBox.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.descriptionTextBox.Name = "descriptionTextBox";
this.descriptionTextBox.Size = new System.Drawing.Size(568, 22);
this.descriptionTextBox.TabIndex = 22;
this.descriptionTextBox.TextChanged += new System.EventHandler(this.descriptionTextBox_TextChanged);
//
// label6
//
this.label6.AutoSize = true;
this.label6.Location = new System.Drawing.Point(13, 138);
this.label6.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(88, 17);
this.label6.TabIndex = 5;
this.label6.Text = "Asset Name:";
//
// label7
//
this.label7.AutoSize = true;
this.label7.Location = new System.Drawing.Point(19, 102);
this.label7.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.label7.Name = "label7";
this.label7.Size = new System.Drawing.Size(83, 17);
this.label7.TabIndex = 7;
this.label7.Text = "Asset Type:";
//
// propertyEditorButton
//
this.propertyEditorButton.Location = new System.Drawing.Point(708, 132);
this.propertyEditorButton.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.propertyEditorButton.Name = "propertyEditorButton";
this.propertyEditorButton.Size = new System.Drawing.Size(115, 28);
this.propertyEditorButton.TabIndex = 23;
this.propertyEditorButton.Text = "Edit Properties";
this.propertyEditorButton.UseVisualStyleBackColor = true;
this.propertyEditorButton.Click += new System.EventHandler(this.propertyEditorButton_Clicked);
//
// Importer
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1084, 697);
this.Controls.Add(this.propertyEditorButton);
this.Controls.Add(this.descriptionTextBox);
this.Controls.Add(this.descriptionLabel);
this.Controls.Add(this.trashPictureBox);
this.Controls.Add(this.label4);
this.Controls.Add(this.filesListBox);
this.Controls.Add(this.filesLabel);
this.Controls.Add(this.toolStrip1);
this.Controls.Add(this.categoryPanel);
this.Controls.Add(this.statusStrip);
this.Controls.Add(this.menuStrip1);
this.Controls.Add(this.assetTypeComboBox);
this.Controls.Add(this.label7);
this.Controls.Add(this.label6);
this.Controls.Add(this.assetNameTextBox);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MainMenuStrip = this.menuStrip1;
this.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.Name = "Importer";
this.Text = "Asset Importer";
this.Resize += new System.EventHandler(this.Importer_Resize);
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.Importer_FormClosing);
this.statusStrip.ResumeLayout(false);
this.statusStrip.PerformLayout();
this.categoryPanel.ResumeLayout(false);
this.categoryPanel.PerformLayout();
this.menuStrip1.ResumeLayout(false);
this.menuStrip1.PerformLayout();
this.toolStrip1.ResumeLayout(false);
this.toolStrip1.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.trashPictureBox)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.TextBox assetNameTextBox;
private System.Windows.Forms.ComboBox assetTypeComboBox;
private System.Windows.Forms.OpenFileDialog openSourceFileDialog;
private System.Windows.Forms.StatusStrip statusStrip;
private System.Windows.Forms.ToolStripStatusLabel repositoryLabel;
private System.Windows.Forms.OpenFileDialog openAssetDialog;
private System.Windows.Forms.SaveFileDialog saveAssetDialog;
private System.Windows.Forms.Panel categoryPanel;
private System.Windows.Forms.ComboBox categoryComboBox;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.MenuStrip menuStrip1;
private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem newAssetToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem openAssetToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem saveAssetToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem saveAssetAsToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem designateRepositoryToolStripMenuItem;
private System.Windows.Forms.ToolStrip toolStrip1;
private System.Windows.Forms.ToolStripButton newAssetToolStripButton;
private System.Windows.Forms.ToolStripButton openAssetToolStripButton;
private System.Windows.Forms.ToolStripButton saveAssetToolStripButton;
private System.Windows.Forms.ToolStripButton designateRepositoryToolStripButton;
private System.Windows.Forms.Label filesLabel;
private System.Windows.Forms.ListBox filesListBox;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.PictureBox trashPictureBox;
private System.Windows.Forms.Label descriptionLabel;
private System.Windows.Forms.TextBox descriptionTextBox;
private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem helpToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem aboutAssetImporterToolStripMenuItem;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.Label label7;
private System.Windows.Forms.ToolStripMenuItem launchOnlineHelpMenuItem;
private System.Windows.Forms.ToolStripMenuItem submitFeedbackMenuItem;
private System.Windows.Forms.ToolStripMenuItem releaseNotesMenuItem;
private System.Windows.Forms.Button propertyEditorButton;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using Microsoft.Extensions.Options;
using Xunit;
namespace Microsoft.Extensions.DependencyInjection
{
// Integration tests for extension methods on IHealthCheckBuilder
//
// We test the longest overload of each 'family' of Add...Check methods, since they chain to each other.
public class HealthChecksBuilderTest
{
[Fact]
public void AddCheck_Instance()
{
// Arrange
var instance = new DelegateHealthCheck((_) =>
{
return Task.FromResult(HealthCheckResult.Healthy());
});
var services = CreateServices();
services.AddHealthChecks().AddCheck("test", failureStatus: HealthStatus.Degraded,tags: new[] { "tag", }, instance: instance);
var serviceProvider = services.BuildServiceProvider();
// Act
var options = serviceProvider.GetRequiredService<IOptions<HealthCheckServiceOptions>>().Value;
// Assert
var registration = Assert.Single(options.Registrations);
Assert.Equal("test", registration.Name);
Assert.Equal(HealthStatus.Degraded, registration.FailureStatus);
Assert.Equal<string>(new[] { "tag", }, registration.Tags);
Assert.Same(instance, registration.Factory(serviceProvider));
}
[Fact]
public void AddCheck_T_TypeActivated()
{
// Arrange
var services = CreateServices();
services.AddHealthChecks().AddCheck<TestHealthCheck>("test", failureStatus: HealthStatus.Degraded, tags: new[] { "tag", });
var serviceProvider = services.BuildServiceProvider();
// Act
var options = serviceProvider.GetRequiredService<IOptions<HealthCheckServiceOptions>>().Value;
// Assert
var registration = Assert.Single(options.Registrations);
Assert.Equal("test", registration.Name);
Assert.Equal(HealthStatus.Degraded, registration.FailureStatus);
Assert.Equal<string>(new[] { "tag", }, registration.Tags);
Assert.IsType<TestHealthCheck>(registration.Factory(serviceProvider));
}
[Fact]
public void AddCheck_T_Service()
{
// Arrange
var instance = new TestHealthCheck();
var services = CreateServices();
services.AddSingleton(instance);
services.AddHealthChecks().AddCheck<TestHealthCheck>("test", failureStatus: HealthStatus.Degraded, tags: new[] { "tag", });
var serviceProvider = services.BuildServiceProvider();
// Act
var options = serviceProvider.GetRequiredService<IOptions<HealthCheckServiceOptions>>().Value;
// Assert
var registration = Assert.Single(options.Registrations);
Assert.Equal("test", registration.Name);
Assert.Equal(HealthStatus.Degraded, registration.FailureStatus);
Assert.Equal<string>(new[] { "tag", }, registration.Tags);
Assert.Same(instance, registration.Factory(serviceProvider));
}
[Fact]
public void AddTypeActivatedCheck()
{
// Arrange
var services = CreateServices();
services
.AddHealthChecks()
.AddTypeActivatedCheck<TestHealthCheckWithArgs>("test", failureStatus: HealthStatus.Degraded, tags: new[] { "tag", }, args: new object[] { 5, "hi", });
var serviceProvider = services.BuildServiceProvider();
// Act
var options = serviceProvider.GetRequiredService<IOptions<HealthCheckServiceOptions>>().Value;
// Assert
var registration = Assert.Single(options.Registrations);
Assert.Equal("test", registration.Name);
Assert.Equal(HealthStatus.Degraded, registration.FailureStatus);
Assert.Equal<string>(new[] { "tag", }, registration.Tags);
var check = Assert.IsType<TestHealthCheckWithArgs>(registration.Factory(serviceProvider));
Assert.Equal(5, check.I);
Assert.Equal("hi", check.S);
}
[Fact]
public void AddDelegateCheck_NoArg()
{
// Arrange
var services = CreateServices();
services.AddHealthChecks().AddCheck("test", tags: new[] { "tag", }, check: () =>
{
return HealthCheckResult.Healthy();
});
var serviceProvider = services.BuildServiceProvider();
// Act
var options = serviceProvider.GetRequiredService<IOptions<HealthCheckServiceOptions>>().Value;
// Assert
var registration = Assert.Single(options.Registrations);
Assert.Equal("test", registration.Name);
Assert.Equal(HealthStatus.Unhealthy, registration.FailureStatus);
Assert.Equal<string>(new[] { "tag", }, registration.Tags);
Assert.IsType<DelegateHealthCheck>(registration.Factory(serviceProvider));
}
[Fact]
public void AddDelegateCheck_CancellationToken()
{
// Arrange
var services = CreateServices();
services.AddHealthChecks().AddCheck("test", (_) =>
{
return HealthCheckResult.Degraded();
}, tags: new[] { "tag", });
var serviceProvider = services.BuildServiceProvider();
// Act
var options = serviceProvider.GetRequiredService<IOptions<HealthCheckServiceOptions>>().Value;
// Assert
var registration = Assert.Single(options.Registrations);
Assert.Equal("test", registration.Name);
Assert.Equal(HealthStatus.Unhealthy, registration.FailureStatus);
Assert.Equal<string>(new[] { "tag", }, registration.Tags);
Assert.IsType<DelegateHealthCheck>(registration.Factory(serviceProvider));
}
[Fact]
public void AddAsyncDelegateCheck_NoArg()
{
// Arrange
var services = CreateServices();
services.AddHealthChecks().AddAsyncCheck("test", () =>
{
return Task.FromResult(HealthCheckResult.Healthy());
}, tags: new[] { "tag", });
var serviceProvider = services.BuildServiceProvider();
// Act
var options = serviceProvider.GetRequiredService<IOptions<HealthCheckServiceOptions>>().Value;
// Assert
var registration = Assert.Single(options.Registrations);
Assert.Equal("test", registration.Name);
Assert.Equal(HealthStatus.Unhealthy, registration.FailureStatus);
Assert.Equal<string>(new[] { "tag", }, registration.Tags);
Assert.IsType<DelegateHealthCheck>(registration.Factory(serviceProvider));
}
[Fact]
public void AddAsyncDelegateCheck_CancellationToken()
{
// Arrange
var services = CreateServices();
services.AddHealthChecks().AddAsyncCheck("test", (_) =>
{
return Task.FromResult(HealthCheckResult.Unhealthy());
}, tags: new[] { "tag", });
var serviceProvider = services.BuildServiceProvider();
// Act
var options = serviceProvider.GetRequiredService<IOptions<HealthCheckServiceOptions>>().Value;
// Assert
var registration = Assert.Single(options.Registrations);
Assert.Equal("test", registration.Name);
Assert.Equal(HealthStatus.Unhealthy, registration.FailureStatus);
Assert.Equal<string>(new[] { "tag", }, registration.Tags);
Assert.IsType<DelegateHealthCheck>(registration.Factory(serviceProvider));
}
[Fact]
public void ChecksCanBeRegisteredInMultipleCallsToAddHealthChecks()
{
var services = new ServiceCollection();
services
.AddHealthChecks()
.AddAsyncCheck("Foo", () => Task.FromResult(HealthCheckResult.Healthy()));
services
.AddHealthChecks()
.AddAsyncCheck("Bar", () => Task.FromResult(HealthCheckResult.Healthy()));
// Act
var options = services.BuildServiceProvider().GetRequiredService<IOptions<HealthCheckServiceOptions>>();
// Assert
Assert.Collection(
options.Value.Registrations,
actual => Assert.Equal("Foo", actual.Name),
actual => Assert.Equal("Bar", actual.Name));
}
private IServiceCollection CreateServices()
{
var services = new ServiceCollection();
services.AddLogging();
services.AddOptions();
return services;
}
private class TestHealthCheck : IHealthCheck
{
public Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)
{
throw new System.NotImplementedException();
}
}
private class TestHealthCheckWithArgs : IHealthCheck
{
public TestHealthCheckWithArgs(int i, string s)
{
I = i;
S = s;
}
public int I { get; set; }
public string S { get; set; }
public Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)
{
throw new System.NotImplementedException();
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
namespace ICSharpCode.XamlDesigner
{
public static class XamlFormatter
{
public static char IndentChar = ' ';
public static int Indenation = 2;
public static int LengthBeforeNewLine = 60;
static StringBuilder sb;
static int currentColumn;
static int nextColumn;
public static string Format(string xaml)
{
sb = new StringBuilder();
currentColumn = 0;
nextColumn = 0;
try {
var doc = XDocument.Parse(xaml);
WalkContainer(doc);
return sb.ToString();
}
catch {
return xaml;
}
}
static void WalkContainer(XContainer node)
{
foreach (var c in node.Nodes()) {
if (c is XElement) {
WalkElement(c as XElement);
} else {
NewLine();
Append(c.ToString().Trim());
}
}
}
static void WalkElement(XElement e)
{
NewLine();
string prefix1 = e.GetPrefixOfNamespace(e.Name.Namespace);
string name1 = prefix1 == null ? e.Name.LocalName : prefix1 + ":" + e.Name.LocalName;
Append("<" + name1);
List<AttributeString> list = new List<AttributeString>();
int length = name1.Length;
foreach (var a in e.Attributes()) {
string prefix2 = e.GetPrefixOfNamespace(a.Name.Namespace);
var g = new AttributeString() { Name = a.Name, Prefix = prefix2, Value = a.Value };
list.Add(g);
length += g.FinalString.Length;
}
list.Sort(AttributeComparrer.Instance);
if (length > LengthBeforeNewLine) {
nextColumn = currentColumn + 1;
for (int i = 0; i < list.Count; i++) {
if (i > 0) {
NewLine();
}
else {
Append(" ");
}
Append(list[i].FinalString);
}
nextColumn -= name1.Length + 2;
}
else {
foreach (var a in list) {
Append(" " + a.FinalString);
}
}
if (e.Nodes().Count() > 0) {
Append(">");
nextColumn += Indenation;
WalkContainer(e);
nextColumn -= Indenation;
NewLine();
Append("</" + name1 + ">");
}
else {
Append(" />");
}
}
static void NewLine()
{
if (sb.Length > 0) {
sb.AppendLine();
sb.Append(new string(' ', nextColumn));
currentColumn = nextColumn;
}
}
static void Append(string s)
{
sb.Append(s);
currentColumn += s.Length;
}
enum AttributeLayout
{
X,
XmlnsMicrosoft,
Xmlns,
XmlnsWithClr,
SpecialOrder,
ByName,
Attached,
WithPrefix
}
class AttributeString
{
public XName Name;
public string Prefix;
public string Value;
public string LocalName {
get { return Name.LocalName; }
}
public string FinalName {
get {
return Prefix == null ? Name.LocalName : Prefix + ":" + Name.LocalName;
}
}
public string FinalString {
get {
return FinalName + "=\"" + Value + "\"";
}
}
public AttributeLayout GetAttributeLayout()
{
if (Prefix == "xmlns" || LocalName == "xmlns") {
if (Value.StartsWith("http://schemas.microsoft.com")) return AttributeLayout.XmlnsMicrosoft;
if (Value.StartsWith("clr")) return AttributeLayout.XmlnsWithClr;
return AttributeLayout.Xmlns;
}
if (Prefix == "x") return AttributeLayout.X;
if (Prefix != null) return AttributeLayout.WithPrefix;
if (LocalName.Contains(".")) return AttributeLayout.Attached;
if (AttributeComparrer.SpecialOrder.Contains(LocalName)) return AttributeLayout.SpecialOrder;
return AttributeLayout.ByName;
}
}
class AttributeComparrer : IComparer<AttributeString>
{
public static AttributeComparrer Instance = new AttributeComparrer();
public int Compare(AttributeString a1, AttributeString a2)
{
var y1 = a1.GetAttributeLayout();
var y2 = a2.GetAttributeLayout();
if (y1 == y2) {
if (y1 == AttributeLayout.SpecialOrder) {
return
Array.IndexOf(SpecialOrder, a1.LocalName).CompareTo(
Array.IndexOf(SpecialOrder, a2.LocalName));
}
return a1.FinalName.CompareTo(a2.FinalName);
}
return y1.CompareTo(y2);
}
public static string[] SpecialOrder = new string[] {
"Name",
"Content",
"Command",
"Executed",
"CanExecute",
"Width",
"Height",
"Margin",
"HorizontalAlignment",
"VerticalAlignment",
"HorizontalContentAlignment",
"VerticalContentAlignment",
"StartPoint",
"EndPoint",
"Offset",
"Color"
};
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
namespace TestCases.XSSF.Streaming
{
using System;
using System.Collections.Generic;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using NPOI.XSSF.Streaming;
using NUnit.Framework;
/**
* Tests the auto-sizing behaviour of {@link SXSSFSheet} when not all
* rows fit into the memory window size etc.
*
* @see Bug #57450 which reported the original mis-behaviour
*/
[TestFixture]
public class TestAutoSizeColumnTracker
{
private SXSSFSheet sheet;
private SXSSFWorkbook workbook;
private AutoSizeColumnTracker tracker;
private static SortedSet<int> columns;
static TestAutoSizeColumnTracker() {
SortedSet<int> _columns = new SortedSet<int>();
_columns.Add(0);
_columns.Add(1);
_columns.Add(3);
columns = (_columns);
}
private static String SHORT_MESSAGE = "short";
private static String LONG_MESSAGE = "This is a test of a long message! This is a test of a long message!";
[SetUp]
public void SetUpSheetAndWorkbook() {
workbook = new SXSSFWorkbook();
sheet = workbook.CreateSheet() as SXSSFSheet;
tracker = new AutoSizeColumnTracker(sheet);
}
[TearDown]
public void TearDownSheetAndWorkbook() {
if (sheet != null) {
sheet.Dispose();
}
if (workbook != null) {
workbook.Close();
}
}
[Test]
public void trackAndUntrackColumn() {
Assume.That(tracker.TrackedColumns.Count == 0);
tracker.TrackColumn(0);
ISet<int> expected = new HashSet<int>();
expected.Add(0);
Assert.AreEqual(expected, tracker.TrackedColumns);
tracker.UntrackColumn(0);
Assert.IsTrue(tracker.TrackedColumns.Count == 0);
}
[Test]
public void trackAndUntrackColumns() {
Assume.That(tracker.TrackedColumns.Count == 0);
tracker.TrackColumns(columns);
Assert.AreEqual(columns, tracker.TrackedColumns);
tracker.UntrackColumn(3);
tracker.UntrackColumn(0);
tracker.UntrackColumn(1);
Assert.IsTrue(tracker.TrackedColumns.Count == 0);
tracker.TrackColumn(0);
tracker.TrackColumns(columns);
tracker.UntrackColumn(4);
Assert.AreEqual(columns, tracker.TrackedColumns);
tracker.UntrackColumns(columns);
Assert.IsTrue(tracker.TrackedColumns.Count == 0);
}
[Test]
public void trackAndUntrackAllColumns() {
Assume.That(tracker.TrackedColumns.Count == 0);
tracker.TrackAllColumns();
Assert.IsTrue(tracker.TrackedColumns.Count == 0);
IRow row = sheet.CreateRow(0);
foreach (int column in columns) {
row.CreateCell(column);
}
// implicitly track the columns
tracker.UpdateColumnWidths(row);
Assert.AreEqual(columns, tracker.TrackedColumns);
tracker.UntrackAllColumns();
Assert.IsTrue(tracker.TrackedColumns.Count == 0);
}
[Test]
public void isColumnTracked() {
Assert.IsFalse(tracker.IsColumnTracked(0));
tracker.TrackColumn(0);
Assert.IsTrue(tracker.IsColumnTracked(0));
tracker.UntrackColumn(0);
Assert.IsFalse(tracker.IsColumnTracked(0));
}
[Test]
public void GetTrackedColumns() {
Assume.That(tracker.TrackedColumns.Count == 0);
foreach (int column in columns) {
tracker.TrackColumn(column);
}
Assert.AreEqual(3, tracker.TrackedColumns.Count);
Assert.AreEqual(columns, tracker.TrackedColumns);
}
[Test]
public void isAllColumnsTracked() {
Assert.IsFalse(tracker.IsAllColumnsTracked());
tracker.TrackAllColumns();
Assert.IsTrue(tracker.IsAllColumnsTracked());
tracker.UntrackAllColumns();
Assert.IsFalse(tracker.IsAllColumnsTracked());
}
[Test]
public void updateColumnWidths_and_getBestFitColumnWidth() {
tracker.TrackAllColumns();
IRow row1 = sheet.CreateRow(0);
IRow row2 = sheet.CreateRow(1);
// A1, B1, D1
foreach (int column in columns) {
row1.CreateCell(column).SetCellValue(LONG_MESSAGE);
row2.CreateCell(column + 1).SetCellValue(SHORT_MESSAGE);
}
tracker.UpdateColumnWidths(row1);
tracker.UpdateColumnWidths(row2);
sheet.AddMergedRegion(CellRangeAddress.ValueOf("D1:E1"));
assumeRequiredFontsAreInstalled(workbook, row1.GetCell(columns.GetEnumerator().Current));
// Excel 2013 and LibreOffice 4.2.8.2 both treat columns with merged regions as blank
/** A B C D E
* 1 LONG LONG LONGMERGE
* 2 SHORT SHORT SHORT
*/
// measured in Excel 2013. Sizes may vary.
int longMsgWidth = (int)(57.43 * 256);
int shortMsgWidth = (int)(4.86 * 256);
CheckColumnWidth(longMsgWidth, 0, true);
CheckColumnWidth(longMsgWidth, 0, false);
CheckColumnWidth(longMsgWidth, 1, true);
CheckColumnWidth(longMsgWidth, 1, false);
CheckColumnWidth(shortMsgWidth, 2, true);
CheckColumnWidth(shortMsgWidth, 2, false);
CheckColumnWidth(-1, 3, true);
CheckColumnWidth(longMsgWidth, 3, false);
CheckColumnWidth(shortMsgWidth, 4, true); //but is it really? shouldn't autosizing column E use "" from E1 and SHORT from E2?
CheckColumnWidth(shortMsgWidth, 4, false);
}
private void CheckColumnWidth(int expectedWidth, int column, bool useMergedCells) {
int bestFitWidth = tracker.GetBestFitColumnWidth(column, useMergedCells);
if (bestFitWidth < 0 && expectedWidth < 0) return;
double abs_error = Math.Abs(bestFitWidth - expectedWidth);
double rel_error = abs_error / expectedWidth;
if (rel_error > 0.25) {
Assert.Fail("check column width: " +
rel_error + ", " + abs_error + ", " +
expectedWidth + ", " + bestFitWidth);
}
}
private static void assumeRequiredFontsAreInstalled(IWorkbook workbook, ICell cell) {
// autoSize will fail if required fonts are not installed, skip this test then
IFont font = workbook.GetFontAt(cell.CellStyle.FontIndex);
//System.out.Println(font.FontHeightInPoints);
//System.out.Println(font.FontName);
Assume.That(SheetUtil.CanComputeColumnWidth(font),
"Cannot verify autoSizeColumn() because the necessary Fonts are not installed on this machine: " + font);
}
}
}
| |
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#if NET452
using System.Collections.Specialized;
using System.Web;
using System.Web.Mvc;
using Moq;
using React.Router;
using React.Tests.Core;
using Xunit;
namespace React.Tests.Router
{
public class HtmlHelperExtensionsTest
{
/// <summary>
/// Creates a mock <see cref="IReactEnvironment"/> and registers it with the IoC container
/// This is only required because <see cref="HtmlHelperExtensions"/> can not be
/// injected :(
/// </summary>
private ReactEnvironmentTest.Mocks ConfigureMockReactEnvironment()
{
var mocks = new ReactEnvironmentTest.Mocks();
mocks.Engine.Setup(x => x.Evaluate<bool>("typeof ComponentName !== 'undefined'")).Returns(true);
var environment = mocks.CreateReactEnvironment();
AssemblyRegistration.Container.Register<IReactEnvironment>(environment);
return mocks;
}
private Mock<IReactEnvironment> ConfigureMockEnvironment()
{
var environment = new Mock<IReactEnvironment>();
AssemblyRegistration.Container.Register(environment.Object);
return environment;
}
private Mock<IReactSiteConfiguration> ConfigureMockConfiguration()
{
var config = new Mock<IReactSiteConfiguration>();
config.SetupGet(x => x.UseServerSideRendering).Returns(true);
AssemblyRegistration.Container.Register(config.Object);
return config;
}
private Mock<IReactIdGenerator> ConfigureReactIdGenerator()
{
var reactIdGenerator = new Mock<IReactIdGenerator>();
AssemblyRegistration.Container.Register(reactIdGenerator.Object);
return reactIdGenerator;
}
/// <summary>
/// Mock an html helper with a mocked response object.
/// Used when testing for server response modification.
/// </summary>
class HtmlHelperMocks
{
public Mock<HtmlHelper> htmlHelper;
public Mock<HttpResponseBase> httpResponse;
public HtmlHelperMocks(HttpRequestBase request = null)
{
var viewDataContainer = new Mock<IViewDataContainer>();
var viewContext = new Mock<ViewContext>();
httpResponse = new Mock<HttpResponseBase>();
htmlHelper = new Mock<HtmlHelper>(viewContext.Object, viewDataContainer.Object);
var httpContextBase = new Mock<HttpContextBase>();
viewContext.Setup(x => x.HttpContext).Returns(httpContextBase.Object);
httpContextBase.Setup(x => x.Request).Returns(request);
httpContextBase.Setup(x => x.Response).Returns(httpResponse.Object);
}
}
/// <summary>
/// Mocks alot of common functionality related to rendering a
/// React Router component.
/// </summary>
class ReactRouterMocks
{
public Mock<IReactSiteConfiguration> config;
public Mock<IReactEnvironment> environment;
public Mock<ReactRouterComponent> component;
public Mock<IReactIdGenerator> reactIdGenerator;
public ReactRouterMocks(
Mock<IReactSiteConfiguration> conf,
Mock<IReactEnvironment> env,
Mock<IReactIdGenerator> idGenerator,
bool clientOnly = false
)
{
config = conf;
environment = env;
reactIdGenerator = idGenerator;
component = new Mock<ReactRouterComponent>(
environment.Object,
config.Object,
reactIdGenerator.Object,
"ComponentName",
"",
"/"
);
var execResult = new Mock<ExecutionResult>();
component.Setup(x => x.RenderRouterWithContext(It.IsAny<bool>(), It.IsAny<bool>(), null))
.Returns(execResult.Object);
environment.Setup(x => x.CreateComponent(
It.IsAny<IReactComponent>(),
It.IsAny<bool>()
)).Returns(component.Object);
environment.Setup(x => x.Execute<string>("JSON.stringify(context);"))
.Returns("{ }");
}
}
[Fact]
public void EngineIsReturnedToPoolAfterRender()
{
var config = ConfigureMockConfiguration();
var environment = ConfigureMockEnvironment();
var reactIdGenerator = ConfigureReactIdGenerator();
var routerMocks = new ReactRouterMocks(config, environment, reactIdGenerator, true);
var htmlHelperMock = new HtmlHelperMocks();
environment.Verify(x => x.ReturnEngineToPool(), Times.Never);
var result = HtmlHelperExtensions.ReactRouter(
htmlHelper: htmlHelperMock.htmlHelper.Object,
componentName: "ComponentName",
props: new { },
path: "/",
htmlTag: "span",
clientOnly: true,
serverOnly: true
);
environment.Verify(x => x.ReturnEngineToPool(), Times.Once);
}
[Fact]
public void ReactWithClientOnlyTrueShouldCallRenderHtmlWithTrue()
{
var config = ConfigureMockConfiguration();
var htmlHelperMock = new HtmlHelperMocks();
var environment = ConfigureMockEnvironment();
var reactIdGenerator = ConfigureReactIdGenerator();
var routerMocks = new ReactRouterMocks(config, environment, reactIdGenerator, true);
var result = HtmlHelperExtensions.ReactRouter(
htmlHelper: htmlHelperMock.htmlHelper.Object,
componentName: "ComponentName",
props: new { },
path: "/",
htmlTag: "span",
clientOnly: true,
serverOnly: false
);
routerMocks.component.Verify(x => x.RenderRouterWithContext(It.Is<bool>(y => y == true), It.Is<bool>(z => z == false), null), Times.Once);
}
[Fact]
public void ReactWithServerOnlyTrueShouldCallRenderHtmlWithTrue()
{
var config = ConfigureMockConfiguration();
var htmlHelperMock = new HtmlHelperMocks();
var environment = ConfigureMockEnvironment();
var reactIdGenerator = ConfigureReactIdGenerator();
var routerMocks = new ReactRouterMocks(config, environment, reactIdGenerator);
var result = HtmlHelperExtensions.ReactRouter(
htmlHelper: htmlHelperMock.htmlHelper.Object,
componentName: "ComponentName",
props: new { },
path: "/",
htmlTag: "span",
clientOnly: false,
serverOnly: true
);
routerMocks.component.Verify(x => x.RenderRouterWithContext(It.Is<bool>(y => y == false), It.Is<bool>(z => z == true), null), Times.Once);
}
[Fact]
public void ShouldModifyStatusCode()
{
var mocks = ConfigureMockReactEnvironment();
ConfigureMockConfiguration();
ConfigureReactIdGenerator();
mocks.Engine.Setup(x => x.Evaluate<string>("JSON.stringify(context);"))
.Returns("{ status: 200 }");
var htmlHelperMock = new HtmlHelperMocks();
HtmlHelperExtensions.ReactRouter(
htmlHelper: htmlHelperMock.htmlHelper.Object,
componentName: "ComponentName",
props: new { },
path: "/"
);
htmlHelperMock.httpResponse.VerifySet(x => x.StatusCode = 200);
}
[Fact]
public void ShouldRunCustomContextHandler()
{
var mocks = ConfigureMockReactEnvironment();
ConfigureMockConfiguration();
ConfigureReactIdGenerator();
mocks.Engine.Setup(x => x.Evaluate<string>("JSON.stringify(context);"))
.Returns("{ status: 200 }");
var htmlHelperMock = new HtmlHelperMocks();
HtmlHelperExtensions.ReactRouter(
htmlHelper: htmlHelperMock.htmlHelper.Object,
componentName: "ComponentName",
props: new { },
path: "/",
contextHandler: (response, context) => response.StatusCode = context.status.Value
);
htmlHelperMock.httpResponse.VerifySet(x => x.StatusCode = 200);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void ShouldHandleQueryParams(bool withOverriddenPath)
{
var mocks = ConfigureMockReactEnvironment();
ConfigureMockConfiguration();
ConfigureReactIdGenerator();
mocks.Engine.Setup(x => x.Evaluate<string>("JSON.stringify(context);"))
.Returns("{ status: 200 }");
var requestMock = new Mock<HttpRequestBase>();
requestMock.SetupGet(x => x.Path).Returns("/test");
var queryStringMock = new Mock<NameValueCollection>();
queryStringMock.Setup(x => x.ToString()).Returns("?a=1&b=2");
requestMock.SetupGet(x => x.QueryString).Returns(queryStringMock.Object);
var htmlHelperMock = new HtmlHelperMocks(requestMock.Object);
var result = HtmlHelperExtensions.ReactRouter(
htmlHelper: htmlHelperMock.htmlHelper.Object,
componentName: "ComponentName",
props: new { },
path: withOverriddenPath ? "/test2?b=1&c=2" : null,
contextHandler: (response, context) => response.StatusCode = context.status.Value
);
htmlHelperMock.httpResponse.VerifySet(x => x.StatusCode = 200);
if (withOverriddenPath)
{
mocks.Engine.Verify(x => x.Evaluate<string>(@"ReactDOMServer.renderToString(React.createElement(ComponentName, Object.assign({}, { location: ""/test2?b=1&c=2"", context: context })))"));
}
else
{
mocks.Engine.Verify(x => x.Evaluate<string>(@"ReactDOMServer.renderToString(React.createElement(ComponentName, Object.assign({}, { location: ""/test?a=1&b=2"", context: context })))"));
}
}
[Theory]
[InlineData("?a='\"1", "?a='\\\"1")]
public void ShouldEscapeQuery(string query, string expected)
{
var mocks = ConfigureMockReactEnvironment();
ConfigureMockConfiguration();
ConfigureReactIdGenerator();
mocks.Engine.Setup(x => x.Evaluate<string>("JSON.stringify(context);"))
.Returns("{ status: 200 }");
var requestMock = new Mock<HttpRequestBase>();
requestMock.SetupGet(x => x.Path).Returns("/test");
var queryStringMock = new Mock<NameValueCollection>();
queryStringMock.Setup(x => x.ToString()).Returns(query);
requestMock.SetupGet(x => x.QueryString).Returns(queryStringMock.Object);
var htmlHelperMock = new HtmlHelperMocks(requestMock.Object);
var result = HtmlHelperExtensions.ReactRouter(
htmlHelper: htmlHelperMock.htmlHelper.Object,
componentName: "ComponentName",
props: new { },
path: null,
contextHandler: (response, context) => response.StatusCode = context.status.Value
);
htmlHelperMock.httpResponse.VerifySet(x => x.StatusCode = 200);
mocks.Engine.Verify(x => x.Evaluate<string>(@"ReactDOMServer.renderToString(React.createElement(ComponentName, Object.assign({}, { location: ""/test" + expected + @""", context: context })))"));
}
[Fact]
public void ShouldRedirectPermanent()
{
var mocks = ConfigureMockReactEnvironment();
ConfigureMockConfiguration();
ConfigureReactIdGenerator();
mocks.Engine.Setup(x => x.Evaluate<string>("JSON.stringify(context);"))
.Returns(@"{ status: 301, url: ""/foo"" }");
var htmlHelperMock = new HtmlHelperMocks();
HtmlHelperExtensions.ReactRouter(
htmlHelper: htmlHelperMock.htmlHelper.Object,
componentName: "ComponentName",
props: new { },
path: "/"
);
htmlHelperMock.httpResponse.Verify(x => x.RedirectPermanent(It.IsAny<string>()));
}
[Fact]
public void ShouldRedirectWithJustUrl()
{
var mocks = ConfigureMockReactEnvironment();
ConfigureMockConfiguration();
ConfigureReactIdGenerator();
mocks.Engine.Setup(x => x.Evaluate<string>("JSON.stringify(context);"))
.Returns(@"{ url: ""/foo"" }");
var htmlHelperMock = new HtmlHelperMocks();
HtmlHelperExtensions.ReactRouter(
htmlHelper: htmlHelperMock.htmlHelper.Object,
componentName: "ComponentName",
props: new { },
path: "/"
);
htmlHelperMock.httpResponse.Verify(x => x.Redirect(It.IsAny<string>()));
}
[Fact]
public void ShouldFailRedirectWithNoUrl()
{
var mocks = ConfigureMockReactEnvironment();
ConfigureMockConfiguration();
ConfigureReactIdGenerator();
mocks.Engine.Setup(x => x.Evaluate<string>("JSON.stringify(context);"))
.Returns("{ status: 301 }");
var htmlHelperMock = new HtmlHelperMocks();
Assert.Throws<ReactRouterException>(() =>
HtmlHelperExtensions.ReactRouter(
htmlHelper: htmlHelperMock.htmlHelper.Object,
componentName: "ComponentName",
props: new { },
path: "/"
)
);
}
}
}
#endif
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/speech/v1beta1/cloud_speech.proto
// Original file comments:
// Copyright 2016 Google 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.
//
#region Designer generated code
using System;
using System.Threading;
using System.Threading.Tasks;
using Grpc.Core;
namespace Google.Cloud.Speech.V1Beta1 {
/// <summary>
/// Service that implements Google Cloud Speech API.
/// </summary>
public static class Speech
{
static readonly string __ServiceName = "google.cloud.speech.v1beta1.Speech";
static readonly Marshaller<global::Google.Cloud.Speech.V1Beta1.SyncRecognizeRequest> __Marshaller_SyncRecognizeRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Speech.V1Beta1.SyncRecognizeRequest.Parser.ParseFrom);
static readonly Marshaller<global::Google.Cloud.Speech.V1Beta1.SyncRecognizeResponse> __Marshaller_SyncRecognizeResponse = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Speech.V1Beta1.SyncRecognizeResponse.Parser.ParseFrom);
static readonly Marshaller<global::Google.Cloud.Speech.V1Beta1.AsyncRecognizeRequest> __Marshaller_AsyncRecognizeRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Speech.V1Beta1.AsyncRecognizeRequest.Parser.ParseFrom);
static readonly Marshaller<global::Google.Longrunning.Operation> __Marshaller_Operation = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Longrunning.Operation.Parser.ParseFrom);
static readonly Marshaller<global::Google.Cloud.Speech.V1Beta1.StreamingRecognizeRequest> __Marshaller_StreamingRecognizeRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Speech.V1Beta1.StreamingRecognizeRequest.Parser.ParseFrom);
static readonly Marshaller<global::Google.Cloud.Speech.V1Beta1.StreamingRecognizeResponse> __Marshaller_StreamingRecognizeResponse = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Speech.V1Beta1.StreamingRecognizeResponse.Parser.ParseFrom);
static readonly Method<global::Google.Cloud.Speech.V1Beta1.SyncRecognizeRequest, global::Google.Cloud.Speech.V1Beta1.SyncRecognizeResponse> __Method_SyncRecognize = new Method<global::Google.Cloud.Speech.V1Beta1.SyncRecognizeRequest, global::Google.Cloud.Speech.V1Beta1.SyncRecognizeResponse>(
MethodType.Unary,
__ServiceName,
"SyncRecognize",
__Marshaller_SyncRecognizeRequest,
__Marshaller_SyncRecognizeResponse);
static readonly Method<global::Google.Cloud.Speech.V1Beta1.AsyncRecognizeRequest, global::Google.Longrunning.Operation> __Method_AsyncRecognize = new Method<global::Google.Cloud.Speech.V1Beta1.AsyncRecognizeRequest, global::Google.Longrunning.Operation>(
MethodType.Unary,
__ServiceName,
"AsyncRecognize",
__Marshaller_AsyncRecognizeRequest,
__Marshaller_Operation);
static readonly Method<global::Google.Cloud.Speech.V1Beta1.StreamingRecognizeRequest, global::Google.Cloud.Speech.V1Beta1.StreamingRecognizeResponse> __Method_StreamingRecognize = new Method<global::Google.Cloud.Speech.V1Beta1.StreamingRecognizeRequest, global::Google.Cloud.Speech.V1Beta1.StreamingRecognizeResponse>(
MethodType.DuplexStreaming,
__ServiceName,
"StreamingRecognize",
__Marshaller_StreamingRecognizeRequest,
__Marshaller_StreamingRecognizeResponse);
/// <summary>Service descriptor</summary>
public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor
{
get { return global::Google.Cloud.Speech.V1Beta1.CloudSpeechReflection.Descriptor.Services[0]; }
}
/// <summary>Base class for server-side implementations of Speech</summary>
public abstract class SpeechBase
{
/// <summary>
/// Perform synchronous speech-recognition: receive results after all audio
/// has been sent and processed.
/// </summary>
public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Speech.V1Beta1.SyncRecognizeResponse> SyncRecognize(global::Google.Cloud.Speech.V1Beta1.SyncRecognizeRequest request, ServerCallContext context)
{
throw new RpcException(new Status(StatusCode.Unimplemented, ""));
}
/// <summary>
/// Perform asynchronous speech-recognition: receive results via the
/// google.longrunning.Operations interface. Returns either an
/// `Operation.error` or an `Operation.response` which contains
/// an `AsyncRecognizeResponse` message.
/// </summary>
public virtual global::System.Threading.Tasks.Task<global::Google.Longrunning.Operation> AsyncRecognize(global::Google.Cloud.Speech.V1Beta1.AsyncRecognizeRequest request, ServerCallContext context)
{
throw new RpcException(new Status(StatusCode.Unimplemented, ""));
}
/// <summary>
/// Perform bidirectional streaming speech-recognition: receive results while
/// sending audio. This method is only available via the gRPC API (not REST).
/// </summary>
public virtual global::System.Threading.Tasks.Task StreamingRecognize(IAsyncStreamReader<global::Google.Cloud.Speech.V1Beta1.StreamingRecognizeRequest> requestStream, IServerStreamWriter<global::Google.Cloud.Speech.V1Beta1.StreamingRecognizeResponse> responseStream, ServerCallContext context)
{
throw new RpcException(new Status(StatusCode.Unimplemented, ""));
}
}
/// <summary>Client for Speech</summary>
public class SpeechClient : ClientBase<SpeechClient>
{
/// <summary>Creates a new client for Speech</summary>
/// <param name="channel">The channel to use to make remote calls.</param>
public SpeechClient(Channel channel) : base(channel)
{
}
/// <summary>Creates a new client for Speech that uses a custom <c>CallInvoker</c>.</summary>
/// <param name="callInvoker">The callInvoker to use to make remote calls.</param>
public SpeechClient(CallInvoker callInvoker) : base(callInvoker)
{
}
/// <summary>Protected parameterless constructor to allow creation of test doubles.</summary>
protected SpeechClient() : base()
{
}
/// <summary>Protected constructor to allow creation of configured clients.</summary>
/// <param name="configuration">The client configuration.</param>
protected SpeechClient(ClientBaseConfiguration configuration) : base(configuration)
{
}
/// <summary>
/// Perform synchronous speech-recognition: receive results after all audio
/// has been sent and processed.
/// </summary>
public virtual global::Google.Cloud.Speech.V1Beta1.SyncRecognizeResponse SyncRecognize(global::Google.Cloud.Speech.V1Beta1.SyncRecognizeRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return SyncRecognize(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Perform synchronous speech-recognition: receive results after all audio
/// has been sent and processed.
/// </summary>
public virtual global::Google.Cloud.Speech.V1Beta1.SyncRecognizeResponse SyncRecognize(global::Google.Cloud.Speech.V1Beta1.SyncRecognizeRequest request, CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_SyncRecognize, null, options, request);
}
/// <summary>
/// Perform synchronous speech-recognition: receive results after all audio
/// has been sent and processed.
/// </summary>
public virtual AsyncUnaryCall<global::Google.Cloud.Speech.V1Beta1.SyncRecognizeResponse> SyncRecognizeAsync(global::Google.Cloud.Speech.V1Beta1.SyncRecognizeRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return SyncRecognizeAsync(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Perform synchronous speech-recognition: receive results after all audio
/// has been sent and processed.
/// </summary>
public virtual AsyncUnaryCall<global::Google.Cloud.Speech.V1Beta1.SyncRecognizeResponse> SyncRecognizeAsync(global::Google.Cloud.Speech.V1Beta1.SyncRecognizeRequest request, CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_SyncRecognize, null, options, request);
}
/// <summary>
/// Perform asynchronous speech-recognition: receive results via the
/// google.longrunning.Operations interface. Returns either an
/// `Operation.error` or an `Operation.response` which contains
/// an `AsyncRecognizeResponse` message.
/// </summary>
public virtual global::Google.Longrunning.Operation AsyncRecognize(global::Google.Cloud.Speech.V1Beta1.AsyncRecognizeRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return AsyncRecognize(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Perform asynchronous speech-recognition: receive results via the
/// google.longrunning.Operations interface. Returns either an
/// `Operation.error` or an `Operation.response` which contains
/// an `AsyncRecognizeResponse` message.
/// </summary>
public virtual global::Google.Longrunning.Operation AsyncRecognize(global::Google.Cloud.Speech.V1Beta1.AsyncRecognizeRequest request, CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_AsyncRecognize, null, options, request);
}
/// <summary>
/// Perform asynchronous speech-recognition: receive results via the
/// google.longrunning.Operations interface. Returns either an
/// `Operation.error` or an `Operation.response` which contains
/// an `AsyncRecognizeResponse` message.
/// </summary>
public virtual AsyncUnaryCall<global::Google.Longrunning.Operation> AsyncRecognizeAsync(global::Google.Cloud.Speech.V1Beta1.AsyncRecognizeRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return AsyncRecognizeAsync(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Perform asynchronous speech-recognition: receive results via the
/// google.longrunning.Operations interface. Returns either an
/// `Operation.error` or an `Operation.response` which contains
/// an `AsyncRecognizeResponse` message.
/// </summary>
public virtual AsyncUnaryCall<global::Google.Longrunning.Operation> AsyncRecognizeAsync(global::Google.Cloud.Speech.V1Beta1.AsyncRecognizeRequest request, CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_AsyncRecognize, null, options, request);
}
/// <summary>
/// Perform bidirectional streaming speech-recognition: receive results while
/// sending audio. This method is only available via the gRPC API (not REST).
/// </summary>
public virtual AsyncDuplexStreamingCall<global::Google.Cloud.Speech.V1Beta1.StreamingRecognizeRequest, global::Google.Cloud.Speech.V1Beta1.StreamingRecognizeResponse> StreamingRecognize(Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return StreamingRecognize(new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Perform bidirectional streaming speech-recognition: receive results while
/// sending audio. This method is only available via the gRPC API (not REST).
/// </summary>
public virtual AsyncDuplexStreamingCall<global::Google.Cloud.Speech.V1Beta1.StreamingRecognizeRequest, global::Google.Cloud.Speech.V1Beta1.StreamingRecognizeResponse> StreamingRecognize(CallOptions options)
{
return CallInvoker.AsyncDuplexStreamingCall(__Method_StreamingRecognize, null, options);
}
protected override SpeechClient NewInstance(ClientBaseConfiguration configuration)
{
return new SpeechClient(configuration);
}
}
/// <summary>Creates service definition that can be registered with a server</summary>
public static ServerServiceDefinition BindService(SpeechBase serviceImpl)
{
return ServerServiceDefinition.CreateBuilder()
.AddMethod(__Method_SyncRecognize, serviceImpl.SyncRecognize)
.AddMethod(__Method_AsyncRecognize, serviceImpl.AsyncRecognize)
.AddMethod(__Method_StreamingRecognize, serviceImpl.StreamingRecognize).Build();
}
}
}
#endregion
| |
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using Microsoft.Owin.Host.SystemWeb.CallEnvironment;
using Microsoft.Owin.Host.SystemWeb.Infrastructure;
namespace Microsoft.Owin.Host.SystemWeb.IntegratedPipeline
{
internal class IntegratedPipelineContext
{
// Ordered list of supported stage names
private static readonly IList<string> StageNames = new[]
{
Constants.StageAuthenticate,
Constants.StagePostAuthenticate,
Constants.StageAuthorize,
Constants.StagePostAuthorize,
Constants.StageResolveCache,
Constants.StagePostResolveCache,
Constants.StageMapHandler,
Constants.StagePostMapHandler,
Constants.StageAcquireState,
Constants.StagePostAcquireState,
Constants.StagePreHandlerExecute,
};
private readonly IntegratedPipelineBlueprint _blueprint;
private State _state;
public IntegratedPipelineContext(IntegratedPipelineBlueprint blueprint)
{
_blueprint = blueprint;
}
public bool PreventNextStage
{
get { return _state.PreventNextStage; }
set { _state.PreventNextStage = value; }
}
public void Initialize(HttpApplication application)
{
for (IntegratedPipelineBlueprintStage stage = _blueprint.FirstStage; stage != null; stage = stage.NextStage)
{
var segment = new IntegratedPipelineContextStage(this, stage);
switch (stage.Name)
{
case Constants.StageAuthenticate:
application.AddOnAuthenticateRequestAsync(segment.BeginEvent, segment.EndEvent);
break;
case Constants.StagePostAuthenticate:
application.AddOnPostAuthenticateRequestAsync(segment.BeginEvent, segment.EndEvent);
break;
case Constants.StageAuthorize:
application.AddOnAuthorizeRequestAsync(segment.BeginEvent, segment.EndEvent);
break;
case Constants.StagePostAuthorize:
application.AddOnPostAuthorizeRequestAsync(segment.BeginEvent, segment.EndEvent);
break;
case Constants.StageResolveCache:
application.AddOnResolveRequestCacheAsync(segment.BeginEvent, segment.EndEvent);
break;
case Constants.StagePostResolveCache:
application.AddOnPostResolveRequestCacheAsync(segment.BeginEvent, segment.EndEvent);
break;
case Constants.StageMapHandler:
application.AddOnMapRequestHandlerAsync(segment.BeginEvent, segment.EndEvent);
break;
case Constants.StagePostMapHandler:
application.AddOnPostMapRequestHandlerAsync(segment.BeginEvent, segment.EndEvent);
break;
case Constants.StageAcquireState:
application.AddOnAcquireRequestStateAsync(segment.BeginEvent, segment.EndEvent);
break;
case Constants.StagePostAcquireState:
application.AddOnPostAcquireRequestStateAsync(segment.BeginEvent, segment.EndEvent);
break;
case Constants.StagePreHandlerExecute:
application.AddOnPreRequestHandlerExecuteAsync(segment.BeginEvent, segment.EndEvent);
break;
default:
throw new NotSupportedException(
string.Format(CultureInfo.InvariantCulture, Resources.Exception_UnsupportedPipelineStage, stage.Name));
}
}
// application.PreSendRequestHeaders += PreSendRequestHeaders; // Null refs for async un-buffered requests with bodies.
application.AddOnEndRequestAsync(BeginFinalWork, EndFinalWork);
}
private void Reset()
{
PushExecutingStage(null);
_state = new State();
}
public static Task DefaultAppInvoked(IDictionary<string, object> env)
{
object value;
if (env.TryGetValue(Constants.IntegratedPipelineContext, out value))
{
var self = (IntegratedPipelineContext)value;
return self._state.ExecutingStage.DefaultAppInvoked(env);
}
throw new InvalidOperationException();
}
public static Task ExitPointInvoked(IDictionary<string, object> env)
{
object value;
if (env.TryGetValue(Constants.IntegratedPipelineContext, out value))
{
var self = (IntegratedPipelineContext)value;
return self._state.ExecutingStage.ExitPointInvoked(env);
}
throw new InvalidOperationException();
}
private IAsyncResult BeginFinalWork(object sender, EventArgs e, AsyncCallback cb, object extradata)
{
var result = new StageAsyncResult(cb, extradata, () => { });
TaskCompletionSource<object> tcs = TakeLastCompletionSource();
if (tcs != null)
{
tcs.TrySetResult(null);
}
if (_state.OriginalTask != null)
{
// System.Web does not allow us to use async void methods to complete the IAsyncResult due to the special sync context.
#pragma warning disable 4014
DoFinalWork(result);
#pragma warning restore 4014
}
else
{
result.TryComplete();
}
result.InitialThreadReturning();
return result;
}
private async Task DoFinalWork(StageAsyncResult result)
{
try
{
await _state.OriginalTask;
_state.CallContext.OnEnd();
CallContextAsyncResult.End(_state.CallContext.AsyncResult);
result.TryComplete();
}
catch (Exception ex)
{
_state.CallContext.AbortIfHeaderSent();
result.Fail(ErrorState.Capture(ex));
}
}
private void EndFinalWork(IAsyncResult ar)
{
Reset();
StageAsyncResult.End(ar);
}
public Func<IDictionary<string, object>, Task> PrepareInitialContext(HttpApplication application)
{
IDictionary<string, object> environment = GetInitialEnvironment(application);
var originalCompletionSource = new TaskCompletionSource<object>();
_state.OriginalTask = originalCompletionSource.Task;
PushLastObjects(environment, originalCompletionSource);
return _blueprint.AppContext.AppFunc;
}
public IDictionary<string, object> GetInitialEnvironment(HttpApplication application)
{
if (_state.CallContext != null)
{
return _state.CallContext.Environment;
}
string requestPath = application.Request.AppRelativeCurrentExecutionFilePath.Substring(1) + application.Request.PathInfo;
_state.CallContext = _blueprint.AppContext.CreateCallContext(
application.Request.RequestContext,
_blueprint.PathBase,
requestPath,
null,
null);
_state.CallContext.CreateEnvironment();
AspNetDictionary environment = _state.CallContext.Environment;
environment.IntegratedPipelineContext = this;
return environment;
}
public void PushExecutingStage(IntegratedPipelineContextStage stage)
{
IntegratedPipelineContextStage prior = Interlocked.Exchange(ref _state.ExecutingStage, stage);
if (prior != null)
{
prior.Reset();
}
}
public void PushLastObjects(IDictionary<string, object> environment, TaskCompletionSource<object> completionSource)
{
IDictionary<string, object> priorEnvironment = Interlocked.CompareExchange(ref _state.LastEnvironment, environment, null);
TaskCompletionSource<object> priorCompletionSource = Interlocked.CompareExchange(ref _state.LastCompletionSource, completionSource, null);
if (priorEnvironment != null || priorCompletionSource != null)
{
// TODO: trace fatal condition
throw new InvalidOperationException();
}
}
public IDictionary<string, object> TakeLastEnvironment()
{
return Interlocked.Exchange(ref _state.LastEnvironment, null);
}
public TaskCompletionSource<object> TakeLastCompletionSource()
{
return Interlocked.Exchange(ref _state.LastCompletionSource, null);
}
// Does stage1 come before stage2?
// Returns false for unknown stages, or equal stages.
internal static bool VerifyStageOrder(string stage1, string stage2)
{
int stage1Index = StageNames.IndexOf(stage1);
int stage2Index = StageNames.IndexOf(stage2);
if (stage1Index == -1 || stage2Index == -1)
{
return false;
}
return stage1Index < stage2Index;
}
private struct State
{
public IDictionary<string, object> LastEnvironment;
public TaskCompletionSource<object> LastCompletionSource;
public Task OriginalTask;
public OwinCallContext CallContext;
public bool PreventNextStage;
public IntegratedPipelineContextStage ExecutingStage;
}
}
}
| |
namespace Scout
{
partial class LoginForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(LoginForm));
this.login = new System.Windows.Forms.Button();
this.cancel = new System.Windows.Forms.Button();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.remember = new System.Windows.Forms.CheckBox();
this.username = new System.Windows.Forms.TextBox();
this.password = new System.Windows.Forms.TextBox();
this.account = new System.Windows.Forms.TextBox();
this.ssl = new System.Windows.Forms.CheckBox();
this.pictureBox1 = new System.Windows.Forms.PictureBox();
this.linkLabel1 = new System.Windows.Forms.LinkLabel();
this.version = new System.Windows.Forms.Label();
this.label5 = new System.Windows.Forms.Label();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
this.SuspendLayout();
//
// login
//
this.login.Location = new System.Drawing.Point(294, 229);
this.login.Name = "login";
this.login.Size = new System.Drawing.Size(90, 46);
this.login.TabIndex = 8;
this.login.Text = "Login";
this.login.UseVisualStyleBackColor = true;
this.login.Click += new System.EventHandler(this.login_Click);
//
// cancel
//
this.cancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.cancel.Location = new System.Drawing.Point(390, 229);
this.cancel.Name = "cancel";
this.cancel.Size = new System.Drawing.Size(90, 46);
this.cancel.TabIndex = 9;
this.cancel.Text = "Exit";
this.cancel.UseVisualStyleBackColor = true;
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(143, 12);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(94, 20);
this.label1.TabIndex = 0;
this.label1.Text = "Username:";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(143, 61);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(88, 20);
this.label2.TabIndex = 1;
this.label2.Text = "Password:";
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(143, 110);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(77, 20);
this.label3.TabIndex = 2;
this.label3.Text = "Account:";
//
// remember
//
this.remember.AutoSize = true;
this.remember.Location = new System.Drawing.Point(15, 251);
this.remember.Name = "remember";
this.remember.Size = new System.Drawing.Size(145, 24);
this.remember.TabIndex = 6;
this.remember.Text = "Remember me";
this.remember.UseVisualStyleBackColor = true;
//
// username
//
this.username.Location = new System.Drawing.Point(243, 12);
this.username.Name = "username";
this.username.Size = new System.Drawing.Size(237, 32);
this.username.TabIndex = 3;
//
// password
//
this.password.Location = new System.Drawing.Point(243, 61);
this.password.Name = "password";
this.password.PasswordChar = '*';
this.password.Size = new System.Drawing.Size(237, 32);
this.password.TabIndex = 4;
//
// account
//
this.account.Font = new System.Drawing.Font("Lucida Sans Unicode", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.account.Location = new System.Drawing.Point(243, 110);
this.account.Name = "account";
this.account.Size = new System.Drawing.Size(237, 28);
this.account.TabIndex = 5;
//
// ssl
//
this.ssl.AutoSize = true;
this.ssl.Location = new System.Drawing.Point(243, 176);
this.ssl.Name = "ssl";
this.ssl.Size = new System.Drawing.Size(62, 24);
this.ssl.TabIndex = 7;
this.ssl.Text = "SSL?";
this.ssl.UseVisualStyleBackColor = true;
//
// pictureBox1
//
this.pictureBox1.Image = ((System.Drawing.Image)(resources.GetObject("pictureBox1.Image")));
this.pictureBox1.Location = new System.Drawing.Point(12, 12);
this.pictureBox1.Name = "pictureBox1";
this.pictureBox1.Size = new System.Drawing.Size(116, 116);
this.pictureBox1.TabIndex = 9;
this.pictureBox1.TabStop = false;
//
// linkLabel1
//
this.linkLabel1.AutoSize = true;
this.linkLabel1.Font = new System.Drawing.Font("Lucida Sans Unicode", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.linkLabel1.Location = new System.Drawing.Point(320, 182);
this.linkLabel1.Name = "linkLabel1";
this.linkLabel1.Size = new System.Drawing.Size(160, 15);
this.linkLabel1.TabIndex = 10;
this.linkLabel1.TabStop = true;
this.linkLabel1.Text = "Tap here for more settings...";
this.linkLabel1.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabel1_LinkClicked);
//
// version
//
this.version.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.version.AutoSize = true;
this.version.Font = new System.Drawing.Font("Lucida Sans Unicode", 8F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.version.ForeColor = System.Drawing.Color.RoyalBlue;
this.version.Location = new System.Drawing.Point(12, 131);
this.version.Name = "version";
this.version.Size = new System.Drawing.Size(55, 15);
this.version.TabIndex = 2;
this.version.Text = "Version";
//
// label5
//
this.label5.AutoSize = true;
this.label5.Font = new System.Drawing.Font("Lucida Sans Unicode", 8F);
this.label5.ForeColor = System.Drawing.Color.DarkBlue;
this.label5.Location = new System.Drawing.Point(240, 145);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(218, 15);
this.label5.TabIndex = 11;
this.label5.Text = "Example: mycompany.projectpath.com";
//
// LoginForm
//
this.AcceptButton = this.login;
this.AutoScaleDimensions = new System.Drawing.SizeF(10F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.AutoSize = true;
this.CancelButton = this.cancel;
this.ClientSize = new System.Drawing.Size(489, 287);
this.ControlBox = false;
this.Controls.Add(this.label5);
this.Controls.Add(this.linkLabel1);
this.Controls.Add(this.pictureBox1);
this.Controls.Add(this.account);
this.Controls.Add(this.password);
this.Controls.Add(this.username);
this.Controls.Add(this.ssl);
this.Controls.Add(this.remember);
this.Controls.Add(this.label2);
this.Controls.Add(this.version);
this.Controls.Add(this.label3);
this.Controls.Add(this.label1);
this.Controls.Add(this.cancel);
this.Controls.Add(this.login);
this.Font = new System.Drawing.Font("Lucida Sans Unicode", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.Margin = new System.Windows.Forms.Padding(5);
this.Name = "LoginForm";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Scout: Please Login";
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button login;
private System.Windows.Forms.Button cancel;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
public System.Windows.Forms.CheckBox remember;
public System.Windows.Forms.TextBox username;
public System.Windows.Forms.TextBox password;
public System.Windows.Forms.TextBox account;
public System.Windows.Forms.CheckBox ssl;
private System.Windows.Forms.PictureBox pictureBox1;
private System.Windows.Forms.LinkLabel linkLabel1;
private System.Windows.Forms.Label version;
private System.Windows.Forms.Label label5;
}
}
| |
//---------------------------------------------------------------------
// <copyright file="FixUp.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner [....]
// @backupOwner [....]
//---------------------------------------------------------------------
using System.Data.Services.Design;
namespace System.Data.EntityModel.Emitters
{
/// <summary>
///
/// </summary>
internal sealed class FixUp
{
#region Internal Property
internal delegate string FixMethod(string line);
#endregion
#region Instance Fields
FixUpType m_type;
private string _class;
private string _method;
private string _property;
#endregion
#region static
private static readonly FixMethod[] _CSFixMethods = new FixMethod[]
{
null,
new FixMethod(CSMarkOverrideMethodAsSealed),
new FixMethod(CSMarkPropertySetAsInternal),
new FixMethod(CSMarkClassAsStatic),
new FixMethod(CSMarkPropertyGetAsPrivate),
new FixMethod(CSMarkPropertyGetAsInternal),
new FixMethod(CSMarkPropertyGetAsPublic),
new FixMethod(CSMarkPropertySetAsPrivate),
new FixMethod(CSMarkPropertySetAsPublic),
new FixMethod(CSMarkMethodAsPartial),
new FixMethod(CSMarkPropertyGetAsProtected),
new FixMethod(CSMarkPropertySetAsProtected)
};
private static readonly FixMethod[] _VBFixMethods = new FixMethod[]
{
null,
new FixMethod(VBMarkOverrideMethodAsSealed),
new FixMethod(VBMarkPropertySetAsInternal),
null, // VB doesn't support static classes (during CodeGen we added a private ctor to the class)
new FixMethod(VBMarkPropertyGetAsPrivate),
new FixMethod(VBMarkPropertyGetAsInternal),
new FixMethod(VBMarkPropertyGetAsPublic),
new FixMethod(VBMarkPropertySetAsPrivate),
new FixMethod(VBMarkPropertySetAsPublic),
new FixMethod(VBMarkMethodAsPartial),
new FixMethod(VBMarkPropertyGetAsProtected),
new FixMethod(VBMarkPropertySetAsProtected)
};
#endregion
#region Public Methods
/// <summary>
///
/// </summary>
/// <param name="fqName"></param>
/// <param name="type"></param>
public FixUp(string fqName,FixUpType type)
{
Type = type;
string[] nameParts = Utils.SplitName(fqName);
if ( type == FixUpType.MarkClassAsStatic )
{
Class = nameParts[nameParts.Length-1];
}
else
{
Class = nameParts[nameParts.Length-2];
string name = nameParts[nameParts.Length-1];
switch ( type )
{
case FixUpType.MarkAbstractMethodAsPartial:
case FixUpType.MarkOverrideMethodAsSealed:
Method = name;
break;
case FixUpType.MarkPropertyGetAsPrivate:
case FixUpType.MarkPropertyGetAsInternal:
case FixUpType.MarkPropertyGetAsPublic:
case FixUpType.MarkPropertyGetAsProtected:
case FixUpType.MarkPropertySetAsPrivate:
case FixUpType.MarkPropertySetAsInternal:
case FixUpType.MarkPropertySetAsPublic:
case FixUpType.MarkPropertySetAsProtected:
Property = name;
break;
}
}
}
/// <summary>
///
/// </summary>
/// <param name="language"></param>
/// <param name="line"></param>
/// <returns></returns>
public string Fix(LanguageOption language, string line)
{
FixMethod method = null;
if ( language == LanguageOption.GenerateCSharpCode )
{
method = _CSFixMethods[(int)Type];
}
else if ( language == LanguageOption.GenerateVBCode )
{
method = _VBFixMethods[(int)Type];
}
if ( method != null )
{
line = method( line );
}
return line;
}
#endregion
#region Public Properties
/// <summary>
///
/// </summary>
/// <value></value>
public string Class
{
get
{
return _class;
}
private set
{
_class = value;
}
}
/// <summary>
///
/// </summary>
/// <value></value>
public string Property
{
get
{
return _property;
}
private set
{
_property = value;
}
}
/// <summary>
///
/// </summary>
/// <value></value>
public string Method
{
get
{
return _method;
}
private set
{
_method = value;
}
}
/// <summary>
///
/// </summary>
/// <value></value>
public FixUpType Type
{
get
{
return m_type;
}
private set
{
m_type = value;
}
}
#endregion
#region Private Methods
/// <summary>
///
/// </summary>
/// <param name="line"></param>
/// <returns></returns>
private static string CSMarkMethodAsPartial(string line)
{
line = ReplaceFirst(line, "public abstract", "partial");
return line;
}
/// <summary>
///
/// </summary>
/// <param name="line"></param>
/// <returns></returns>
private static string VBMarkMethodAsPartial(string line)
{
line = ReplaceFirst(line, "Public MustOverride", "Partial Private");
line += Environment.NewLine + " End Sub";
return line;
}
private static string ReplaceFirst(string line, string str1, string str2)
{
int idx = line.IndexOf(str1, StringComparison.Ordinal);
if (idx >= 0)
{
line = line.Remove(idx, str1.Length);
line = line.Insert(idx, str2);
}
return line;
}
/// <summary>
///
/// </summary>
/// <param name="line"></param>
/// <returns></returns>
private static string CSMarkOverrideMethodAsSealed(string line)
{
return InsertBefore(line,"override","sealed");
}
/// <summary>
///
/// </summary>
/// <param name="line"></param>
/// <returns></returns>
private static string VBMarkOverrideMethodAsSealed(string line)
{
return InsertBefore(line, "Overrides", "NotOverridable");
}
/// <summary>
///
/// </summary>
/// <param name="line"></param>
/// <returns></returns>
private static string CSMarkPropertySetAsInternal(string line)
{
return InsertBefore(line,"set","internal");
}
/// <summary>
///
/// </summary>
/// <param name="line"></param>
/// <returns></returns>
private static string VBMarkPropertySetAsInternal(string line)
{
return InsertBefore(line,"Set","Friend");
}
private static string CSMarkPropertyGetAsPrivate(string line)
{
return InsertBefore(line, "get", "private");
}
private static string VBMarkPropertyGetAsPrivate(string line)
{
return InsertBefore(line, "Get", "Private");
}
private static string CSMarkPropertyGetAsInternal(string line)
{
return InsertBefore(line, "get", "internal");
}
private static string VBMarkPropertyGetAsInternal(string line)
{
return InsertBefore(line, "Get", "Friend");
}
private static string CSMarkPropertySetAsProtected(string line)
{
return InsertBefore(line, "set", "protected");
}
private static string VBMarkPropertySetAsProtected(string line)
{
return InsertBefore(line, "Set", "Protected");
}
private static string CSMarkPropertyGetAsProtected(string line)
{
return InsertBefore(line, "get", "protected");
}
private static string VBMarkPropertyGetAsProtected(string line)
{
return InsertBefore(line, "Get", "Protected");
}
private static string CSMarkPropertyGetAsPublic(string line)
{
return InsertBefore(line, "get", "public");
}
private static string VBMarkPropertyGetAsPublic(string line)
{
return InsertBefore(line, "Get", "Public");
}
private static string CSMarkPropertySetAsPrivate(string line)
{
return InsertBefore(line, "set", "private");
}
private static string VBMarkPropertySetAsPrivate(string line)
{
return InsertBefore(line, "Set", "Private");
}
private static string CSMarkPropertySetAsPublic(string line)
{
return InsertBefore(line, "set", "public");
}
private static string VBMarkPropertySetAsPublic(string line)
{
return InsertBefore(line, "Set", "Public");
}
/// <summary>
///
/// </summary>
/// <param name="line"></param>
/// <returns></returns>
private static string CSMarkClassAsStatic(string line)
{
if ( IndexOfKeyword(line,"static") >= 0 )
return line;
int insertPoint = IndexOfKeyword(line,"class");
if ( insertPoint < 0 )
return line;
// nothing can be between partial and class
int partialIndex = IndexOfKeyword(line,"partial");
if ( partialIndex >= 0 )
insertPoint = partialIndex;
return line.Insert(insertPoint,"static ");
}
/// <summary>
/// Inserts one keyword before another one.
/// Does nothing if the keyword to be inserted already exists in the line OR if the keyword to insert before doesn't
/// </summary>
/// <param name="line">line of text to examine</param>
/// <param name="searchText">keyword to search for </param>
/// <param name="insertText">keyword to be inserted</param>
/// <returns>the possibly modified line line</returns>
private static string InsertBefore(string line,string searchText,string insertText)
{
if ( IndexOfKeyword(line,insertText) >= 0 )
return line;
int index = IndexOfKeyword(line,searchText);
if ( index < 0 )
return line;
return line.Insert(index,insertText+" ");
}
/// <summary>
/// Finds location of a keyword in a line.
/// keyword must be at the beginning of the line or preceeded by whitespace AND at the end of the line or followed by whitespace
/// </summary>
/// <param name="line">line to seach</param>
/// <param name="keyword">keyword to search for</param>
/// <returns>location of first character of keyword</returns>
private static int IndexOfKeyword(string line,string keyword)
{
int index = line.IndexOf(keyword,StringComparison.Ordinal);
if ( index < 0 )
return index;
int indexAfter = index+keyword.Length;
if ( (index == 0 || char.IsWhiteSpace(line,index-1)) && (indexAfter == line.Length || char.IsWhiteSpace(line,indexAfter)) )
return index;
return -1;
}
#endregion
}
}
| |
/* ====================================================================
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.HSLF.Record
{
using System;
using System.IO;
using NPOI.Util;
using NPOI.HSLF.Util;
using System.Collections.Generic;
/**
* Abstract class which all Container records will extend. Providers
* helpful methods for writing child records out to disk
*
* @author Nick Burch
*/
public abstract class RecordContainer : Record
{
protected Record[] _children;
//private Boolean changingChildRecordsLock = true;
/**
* Return any children
*/
public override Record[] GetChildRecords() { return _children; }
/**
* We're not an atom
*/
public override bool IsAnAtom
{
get { return false; }
}
/* ===============================================================
* Internal Move Helpers
* ===============================================================
*/
/**
* Finds the location of the given child record
*/
private int FindChildLocation(Record child)
{
// Synchronized as we don't want things changing
// as we're doing our search
lock (this)
{
for (int i = 0; i < _children.Length; i++)
{
if (_children[i].Equals(child))
{
return i;
}
}
}
return -1;
}
/**
* Adds a child record, at the very end.
* @param newChild The child record to add
*/
private void AppendChild(Record newChild)
{
lock (this)
{
// Copy over, and pop the child in at the end
Record[] nc = new Record[(_children.Length + 1)];
Array.Copy(_children, 0, nc, 0, _children.Length);
// Switch the arrays
nc[_children.Length] = newChild;
_children = nc;
}
}
/**
* Adds the given new Child Record at the given location,
* shuffling everything from there on down by one
* @param newChild
* @param position
*/
private void AddChildAt(Record newChild, int position)
{
lock (this)
{
// Firstly, have the child Added in at the end
AppendChild(newChild);
// Now, have them moved to the right place
MoveChildRecords((_children.Length - 1), position, 1);
}
}
/**
* Moves <i>number</i> child records from <i>oldLoc</i>
* to <i>newLoc</i>. Caller must have the changingChildRecordsLock
* @param oldLoc the current location of the records to move
* @param newLoc the new location for the records
* @param number the number of records to move
*/
private void MoveChildRecords(int oldLoc, int newLoc, int number)
{
if (oldLoc == newLoc) { return; }
if (number == 0) { return; }
// Check that we're not asked to move too many
if (oldLoc + number > _children.Length)
{
throw new ArgumentException("Asked to move more records than there are!");
}
// Do the move
Arrays.ArrayMoveWithin(_children, oldLoc, newLoc, number);
}
/**
* Finds the first child record of the given type,
* or null if none of the child records are of the
* given type. Does not descend.
*/
public Record FindFirstOfType(long type)
{
for (int i = 0; i < _children.Length; i++)
{
if (_children[i].RecordType == type)
{
return _children[i];
}
}
return null;
}
/**
* Remove a child record from this record Container
*
* @param ch the child to remove
* @return the Removed record
*/
public Record RemoveChild(Record ch)
{
Record rm = null;
List<Record> lst = new List<Record>();
foreach (Record r in _children)
{
if (r != ch) lst.Add(r);
else rm = r;
}
_children = lst.ToArray();
return rm;
}
/* ===============================================================
* External Move Methods
* ===============================================================
*/
/**
* Add a new child record onto a record's list of children.
*/
public void AppendChildRecord(Record newChild)
{
lock (this)
{
AppendChild(newChild);
}
}
/**
* Adds the given Child Record after the supplied record
* @param newChild
* @param after
*/
public void AddChildAfter(Record newChild, Record after)
{
lock (this)
{
// Decide where we're going to put it
int loc = FindChildLocation(after);
if (loc == -1)
{
throw new ArgumentException("Asked to add a new child after another record, but that record wasn't one of our children!");
}
// Add one place after the supplied record
AddChildAt(newChild, loc + 1);
}
}
/**
* Adds the given Child Record before the supplied record
* @param newChild
* @param before
*/
public void AddChildBefore(Record newChild, Record before)
{
lock (this)
{
// Decide where we're going to put it
int loc = FindChildLocation(before);
if (loc == -1)
{
throw new ArgumentException("Asked to add a new child before another record, but that record wasn't one of our children!");
}
// Add at the place of the supplied record
AddChildAt(newChild, loc);
}
}
/**
* Moves the given Child Record to before the supplied record
*/
public void MoveChildBefore(Record child, Record before)
{
MoveChildrenBefore(child, 1, before);
}
/**
* Moves the given Child Records to before the supplied record
*/
public void MoveChildrenBefore(Record firstChild, int number, Record before)
{
if (number < 1) { return; }
lock (this)
{
// Decide where we're going to put them
int newLoc = FindChildLocation(before);
if (newLoc == -1)
{
throw new ArgumentException("Asked to move children before another record, but that record wasn't one of our children!");
}
// Figure out where they are now
int oldLoc = FindChildLocation(firstChild);
if (oldLoc == -1)
{
throw new ArgumentException("Asked to move a record that wasn't a child!");
}
// Actually move
MoveChildRecords(oldLoc, newLoc, number);
}
}
/**
* Moves the given Child Records to after the supplied record
*/
public void MoveChildrenAfter(Record firstChild, int number, Record after)
{
if (number < 1) { return; }
lock (this)
{
// Decide where we're going to put them
int newLoc = FindChildLocation(after);
if (newLoc == -1)
{
throw new ArgumentException("Asked to move children before another record, but that record wasn't one of our children!");
}
// We actually want after this though
newLoc++;
// Figure out where they are now
int oldLoc = FindChildLocation(firstChild);
if (oldLoc == -1)
{
throw new ArgumentException("Asked to move a record that wasn't a child!");
}
// Actually move
MoveChildRecords(oldLoc, newLoc, number);
}
}
/**
* Set child records.
*
* @param records the new child records
*/
public void SetChildRecord(Record[] records)
{
this._children = records;
}
/* ===============================================================
* External Serialisation Methods
* ===============================================================
*/
/**
* Write out our header, and our children.
* @param headerA the first byte of the header
* @param headerB the second byte of the header
* @param type the record type
* @param children our child records
* @param out the stream to write to
*/
public void WriteOut(byte headerA, byte headerB, long type, Record[] children, Stream out1)
{
// If we have a mutable output stream, take advantage of that
if (out1 is MutableMemoryStream)
{
MutableMemoryStream mout =
(MutableMemoryStream)out1;
// Grab current size
int oldSize = mout.GetBytesWritten();
// Write out our header, less the size
mout.Write(new byte[] { headerA, headerB });
byte[] typeB = new byte[2];
LittleEndian.PutShort(typeB, (short)type);
mout.Write(typeB);
mout.Write(new byte[4]);
// Write out the children
for (int i = 0; i < children.Length; i++)
{
children[i].WriteOut(mout);
}
// Update our header with the size
// Don't forget to knock 8 more off, since we don't include the
// header in the size
int length = mout.GetBytesWritten() - oldSize - 8;
byte[] size = new byte[4];
LittleEndian.PutInt(size, 0, length);
mout.OverWrite(size, oldSize + 4);
}
else
{
// Going to have to do it a slower way, because we have
// to update the length come the end
// Create a MemoryStream to hold everything in
MemoryStream baos = new MemoryStream();
// Write out our header, less the size
baos.Write(new byte[] { headerA, headerB }, 0, 2);
byte[] typeB = new byte[2];
LittleEndian.PutShort(typeB, (short)type);
baos.Write(typeB, 2, 2);
baos.Write(new byte[] { 0, 0, 0, 0 }, 4, 4);
// Write out our children
for (int i = 0; i < children.Length; i++)
{
children[i].WriteOut(baos);
}
// Grab the bytes back
byte[] toWrite = baos.ToArray();
// Update our header with the size
// Don't forget to knock 8 more off, since we don't include the
// header in the size
LittleEndian.PutInt(toWrite, 4, (toWrite.Length - 8));
// Write out the bytes
out1.Write(toWrite, (int)out1.Position, toWrite.Length);
}
}
}
}
| |
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
*
* ***************************************************************************/
namespace System.Management.Automation.Interpreter
{
internal abstract class NumericConvertInstruction : Instruction
{
internal readonly TypeCode _from, _to;
protected NumericConvertInstruction(TypeCode from, TypeCode to)
{
_from = from;
_to = to;
}
public override int ConsumedStack { get { return 1; } }
public override int ProducedStack { get { return 1; } }
public override string ToString()
{
return InstructionName + "(" + _from + "->" + _to + ")";
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")]
internal sealed class Unchecked : NumericConvertInstruction
{
public override string InstructionName { get { return "UncheckedConvert"; } }
public Unchecked(TypeCode from, TypeCode to)
: base(from, to)
{
}
public override int Run(InterpretedFrame frame)
{
frame.Push(Convert(frame.Pop()));
return +1;
}
private object Convert(object obj)
{
switch (_from)
{
case TypeCode.Byte: return ConvertInt32((Byte)obj);
case TypeCode.SByte: return ConvertInt32((SByte)obj);
case TypeCode.Int16: return ConvertInt32((Int16)obj);
case TypeCode.Char: return ConvertInt32((Char)obj);
case TypeCode.Int32: return ConvertInt32((Int32)obj);
case TypeCode.Int64: return ConvertInt64((Int64)obj);
case TypeCode.UInt16: return ConvertInt32((UInt16)obj);
case TypeCode.UInt32: return ConvertInt64((UInt32)obj);
case TypeCode.UInt64: return ConvertUInt64((UInt64)obj);
case TypeCode.Single: return ConvertDouble((Single)obj);
case TypeCode.Double: return ConvertDouble((Double)obj);
default: throw Assert.Unreachable;
}
}
private object ConvertInt32(int obj)
{
unchecked
{
switch (_to)
{
case TypeCode.Byte: return (Byte)obj;
case TypeCode.SByte: return (SByte)obj;
case TypeCode.Int16: return (Int16)obj;
case TypeCode.Char: return (Char)obj;
case TypeCode.Int32: return (Int32)obj;
case TypeCode.Int64: return (Int64)obj;
case TypeCode.UInt16: return (UInt16)obj;
case TypeCode.UInt32: return (UInt32)obj;
case TypeCode.UInt64: return (UInt64)obj;
case TypeCode.Single: return (Single)obj;
case TypeCode.Double: return (Double)obj;
default: throw Assert.Unreachable;
}
}
}
private object ConvertInt64(Int64 obj)
{
unchecked
{
switch (_to)
{
case TypeCode.Byte: return (Byte)obj;
case TypeCode.SByte: return (SByte)obj;
case TypeCode.Int16: return (Int16)obj;
case TypeCode.Char: return (Char)obj;
case TypeCode.Int32: return (Int32)obj;
case TypeCode.Int64: return (Int64)obj;
case TypeCode.UInt16: return (UInt16)obj;
case TypeCode.UInt32: return (UInt32)obj;
case TypeCode.UInt64: return (UInt64)obj;
case TypeCode.Single: return (Single)obj;
case TypeCode.Double: return (Double)obj;
default: throw Assert.Unreachable;
}
}
}
private object ConvertUInt64(UInt64 obj)
{
unchecked
{
switch (_to)
{
case TypeCode.Byte: return (Byte)obj;
case TypeCode.SByte: return (SByte)obj;
case TypeCode.Int16: return (Int16)obj;
case TypeCode.Char: return (Char)obj;
case TypeCode.Int32: return (Int32)obj;
case TypeCode.Int64: return (Int64)obj;
case TypeCode.UInt16: return (UInt16)obj;
case TypeCode.UInt32: return (UInt32)obj;
case TypeCode.UInt64: return (UInt64)obj;
case TypeCode.Single: return (Single)obj;
case TypeCode.Double: return (Double)obj;
default: throw Assert.Unreachable;
}
}
}
private object ConvertDouble(Double obj)
{
unchecked
{
switch (_to)
{
case TypeCode.Byte: return (Byte)obj;
case TypeCode.SByte: return (SByte)obj;
case TypeCode.Int16: return (Int16)obj;
case TypeCode.Char: return (Char)obj;
case TypeCode.Int32: return (Int32)obj;
case TypeCode.Int64: return (Int64)obj;
case TypeCode.UInt16: return (UInt16)obj;
case TypeCode.UInt32: return (UInt32)obj;
case TypeCode.UInt64: return (UInt64)obj;
case TypeCode.Single: return (Single)obj;
case TypeCode.Double: return (Double)obj;
default: throw Assert.Unreachable;
}
}
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")]
internal sealed class Checked : NumericConvertInstruction
{
public override string InstructionName { get { return "CheckedConvert"; } }
public Checked(TypeCode from, TypeCode to)
: base(from, to)
{
}
public override int Run(InterpretedFrame frame)
{
frame.Push(Convert(frame.Pop()));
return +1;
}
private object Convert(object obj)
{
switch (_from)
{
case TypeCode.Byte: return ConvertInt32((Byte)obj);
case TypeCode.SByte: return ConvertInt32((SByte)obj);
case TypeCode.Int16: return ConvertInt32((Int16)obj);
case TypeCode.Char: return ConvertInt32((Char)obj);
case TypeCode.Int32: return ConvertInt32((Int32)obj);
case TypeCode.Int64: return ConvertInt64((Int64)obj);
case TypeCode.UInt16: return ConvertInt32((UInt16)obj);
case TypeCode.UInt32: return ConvertInt64((UInt32)obj);
case TypeCode.UInt64: return ConvertUInt64((UInt64)obj);
case TypeCode.Single: return ConvertDouble((Single)obj);
case TypeCode.Double: return ConvertDouble((Double)obj);
default: throw Assert.Unreachable;
}
}
private object ConvertInt32(int obj)
{
checked
{
switch (_to)
{
case TypeCode.Byte: return (Byte)obj;
case TypeCode.SByte: return (SByte)obj;
case TypeCode.Int16: return (Int16)obj;
case TypeCode.Char: return (Char)obj;
case TypeCode.Int32: return (Int32)obj;
case TypeCode.Int64: return (Int64)obj;
case TypeCode.UInt16: return (UInt16)obj;
case TypeCode.UInt32: return (UInt32)obj;
case TypeCode.UInt64: return (UInt64)obj;
case TypeCode.Single: return (Single)obj;
case TypeCode.Double: return (Double)obj;
default: throw Assert.Unreachable;
}
}
}
private object ConvertInt64(Int64 obj)
{
checked
{
switch (_to)
{
case TypeCode.Byte: return (Byte)obj;
case TypeCode.SByte: return (SByte)obj;
case TypeCode.Int16: return (Int16)obj;
case TypeCode.Char: return (Char)obj;
case TypeCode.Int32: return (Int32)obj;
case TypeCode.Int64: return (Int64)obj;
case TypeCode.UInt16: return (UInt16)obj;
case TypeCode.UInt32: return (UInt32)obj;
case TypeCode.UInt64: return (UInt64)obj;
case TypeCode.Single: return (Single)obj;
case TypeCode.Double: return (Double)obj;
default: throw Assert.Unreachable;
}
}
}
private object ConvertUInt64(UInt64 obj)
{
checked
{
switch (_to)
{
case TypeCode.Byte: return (Byte)obj;
case TypeCode.SByte: return (SByte)obj;
case TypeCode.Int16: return (Int16)obj;
case TypeCode.Char: return (Char)obj;
case TypeCode.Int32: return (Int32)obj;
case TypeCode.Int64: return (Int64)obj;
case TypeCode.UInt16: return (UInt16)obj;
case TypeCode.UInt32: return (UInt32)obj;
case TypeCode.UInt64: return (UInt64)obj;
case TypeCode.Single: return (Single)obj;
case TypeCode.Double: return (Double)obj;
default: throw Assert.Unreachable;
}
}
}
private object ConvertDouble(Double obj)
{
checked
{
switch (_to)
{
case TypeCode.Byte: return (Byte)obj;
case TypeCode.SByte: return (SByte)obj;
case TypeCode.Int16: return (Int16)obj;
case TypeCode.Char: return (Char)obj;
case TypeCode.Int32: return (Int32)obj;
case TypeCode.Int64: return (Int64)obj;
case TypeCode.UInt16: return (UInt16)obj;
case TypeCode.UInt32: return (UInt32)obj;
case TypeCode.UInt64: return (UInt64)obj;
case TypeCode.Single: return (Single)obj;
case TypeCode.Double: return (Double)obj;
default: throw Assert.Unreachable;
}
}
}
}
}
}
| |
// 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.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization.Formatters.Tests;
using Xunit;
namespace System.Tests
{
public static class TestExtensionMethod
{
public static DelegateTests.TestStruct TestFunc(this DelegateTests.TestClass testparam)
{
return testparam.structField;
}
public static void IncrementX(this DelegateTests.TestSerializableClass t)
{
t.x++;
}
}
public static unsafe class DelegateTests
{
public struct TestStruct
{
public object o1;
public object o2;
}
public class TestClass
{
public TestStruct structField;
}
[Serializable]
public class TestSerializableClass
{
public int x = 1;
}
private static void EmptyFunc() { }
public delegate TestStruct StructReturningDelegate();
[Fact]
public static void ClosedStaticDelegate()
{
TestClass foo = new TestClass();
foo.structField.o1 = new object();
foo.structField.o2 = new object();
StructReturningDelegate testDelegate = foo.TestFunc;
TestStruct returnedStruct = testDelegate();
Assert.Same(foo.structField.o1, returnedStruct.o1);
Assert.Same(foo.structField.o2, returnedStruct.o2);
}
[Fact]
public static void ClosedStaticDelegateSerialization()
{
var t = new TestSerializableClass();
Assert.Equal(1, t.x);
Action d = t.IncrementX;
d();
Assert.Equal(2, t.x);
d = BinaryFormatterHelpers.Clone(d);
t = (TestSerializableClass)d.Target;
Assert.Equal(2, t.x);
d();
Assert.Equal(3, t.x);
}
public class A { }
public class B : A { }
public delegate A DynamicInvokeDelegate(A nonRefParam1, B nonRefParam2, ref A refParam, out B outParam);
public static A DynamicInvokeTestFunction(A nonRefParam1, B nonRefParam2, ref A refParam, out B outParam)
{
outParam = (B)refParam;
refParam = nonRefParam2;
return nonRefParam1;
}
[Fact]
public static void DynamicInvoke()
{
A a1 = new A();
A a2 = new A();
B b1 = new B();
B b2 = new B();
DynamicInvokeDelegate testDelegate = DynamicInvokeTestFunction;
// Check that the delegate behaves as expected
A refParam = b2;
B outParam = null;
A returnValue = testDelegate(a1, b1, ref refParam, out outParam);
Assert.Same(returnValue, a1);
Assert.Same(refParam, b1);
Assert.Same(outParam, b2);
// Check dynamic invoke behavior
object[] parameters = new object[] { a1, b1, b2, null };
object retVal = testDelegate.DynamicInvoke(parameters);
Assert.Same(retVal, a1);
Assert.Same(parameters[2], b1);
Assert.Same(parameters[3], b2);
// Check invoke on a delegate that takes no parameters.
Action emptyDelegate = EmptyFunc;
emptyDelegate.DynamicInvoke(new object[] { });
emptyDelegate.DynamicInvoke(null);
}
[Fact]
public static void DynamicInvoke_MissingTypeForDefaultParameter_Succeeds()
{
// Passing Type.Missing with default.
Delegate d = new IntIntDelegateWithDefault(IntIntMethod);
d.DynamicInvoke(7, Type.Missing);
}
[Fact]
public static void DynamicInvoke_MissingTypeForNonDefaultParameter_ThrowsArgumentException()
{
Delegate d = new IntIntDelegate(IntIntMethod);
AssertExtensions.Throws<ArgumentException>("parameters", () => d.DynamicInvoke(7, Type.Missing));
}
[Theory]
[InlineData(new object[] { 7 }, new object[] { 8 })]
[InlineData(new object[] { null }, new object[] { 1 })]
public static void DynamicInvoke_RefValueTypeParameter(object[] args, object[] expected)
{
Delegate d = new RefIntDelegate(RefIntMethod);
d.DynamicInvoke(args);
Assert.Equal(expected, args);
}
[Fact]
public static void DynamicInvoke_NullRefValueTypeParameter_ReturnsValueTypeDefault()
{
Delegate d = new RefValueTypeDelegate(RefValueTypeMethod);
object[] args = new object[] { null };
d.DynamicInvoke(args);
MyStruct s = (MyStruct)(args[0]);
Assert.Equal(s.X, 7);
Assert.Equal(s.Y, 8);
}
[Fact]
public static void DynamicInvoke_TypeDoesntExactlyMatchRefValueType_ThrowsArgumentException()
{
Delegate d = new RefIntDelegate(RefIntMethod);
Assert.Throws<ArgumentException>(null, () => d.DynamicInvoke((uint)7));
Assert.Throws<ArgumentException>(null, () => d.DynamicInvoke(IntEnum.One));
}
[Theory]
[InlineData(7, (short)7)] // uint -> int
[InlineData(7, IntEnum.Seven)] // Enum (int) -> int
[InlineData(7, ShortEnum.Seven)] // Enum (short) -> int
public static void DynamicInvoke_ValuePreservingPrimitiveWidening_Succeeds(object o1, object o2)
{
Delegate d = new IntIntDelegate(IntIntMethod);
d.DynamicInvoke(o1, o2);
}
[Theory]
[InlineData(IntEnum.Seven, 7)]
[InlineData(IntEnum.Seven, (short)7)]
public static void DynamicInvoke_ValuePreservingWideningToEnum_Succeeds(object o1, object o2)
{
Delegate d = new EnumEnumDelegate(EnumEnumMethod);
d.DynamicInvoke(o1, o2);
}
[Fact]
public static void DynamicInvoke_SizePreservingNonVauePreservingConversion_ThrowsArgumentException()
{
Delegate d = new IntIntDelegate(IntIntMethod);
Assert.Throws<ArgumentException>(null, () => d.DynamicInvoke(7, (uint)7));
Assert.Throws<ArgumentException>(null, () => d.DynamicInvoke(7, U4.Seven));
}
[Fact]
public static void DynamicInvoke_NullValueType_Succeeds()
{
Delegate d = new ValueTypeDelegate(ValueTypeMethod);
d.DynamicInvoke(new object[] { null });
}
[Fact]
public static void DynamicInvoke_ConvertMatchingTToNullable_Succeeds()
{
Delegate d = new NullableDelegate(NullableMethod);
d.DynamicInvoke(7);
}
[Fact]
public static void DynamicInvoke_ConvertNonMatchingTToNullable_ThrowsArgumentException()
{
Delegate d = new NullableDelegate(NullableMethod);
Assert.Throws<ArgumentException>(null, () => d.DynamicInvoke((short)7));
Assert.Throws<ArgumentException>(null, () => d.DynamicInvoke(IntEnum.Seven));
}
[Fact]
public static void DynamicInvoke_DefaultParameter_AllPrimitiveParametersWithMissingValues()
{
object[] parameters = new object[13];
for (int i = 0; i < parameters.Length; i++) { parameters[i] = Type.Missing; }
Assert.Equal(
"True, test, c, 2, -1, -3, 4, -5, 6, -7, 8, 9.1, 11.12",
(string)(new AllPrimitivesWithDefaultValues(AllPrimitivesMethod)).DynamicInvoke(parameters));
}
[Fact]
public static void DynamicInvoke_DefaultParameter_AllPrimitiveParametersWithAllExplicitValues()
{
Assert.Equal(
"False, value, d, 102, -101, -103, 104, -105, 106, -107, 108, 109.1, 111.12",
(string)(new AllPrimitivesWithDefaultValues(AllPrimitivesMethod)).DynamicInvoke(
new object[13]
{
false,
"value",
'd',
(byte)102,
(sbyte)-101,
(short)-103,
(UInt16)104,
(int)-105,
(UInt32)106,
(long)-107,
(UInt64)108,
(Single)109.1,
(Double)111.12
}
));
}
[Fact]
public static void DynamicInvoke_DefaultParameter_AllPrimitiveParametersWithSomeExplicitValues()
{
Assert.Equal(
"False, test, d, 2, -101, -3, 104, -5, 106, -7, 108, 9.1, 111.12",
(string)(new AllPrimitivesWithDefaultValues(AllPrimitivesMethod)).DynamicInvoke(
new object[13]
{
false,
Type.Missing,
'd',
Type.Missing,
(sbyte)-101,
Type.Missing,
(UInt16)104,
Type.Missing,
(UInt32)106,
Type.Missing,
(UInt64)108,
Type.Missing,
(Double)111.12
}
));
}
[Fact]
public static void DynamicInvoke_DefaultParameter_StringParameterWithMissingValue()
{
Assert.Equal
("test",
(string)(new StringWithDefaultValue(StringMethod)).DynamicInvoke(new object[] { Type.Missing }));
}
[Fact]
public static void DynamicInvoke_DefaultParameter_StringParameterWithExplicitValue()
{
Assert.Equal(
"value",
(string)(new StringWithDefaultValue(StringMethod)).DynamicInvoke(new object[] { "value" }));
}
[Fact]
public static void DynamicInvoke_DefaultParameter_ReferenceTypeParameterWithMissingValue()
{
Assert.Null((new ReferenceWithDefaultValue(ReferenceMethod)).DynamicInvoke(new object[] { Type.Missing }));
}
[Fact]
public static void DynamicInvoke_DefaultParameter_ReferenceTypeParameterWithExplicitValue()
{
CustomReferenceType referenceInstance = new CustomReferenceType();
Assert.Same(
referenceInstance,
(new ReferenceWithDefaultValue(ReferenceMethod)).DynamicInvoke(new object[] { referenceInstance }));
}
[Fact]
public static void DynamicInvoke_DefaultParameter_ValueTypeParameterWithMissingValue()
{
Assert.Equal(
0,
((CustomValueType)(new ValueTypeWithDefaultValue(ValueTypeMethod)).DynamicInvoke(new object[] { Type.Missing })).Id);
}
[Fact]
public static void DynamicInvoke_DefaultParameter_ValueTypeParameterWithExplicitValue()
{
Assert.Equal(
1,
((CustomValueType)(new ValueTypeWithDefaultValue(ValueTypeMethod)).DynamicInvoke(new object[] { new CustomValueType { Id = 1 } })).Id);
}
[Fact]
public static void DynamicInvoke_DefaultParameter_DateTimeParameterWithMissingValue()
{
Assert.Equal(
new DateTime(42),
(DateTime)(new DateTimeWithDefaultValueAttribute(DateTimeMethod)).DynamicInvoke(new object[] { Type.Missing }));
}
[Fact]
public static void DynamicInvoke_DefaultParameter_DateTimeParameterWithExplicitValue()
{
Assert.Equal(
new DateTime(43),
(DateTime)(new DateTimeWithDefaultValueAttribute(DateTimeMethod)).DynamicInvoke(new object[] { new DateTime(43) }));
}
[Fact]
public static void DynamicInvoke_DefaultParameter_DecimalParameterWithAttributeAndMissingValue()
{
Assert.Equal(
new decimal(4, 3, 2, true, 1),
(decimal)(new DecimalWithDefaultValueAttribute(DecimalMethod)).DynamicInvoke(new object[] { Type.Missing }));
}
[Fact]
public static void DynamicInvoke_DefaultParameter_DecimalParameterWithAttributeAndExplicitValue()
{
Assert.Equal(
new decimal(12, 13, 14, true, 1),
(decimal)(new DecimalWithDefaultValueAttribute(DecimalMethod)).DynamicInvoke(new object[] { new decimal(12, 13, 14, true, 1) }));
}
[Fact]
public static void DynamicInvoke_DefaultParameter_DecimalParameterWithMissingValue()
{
Assert.Equal(
3.14m,
(decimal)(new DecimalWithDefaultValue(DecimalMethod)).DynamicInvoke(new object[] { Type.Missing }));
}
[Fact]
public static void DynamicInvoke_DefaultParameter_DecimalParameterWithExplicitValue()
{
Assert.Equal(
103.14m,
(decimal)(new DecimalWithDefaultValue(DecimalMethod)).DynamicInvoke(new object[] { 103.14m }));
}
[Fact]
public static void DynamicInvoke_DefaultParameter_NullableIntWithMissingValue()
{
Assert.Null((int?)(new NullableIntWithDefaultValue(NullableIntMethod)).DynamicInvoke(new object[] { Type.Missing }));
}
[Fact]
public static void DynamicInvoke_DefaultParameter_NullableIntWithExplicitValue()
{
Assert.Equal(
(int?)42,
(int?)(new NullableIntWithDefaultValue(NullableIntMethod)).DynamicInvoke(new object[] { (int?)42 }));
}
[Fact]
public static void DynamicInvoke_DefaultParameter_EnumParameterWithMissingValue()
{
Assert.Equal(
IntEnum.Seven,
(IntEnum)(new EnumWithDefaultValue(EnumMethod)).DynamicInvoke(new object[] { Type.Missing }));
}
[Fact]
public static void DynamicInvoke_OptionalParameter_WithExplicitValue()
{
Assert.Equal(
"value",
(new OptionalObjectParameter(ObjectMethod)).DynamicInvoke(new object[] { "value" }));
}
[Fact]
public static void DynamicInvoke_OptionalParameter_WithMissingValue()
{
Assert.Equal(
Type.Missing,
(new OptionalObjectParameter(ObjectMethod)).DynamicInvoke(new object[] { Type.Missing }));
}
[Fact]
public static void DynamicInvoke_OptionalParameterUnassingableFromMissing_WithMissingValue()
{
Assert.Throws<ArgumentException>(() => (new OptionalStringParameter(StringMethod)).DynamicInvoke(new object[] { Type.Missing }));
}
[Fact]
public static void DynamicInvoke_ParameterSpecification_ArrayOfStrings()
{
Assert.Equal(
"value",
(new StringParameter(StringMethod)).DynamicInvoke(new string[] { "value" }));
}
[Fact]
public static void DynamicInvoke_ParameterSpecification_ArrayOfMissing()
{
Assert.Same(
Missing.Value,
(new OptionalObjectParameter(ObjectMethod)).DynamicInvoke(new Missing[] { Missing.Value }));
}
private static void IntIntMethod(int expected, int actual)
{
Assert.Equal(expected, actual);
}
private delegate void IntIntDelegate(int expected, int actual);
private delegate void IntIntDelegateWithDefault(int expected, int actual = 7);
private static void RefIntMethod(ref int i) => i++;
private delegate void RefIntDelegate(ref int i);
private struct MyStruct
{
public int X;
public int Y;
}
private static void RefValueTypeMethod(ref MyStruct s)
{
s.X += 7;
s.Y += 8;
}
private delegate void RefValueTypeDelegate(ref MyStruct s);
private static void EnumEnumMethod(IntEnum expected, IntEnum actual)
{
Assert.Equal(expected, actual);
}
private delegate void EnumEnumDelegate(IntEnum expected, IntEnum actual);
private static void ValueTypeMethod(MyStruct s)
{
Assert.Equal(s.X, 0);
Assert.Equal(s.Y, 0);
}
private delegate void ValueTypeDelegate(MyStruct s);
private static void NullableMethod(int? n)
{
Assert.True(n.HasValue);
Assert.Equal(n.Value, 7);
}
private delegate void NullableDelegate(int? s);
private enum ShortEnum : short
{
One = 1,
Seven = 7,
}
private enum IntEnum : int
{
One = 1,
Seven = 7,
}
private enum U4 : uint
{
One = 1,
Seven = 7,
}
private delegate string AllPrimitivesWithDefaultValues(
bool boolean = true,
string str = "test",
char character = 'c',
byte unsignedbyte = 2,
sbyte signedbyte = -1,
Int16 int16 = -3,
UInt16 uint16 = 4,
Int32 int32 = -5,
UInt32 uint32 = 6,
Int64 int64 = -7,
UInt64 uint64 = 8,
Single single = (Single)9.1,
Double dbl = 11.12);
private static string AllPrimitivesMethod(
bool boolean,
string str,
char character,
byte unsignedbyte,
sbyte signedbyte,
Int16 int16,
UInt16 uint16,
Int32 int32,
UInt32 uint32,
Int64 int64,
UInt64 uint64,
Single single,
Double dbl)
{
return FormattableString.Invariant($"{boolean}, {str}, {character}, {unsignedbyte}, {signedbyte}, {int16}, {uint16}, {int32}, {uint32}, {int64}, {uint64}, {single}, {dbl}");
}
private delegate string StringParameter(string parameter);
private delegate string StringWithDefaultValue(string parameter = "test");
private static string StringMethod(string parameter)
{
return parameter;
}
private class CustomReferenceType { };
private delegate CustomReferenceType ReferenceWithDefaultValue(CustomReferenceType parameter = null);
private static CustomReferenceType ReferenceMethod(CustomReferenceType parameter)
{
return parameter;
}
private struct CustomValueType { public int Id; };
private delegate CustomValueType ValueTypeWithDefaultValue(CustomValueType parameter = default(CustomValueType));
private static CustomValueType ValueTypeMethod(CustomValueType parameter)
{
return parameter;
}
private delegate DateTime DateTimeWithDefaultValueAttribute([DateTimeConstant(42)] DateTime parameter);
private static DateTime DateTimeMethod(DateTime parameter)
{
return parameter;
}
private delegate decimal DecimalWithDefaultValueAttribute([DecimalConstant(1, 1, 2, 3, 4)] decimal parameter);
private delegate decimal DecimalWithDefaultValue(decimal parameter = 3.14m);
private static decimal DecimalMethod(decimal parameter)
{
return parameter;
}
private delegate int? NullableIntWithDefaultValue(int? parameter = null);
private static int? NullableIntMethod(int? parameter)
{
return parameter;
}
private delegate IntEnum EnumWithDefaultValue(IntEnum parameter = IntEnum.Seven);
private static IntEnum EnumMethod(IntEnum parameter = IntEnum.Seven)
{
return parameter;
}
private delegate object OptionalObjectParameter([Optional] object parameter);
private static object ObjectMethod(object parameter)
{
return parameter;
}
private delegate string OptionalStringParameter([Optional] string parameter);
}
public static class CreateDelegateTests
{
#region Tests
[Fact]
public static void CreateDelegate1_Method_Static()
{
C c = new C();
MethodInfo mi = typeof(C).GetMethod("S");
Delegate dg = Delegate.CreateDelegate(typeof(D), mi);
Assert.Same(mi, dg.Method);
Assert.Null(dg.Target);
D d = (D)dg;
d(c);
}
[Fact]
public static void CreateDelegate1_Method_Null()
{
try
{
Delegate.CreateDelegate(typeof(D), (MethodInfo)null);
}
catch (ArgumentNullException ex)
{
Assert.Equal(typeof(ArgumentNullException), ex.GetType());
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
Assert.NotNull(ex.ParamName);
Assert.Equal("method", ex.ParamName);
}
}
[Fact]
public static void CreateDelegate1_Type_Null()
{
MethodInfo mi = typeof(C).GetMethod("S");
try
{
Delegate.CreateDelegate((Type)null, mi);
}
catch (ArgumentNullException ex)
{
Assert.Equal(typeof(ArgumentNullException), ex.GetType());
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
Assert.NotNull(ex.ParamName);
Assert.Equal("type", ex.ParamName);
}
}
[Fact]
public static void CreateDelegate2()
{
E e;
e = (E)Delegate.CreateDelegate(typeof(E), new B(), "Execute");
Assert.NotNull(e);
Assert.Equal(4, e(new C()));
e = (E)Delegate.CreateDelegate(typeof(E), new C(), "Execute");
Assert.NotNull(e);
Assert.Equal(4, e(new C()));
e = (E)Delegate.CreateDelegate(typeof(E), new C(), "DoExecute");
Assert.NotNull(e);
Assert.Equal(102, e(new C()));
}
[Fact]
public static void CreateDelegate2_Method_ArgumentsMismatch()
{
try
{
Delegate.CreateDelegate(typeof(E), new B(),
"StartExecute");
}
catch (ArgumentException ex)
{
// Error binding to target method
Assert.Equal(typeof(ArgumentException), ex.GetType());
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
Assert.Null(ex.ParamName);
}
}
[Fact]
public static void CreateDelegate2_Method_CaseMismatch()
{
try
{
Delegate.CreateDelegate(typeof(E), new B(), "ExecutE");
}
catch (ArgumentException ex)
{
// Error binding to target method
Assert.Equal(typeof(ArgumentException), ex.GetType());
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
Assert.Null(ex.ParamName);
}
}
[Fact]
public static void CreateDelegate2_Method_DoesNotExist()
{
try
{
Delegate.CreateDelegate(typeof(E), new B(),
"DoesNotExist");
}
catch (ArgumentException ex)
{
// Error binding to target method
Assert.Equal(typeof(ArgumentException), ex.GetType());
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
Assert.Null(ex.ParamName);
}
}
[Fact]
public static void CreateDelegate2_Method_Null()
{
C c = new C();
try
{
Delegate.CreateDelegate(typeof(D), c, (string)null);
}
catch (ArgumentNullException ex)
{
Assert.Equal(typeof(ArgumentNullException), ex.GetType());
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
Assert.NotNull(ex.ParamName);
Assert.Equal("method", ex.ParamName);
}
}
[Fact]
public static void CreateDelegate2_Method_ReturnTypeMismatch()
{
try
{
Delegate.CreateDelegate(typeof(E), new B(),
"DoExecute");
}
catch (ArgumentException ex)
{
// Error binding to target method
Assert.Equal(typeof(ArgumentException), ex.GetType());
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
Assert.Null(ex.ParamName);
}
}
[Fact]
public static void CreateDelegate2_Method_Static()
{
try
{
Delegate.CreateDelegate(typeof(E), new B(), "Run");
}
catch (ArgumentException ex)
{
// Error binding to target method
Assert.Equal(typeof(ArgumentException), ex.GetType());
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
Assert.Null(ex.ParamName);
}
}
[Fact]
public static void CreateDelegate2_Target_Null()
{
try
{
Delegate.CreateDelegate(typeof(D), null, "N");
}
catch (ArgumentNullException ex)
{
Assert.Equal(typeof(ArgumentNullException), ex.GetType());
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
Assert.NotNull(ex.ParamName);
Assert.Equal("target", ex.ParamName);
}
}
[Fact]
public static void CreateDelegate2_Type_Null()
{
C c = new C();
try
{
Delegate.CreateDelegate((Type)null, c, "N");
}
catch (ArgumentNullException ex)
{
Assert.Equal(typeof(ArgumentNullException), ex.GetType());
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
Assert.NotNull(ex.ParamName);
Assert.Equal("type", ex.ParamName);
}
}
[Fact]
public static void CreateDelegate3()
{
E e;
// matching static method
e = (E)Delegate.CreateDelegate(typeof(E), typeof(B), "Run");
Assert.NotNull(e);
Assert.Equal(5, e(new C()));
// matching static method
e = (E)Delegate.CreateDelegate(typeof(E), typeof(C), "Run");
Assert.NotNull(e);
Assert.Equal(5, e(new C()));
// matching static method
e = (E)Delegate.CreateDelegate(typeof(E), typeof(C), "DoRun");
Assert.NotNull(e);
Assert.Equal(107, e(new C()));
}
[Fact]
public static void CreateDelegate3_Method_ArgumentsMismatch()
{
try
{
Delegate.CreateDelegate(typeof(E), typeof(B),
"StartRun");
}
catch (ArgumentException ex)
{
// Error binding to target method
Assert.Equal(typeof(ArgumentException), ex.GetType());
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
Assert.Null(ex.ParamName);
}
}
[Fact]
public static void CreateDelegate3_Method_CaseMismatch()
{
try
{
Delegate.CreateDelegate(typeof(E), typeof(B), "RuN");
}
catch (ArgumentException ex)
{
// Error binding to target method
Assert.Equal(typeof(ArgumentException), ex.GetType());
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
Assert.Null(ex.ParamName);
}
}
[Fact]
public static void CreateDelegate3_Method_DoesNotExist()
{
try
{
Delegate.CreateDelegate(typeof(E), typeof(B),
"DoesNotExist");
}
catch (ArgumentException ex)
{
// Error binding to target method
Assert.Equal(typeof(ArgumentException), ex.GetType());
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
Assert.Null(ex.ParamName);
}
}
[Fact]
public static void CreateDelegate3_Method_Instance()
{
try
{
Delegate.CreateDelegate(typeof(E), typeof(B), "Execute");
}
catch (ArgumentException ex)
{
// Error binding to target method
Assert.Equal(typeof(ArgumentException), ex.GetType());
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
Assert.Null(ex.ParamName);
}
}
[Fact]
public static void CreateDelegate3_Method_Null()
{
try
{
Delegate.CreateDelegate(typeof(D), typeof(C), (string)null);
}
catch (ArgumentNullException ex)
{
Assert.Equal(typeof(ArgumentNullException), ex.GetType());
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
Assert.NotNull(ex.ParamName);
Assert.Equal("method", ex.ParamName);
}
}
[Fact]
public static void CreateDelegate3_Method_ReturnTypeMismatch()
{
try
{
Delegate.CreateDelegate(typeof(E), typeof(B),
"DoRun");
}
catch (ArgumentException ex)
{
// Error binding to target method
Assert.Equal(typeof(ArgumentException), ex.GetType());
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
Assert.Null(ex.ParamName);
}
}
[Fact]
public static void CreateDelegate3_Target_Null()
{
try
{
Delegate.CreateDelegate(typeof(D), (Type)null, "S");
}
catch (ArgumentNullException ex)
{
Assert.Equal(typeof(ArgumentNullException), ex.GetType());
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
Assert.NotNull(ex.ParamName);
Assert.Equal("target", ex.ParamName);
}
}
[Fact]
public static void CreateDelegate3_Type_Null()
{
try
{
Delegate.CreateDelegate((Type)null, typeof(C), "S");
}
catch (ArgumentNullException ex)
{
Assert.Equal(typeof(ArgumentNullException), ex.GetType());
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
Assert.NotNull(ex.ParamName);
Assert.Equal("type", ex.ParamName);
}
}
[Fact]
public static void CreateDelegate4()
{
E e;
B b = new B();
// instance method, exact case, ignore case
e = (E)Delegate.CreateDelegate(typeof(E), b, "Execute", true);
Assert.NotNull(e);
Assert.Equal(4, e(new C()));
// instance method, exact case, do not ignore case
e = (E)Delegate.CreateDelegate(typeof(E), b, "Execute", false);
Assert.NotNull(e);
Assert.Equal(4, e(new C()));
// instance method, case mismatch, ignore case
e = (E)Delegate.CreateDelegate(typeof(E), b, "ExecutE", true);
Assert.NotNull(e);
Assert.Equal(4, e(new C()));
C c = new C();
// instance method, exact case, ignore case
e = (E)Delegate.CreateDelegate(typeof(E), c, "Execute", true);
Assert.NotNull(e);
Assert.Equal(4, e(new C()));
// instance method, exact case, ignore case
e = (E)Delegate.CreateDelegate(typeof(E), c, "DoExecute", true);
Assert.NotNull(e);
Assert.Equal(102, e(new C()));
// instance method, exact case, do not ignore case
e = (E)Delegate.CreateDelegate(typeof(E), c, "Execute", false);
Assert.NotNull(e);
Assert.Equal(4, e(new C()));
// instance method, case mismatch, ignore case
e = (E)Delegate.CreateDelegate(typeof(E), c, "ExecutE", true);
Assert.NotNull(e);
Assert.Equal(4, e(new C()));
}
[Fact]
public static void CreateDelegate4_Method_ArgumentsMismatch()
{
try
{
Delegate.CreateDelegate(typeof(E), new B(),
"StartExecute", false);
}
catch (ArgumentException ex)
{
// Error binding to target method
Assert.Equal(typeof(ArgumentException), ex.GetType());
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
Assert.Null(ex.ParamName);
}
}
[Fact]
public static void CreateDelegate4_Method_CaseMismatch()
{
// instance method, case mismatch, do not igore case
try
{
Delegate.CreateDelegate(typeof(E), new B(),
"ExecutE", false);
}
catch (ArgumentException ex)
{
// Error binding to target method
Assert.Equal(typeof(ArgumentException), ex.GetType());
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
Assert.Null(ex.ParamName);
}
}
[Fact]
public static void CreateDelegate4_Method_DoesNotExist()
{
try
{
Delegate.CreateDelegate(typeof(E), new B(),
"DoesNotExist", false);
}
catch (ArgumentException ex)
{
// Error binding to target method
Assert.Equal(typeof(ArgumentException), ex.GetType());
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
Assert.Null(ex.ParamName);
}
}
[Fact]
public static void CreateDelegate4_Method_Null()
{
try
{
Delegate.CreateDelegate(typeof(D), new C(),
(string)null, true);
}
catch (ArgumentNullException ex)
{
Assert.Equal(typeof(ArgumentNullException), ex.GetType());
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
Assert.NotNull(ex.ParamName);
Assert.Equal("method", ex.ParamName);
}
}
[Fact]
public static void CreateDelegate4_Method_ReturnTypeMismatch()
{
try
{
Delegate.CreateDelegate(typeof(E), new B(),
"DoExecute", false);
}
catch (ArgumentException ex)
{
// Error binding to target method
Assert.Equal(typeof(ArgumentException), ex.GetType());
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
Assert.Null(ex.ParamName);
}
}
[Fact]
public static void CreateDelegate4_Method_Static()
{
try
{
Delegate.CreateDelegate(typeof(E), new B(), "Run", true);
}
catch (ArgumentException ex)
{
// Error binding to target method
Assert.Equal(typeof(ArgumentException), ex.GetType());
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
Assert.Null(ex.ParamName);
}
}
[Fact]
public static void CreateDelegate4_Target_Null()
{
try
{
Delegate.CreateDelegate(typeof(D), null, "N", true);
}
catch (ArgumentNullException ex)
{
Assert.Equal(typeof(ArgumentNullException), ex.GetType());
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
Assert.NotNull(ex.ParamName);
Assert.Equal("target", ex.ParamName);
}
}
[Fact]
public static void CreateDelegate4_Type_Null()
{
C c = new C();
try
{
Delegate.CreateDelegate((Type)null, c, "N", true);
}
catch (ArgumentNullException ex)
{
Assert.Equal(typeof(ArgumentNullException), ex.GetType());
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
Assert.NotNull(ex.ParamName);
Assert.Equal("type", ex.ParamName);
}
}
[Fact]
public static void CreateDelegate9()
{
E e;
// do not ignore case, do not throw bind failure
e = (E)Delegate.CreateDelegate(typeof(E), new B(),
"Execute", false, false);
Assert.NotNull(e);
Assert.Equal(4, e(new C()));
// do not ignore case, throw bind failure
e = (E)Delegate.CreateDelegate(typeof(E), new B(),
"Execute", false, true);
Assert.NotNull(e);
Assert.Equal(4, e(new C()));
// ignore case, do not throw bind failure
e = (E)Delegate.CreateDelegate(typeof(E), new B(),
"Execute", true, false);
Assert.NotNull(e);
Assert.Equal(4, e(new C()));
// ignore case, throw bind failure
e = (E)Delegate.CreateDelegate(typeof(E), new B(),
"Execute", true, true);
Assert.NotNull(e);
Assert.Equal(4, e(new C()));
// do not ignore case, do not throw bind failure
e = (E)Delegate.CreateDelegate(typeof(E), new C(),
"Execute", false, false);
Assert.NotNull(e);
Assert.Equal(4, e(new C()));
// do not ignore case, throw bind failure
e = (E)Delegate.CreateDelegate(typeof(E), new C(),
"Execute", false, true);
Assert.NotNull(e);
Assert.Equal(4, e(new C()));
// ignore case, do not throw bind failure
e = (E)Delegate.CreateDelegate(typeof(E), new C(),
"Execute", true, false);
Assert.NotNull(e);
Assert.Equal(4, e(new C()));
// ignore case, throw bind failure
e = (E)Delegate.CreateDelegate(typeof(E), new C(),
"Execute", true, true);
Assert.NotNull(e);
Assert.Equal(4, e(new C()));
// do not ignore case, do not throw bind failure
e = (E)Delegate.CreateDelegate(typeof(E), new C(),
"DoExecute", false, false);
Assert.NotNull(e);
Assert.Equal(102, e(new C()));
// do not ignore case, throw bind failure
e = (E)Delegate.CreateDelegate(typeof(E), new C(),
"DoExecute", false, true);
Assert.NotNull(e);
Assert.Equal(102, e(new C()));
// ignore case, do not throw bind failure
e = (E)Delegate.CreateDelegate(typeof(E), new C(),
"DoExecute", true, false);
Assert.NotNull(e);
Assert.Equal(102, e(new C()));
// ignore case, throw bind failure
e = (E)Delegate.CreateDelegate(typeof(E), new C(),
"DoExecute", true, true);
Assert.NotNull(e);
Assert.Equal(102, e(new C()));
}
[Fact]
public static void CreateDelegate9_Method_ArgumentsMismatch()
{
// throw bind failure
try
{
Delegate.CreateDelegate(typeof(E), new B(),
"StartExecute", false, true);
}
catch (ArgumentException ex)
{
// Error binding to target method
Assert.Equal(typeof(ArgumentException), ex.GetType());
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
Assert.Null(ex.ParamName);
}
// do not throw on bind failure
E e = (E)Delegate.CreateDelegate(typeof(E), new B(),
"StartExecute", false, false);
Assert.Null(e);
}
[Fact]
public static void CreateDelegate9_Method_CaseMismatch()
{
E e;
// do not ignore case, throw bind failure
try
{
Delegate.CreateDelegate(typeof(E), new B(),
"ExecutE", false, true);
}
catch (ArgumentException ex)
{
// Error binding to target method
Assert.Equal(typeof(ArgumentException), ex.GetType());
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
Assert.Null(ex.ParamName);
}
// do not ignore case, do not throw bind failure
e = (E)Delegate.CreateDelegate(typeof(E), new B(),
"ExecutE", false, false);
Assert.Null(e);
// ignore case, throw bind failure
e = (E)Delegate.CreateDelegate(typeof(E), new B(),
"ExecutE", true, true);
Assert.NotNull(e);
Assert.Equal(4, e(new C()));
// ignore case, do not throw bind failure
e = (E)Delegate.CreateDelegate(typeof(E), new B(),
"ExecutE", true, false);
Assert.NotNull(e);
Assert.Equal(4, e(new C()));
}
[Fact]
public static void CreateDelegate9_Method_DoesNotExist()
{
// throw bind failure
try
{
Delegate.CreateDelegate(typeof(E), new B(),
"DoesNotExist", false, true);
}
catch (ArgumentException ex)
{
// Error binding to target method
Assert.Equal(typeof(ArgumentException), ex.GetType());
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
Assert.Null(ex.ParamName);
}
// do not throw on bind failure
E e = (E)Delegate.CreateDelegate(typeof(E), new B(),
"DoesNotExist", false, false);
Assert.Null(e);
}
[Fact]
public static void CreateDelegate9_Method_Null()
{
try
{
Delegate.CreateDelegate(typeof(E), new B(),
(string)null, false, false);
}
catch (ArgumentNullException ex)
{
Assert.Equal(typeof(ArgumentNullException), ex.GetType());
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
Assert.NotNull(ex.ParamName);
Assert.Equal("method", ex.ParamName);
}
}
[Fact]
public static void CreateDelegate9_Method_ReturnTypeMismatch()
{
// throw bind failure
try
{
Delegate.CreateDelegate(typeof(E), new B(),
"DoExecute", false, true);
}
catch (ArgumentException ex)
{
// Error binding to target method
Assert.Equal(typeof(ArgumentException), ex.GetType());
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
Assert.Null(ex.ParamName);
}
// do not throw on bind failure
E e = (E)Delegate.CreateDelegate(typeof(E), new B(),
"DoExecute", false, false);
Assert.Null(e);
}
[Fact]
public static void CreateDelegate9_Method_Static()
{
// throw bind failure
try
{
Delegate.CreateDelegate(typeof(E), new B(),
"Run", true, true);
}
catch (ArgumentException ex)
{
// Error binding to target method
Assert.Equal(typeof(ArgumentException), ex.GetType());
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
Assert.Null(ex.ParamName);
}
// do not throw on bind failure
E e = (E)Delegate.CreateDelegate(typeof(E), new B(),
"Run", true, false);
Assert.Null(e);
}
[Fact]
public static void CreateDelegate9_Target_Null()
{
try
{
Delegate.CreateDelegate(typeof(E), (object)null,
"Execute", true, false);
}
catch (ArgumentNullException ex)
{
Assert.Equal(typeof(ArgumentNullException), ex.GetType());
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
Assert.NotNull(ex.ParamName);
Assert.Equal("target", ex.ParamName);
}
}
[Fact]
public static void CreateDelegate9_Type_Null()
{
try
{
Delegate.CreateDelegate((Type)null, new B(),
"Execute", true, false);
}
catch (ArgumentNullException ex)
{
Assert.Equal(typeof(ArgumentNullException), ex.GetType());
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
Assert.NotNull(ex.ParamName);
Assert.Equal("type", ex.ParamName);
}
}
#endregion Tests
#region Test Setup
public class B
{
public virtual string retarg3(string s)
{
return s;
}
static int Run(C x)
{
return 5;
}
public static void DoRun(C x)
{
}
public static int StartRun(C x, B b)
{
return 6;
}
int Execute(C c)
{
return 4;
}
public static void DoExecute(C c)
{
}
public int StartExecute(C c, B b)
{
return 3;
}
}
public class C : B, Iface
{
public string retarg(string s)
{
return s;
}
public string retarg2(Iface iface, string s)
{
return s + "2";
}
public override string retarg3(string s)
{
return s + "2";
}
static void Run(C x)
{
}
public new static int DoRun(C x)
{
return 107;
}
void Execute(C c)
{
}
public new int DoExecute(C c)
{
return 102;
}
public static void M()
{
}
public static void N(C c)
{
}
public static void S(C c)
{
}
private void PrivateInstance()
{
}
}
public interface Iface
{
string retarg(string s);
}
public delegate void D(C c);
public delegate int E(C c);
#endregion Test Setup
}
}
| |
// =================================================================================================
// ADOBE SYSTEMS INCORPORATED
// Copyright 2006 Adobe Systems Incorporated
// All Rights Reserved
//
// NOTICE: Adobe permits you to use, modify, and distribute this file in accordance with the terms
// of the Adobe license agreement accompanying it.
// =================================================================================================
using System;
using Com.Adobe.Xmp;
using Com.Adobe.Xmp.Impl.Xpath;
using Com.Adobe.Xmp.Options;
using Sharpen;
namespace Com.Adobe.Xmp.Impl
{
/// <summary>Utilities for <code>XMPNode</code>.</summary>
/// <since>Aug 28, 2006</since>
public class XMPNodeUtils : XMPConst
{
internal const int CltNoValues = 0;
internal const int CltSpecificMatch = 1;
internal const int CltSingleGeneric = 2;
internal const int CltMultipleGeneric = 3;
internal const int CltXdefault = 4;
internal const int CltFirstItem = 5;
/// <summary>Private Constructor</summary>
private XMPNodeUtils()
{
}
// EMPTY
/// <summary>Find or create a schema node if <code>createNodes</code> is false and</summary>
/// <param name="tree">the root of the xmp tree.</param>
/// <param name="namespaceURI">a namespace</param>
/// <param name="createNodes">
/// a flag indicating if the node shall be created if not found.
/// <em>Note:</em> The namespace must be registered prior to this call.
/// </param>
/// <returns>
/// Returns the schema node if found, <code>null</code> otherwise.
/// Note: If <code>createNodes</code> is <code>true</code>, it is <b>always</b>
/// returned a valid node.
/// </returns>
/// <exception cref="Com.Adobe.Xmp.XMPException">
/// An exception is only thrown if an error occurred, not if a
/// node was not found.
/// </exception>
internal static XMPNode FindSchemaNode(XMPNode tree, string namespaceURI, bool createNodes)
{
return FindSchemaNode(tree, namespaceURI, null, createNodes);
}
/// <summary>Find or create a schema node if <code>createNodes</code> is true.</summary>
/// <param name="tree">the root of the xmp tree.</param>
/// <param name="namespaceURI">a namespace</param>
/// <param name="suggestedPrefix">If a prefix is suggested, the namespace is allowed to be registered.</param>
/// <param name="createNodes">
/// a flag indicating if the node shall be created if not found.
/// <em>Note:</em> The namespace must be registered prior to this call.
/// </param>
/// <returns>
/// Returns the schema node if found, <code>null</code> otherwise.
/// Note: If <code>createNodes</code> is <code>true</code>, it is <b>always</b>
/// returned a valid node.
/// </returns>
/// <exception cref="Com.Adobe.Xmp.XMPException">
/// An exception is only thrown if an error occurred, not if a
/// node was not found.
/// </exception>
internal static XMPNode FindSchemaNode(XMPNode tree, string namespaceURI, string suggestedPrefix, bool createNodes)
{
System.Diagnostics.Debug.Assert(tree.GetParent() == null);
// make sure that its the root
XMPNode schemaNode = tree.FindChildByName(namespaceURI);
if (schemaNode == null && createNodes)
{
schemaNode = new XMPNode(namespaceURI, new PropertyOptions().SetSchemaNode(true));
schemaNode.SetImplicit(true);
// only previously registered schema namespaces are allowed in the XMP tree.
string prefix = XMPMetaFactory.GetSchemaRegistry().GetNamespacePrefix(namespaceURI);
if (prefix == null)
{
if (suggestedPrefix != null && suggestedPrefix.Length != 0)
{
prefix = XMPMetaFactory.GetSchemaRegistry().RegisterNamespace(namespaceURI, suggestedPrefix);
}
else
{
throw new XMPException("Unregistered schema namespace URI", XMPErrorConstants.Badschema);
}
}
schemaNode.SetValue(prefix);
tree.AddChild(schemaNode);
}
return schemaNode;
}
/// <summary>Find or create a child node under a given parent node.</summary>
/// <remarks>
/// Find or create a child node under a given parent node. If the parent node is no
/// Returns the found or created child node.
/// </remarks>
/// <param name="parent">the parent node</param>
/// <param name="childName">the node name to find</param>
/// <param name="createNodes">flag, if new nodes shall be created.</param>
/// <returns>Returns the found or created node or <code>null</code>.</returns>
/// <exception cref="Com.Adobe.Xmp.XMPException">Thrown if</exception>
internal static XMPNode FindChildNode(XMPNode parent, string childName, bool createNodes)
{
if (!parent.GetOptions().IsSchemaNode() && !parent.GetOptions().IsStruct())
{
if (!parent.IsImplicit())
{
throw new XMPException("Named children only allowed for schemas and structs", XMPErrorConstants.Badxpath);
}
else
{
if (parent.GetOptions().IsArray())
{
throw new XMPException("Named children not allowed for arrays", XMPErrorConstants.Badxpath);
}
else
{
if (createNodes)
{
parent.GetOptions().SetStruct(true);
}
}
}
}
XMPNode childNode = parent.FindChildByName(childName);
if (childNode == null && createNodes)
{
PropertyOptions options = new PropertyOptions();
childNode = new XMPNode(childName, options);
childNode.SetImplicit(true);
parent.AddChild(childNode);
}
System.Diagnostics.Debug.Assert(childNode != null || !createNodes);
return childNode;
}
/// <summary>Follow an expanded path expression to find or create a node.</summary>
/// <param name="xmpTree">the node to begin the search.</param>
/// <param name="xpath">the complete xpath</param>
/// <param name="createNodes">
/// flag if nodes shall be created
/// (when called by <code>setProperty()</code>)
/// </param>
/// <param name="leafOptions">
/// the options for the created leaf nodes (only when
/// <code>createNodes == true</code>).
/// </param>
/// <returns>Returns the node if found or created or <code>null</code>.</returns>
/// <exception cref="Com.Adobe.Xmp.XMPException">
/// An exception is only thrown if an error occurred,
/// not if a node was not found.
/// </exception>
internal static XMPNode FindNode(XMPNode xmpTree, XMPPath xpath, bool createNodes, PropertyOptions leafOptions)
{
// check if xpath is set.
if (xpath == null || xpath.Size() == 0)
{
throw new XMPException("Empty XMPPath", XMPErrorConstants.Badxpath);
}
// Root of implicitly created subtree to possible delete it later.
// Valid only if leaf is new.
XMPNode rootImplicitNode = null;
XMPNode currNode = null;
// resolve schema step
currNode = FindSchemaNode(xmpTree, xpath.GetSegment(XMPPath.StepSchema).GetName(), createNodes);
if (currNode == null)
{
return null;
}
else
{
if (currNode.IsImplicit())
{
currNode.SetImplicit(false);
// Clear the implicit node bit.
rootImplicitNode = currNode;
}
}
// Save the top most implicit node.
// Now follow the remaining steps of the original XMPPath.
try
{
for (int i = 1; i < xpath.Size(); i++)
{
currNode = FollowXPathStep(currNode, xpath.GetSegment(i), createNodes);
if (currNode == null)
{
if (createNodes)
{
// delete implicitly created nodes
DeleteNode(rootImplicitNode);
}
return null;
}
else
{
if (currNode.IsImplicit())
{
// clear the implicit node flag
currNode.SetImplicit(false);
// if node is an ALIAS (can be only in root step, auto-create array
// when the path has been resolved from a not simple alias type
if (i == 1 && xpath.GetSegment(i).IsAlias() && xpath.GetSegment(i).GetAliasForm() != 0)
{
currNode.GetOptions().SetOption(xpath.GetSegment(i).GetAliasForm(), true);
}
else
{
// "CheckImplicitStruct" in C++
if (i < xpath.Size() - 1 && xpath.GetSegment(i).GetKind() == XMPPath.StructFieldStep && !currNode.GetOptions().IsCompositeProperty())
{
currNode.GetOptions().SetStruct(true);
}
}
if (rootImplicitNode == null)
{
rootImplicitNode = currNode;
}
}
}
}
}
catch (XMPException e)
{
// Save the top most implicit node.
// if new notes have been created prior to the error, delete them
if (rootImplicitNode != null)
{
DeleteNode(rootImplicitNode);
}
throw;
}
if (rootImplicitNode != null)
{
// set options only if a node has been successful created
currNode.GetOptions().MergeWith(leafOptions);
currNode.SetOptions(currNode.GetOptions());
}
return currNode;
}
/// <summary>Deletes the the given node and its children from its parent.</summary>
/// <remarks>
/// Deletes the the given node and its children from its parent.
/// Takes care about adjusting the flags.
/// </remarks>
/// <param name="node">the top-most node to delete.</param>
internal static void DeleteNode(XMPNode node)
{
XMPNode parent = node.GetParent();
if (node.GetOptions().IsQualifier())
{
// root is qualifier
parent.RemoveQualifier(node);
}
else
{
// root is NO qualifier
parent.RemoveChild(node);
}
// delete empty Schema nodes
if (!parent.HasChildren() && parent.GetOptions().IsSchemaNode())
{
parent.GetParent().RemoveChild(parent);
}
}
/// <summary>This is setting the value of a leaf node.</summary>
/// <param name="node">an XMPNode</param>
/// <param name="value">a value</param>
internal static void SetNodeValue(XMPNode node, object value)
{
string strValue = SerializeNodeValue(value);
if (!(node.GetOptions().IsQualifier() && XMPConstConstants.XmlLang.Equals(node.GetName())))
{
node.SetValue(strValue);
}
else
{
node.SetValue(Utils.NormalizeLangValue(strValue));
}
}
/// <summary>Verifies the PropertyOptions for consistancy and updates them as needed.</summary>
/// <remarks>
/// Verifies the PropertyOptions for consistancy and updates them as needed.
/// If options are <code>null</code> they are created with default values.
/// </remarks>
/// <param name="options">the <code>PropertyOptions</code></param>
/// <param name="itemValue">the node value to set</param>
/// <returns>Returns the updated options.</returns>
/// <exception cref="Com.Adobe.Xmp.XMPException">If the options are not consistant.</exception>
internal static PropertyOptions VerifySetOptions(PropertyOptions options, object itemValue)
{
// create empty and fix existing options
if (options == null)
{
// set default options
options = new PropertyOptions();
}
if (options.IsArrayAltText())
{
options.SetArrayAlternate(true);
}
if (options.IsArrayAlternate())
{
options.SetArrayOrdered(true);
}
if (options.IsArrayOrdered())
{
options.SetArray(true);
}
if (options.IsCompositeProperty() && itemValue != null && itemValue.ToString().Length > 0)
{
throw new XMPException("Structs and arrays can't have values", XMPErrorConstants.Badoptions);
}
options.AssertConsistency(options.GetOptions());
return options;
}
/// <summary>
/// Converts the node value to String, apply special conversions for defined
/// types in XMP.
/// </summary>
/// <param name="value">the node value to set</param>
/// <returns>Returns the String representation of the node value.</returns>
internal static string SerializeNodeValue(object value)
{
string strValue;
if (value == null)
{
strValue = null;
}
else
{
if (value is bool)
{
strValue = XMPUtils.ConvertFromBoolean(((bool)value));
}
else
{
if (value is int)
{
strValue = XMPUtils.ConvertFromInteger(((int)value).IntValue());
}
else
{
if (value is long)
{
strValue = XMPUtils.ConvertFromLong(((long)value).LongValue());
}
else
{
if (value is double)
{
strValue = XMPUtils.ConvertFromDouble(((double)value).DoubleValue());
}
else
{
if (value is XMPDateTime)
{
strValue = XMPUtils.ConvertFromDate((XMPDateTime)value);
}
else
{
if (value is Sharpen.GregorianCalendar)
{
XMPDateTime dt = XMPDateTimeFactory.CreateFromCalendar((Sharpen.GregorianCalendar)value);
strValue = XMPUtils.ConvertFromDate(dt);
}
else
{
if (value is sbyte[])
{
strValue = XMPUtils.EncodeBase64((sbyte[])value);
}
else
{
strValue = value.ToString();
}
}
}
}
}
}
}
}
return strValue != null ? Utils.RemoveControlChars(strValue) : null;
}
/// <summary>
/// After processing by ExpandXPath, a step can be of these forms:
/// <ul>
/// <li>qualName - A top level property or struct field.
/// </summary>
/// <remarks>
/// After processing by ExpandXPath, a step can be of these forms:
/// <ul>
/// <li>qualName - A top level property or struct field.
/// <li>[index] - An element of an array.
/// <li>[last()] - The last element of an array.
/// <li>[qualName="value"] - An element in an array of structs, chosen by a field value.
/// <li>[?qualName="value"] - An element in an array, chosen by a qualifier value.
/// <li>?qualName - A general qualifier.
/// </ul>
/// Find the appropriate child node, resolving aliases, and optionally creating nodes.
/// </remarks>
/// <param name="parentNode">the node to start to start from</param>
/// <param name="nextStep">the xpath segment</param>
/// <param name="createNodes"></param>
/// <returns>returns the found or created XMPPath node</returns>
/// <exception cref="Com.Adobe.Xmp.XMPException"></exception>
private static XMPNode FollowXPathStep(XMPNode parentNode, XMPPathSegment nextStep, bool createNodes)
{
XMPNode nextNode = null;
int index = 0;
int stepKind = nextStep.GetKind();
if (stepKind == XMPPath.StructFieldStep)
{
nextNode = FindChildNode(parentNode, nextStep.GetName(), createNodes);
}
else
{
if (stepKind == XMPPath.QualifierStep)
{
nextNode = FindQualifierNode(parentNode, Sharpen.Runtime.Substring(nextStep.GetName(), 1), createNodes);
}
else
{
// This is an array indexing step. First get the index, then get the node.
if (!parentNode.GetOptions().IsArray())
{
throw new XMPException("Indexing applied to non-array", XMPErrorConstants.Badxpath);
}
if (stepKind == XMPPath.ArrayIndexStep)
{
index = FindIndexedItem(parentNode, nextStep.GetName(), createNodes);
}
else
{
if (stepKind == XMPPath.ArrayLastStep)
{
index = parentNode.GetChildrenLength();
}
else
{
if (stepKind == XMPPath.FieldSelectorStep)
{
string[] result = Utils.SplitNameAndValue(nextStep.GetName());
string fieldName = result[0];
string fieldValue = result[1];
index = LookupFieldSelector(parentNode, fieldName, fieldValue);
}
else
{
if (stepKind == XMPPath.QualSelectorStep)
{
string[] result = Utils.SplitNameAndValue(nextStep.GetName());
string qualName = result[0];
string qualValue = result[1];
index = LookupQualSelector(parentNode, qualName, qualValue, nextStep.GetAliasForm());
}
else
{
throw new XMPException("Unknown array indexing step in FollowXPathStep", XMPErrorConstants.Internalfailure);
}
}
}
}
if (1 <= index && index <= parentNode.GetChildrenLength())
{
nextNode = parentNode.GetChild(index);
}
}
}
return nextNode;
}
/// <summary>Find or create a qualifier node under a given parent node.</summary>
/// <remarks>
/// Find or create a qualifier node under a given parent node. Returns a pointer to the
/// qualifier node, and optionally an iterator for the node's position in
/// the parent's vector of qualifiers. The iterator is unchanged if no qualifier node (null)
/// is returned.
/// <em>Note:</em> On entry, the qualName parameter must not have the leading '?' from the
/// XMPPath step.
/// </remarks>
/// <param name="parent">the parent XMPNode</param>
/// <param name="qualName">the qualifier name</param>
/// <param name="createNodes">flag if nodes shall be created</param>
/// <returns>Returns the qualifier node if found or created, <code>null</code> otherwise.</returns>
/// <exception cref="Com.Adobe.Xmp.XMPException"></exception>
private static XMPNode FindQualifierNode(XMPNode parent, string qualName, bool createNodes)
{
System.Diagnostics.Debug.Assert(!qualName.StartsWith("?"));
XMPNode qualNode = parent.FindQualifierByName(qualName);
if (qualNode == null && createNodes)
{
qualNode = new XMPNode(qualName, null);
qualNode.SetImplicit(true);
parent.AddQualifier(qualNode);
}
return qualNode;
}
/// <param name="arrayNode">an array node</param>
/// <param name="segment">the segment containing the array index</param>
/// <param name="createNodes">flag if new nodes are allowed to be created.</param>
/// <returns>Returns the index or index = -1 if not found</returns>
/// <exception cref="Com.Adobe.Xmp.XMPException">Throws Exceptions</exception>
private static int FindIndexedItem(XMPNode arrayNode, string segment, bool createNodes)
{
int index = 0;
try
{
segment = Sharpen.Runtime.Substring(segment, 1, segment.Length - 1);
index = System.Convert.ToInt32(segment);
if (index < 1)
{
throw new XMPException("Array index must be larger than zero", XMPErrorConstants.Badxpath);
}
}
catch (FormatException)
{
throw new XMPException("Array index not digits.", XMPErrorConstants.Badxpath);
}
if (createNodes && index == arrayNode.GetChildrenLength() + 1)
{
// Append a new last + 1 node.
XMPNode newItem = new XMPNode(XMPConstConstants.ArrayItemName, null);
newItem.SetImplicit(true);
arrayNode.AddChild(newItem);
}
return index;
}
/// <summary>
/// Searches for a field selector in a node:
/// [fieldName="value] - an element in an array of structs, chosen by a field value.
/// </summary>
/// <remarks>
/// Searches for a field selector in a node:
/// [fieldName="value] - an element in an array of structs, chosen by a field value.
/// No implicit nodes are created by field selectors.
/// </remarks>
/// <param name="arrayNode"/>
/// <param name="fieldName"/>
/// <param name="fieldValue"/>
/// <returns>Returns the index of the field if found, otherwise -1.</returns>
/// <exception cref="Com.Adobe.Xmp.XMPException"></exception>
private static int LookupFieldSelector(XMPNode arrayNode, string fieldName, string fieldValue)
{
int result = -1;
for (int index = 1; index <= arrayNode.GetChildrenLength() && result < 0; index++)
{
XMPNode currItem = arrayNode.GetChild(index);
if (!currItem.GetOptions().IsStruct())
{
throw new XMPException("Field selector must be used on array of struct", XMPErrorConstants.Badxpath);
}
for (int f = 1; f <= currItem.GetChildrenLength(); f++)
{
XMPNode currField = currItem.GetChild(f);
if (!fieldName.Equals(currField.GetName()))
{
continue;
}
if (fieldValue.Equals(currField.GetValue()))
{
result = index;
break;
}
}
}
return result;
}
/// <summary>
/// Searches for a qualifier selector in a node:
/// [?qualName="value"] - an element in an array, chosen by a qualifier value.
/// </summary>
/// <remarks>
/// Searches for a qualifier selector in a node:
/// [?qualName="value"] - an element in an array, chosen by a qualifier value.
/// No implicit nodes are created for qualifier selectors,
/// except for an alias to an x-default item.
/// </remarks>
/// <param name="arrayNode">an array node</param>
/// <param name="qualName">the qualifier name</param>
/// <param name="qualValue">the qualifier value</param>
/// <param name="aliasForm">
/// in case the qual selector results from an alias,
/// an x-default node is created if there has not been one.
/// </param>
/// <returns>Returns the index of th</returns>
/// <exception cref="Com.Adobe.Xmp.XMPException"></exception>
private static int LookupQualSelector(XMPNode arrayNode, string qualName, string qualValue, int aliasForm)
{
if (XMPConstConstants.XmlLang.Equals(qualName))
{
qualValue = Utils.NormalizeLangValue(qualValue);
int index = Com.Adobe.Xmp.Impl.XMPNodeUtils.LookupLanguageItem(arrayNode, qualValue);
if (index < 0 && (aliasForm & AliasOptions.PropArrayAltText) > 0)
{
XMPNode langNode = new XMPNode(XMPConstConstants.ArrayItemName, null);
XMPNode xdefault = new XMPNode(XMPConstConstants.XmlLang, XMPConstConstants.XDefault, null);
langNode.AddQualifier(xdefault);
arrayNode.AddChild(1, langNode);
return 1;
}
else
{
return index;
}
}
else
{
for (int index = 1; index < arrayNode.GetChildrenLength(); index++)
{
XMPNode currItem = arrayNode.GetChild(index);
for (Iterator it = currItem.IterateQualifier(); it.HasNext(); )
{
XMPNode qualifier = (XMPNode)it.Next();
if (qualName.Equals(qualifier.GetName()) && qualValue.Equals(qualifier.GetValue()))
{
return index;
}
}
}
return -1;
}
}
/// <summary>Make sure the x-default item is first.</summary>
/// <remarks>
/// Make sure the x-default item is first. Touch up "single value"
/// arrays that have a default plus one real language. This case should have
/// the same value for both items. Older Adobe apps were hardwired to only
/// use the "x-default" item, so we copy that value to the other
/// item.
/// </remarks>
/// <param name="arrayNode">an alt text array node</param>
internal static void NormalizeLangArray(XMPNode arrayNode)
{
if (!arrayNode.GetOptions().IsArrayAltText())
{
return;
}
// check if node with x-default qual is first place
for (int i = 2; i <= arrayNode.GetChildrenLength(); i++)
{
XMPNode child = arrayNode.GetChild(i);
if (child.HasQualifier() && XMPConstConstants.XDefault.Equals(child.GetQualifier(1).GetValue()))
{
// move node to first place
try
{
arrayNode.RemoveChild(i);
arrayNode.AddChild(1, child);
}
catch (XMPException)
{
// cannot occur, because same child is removed before
System.Diagnostics.Debug.Assert(false);
}
if (i == 2)
{
arrayNode.GetChild(2).SetValue(child.GetValue());
}
break;
}
}
}
/// <summary>See if an array is an alt-text array.</summary>
/// <remarks>
/// See if an array is an alt-text array. If so, make sure the x-default item
/// is first.
/// </remarks>
/// <param name="arrayNode">the array node to check if its an alt-text array</param>
internal static void DetectAltText(XMPNode arrayNode)
{
if (arrayNode.GetOptions().IsArrayAlternate() && arrayNode.HasChildren())
{
bool isAltText = false;
for (Iterator it = arrayNode.IterateChildren(); it.HasNext(); )
{
XMPNode child = (XMPNode)it.Next();
if (child.GetOptions().GetHasLanguage())
{
isAltText = true;
break;
}
}
if (isAltText)
{
arrayNode.GetOptions().SetArrayAltText(true);
NormalizeLangArray(arrayNode);
}
}
}
/// <summary>Appends a language item to an alt text array.</summary>
/// <param name="arrayNode">the language array</param>
/// <param name="itemLang">the language of the item</param>
/// <param name="itemValue">the content of the item</param>
/// <exception cref="Com.Adobe.Xmp.XMPException">Thrown if a duplicate property is added</exception>
internal static void AppendLangItem(XMPNode arrayNode, string itemLang, string itemValue)
{
XMPNode newItem = new XMPNode(XMPConstConstants.ArrayItemName, itemValue, null);
XMPNode langQual = new XMPNode(XMPConstConstants.XmlLang, itemLang, null);
newItem.AddQualifier(langQual);
if (!XMPConstConstants.XDefault.Equals(langQual.GetValue()))
{
arrayNode.AddChild(newItem);
}
else
{
arrayNode.AddChild(1, newItem);
}
}
/// <summary>
/// <ol>
/// <li>Look for an exact match with the specific language.
/// </summary>
/// <remarks>
/// <ol>
/// <li>Look for an exact match with the specific language.
/// <li>If a generic language is given, look for partial matches.
/// <li>Look for an "x-default"-item.
/// <li>Choose the first item.
/// </ol>
/// </remarks>
/// <param name="arrayNode">the alt text array node</param>
/// <param name="genericLang">the generic language</param>
/// <param name="specificLang">the specific language</param>
/// <returns>
/// Returns the kind of match as an Integer and the found node in an
/// array.
/// </returns>
/// <exception cref="Com.Adobe.Xmp.XMPException"/>
internal static object[] ChooseLocalizedText(XMPNode arrayNode, string genericLang, string specificLang)
{
// See if the array has the right form. Allow empty alt arrays,
// that is what parsing returns.
if (!arrayNode.GetOptions().IsArrayAltText())
{
throw new XMPException("Localized text array is not alt-text", XMPErrorConstants.Badxpath);
}
else
{
if (!arrayNode.HasChildren())
{
return new object[] { Com.Adobe.Xmp.Impl.XMPNodeUtils.CltNoValues, null };
}
}
int foundGenericMatches = 0;
XMPNode resultNode = null;
XMPNode xDefault = null;
// Look for the first partial match with the generic language.
for (Iterator it = arrayNode.IterateChildren(); it.HasNext(); )
{
XMPNode currItem = (XMPNode)it.Next();
// perform some checks on the current item
if (currItem.GetOptions().IsCompositeProperty())
{
throw new XMPException("Alt-text array item is not simple", XMPErrorConstants.Badxpath);
}
else
{
if (!currItem.HasQualifier() || !XMPConstConstants.XmlLang.Equals(currItem.GetQualifier(1).GetName()))
{
throw new XMPException("Alt-text array item has no language qualifier", XMPErrorConstants.Badxpath);
}
}
string currLang = currItem.GetQualifier(1).GetValue();
// Look for an exact match with the specific language.
if (specificLang.Equals(currLang))
{
return new object[] { Com.Adobe.Xmp.Impl.XMPNodeUtils.CltSpecificMatch, currItem };
}
else
{
if (genericLang != null && currLang.StartsWith(genericLang))
{
if (resultNode == null)
{
resultNode = currItem;
}
// ! Don't return/break, need to look for other matches.
foundGenericMatches++;
}
else
{
if (XMPConstConstants.XDefault.Equals(currLang))
{
xDefault = currItem;
}
}
}
}
// evaluate loop
if (foundGenericMatches == 1)
{
return new object[] { Com.Adobe.Xmp.Impl.XMPNodeUtils.CltSingleGeneric, resultNode };
}
else
{
if (foundGenericMatches > 1)
{
return new object[] { Com.Adobe.Xmp.Impl.XMPNodeUtils.CltMultipleGeneric, resultNode };
}
else
{
if (xDefault != null)
{
return new object[] { Com.Adobe.Xmp.Impl.XMPNodeUtils.CltXdefault, xDefault };
}
else
{
// Everything failed, choose the first item.
return new object[] { Com.Adobe.Xmp.Impl.XMPNodeUtils.CltFirstItem, arrayNode.GetChild(1) };
}
}
}
}
/// <summary>Looks for the appropriate language item in a text alternative array.item</summary>
/// <param name="arrayNode">an array node</param>
/// <param name="language">the requested language</param>
/// <returns>Returns the index if the language has been found, -1 otherwise.</returns>
/// <exception cref="Com.Adobe.Xmp.XMPException"/>
internal static int LookupLanguageItem(XMPNode arrayNode, string language)
{
if (!arrayNode.GetOptions().IsArray())
{
throw new XMPException("Language item must be used on array", XMPErrorConstants.Badxpath);
}
for (int index = 1; index <= arrayNode.GetChildrenLength(); index++)
{
XMPNode child = arrayNode.GetChild(index);
if (!child.HasQualifier() || !XMPConstConstants.XmlLang.Equals(child.GetQualifier(1).GetName()))
{
continue;
}
else
{
if (language.Equals(child.GetQualifier(1).GetValue()))
{
return index;
}
}
}
return -1;
}
}
}
| |
// Copyright 2004-2011 Castle Project - http://www.castleproject.org/
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace Telerik.JustMock.Core.Castle.Core
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
/// <summary>
/// Readonly implementation of <see cref="IDictionary"/> which uses an anonymous object as its source. Uses names of properties as keys, and property values as... well - values. Keys are not case sensitive.
/// </summary>
internal sealed class ReflectionBasedDictionaryAdapter : IDictionary
{
private readonly Dictionary<string, object> properties =
new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
/// <summary>
/// Initializes a new instance of the <see cref = "ReflectionBasedDictionaryAdapter" /> class.
/// </summary>
/// <param name = "target">The target.</param>
public ReflectionBasedDictionaryAdapter(object target)
{
if (target == null)
{
throw new ArgumentNullException("target");
}
Read(properties, target);
}
/// <summary>
/// Gets the number of elements contained in the <see cref = "T:System.Collections.ICollection" />.
/// </summary>
/// <value></value>
/// <returns>The number of elements contained in the <see cref = "T:System.Collections.ICollection" />.</returns>
public int Count
{
get { return properties.Count; }
}
/// <summary>
/// Gets a value indicating whether access to the <see cref = "T:System.Collections.ICollection" /> is synchronized (thread safe).
/// </summary>
/// <value></value>
/// <returns>true if access to the <see cref = "T:System.Collections.ICollection" /> is synchronized (thread safe); otherwise, false.</returns>
public bool IsSynchronized
{
get { return false; }
}
/// <summary>
/// Gets an object that can be used to synchronize access to the <see cref = "T:System.Collections.ICollection" />.
/// </summary>
/// <value></value>
/// <returns>An object that can be used to synchronize access to the <see cref = "T:System.Collections.ICollection" />.</returns>
public object SyncRoot
{
get { return properties; }
}
/// <summary>
/// Gets a value indicating whether the <see cref = "T:System.Collections.IDictionary" /> object is read-only.
/// </summary>
/// <value></value>
/// <returns>true if the <see cref = "T:System.Collections.IDictionary" /> object is read-only; otherwise, false.</returns>
public bool IsReadOnly
{
get { return true; }
}
/// <summary>
/// Gets or sets the <see cref = "Object" /> with the specified key.
/// </summary>
/// <value></value>
public object this[object key]
{
get
{
object value;
properties.TryGetValue(key.ToString(), out value);
return value;
}
set { throw new NotImplementedException(); }
}
/// <summary>
/// Gets an <see cref = "T:System.Collections.ICollection" /> object containing the keys of the <see
/// cref = "T:System.Collections.IDictionary" /> object.
/// </summary>
/// <value></value>
/// <returns>An <see cref = "T:System.Collections.ICollection" /> object containing the keys of the <see
/// cref = "T:System.Collections.IDictionary" /> object.</returns>
public ICollection Keys
{
get { return properties.Keys; }
}
/// <summary>
/// Gets an <see cref = "T:System.Collections.ICollection" /> object containing the values in the <see
/// cref = "T:System.Collections.IDictionary" /> object.
/// </summary>
/// <value></value>
/// <returns>An <see cref = "T:System.Collections.ICollection" /> object containing the values in the <see
/// cref = "T:System.Collections.IDictionary" /> object.</returns>
public ICollection Values
{
get { return properties.Values; }
}
/// <summary>
/// Gets a value indicating whether the <see cref = "T:System.Collections.IDictionary" /> object has a fixed size.
/// </summary>
/// <value></value>
/// <returns>true if the <see cref = "T:System.Collections.IDictionary" /> object has a fixed size; otherwise, false.</returns>
bool IDictionary.IsFixedSize
{
get { throw new NotImplementedException(); }
}
/// <summary>
/// Adds an element with the provided key and value to the <see cref = "T:System.Collections.IDictionary" /> object.
/// </summary>
/// <param name = "key">The <see cref = "T:System.Object" /> to use as the key of the element to add.</param>
/// <param name = "value">The <see cref = "T:System.Object" /> to use as the value of the element to add.</param>
/// <exception cref = "T:System.ArgumentNullException">
/// <paramref name = "key" /> is null. </exception>
/// <exception cref = "T:System.ArgumentException">An element with the same key already exists in the <see
/// cref = "T:System.Collections.IDictionary" /> object. </exception>
/// <exception cref = "T:System.NotSupportedException">The <see cref = "T:System.Collections.IDictionary" /> is read-only.-or- The <see
/// cref = "T:System.Collections.IDictionary" /> has a fixed size. </exception>
public void Add(object key, object value)
{
throw new NotImplementedException();
}
/// <summary>
/// Removes all elements from the <see cref = "T:System.Collections.IDictionary" /> object.
/// </summary>
/// <exception cref = "T:System.NotSupportedException">The <see cref = "T:System.Collections.IDictionary" /> object is read-only. </exception>
public void Clear()
{
throw new NotImplementedException();
}
/// <summary>
/// Determines whether the <see cref = "T:System.Collections.IDictionary" /> object contains an element with the specified key.
/// </summary>
/// <param name = "key">The key to locate in the <see cref = "T:System.Collections.IDictionary" /> object.</param>
/// <returns>
/// true if the <see cref = "T:System.Collections.IDictionary" /> contains an element with the key; otherwise, false.
/// </returns>
/// <exception cref = "T:System.ArgumentNullException">
/// <paramref name = "key" /> is null. </exception>
public bool Contains(object key)
{
return properties.ContainsKey(key.ToString());
}
/// <summary>
/// Removes the element with the specified key from the <see cref = "T:System.Collections.IDictionary" /> object.
/// </summary>
/// <param name = "key">The key of the element to remove.</param>
/// <exception cref = "T:System.ArgumentNullException">
/// <paramref name = "key" /> is null. </exception>
/// <exception cref = "T:System.NotSupportedException">The <see cref = "T:System.Collections.IDictionary" /> object is read-only.-or- The <see
/// cref = "T:System.Collections.IDictionary" /> has a fixed size. </exception>
public void Remove(object key)
{
}
/// <summary>
/// Returns an enumerator that iterates through a collection.
/// </summary>
/// <returns>
/// An <see cref = "T:System.Collections.IEnumerator" /> object that can be used to iterate through the collection.
/// </returns>
public IEnumerator GetEnumerator()
{
return new DictionaryEntryEnumeratorAdapter(properties.GetEnumerator());
}
/// <summary>
/// Copies the elements of the <see cref = "T:System.Collections.ICollection" /> to an <see cref = "T:System.Array" />, starting at a particular <see
/// cref = "T:System.Array" /> index.
/// </summary>
/// <param name = "array">The one-dimensional <see cref = "T:System.Array" /> that is the destination of the elements copied from <see
/// cref = "T:System.Collections.ICollection" />. The <see cref = "T:System.Array" /> must have zero-based indexing.</param>
/// <param name = "index">The zero-based index in <paramref name = "array" /> at which copying begins.</param>
/// <exception cref = "T:System.ArgumentNullException">
/// <paramref name = "array" /> is null. </exception>
/// <exception cref = "T:System.ArgumentOutOfRangeException">
/// <paramref name = "index" /> is less than zero. </exception>
/// <exception cref = "T:System.ArgumentException">
/// <paramref name = "array" /> is multidimensional.-or- <paramref name = "index" /> is equal to or greater than the length of <paramref
/// name = "array" />.-or- The number of elements in the source <see cref = "T:System.Collections.ICollection" /> is greater than the available space from <paramref
/// name = "index" /> to the end of the destination <paramref name = "array" />. </exception>
/// <exception cref = "T:System.ArgumentException">The type of the source <see cref = "T:System.Collections.ICollection" /> cannot be cast automatically to the type of the destination <paramref
/// name = "array" />. </exception>
void ICollection.CopyTo(Array array, int index)
{
throw new NotImplementedException();
}
/// <summary>
/// Returns an <see cref = "T:System.Collections.IDictionaryEnumerator" /> object for the <see
/// cref = "T:System.Collections.IDictionary" /> object.
/// </summary>
/// <returns>
/// An <see cref = "T:System.Collections.IDictionaryEnumerator" /> object for the <see
/// cref = "T:System.Collections.IDictionary" /> object.
/// </returns>
IDictionaryEnumerator IDictionary.GetEnumerator()
{
return new DictionaryEntryEnumeratorAdapter(properties.GetEnumerator());
}
/// <summary>
/// Reads values of properties from <paramref name = "valuesAsAnonymousObject" /> and inserts them into <paramref
/// name = "targetDictionary" /> using property names as keys.
/// </summary>
/// <param name = "targetDictionary"></param>
/// <param name = "valuesAsAnonymousObject"></param>
public static void Read(IDictionary targetDictionary, object valuesAsAnonymousObject)
{
var targetType = valuesAsAnonymousObject.GetType();
foreach (var property in GetReadableProperties(targetType))
{
var value = GetPropertyValue(valuesAsAnonymousObject, property);
targetDictionary[property.Name] = value;
}
}
private static object GetPropertyValue(object target, PropertyInfo property)
{
return property.GetValue(target, null);
}
private static IEnumerable<PropertyInfo> GetReadableProperties(Type targetType)
{
return targetType.GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(IsReadable);
}
private static bool IsReadable(PropertyInfo property)
{
return property.CanRead && property.GetIndexParameters().Length == 0;
}
private class DictionaryEntryEnumeratorAdapter : IDictionaryEnumerator
{
private readonly IDictionaryEnumerator enumerator;
private KeyValuePair<string, object> current;
public DictionaryEntryEnumeratorAdapter(IDictionaryEnumerator enumerator)
{
this.enumerator = enumerator;
}
public DictionaryEntry Entry
{
get { return new DictionaryEntry(Key, Value); }
}
public object Key
{
get { return current.Key; }
}
public object Value
{
get { return current.Value; }
}
public object Current
{
get { return new DictionaryEntry(Key, Value); }
}
public bool MoveNext()
{
var moved = enumerator.MoveNext();
if (moved)
{
current = (KeyValuePair<string, object>)enumerator.Current;
}
return moved;
}
public void Reset()
{
enumerator.Reset();
}
}
}
}
| |
//=============================================================================
// System : Sandcastle Help File Builder Utilities
// File : ApiFilterCollection.cs
// Author : Eric Woodruff (Eric@EWoodruff.us)
// Updated : 07/03/2008
// Note : Copyright 2007-2008, Eric Woodruff, All rights reserved
// Compiler: Microsoft Visual C#
//
// This file contains a collection class used to hold the API filter entries
// for MRefBuilder to remove.
//
// This code is published under the Microsoft Public License (Ms-PL). A copy
// of the license should be distributed with the code. It can also be found
// at the project website: http://SHFB.CodePlex.com. This notice, the
// author's name, and all copyright notices must remain intact in all
// applications, documentation, and source files.
//
// Version Date Who Comments
// ============================================================================
// 1.5.0.2 07/16/2007 EFW Created the code
// 1.8.0.0 07/03/2008 EFW Rewrote to support MSBuild project format
//=============================================================================
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing.Design;
using System.IO;
using System.Text;
using System.Xml;
using SandcastleBuilder.Utils.Design;
namespace SandcastleBuilder.Utils
{
/// <summary>
/// This collection class is used to hold the API filter entries for
/// MRefBuilder to remove.
/// </summary>
/// <remarks><note type="note">Unlike other collections in the project,
/// this one is cleared and rebuilt if it changes. As such, the contained
/// items do not notify the project when they change as they are created
/// anew each time the collection is rebuilt.</note></remarks>
[TypeConverter(typeof(ApiFilterCollectionTypeConverter)),
Editor(typeof(ApiFilterEditor), typeof(UITypeEditor))]
public class ApiFilterCollection : BindingList<ApiFilter>, ICloneable
{
#region Private data members
//=====================================================================
private SandcastleProject projectFile;
private bool isDirty;
#endregion
#region Properties
//=====================================================================
/// <summary>
/// This is used to get or set the dirty state of the collection
/// </summary>
public bool IsDirty
{
get { return isDirty; }
set { isDirty = value; }
}
/// <summary>
/// This is used to get a reference to the project that owns the
/// collection.
/// </summary>
/// <remarks>Child collections do not contain a reference to the
/// project file.</remarks>
public SandcastleProject Project
{
get { return projectFile; }
}
#endregion
#region Constructor
//=====================================================================
/// <summary>
/// Internal constructor
/// </summary>
/// <param name="project">The project that owns the collection</param>
/// <remarks>Child collections do not contain a reference to the
/// project file.</remarks>
internal ApiFilterCollection(SandcastleProject project)
{
projectFile = project;
}
#endregion
#region Sort collection
//=====================================================================
/// <summary>
/// This is used to sort the collection
/// </summary>
/// <remarks>All top level items and their children are sorted by
/// API entry type and then by name</remarks>
public void Sort()
{
((List<ApiFilter>)base.Items).Sort(
delegate(ApiFilter x, ApiFilter y)
{
return Comparer<ApiFilter>.Default.Compare(x, y);
});
foreach(ApiFilter te in this)
te.Children.Sort();
}
#endregion
#region Read/write API filter items from/to XML
//=====================================================================
/// <summary>
/// This is used to load existing API filter items from the project
/// file.
/// </summary>
/// <param name="apiFilter">The API filter items</param>
/// <remarks>The information is stored as an XML fragment</remarks>
internal void FromXml(string apiFilter)
{
ApiFilter filter;
XmlTextReader xr = null;
try
{
xr = new XmlTextReader(apiFilter, XmlNodeType.Element,
new XmlParserContext(null, null, null, XmlSpace.Default));
xr.MoveToContent();
while(!xr.EOF)
{
if(xr.NodeType == XmlNodeType.Element &&
xr.Name == "Filter")
{
filter = new ApiFilter();
filter.FromXml(xr);
this.Add(filter);
}
xr.Read();
}
}
finally
{
if(xr != null)
xr.Close();
isDirty = false;
}
}
/// <summary>
/// This is used to write the API filter info to an XML fragment ready
/// for storing in the project file.
/// </summary>
/// <returns>The XML fragment containing the help attribute info</returns>
internal string ToXml()
{
MemoryStream ms = new MemoryStream(10240);
XmlTextWriter xw = null;
try
{
xw = new XmlTextWriter(ms, new UTF8Encoding(false));
xw.Formatting = Formatting.Indented;
foreach(ApiFilter filter in this)
filter.ToXml(xw);
xw.Flush();
return Encoding.UTF8.GetString(ms.ToArray());
}
finally
{
if(xw != null)
xw.Close();
ms.Dispose();
}
}
#endregion
#region Add/merge child members
//=====================================================================
// Add or merge child members to the collection based on namespace
// comment or <exclude/> tag exclusions.
/// <summary>
/// This is used to merge an entry with the filter collection
/// </summary>
/// <param name="entryType">The entry type</param>
/// <param name="fullName">The member's full name</param>
/// <param name="isExposed">True to expose it, false to remove it</param>
/// <param name="isProjectExclude">True if this is a project exclude
/// (currently this will always be true).</param>
/// <returns>True if merged without conflict or false if the merged
/// member conflicted with an existing entry. The existing entry
/// will take precedence.</returns>
public bool MergeEntry(ApiEntryType entryType, string fullName,
bool isExposed, bool isProjectExclude)
{
ApiFilter newEntry;
foreach(ApiFilter child in this)
if(child.FullName == fullName)
{
// If the exposure doesn't match, use the existing
// entry and ignore the merged entry
if(child.IsExposed != isExposed)
return false;
child.IsProjectExclude = isProjectExclude;
return true;
}
// It's a new one
newEntry = new ApiFilter(entryType, fullName, isExposed);
newEntry.IsProjectExclude = isProjectExclude;
this.Add(newEntry);
return true;
}
/// <summary>
/// Add a new type entry to this namespace collection
/// </summary>
/// <param name="fullName">The full name of the entry</param>
/// <param name="nameSpace">The namespace</param>
/// <param name="typeName">The type name</param>
/// <param name="memberName">The member</param>
/// <returns>True if merged without conflict or false if the merged
/// member conflicted with an existing entry. The existing entry
/// will take precedence.</returns>
/// <remarks>Entries added by this method are exclusions based on
/// namespace comment or <exclude/> tag exclusions.</remarks>
public bool AddNamespaceChild(string fullName, string nameSpace,
string typeName, string memberName)
{
ApiFilter newEntry;
// Find the namespace. The entry is only added if the namespace
// is exposed.
foreach(ApiFilter entry in this)
if(entry.FullName == nameSpace)
{
if(entry.IsExposed)
{
if(memberName != null)
return entry.Children.AddTypeChild(fullName,
typeName, memberName);
return entry.Children.MergeEntry(ApiEntryType.Class,
fullName.Substring(2), false, true);
}
return true; // Excluded by default
}
// New namespace
newEntry = new ApiFilter(ApiEntryType.Namespace, nameSpace, true);
newEntry.IsProjectExclude = true;
base.Add(newEntry);
newEntry.Children.AddTypeChild(fullName, typeName, memberName);
return true;
}
/// <summary>
/// Add a new member entry to this type collection
/// </summary>
/// <param name="fullName">The full name of the entry</param>
/// <param name="typeName">The type name</param>
/// <param name="memberName">The member</param>
/// <returns>True if merged without conflict or false if the merged
/// member conflicted with an existing entry. The existing entry
/// will take precedence.</returns>
/// <remarks>Entries added by this method are exclusions based on
/// namespace comment or <exclude/> tag exclusions.</remarks>
public bool AddTypeChild(string fullName, string typeName,
string memberName)
{
ApiFilter newEntry, childEntry;
// Find the type
foreach(ApiFilter entry in this)
if(entry.FullName == typeName)
{
// The entry is only added if the namespace is exposed
if(entry.IsExposed)
return entry.Children.MergeEntry(
ApiFilter.ApiEntryTypeFromLetter(fullName[0]),
fullName.Substring(2), false, true);
return true; // Excluded by default
}
// New type
newEntry = new ApiFilter(ApiEntryType.Class, typeName,
(memberName != null));
newEntry.IsProjectExclude = true;
base.Add(newEntry);
if(memberName != null)
{
childEntry = new ApiFilter(ApiFilter.ApiEntryTypeFromLetter(
fullName[0]), fullName.Substring(2), false);
childEntry.IsProjectExclude = true;
newEntry.Children.Add(childEntry);
}
return true;
}
#endregion
#region Method overrides
//=====================================================================
/// <summary>
/// This is overridden to mark the collection as dirty when it changes
/// </summary>
/// <param name="e">The event arguments</param>
protected override void OnListChanged(ListChangedEventArgs e)
{
isDirty = true;
base.OnListChanged(e);
}
/// <summary>
/// Convert the API filter entry and its children to a string
/// </summary>
/// <returns>The entries in the MRefBuilder API filter XML format</returns>
public override string ToString()
{
StringBuilder sb = new StringBuilder(10240);
sb.Append("<apiFilter expose=\"true\">\r\n");
foreach(ApiFilter entry in this)
entry.ConvertToString(sb);
sb.Append("</apiFilter>\r\n");
return sb.ToString();
}
#endregion
#region ICloneable Members
//=====================================================================
/// <summary>
/// Clone the API filter collection
/// </summary>
/// <returns>A clone of the collection</returns>
public object Clone()
{
ApiFilterCollection clone = new ApiFilterCollection(projectFile);
foreach(ApiFilter filter in this)
clone.Add((ApiFilter)filter.Clone());
return clone;
}
#endregion
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="MemberAliasPropertyInfo.cs" company="Sirenix IVS">
// Copyright (c) 2018 Sirenix IVS
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
//-----------------------------------------------------------------------
namespace Stratus.OdinSerializer.Utilities
{
using System;
using System.Globalization;
using System.Reflection;
/// <summary>
/// Provides a methods of representing imaginary properties which are unique to serialization.
/// <para />
/// We aggregate the PropertyInfo associated with this member and return a mangled form of the name.
/// </summary>
/// <seealso cref="System.Reflection.FieldInfo" />
public sealed class MemberAliasPropertyInfo : PropertyInfo
{
/// <summary>
/// The default fake name separator string.
/// </summary>
private const string FakeNameSeparatorString = "+";
private PropertyInfo aliasedProperty;
private string mangledName;
/// <summary>
/// Initializes a new instance of the <see cref="MemberAliasPropertyInfo"/> class.
/// </summary>
/// <param name="prop">The property to alias.</param>
/// <param name="namePrefix">The name prefix to use.</param>
public MemberAliasPropertyInfo(PropertyInfo prop, string namePrefix)
{
this.aliasedProperty = prop;
this.mangledName = string.Concat(namePrefix, FakeNameSeparatorString, this.aliasedProperty.Name);
}
/// <summary>
/// Initializes a new instance of the <see cref="MemberAliasPropertyInfo"/> class.
/// </summary>
/// <param name="prop">The property to alias.</param>
/// <param name="namePrefix">The name prefix to use.</param>
/// <param name="separatorString">The separator string to use.</param>
public MemberAliasPropertyInfo(PropertyInfo prop, string namePrefix, string separatorString)
{
this.aliasedProperty = prop;
this.mangledName = string.Concat(namePrefix, separatorString, this.aliasedProperty.Name);
}
/// <summary>
/// The backing PropertyInfo that is being aliased.
/// </summary>
public PropertyInfo AliasedProperty { get { return this.aliasedProperty; } }
/// <summary>
/// Gets the module in which the type that declares the member represented by the current <see cref="T:System.Reflection.MemberInfo" /> is defined.
/// </summary>
public override Module Module { get { return this.aliasedProperty.Module; } }
/// <summary>
/// Gets a value that identifies a metadata element.
/// </summary>
public override int MetadataToken { get { return this.aliasedProperty.MetadataToken; } }
/// <summary>
/// Gets the name of the current member.
/// </summary>
public override string Name { get { return this.mangledName; } }
/// <summary>
/// Gets the class that declares this member.
/// </summary>
public override Type DeclaringType { get { return this.aliasedProperty.DeclaringType; } }
/// <summary>
/// Gets the class object that was used to obtain this instance of MemberInfo.
/// </summary>
public override Type ReflectedType { get { return this.aliasedProperty.ReflectedType; } }
/// <summary>
/// Gets the type of the property.
/// </summary>
/// <value>
/// The type of the property.
/// </value>
public override Type PropertyType { get { return this.aliasedProperty.PropertyType; } }
/// <summary>
/// Gets the attributes.
/// </summary>
/// <value>
/// The attributes.
/// </value>
public override PropertyAttributes Attributes { get { return this.aliasedProperty.Attributes; } }
/// <summary>
/// Gets a value indicating whether this instance can read.
/// </summary>
/// <value>
/// <c>true</c> if this instance can read; otherwise, <c>false</c>.
/// </value>
public override bool CanRead { get { return this.aliasedProperty.CanRead; } }
/// <summary>
/// Gets a value indicating whether this instance can write.
/// </summary>
/// <value>
/// <c>true</c> if this instance can write; otherwise, <c>false</c>.
/// </value>
public override bool CanWrite { get { return this.aliasedProperty.CanWrite; } }
/// <summary>
/// When overridden in a derived class, returns an array of all custom attributes applied to this member.
/// </summary>
/// <param name="inherit">True to search this member's inheritance chain to find the attributes; otherwise, false. This parameter is ignored for properties and events; see Remarks.</param>
/// <returns>
/// An array that contains all the custom attributes applied to this member, or an array with zero elements if no attributes are defined.
/// </returns>
public override object[] GetCustomAttributes(bool inherit)
{
return this.aliasedProperty.GetCustomAttributes(inherit);
}
/// <summary>
/// When overridden in a derived class, returns an array of custom attributes applied to this member and identified by <see cref="T:System.Type" />.
/// </summary>
/// <param name="attributeType">The type of attribute to search for. Only attributes that are assignable to this type are returned.</param>
/// <param name="inherit">True to search this member's inheritance chain to find the attributes; otherwise, false. This parameter is ignored for properties and events; see Remarks.</param>
/// <returns>
/// An array of custom attributes applied to this member, or an array with zero elements if no attributes assignable to <paramref name="attributeType" /> have been applied.
/// </returns>
public override object[] GetCustomAttributes(Type attributeType, bool inherit)
{
return this.aliasedProperty.GetCustomAttributes(attributeType, inherit);
}
/// <summary>
/// When overridden in a derived class, indicates whether one or more attributes of the specified type or of its derived types is applied to this member.
/// </summary>
/// <param name="attributeType">The type of custom attribute to search for. The search includes derived types.</param>
/// <param name="inherit">True to search this member's inheritance chain to find the attributes; otherwise, false. This parameter is ignored for properties and events; see Remarks.</param>
/// <returns>
/// True if one or more instances of <paramref name="attributeType" /> or any of its derived types is applied to this member; otherwise, false.
/// </returns>
public override bool IsDefined(Type attributeType, bool inherit)
{
return this.aliasedProperty.IsDefined(attributeType, inherit);
}
/// <summary>
/// Returns an array whose elements reflect the public and, if specified, non-public get, set, and other accessors of the property reflected by the current instance.
/// </summary>
/// <param name="nonPublic">Indicates whether non-public methods should be returned in the MethodInfo array. true if non-public methods are to be included; otherwise, false.</param>
/// <returns>
/// An array of <see cref="T:System.Reflection.MethodInfo" /> objects whose elements reflect the get, set, and other accessors of the property reflected by the current instance. If <paramref name="nonPublic" /> is true, this array contains public and non-public get, set, and other accessors. If <paramref name="nonPublic" /> is false, this array contains only public get, set, and other accessors. If no accessors with the specified visibility are found, this method returns an array with zero (0) elements.
/// </returns>
public override MethodInfo[] GetAccessors(bool nonPublic)
{
return this.aliasedProperty.GetAccessors(nonPublic);
}
/// <summary>
/// When overridden in a derived class, returns the public or non-public get accessor for this property.
/// </summary>
/// <param name="nonPublic">Indicates whether a non-public get accessor should be returned. true if a non-public accessor is to be returned; otherwise, false.</param>
/// <returns>
/// A MethodInfo object representing the get accessor for this property, if <paramref name="nonPublic" /> is true. Returns null if <paramref name="nonPublic" /> is false and the get accessor is non-public, or if <paramref name="nonPublic" /> is true but no get accessors exist.
/// </returns>
public override MethodInfo GetGetMethod(bool nonPublic)
{
return this.aliasedProperty.GetGetMethod(nonPublic);
}
/// <summary>
/// Gets the index parameters of the property.
/// </summary>
/// <returns>The index parameters of the property.</returns>
public override ParameterInfo[] GetIndexParameters()
{
return this.aliasedProperty.GetIndexParameters();
}
/// <summary>
/// When overridden in a derived class, returns the set accessor for this property.
/// </summary>
/// <param name="nonPublic">Indicates whether the accessor should be returned if it is non-public. true if a non-public accessor is to be returned; otherwise, false.</param>
/// <returns>
/// Value Condition A <see cref="T:System.Reflection.MethodInfo" /> object representing the Set method for this property. The set accessor is public.-or- <paramref name="nonPublic" /> is true and the set accessor is non-public. null<paramref name="nonPublic" /> is true, but the property is read-only.-or- <paramref name="nonPublic" /> is false and the set accessor is non-public.-or- There is no set accessor.
/// </returns>
public override MethodInfo GetSetMethod(bool nonPublic)
{
return this.aliasedProperty.GetSetMethod(nonPublic);
}
/// <summary>
/// Gets the value of the property on the given instance.
/// </summary>
/// <param name="obj">The object to invoke the getter on.</param>
/// <param name="invokeAttr">The <see cref="BindingFlags"/> to invoke with.</param>
/// <param name="binder">The binder to use.</param>
/// <param name="index">The indices to use.</param>
/// <param name="culture">The culture to use.</param>
/// <returns>The value of the property on the given instance.</returns>
public override object GetValue(object obj, BindingFlags invokeAttr, Binder binder, object[] index, CultureInfo culture)
{
return this.aliasedProperty.GetValue(obj, invokeAttr, binder, index, culture);
}
/// <summary>
/// Sets the value of the property on the given instance.
/// </summary>
/// <param name="obj">The object to set the value on.</param>
/// <param name="value">The value to set.</param>
/// <param name="invokeAttr">The <see cref="BindingFlags"/> to invoke with.</param>
/// <param name="binder">The binder to use.</param>
/// <param name="index">The indices to use.</param>
/// <param name="culture">The culture to use.</param>
public override void SetValue(object obj, object value, BindingFlags invokeAttr, Binder binder, object[] index, CultureInfo culture)
{
this.aliasedProperty.SetValue(obj, value, invokeAttr, binder, index, culture);
}
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Web;
using System.Web.Hosting;
using System.Web.Mvc;
using System.Web.Routing;
namespace ServiceStack.Mvc
{
public enum BundleOptions
{
Normal,
Minified,
Combined,
MinifiedAndCombined
}
public static class Bundler
{
public static Func<bool> CachePaths = IsProduction;
public static Func<string, BundleOptions, string> DefaultUrlFilter = ProcessVirtualPathDefault;
// Logic to determine if the app is running in production or dev environment
public static bool IsProduction()
{
return (HttpContext.Current != null && !HttpContext.Current.IsDebuggingEnabled);
}
public static bool FileExists(string virtualPath)
{
if (!HostingEnvironment.IsHosted) return false;
var filePath = HostingEnvironment.MapPath(virtualPath);
return File.Exists(filePath);
}
static DateTime centuryBegin = new DateTime(2001, 1, 1);
public static string TimestampString(string virtualPath)
{
try
{
if (HostingEnvironment.IsHosted)
{
var filePath = HostingEnvironment.MapPath(virtualPath);
return Convert.ToString((File.GetLastWriteTimeUtc(filePath).Ticks - centuryBegin.Ticks) / 1000000000, 16);
}
}
catch { } //ignore
return string.Empty;
}
private static TVal GetOrAdd<TKey, TVal>(this Dictionary<TKey, TVal> map, TKey key, Func<TKey, TVal> factoryFn)
{
lock (map)
{
TVal ret;
if (!map.TryGetValue(key, out ret))
{
map[key] = ret = factoryFn(key);
}
return ret;
}
}
private static void SafeClear<TKey, TVal>(this Dictionary<TKey, TVal> map)
{
lock (map) map.Clear();
}
static readonly Dictionary<string,string> VirutalPathCache = new Dictionary<string, string>();
private static string ProcessVirtualPathDefault(string virtualPath, BundleOptions options)
{
if (!CachePaths()) VirutalPathCache.SafeClear();
return VirutalPathCache.GetOrAdd(virtualPath, str => {
// The path that comes in starts with ~/ and must first be made absolute
if (options == BundleOptions.Minified || options == BundleOptions.MinifiedAndCombined)
{
if (virtualPath.EndsWith(".js") && !virtualPath.EndsWith(".min.js"))
{
var minPath = virtualPath.Replace(".js", ".min.js");
if (FileExists(minPath))
virtualPath = minPath;
}
else if (virtualPath.EndsWith(".css") && !virtualPath.EndsWith(".min.css"))
{
var minPath = virtualPath.Replace(".css", ".min.css");
if (FileExists(minPath))
virtualPath = minPath;
}
}
var path = virtualPath;
if (virtualPath.IndexOf("://", StringComparison.Ordinal) == -1)
{
path = VirtualPathUtility.ToAbsolute(virtualPath);
var cacheBreaker = TimestampString(virtualPath);
if (!string.IsNullOrEmpty(cacheBreaker))
{
path += path.IndexOf('?') == -1
? "?" + cacheBreaker
: "&" + cacheBreaker;
}
}
// Add your own modifications here before returning the path
return path;
});
}
private static string RewriteUrl(this string relativePath, BundleOptions options=BundleOptions.Normal)
{
return DefaultUrlFilter(relativePath, options);
}
public static MvcHtmlString ToMvcHtmlString(this string s)
{
return MvcHtmlString.Create(s);
}
public static MvcHtmlString ToMvcHtmlString(this TagBuilder t)
{
return t.ToString().ToMvcHtmlString();
}
public static MvcHtmlString ToMvcHtmlString(this TagBuilder t, TagRenderMode mode)
{
return t.ToString(mode).ToMvcHtmlString();
}
public static MvcHtmlString Link(this HtmlHelper html, string rel, string href, object htmlAttributes = null, BundleOptions options = BundleOptions.Normal)
{
if (string.IsNullOrEmpty(href))
return MvcHtmlString.Empty;
if (href.StartsWith("~/"))
href = href.Replace("~/", VirtualPathUtility.ToAbsolute("~"));
var tag = new TagBuilder("link");
tag.MergeAttribute("rel", rel);
tag.MergeAttribute("href", href.RewriteUrl(options));
if (htmlAttributes != null)
tag.MergeAttributes(new RouteValueDictionary(htmlAttributes));
return tag.ToString(TagRenderMode.SelfClosing).ToMvcHtmlString();
}
public static MvcHtmlString Css(this HtmlHelper html, string href, string media = null, BundleOptions options = BundleOptions.Minified)
{
return media != null
? html.Link("stylesheet", href, new { media }, options)
: html.Link("stylesheet", href, null, options);
}
public static T If<T>(this HtmlHelper html, bool predicate, T whenTrue, T whenFalse)
{
return predicate ? whenTrue : whenFalse;
}
public static MvcHtmlString Img(this HtmlHelper html, string src, string alt, string link = null, object htmlAttributes = null)
{
if (string.IsNullOrEmpty(src))
return MvcHtmlString.Empty;
if (src.StartsWith("~/"))
src = src.Replace("~/", VirtualPathUtility.ToAbsolute("~"));
var tag = new TagBuilder("img");
tag.MergeAttribute("src", src.RewriteUrl());
tag.MergeAttribute("alt", alt);
if (htmlAttributes != null)
tag.MergeAttributes(new RouteValueDictionary(htmlAttributes));
if (!string.IsNullOrEmpty(link))
{
var a = new TagBuilder("a");
a.MergeAttribute("href", link);
a.InnerHtml = tag.ToString(TagRenderMode.Normal);
return a.ToMvcHtmlString();
}
return tag.ToString(TagRenderMode.SelfClosing).ToMvcHtmlString();
}
public static MvcHtmlString Js(this HtmlHelper html, string src, BundleOptions options = BundleOptions.Minified)
{
if (string.IsNullOrEmpty(src))
return MvcHtmlString.Empty;
if (src.StartsWith("~/"))
src = src.Replace("~/", VirtualPathUtility.ToAbsolute("~"));
var tag = new TagBuilder("script");
tag.MergeAttribute("type", "text/javascript");
tag.MergeAttribute("src", src.RewriteUrl(options));
return tag.ToString(TagRenderMode.Normal).ToMvcHtmlString();
}
public static MvcHtmlString Img(this HtmlHelper html, Uri url, string alt, Uri link = null, object htmlAttributes = null)
{
return html.Img(url.ToString(), alt, link != null ? link.ToString() : "", htmlAttributes);
}
public static string ToJsBool(this bool value)
{
return value.ToString(CultureInfo.InvariantCulture).ToLower();
}
static readonly Dictionary<string, MvcHtmlString> BundleCache = new Dictionary<string, MvcHtmlString>();
public static MvcHtmlString RenderJsBundle(this HtmlHelper html, string bundlePath, BundleOptions options = BundleOptions.Minified)
{
if (string.IsNullOrEmpty(bundlePath))
return MvcHtmlString.Empty;
if (!CachePaths()) BundleCache.SafeClear();
return BundleCache.GetOrAdd(bundlePath, str => {
var filePath = HostingEnvironment.MapPath(bundlePath);
var baseUrl = VirtualPathUtility.GetDirectory(bundlePath);
if (options == BundleOptions.Combined)
return html.Js(bundlePath.Replace(".bundle", ""), options);
if (options == BundleOptions.MinifiedAndCombined)
return html.Js(bundlePath.Replace(".js.bundle", ".min.js"), options);
var jsFiles = File.ReadAllLines(filePath);
var scripts = new StringBuilder();
foreach (var file in jsFiles)
{
var jsFile = file.Trim().Replace(".coffee", ".js");
var jsSrc = Path.Combine(baseUrl, jsFile);
scripts.AppendLine(
html.Js(jsSrc, options).ToString()
);
}
return scripts.ToString().ToMvcHtmlString();
});
}
public static MvcHtmlString RenderCssBundle(this HtmlHelper html, string bundlePath, BundleOptions options = BundleOptions.Minified, string media = null)
{
if (string.IsNullOrEmpty(bundlePath))
return MvcHtmlString.Empty;
if (!CachePaths()) BundleCache.SafeClear();
return BundleCache.GetOrAdd(bundlePath, str => {
var filePath = HostingEnvironment.MapPath(bundlePath);
var baseUrl = VirtualPathUtility.GetDirectory(bundlePath);
if (options == BundleOptions.Combined)
return html.Css(bundlePath.Replace(".bundle", ""), media, options);
if (options == BundleOptions.MinifiedAndCombined)
return html.Css(bundlePath.Replace(".css.bundle", ".min.css"), media, options);
var cssFiles = File.ReadAllLines(filePath);
var styles = new StringBuilder();
foreach (var file in cssFiles)
{
var cssFile = file.Trim().Replace(".less", ".css");
var cssSrc = Path.Combine(baseUrl, cssFile);
styles.AppendLine(
html.Css(cssSrc, media, options).ToString()
);
}
return styles.ToString().ToMvcHtmlString();
});
}
}
}
| |
// 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 HorizontalSubtractSingle()
{
var test = new HorizontalBinaryOpTest__HorizontalSubtractSingle();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse.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 (Sse.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();
if (Sse.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse.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();
if (Sse.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (Sse.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (Sse.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (Sse.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class HorizontalBinaryOpTest__HorizontalSubtractSingle
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Single[] inArray1, Single[] inArray2, Single[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Single>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Single>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Single, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Single, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<Single> _fld1;
public Vector128<Single> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
return testStruct;
}
public void RunStructFldScenario(HorizontalBinaryOpTest__HorizontalSubtractSingle testClass)
{
var result = Sse3.HorizontalSubtract(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(HorizontalBinaryOpTest__HorizontalSubtractSingle testClass)
{
fixed (Vector128<Single>* pFld1 = &_fld1)
fixed (Vector128<Single>* pFld2 = &_fld2)
{
var result = Sse3.HorizontalSubtract(
Sse.LoadVector128((Single*)(pFld1)),
Sse.LoadVector128((Single*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single);
private static Single[] _data1 = new Single[Op1ElementCount];
private static Single[] _data2 = new Single[Op2ElementCount];
private static Vector128<Single> _clsVar1;
private static Vector128<Single> _clsVar2;
private Vector128<Single> _fld1;
private Vector128<Single> _fld2;
private DataTable _dataTable;
static HorizontalBinaryOpTest__HorizontalSubtractSingle()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
}
public HorizontalBinaryOpTest__HorizontalSubtractSingle()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
_dataTable = new DataTable(_data1, _data2, new Single[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Sse3.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Sse3.HorizontalSubtract(
Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Sse3.HorizontalSubtract(
Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Sse3.HorizontalSubtract(
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Sse3).GetMethod(nameof(Sse3.HorizontalSubtract), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse3).GetMethod(nameof(Sse3.HorizontalSubtract), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse3).GetMethod(nameof(Sse3.HorizontalSubtract), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse3.HorizontalSubtract(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Single>* pClsVar1 = &_clsVar1)
fixed (Vector128<Single>* pClsVar2 = &_clsVar2)
{
var result = Sse3.HorizontalSubtract(
Sse.LoadVector128((Single*)(pClsVar1)),
Sse.LoadVector128((Single*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr);
var result = Sse3.HorizontalSubtract(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr));
var op2 = Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr));
var result = Sse3.HorizontalSubtract(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr));
var op2 = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr));
var result = Sse3.HorizontalSubtract(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new HorizontalBinaryOpTest__HorizontalSubtractSingle();
var result = Sse3.HorizontalSubtract(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new HorizontalBinaryOpTest__HorizontalSubtractSingle();
fixed (Vector128<Single>* pFld1 = &test._fld1)
fixed (Vector128<Single>* pFld2 = &test._fld2)
{
var result = Sse3.HorizontalSubtract(
Sse.LoadVector128((Single*)(pFld1)),
Sse.LoadVector128((Single*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse3.HorizontalSubtract(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Single>* pFld1 = &_fld1)
fixed (Vector128<Single>* pFld2 = &_fld2)
{
var result = Sse3.HorizontalSubtract(
Sse.LoadVector128((Single*)(pFld1)),
Sse.LoadVector128((Single*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Sse3.HorizontalSubtract(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Sse3.HorizontalSubtract(
Sse.LoadVector128((Single*)(&test._fld1)),
Sse.LoadVector128((Single*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<Single> op1, Vector128<Single> op2, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] inArray2 = new Single[Op2ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] inArray2 = new Single[Op2ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Single>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Single>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Single[] left, Single[] right, Single[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (var outer = 0; outer < (LargestVectorSize / 16); outer++)
{
for (var inner = 0; inner < (8 / sizeof(Single)); inner++)
{
var i1 = (outer * (16 / sizeof(Single))) + inner;
var i2 = i1 + (8 / sizeof(Single));
var i3 = (outer * (16 / sizeof(Single))) + (inner * 2);
if (BitConverter.SingleToInt32Bits(result[i1]) != BitConverter.SingleToInt32Bits(left[i3] - left[i3 + 1]))
{
succeeded = false;
break;
}
if (BitConverter.SingleToInt32Bits(result[i2]) != BitConverter.SingleToInt32Bits(right[i3] - right[i3 + 1]))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse3)}.{nameof(Sse3.HorizontalSubtract)}<Single>(Vector128<Single>, Vector128<Single>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
namespace ChoETL
{
#region NameSpaces
using System;
using System.Linq;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
#endregion NameSpaces
#region ChoAssemblyManager Class
public static class ChoAssemblyManager
{
#region Shared Data Members (Private)
/// <summary>
/// Holds the loaded assemblies.
/// </summary>
private static Dictionary<string, Assembly> _assemblyCache = new Dictionary<string, Assembly>();
private static readonly object _syncRoot = new object();
/// <summary>
/// Holds the missing assembly cache.
/// </summary>
private static List<string> _missingAssemblyCache = new List<string>();
#endregion
#region Constructors
static ChoAssemblyManager()
{
Clear();
}
#endregion
#region Shared Members (Public)
public static void Clear()
{
lock (_syncRoot)
{
_assemblyCache.Clear();
_missingAssemblyCache.Clear();
}
}
public static bool ContainsAssembly(string assemblyName)
{
ChoGuard.ArgumentNotNullOrEmpty(assemblyName, "AssemblyName");
return _assemblyCache.ContainsKey(assemblyName);
}
public static bool ContainsAssembly(Assembly assembly)
{
ChoGuard.ArgumentNotNull(assembly, "Assembly");
return _assemblyCache.ContainsKey(assembly.FullName);
}
public static void AddAssemblyToCache(Assembly assembly)
{
ChoGuard.ArgumentNotNull(assembly, "Assembly");
lock (_syncRoot)
{
if (ContainsAssembly(assembly)) return;
_assemblyCache.Add(assembly.FullName, assembly);
}
}
public static Assembly GetAssemblyFromCache(string assemblyFileName)
{
ChoGuard.ArgumentNotNullOrEmpty(assemblyFileName, "AssemblyFileName");
return _assemblyCache[assemblyFileName];
}
public static void AddMissingAssembly(string assemblyFileName)
{
ChoGuard.ArgumentNotNullOrEmpty(assemblyFileName, "Assembly File Name");
lock (_syncRoot)
{
if (_missingAssemblyCache.Contains(assemblyFileName)) return;
_missingAssemblyCache.Add(assemblyFileName);
}
}
#endregion
internal static bool ContainsAsMissingAssembly(string assemblyFileName)
{
lock (_syncRoot)
{
return _missingAssemblyCache.Contains(assemblyFileName);
}
}
}
#endregion ChoAssemblyManager Class
public static class ChoAssemblyResolver
{
#region Shared Data Members (Private)
private static HashSet<string> _paths = new HashSet<string>();
#endregion Shared Data Members (Private)
#region Public Instance Constructors
static ChoAssemblyResolver()
{
//_paths.Add(Directory.GetDirectories(ChoAssembly.GetEntryAssemblyLocation(), "*.*", SearchOption.AllDirectories));
AppDomain.CurrentDomain.AssemblyResolve +=
new ResolveEventHandler(AssemblyResolve);
AppDomain.CurrentDomain.AssemblyLoad +=
new AssemblyLoadEventHandler(AssemblyLoad);
}
#endregion Public Instance Constructors
#region Public Shared Methods
/// <summary>
/// Installs the assembly resolver by hooking up to the
/// <see cref="AppDomain.AssemblyResolve" /> event.
/// </summary>
public static void Attach()
{
}
/// <summary>
/// Uninstalls the assembly resolver.
/// </summary>
public static void Clear()
{
ChoAssemblyManager.Clear();
AppDomain.CurrentDomain.AssemblyResolve -=
new ResolveEventHandler(AssemblyResolve);
AppDomain.CurrentDomain.AssemblyLoad -=
new AssemblyLoadEventHandler(AssemblyLoad);
}
#endregion Public Instance Methods
#region Private Shared Methods
/// <summary>
/// Resolves an assembly not found by the system using the assembly
/// cache.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="args">A <see cref="ResolveEventArgs" /> that contains the event data.</param>
/// <returns>
/// The loaded assembly, or <see langword="null" /> if not found.
/// </returns>
private static Assembly AssemblyResolve(object sender, ResolveEventArgs args)
{
Assembly assembly = DiscoverAssembly(sender, args);
if (assembly != null)
ChoAssembly.AddToLoadedAssembly(assembly);
return assembly;
}
private static Assembly DiscoverAssembly(object sender, ResolveEventArgs args)
{
bool isFullName = args.Name.IndexOf("Version=") != -1;
// first try to find an already loaded assembly
Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
foreach (Assembly assembly in assemblies)
{
if (isFullName)
{
if (assembly.FullName == args.Name)
{
// return assembly from AppDomain
return assembly;
}
}
else if (assembly.GetName(false).Name == args.Name)
{
// return assembly from AppDomain
return assembly;
}
}
if (ChoAssemblyManager.ContainsAsMissingAssembly(args.Name))
return null;
// find assembly in cache
if (ChoAssemblyManager.ContainsAssembly(args.Name))
{
// return assembly from cache
return (Assembly)ChoAssemblyManager.GetAssemblyFromCache(args.Name);
}
else
{
//String resourceName = "AssemblyLoadingAndReflection." + new AssemblyName(args.Name).Name + ".dll";
//if (Assembly.GetExecutingAssembly().GetManifestResourceInfo(resourceName) != null)
//{
// using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName))
// {
// Byte[] assemblyData = new Byte[stream.Length];
// stream.Read(assemblyData, 0, assemblyData.Length);
// return Assembly.Load(assemblyData);
// }
//}
string assmeblyFileName = null;
string[] asms = args.Name.Split(new char[] { ',' });
int index = args.Name.IndexOf(',');
var name = index < 0 ? args.Name + ".dll" : args.Name.Substring(0, index) + ".dll";
Assembly resAssembly = LoadAssemblyFromResource(name);
if (resAssembly != null)
return resAssembly;
bool fileFound = false;
foreach (string path in _paths)
{
if (path == null || path.Trim().Length == 0) continue;
assmeblyFileName = Path.Combine(path, name);
if (File.Exists(assmeblyFileName))
{
fileFound = true;
break;
}
}
if (fileFound)
{
return Assembly.LoadFile(assmeblyFileName);
}
else if (!assmeblyFileName.IsNullOrEmpty())
ChoAssemblyManager.AddMissingAssembly(args.Name);
}
return null;
}
private static Assembly LoadAssemblyFromResource(string name)
{
//Assembly thisAssembly = Assembly.GetEntryAssembly();
foreach (Assembly thisAssembly in ChoAssembly.GetLoadedAssemblies())
{
if (thisAssembly.IsDynamic) continue;
try
{
//Load form Embedded Resources - This Function is not called if the Assembly is in the Application Folder
var resources = thisAssembly.GetManifestResourceNames().Where(s => s.EndsWith(name));
if (resources.Count() > 0)
{
var resourceName = resources.First();
using (Stream stream = thisAssembly.GetManifestResourceStream(resourceName))
{
if (stream == null) return null;
var block = new byte[stream.Length];
stream.Read(block, 0, block.Length);
return Assembly.Load(block);
}
}
}
catch (Exception ex)
{
ChoETLLog.Error(ex.ToString());
}
}
return null;
}
/// <summary>
/// Occurs when an assembly is loaded. The loaded assembly is added
/// to the assembly cache.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="args">An <see cref="AssemblyLoadEventArgs" /> that contains the event data.</param>
private static void AssemblyLoad(object sender, AssemblyLoadEventArgs args)
{
ChoAssemblyManager.AddAssemblyToCache(args.LoadedAssembly);
}
#endregion Private Instance Methods
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using pltkw3msPayment.Areas.HelpPage.ModelDescriptions;
using pltkw3msPayment.Areas.HelpPage.Models;
namespace pltkw3msPayment.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.MirrorRecursiveTypes
{
using Microsoft.Rest;
using Models;
/// <summary>
/// Some cool documentation.
/// </summary>
public partial class RecursiveTypesAPI : Microsoft.Rest.ServiceClient<RecursiveTypesAPI>, IRecursiveTypesAPI
{
/// <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>
/// Initializes a new instance of the RecursiveTypesAPI class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public RecursiveTypesAPI(params System.Net.Http.DelegatingHandler[] handlers) : base(handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the RecursiveTypesAPI 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>
public RecursiveTypesAPI(System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the RecursiveTypesAPI 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>
public RecursiveTypesAPI(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 RecursiveTypesAPI 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="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public RecursiveTypesAPI(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>
/// An optional partial-method to perform custom initialization.
///</summary>
partial void CustomInitialize();
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
this.BaseUri = new System.Uri("https://management.azure.com/");
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()
}
};
DeserializationSettings = new Newtonsoft.Json.JsonSerializerSettings
{
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new Microsoft.Rest.Serialization.ReadOnlyJsonContractResolver(),
Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter>
{
new Microsoft.Rest.Serialization.Iso8601TimeSpanConverter()
}
};
CustomInitialize();
}
/// <summary>
/// Products
/// </summary>
/// <remarks>
/// The Products endpoint returns information about the Uber products offered
/// at a given location. The response includes the display name and other
/// details about each product, and lists the products in the proper display
/// order.
/// </remarks>
/// <param name='subscriptionId'>
/// Subscription Id.
/// </param>
/// <param name='resourceGroupName'>
/// Resource Group Id.
/// </param>
/// <param name='apiVersion'>
/// API Id.
/// </param>
/// <param name='body'>
/// API body mody.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <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>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<Product>> PostWithHttpMessagesAsync(string subscriptionId, string resourceGroupName, string apiVersion, Product body = default(Product), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (subscriptionId == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "subscriptionId");
}
if (resourceGroupName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName");
}
if (apiVersion == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "apiVersion");
}
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("subscriptionId", subscriptionId);
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("body", body);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "Post", tracingParameters);
}
// Construct URL
var _baseUrl = this.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/Microsoft.Cache/Redis").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(subscriptionId));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{apiVersion}", System.Uri.EscapeDataString(apiVersion));
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(body != null)
{
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(body, this.SerializationSettings);
_httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.HttpOperationResponse<Product>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Product>(_responseContent, this.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
#region File Description
//-----------------------------------------------------------------------------
// SmokePlumeParticleSystem.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
#region Using Statements
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using ParticlesSettings;
#endregion
namespace Particles2DPipelineSample
{
public class ParticleSystem : DrawableGameComponent
{
// these two values control the order that particle systems are drawn in.
// typically, particles that use additive blending should be drawn on top of
// particles that use regular alpha blending. ParticleSystems should therefore
// set their DrawOrder to the appropriate value in InitializeConstants, though
// it is possible to use other values for more advanced effects.
public const int AlphaBlendDrawOrder = 100;
public const int AdditiveDrawOrder = 200;
private SpriteBatch spriteBatch;
// the texture this particle system will use.
private Texture2D texture;
// the origin when we're drawing textures. this will be the middle of the
// texture.
private Vector2 origin;
// the array of particles used by this system. these are reused, so that calling
// AddParticles will only cause allocations if we're trying to create more particles
// than we have available
private List<Particle> particles;
// the queue of free particles keeps track of particles that are not curently
// being used by an effect. when a new effect is requested, particles are taken
// from this queue. when particles are finished they are put onto this queue.
private Queue<Particle> freeParticles;
// The settings used for this particle system
private ParticleSystemSettings settings;
// The asset name used to load our settings from a file.
private string settingsAssetName;
// the BlendState used when rendering the particles.
private BlendState blendState;
/// <summary>
/// returns the number of particles that are available for a new effect.
/// </summary>
public int FreeParticleCount
{
get { return freeParticles.Count; }
}
/// <summary>
/// Constructs a new ParticleSystem.
/// </summary>
/// <param name="game">The host for this particle system.</param>
/// <param name="settingsAssetName">The name of the settings file to load
/// used when creating and updating particles in the system.</param>
public ParticleSystem(Game game, string settingsAssetName)
: this(game, settingsAssetName, 10)
{ }
/// <summary>
/// Constructs a new ParticleSystem.
/// </summary>
/// <param name="game">The host for this particle system.</param>
/// <param name="settingsAssetName">The name of the settings file to load
/// used when creating and updating particles in the system.</param>
/// <param name="initialParticleCount">The initial number of particles this
/// system expects to use. The system will grow as needed, however setting
/// this value to be as close as possible will reduce allocations.</param>
public ParticleSystem(Game game, string settingsAssetName, int initialParticleCount)
: base(game)
{
this.settingsAssetName = settingsAssetName;
// we create the particle list and queue with our initial count and create that
// many particles. If we picked a reasonable value, our system will not allocate
// any more objects after this point, however the AddParticles method will allocate
// more particles as needed.
particles = new List<Particle>(initialParticleCount);
freeParticles = new Queue<Particle>(initialParticleCount);
for (int i = 0; i < initialParticleCount; i++)
{
particles.Add(new Particle());
freeParticles.Enqueue(particles[i]);
}
}
/// <summary>
/// Override the base class LoadContent to load the texture. once it's
/// loaded, calculate the origin.
/// </summary>
protected override void LoadContent()
{
// Load our settings
settings = Game.Content.Load<ParticleSystemSettings>(settingsAssetName);
// load the texture....
texture = Game.Content.Load<Texture2D>(settings.TextureFilename);
// ... and calculate the center. this'll be used in the draw call, we
// always want to rotate and scale around this point.
origin.X = texture.Width / 2;
origin.Y = texture.Height / 2;
// create the SpriteBatch that will draw the particles
spriteBatch = new SpriteBatch(GraphicsDevice);
// create the blend state using the values from our settings
blendState = new BlendState
{
AlphaSourceBlend = settings.SourceBlend,
ColorSourceBlend = settings.SourceBlend,
AlphaDestinationBlend = settings.DestinationBlend,
ColorDestinationBlend = settings.DestinationBlend
};
base.LoadContent();
}
/// <summary>
/// PickRandomDirection is used by AddParticle to decide which direction
/// particles will move.
/// </summary>
private Vector2 PickRandomDirection()
{
float angle = ParticleHelpers.RandomBetween(settings.MinDirectionAngle, settings.MaxDirectionAngle);
// our settings angles are in degrees, so we must convert to radians
angle = MathHelper.ToRadians(angle);
return new Vector2((float)Math.Cos(angle), (float)Math.Sin(angle));
}
/// <summary>
/// AddParticles's job is to add an effect somewhere on the screen. If there
/// aren't enough particles in the freeParticles queue, it will use as many as
/// it can. This means that if there not enough particles available, calling
/// AddParticles will have no effect.
/// </summary>
/// <param name="where">Where the particle effect should be created</param>
/// <param name="velocity">A base velocity for all particles. This is weighted
/// by the EmitterVelocitySensitivity specified in the settings for the
/// particle system.</param>
public void AddParticles(Vector2 where, Vector2 velocity)
{
// the number of particles we want for this effect is a random number
// somewhere between the two constants specified by the settings.
int numParticles =
ParticleHelpers.Random.Next(settings.MinNumParticles, settings.MaxNumParticles);
// create that many particles, if you can.
for (int i = 0; i < numParticles; i++)
{
// if we're out of free particles, we allocate another ten particles
// which should keep us going.
if (freeParticles.Count == 0)
{
for (int j = 0; j < 10; j++)
{
Particle newParticle = new Particle();
particles.Add(newParticle);
freeParticles.Enqueue(newParticle);
}
}
// grab a particle from the freeParticles queue, and Initialize it.
Particle p = freeParticles.Dequeue();
InitializeParticle(p, where, velocity);
}
}
/// <summary>
/// InitializeParticle randomizes some properties for a particle, then
/// calls initialize on it. It can be overriden by subclasses if they
/// want to modify the way particles are created. For example,
/// SmokePlumeParticleSystem overrides this function make all particles
/// accelerate to the right, simulating wind.
/// </summary>
/// <param name="p">the particle to initialize</param>
/// <param name="where">the position on the screen that the particle should be
/// </param>
/// <param name="velocity">The base velocity that the particle should have</param>
private void InitializeParticle(Particle p, Vector2 where, Vector2 velocity)
{
// Adjust the input velocity based on how much
// this particle system wants to be affected by it.
velocity *= settings.EmitterVelocitySensitivity;
// Adjust the velocity based on our random values
Vector2 direction = PickRandomDirection();
float speed = ParticleHelpers.RandomBetween(settings.MinInitialSpeed, settings.MaxInitialSpeed);
velocity += direction * speed;
// pick some random values for our particle
float lifetime =
ParticleHelpers.RandomBetween(settings.MinLifetime, settings.MaxLifetime);
float scale =
ParticleHelpers.RandomBetween(settings.MinSize, settings.MaxSize);
float rotationSpeed =
ParticleHelpers.RandomBetween(settings.MinRotationSpeed, settings.MaxRotationSpeed);
// our settings angles are in degrees, so we must convert to radians
rotationSpeed = MathHelper.ToRadians(rotationSpeed);
// figure out our acceleration base on our AccelerationMode
Vector2 acceleration = Vector2.Zero;
switch (settings.AccelerationMode)
{
case AccelerationMode.Scalar:
// randomly pick our acceleration using our direction and
// the MinAcceleration/MaxAcceleration values
float accelerationScale = ParticleHelpers.RandomBetween(
settings.MinAccelerationScale, settings.MaxAccelerationScale);
acceleration = direction * accelerationScale;
break;
case AccelerationMode.EndVelocity:
// Compute our acceleration based on our ending velocity from the settings.
// We'll use the equation vt = v0 + (a0 * t). (If you're not familar with
// this, it's one of the basic kinematics equations for constant
// acceleration, and basically says:
// velocity at time t = initial velocity + acceleration * t)
// We're solving for a0 by substituting t for our lifetime, v0 for our
// velocity, and vt as velocity * settings.EndVelocity.
acceleration = (velocity * (settings.EndVelocity - 1)) / lifetime;
break;
case AccelerationMode.Vector:
acceleration = new Vector2(
ParticleHelpers.RandomBetween(settings.MinAccelerationVector.X, settings.MaxAccelerationVector.X),
ParticleHelpers.RandomBetween(settings.MinAccelerationVector.Y, settings.MaxAccelerationVector.Y));
break;
default:
break;
}
// then initialize it with those random values. initialize will save those,
// and make sure it is marked as active.
p.Initialize(
where,
velocity,
acceleration,
lifetime,
scale,
rotationSpeed);
}
/// <summary>
/// overriden from DrawableGameComponent, Update will update all of the active
/// particles.
/// </summary>
public override void Update(GameTime gameTime)
{
// calculate dt, the change in the since the last frame. the particle
// updates will use this value.
float dt = (float)gameTime.ElapsedGameTime.TotalSeconds;
// go through all of the particles...
foreach (Particle p in particles)
{
if (p.Active)
{
// ... and if they're active, update them.
p.Acceleration += settings.Gravity * dt;
p.Update(dt);
// if that update finishes them, put them onto the free particles
// queue.
if (!p.Active)
{
freeParticles.Enqueue(p);
}
}
}
base.Update(gameTime);
}
/// <summary>
/// overriden from DrawableGameComponent, Draw will use ParticleSampleGame's
/// sprite batch to render all of the active particles.
/// </summary>
public override void Draw(GameTime gameTime)
{
// tell sprite batch to begin, using the spriteBlendMode specified in
// initializeConstants
spriteBatch.Begin(SpriteSortMode.Deferred, blendState);
foreach (Particle p in particles)
{
// skip inactive particles
if (!p.Active)
continue;
// normalized lifetime is a value from 0 to 1 and represents how far
// a particle is through its life. 0 means it just started, .5 is half
// way through, and 1.0 means it's just about to be finished.
// this value will be used to calculate alpha and scale, to avoid
// having particles suddenly appear or disappear.
float normalizedLifetime = p.TimeSinceStart / p.Lifetime;
// we want particles to fade in and fade out, so we'll calculate alpha
// to be (normalizedLifetime) * (1-normalizedLifetime). this way, when
// normalizedLifetime is 0 or 1, alpha is 0. the maximum value is at
// normalizedLifetime = .5, and is
// (normalizedLifetime) * (1-normalizedLifetime)
// (.5) * (1-.5)
// .25
// since we want the maximum alpha to be 1, not .25, we'll scale the
// entire equation by 4.
float alpha = 4 * normalizedLifetime * (1 - normalizedLifetime);
Color color = Color.White * alpha;
// make particles grow as they age. they'll start at 75% of their size,
// and increase to 100% once they're finished.
float scale = p.Scale * (.75f + .25f * normalizedLifetime);
spriteBatch.Draw(texture, p.Position, null, color,
p.Rotation, origin, scale, SpriteEffects.None, 0.0f);
}
spriteBatch.End();
base.Draw(gameTime);
}
}
}
| |
// file: core/math/math_2d.h
// commit: 7ad14e7a3e6f87ddc450f7e34621eb5200808451
// file: core/math/math_2d.cpp
// commit: 7ad14e7a3e6f87ddc450f7e34621eb5200808451
// file: core/variant_call.cpp
// commit: 5ad9be4c24e9d7dc5672fdc42cea896622fe5685
using System;
using System.Runtime.InteropServices;
#if REAL_T_IS_DOUBLE
using real_t = System.Double;
#else
using real_t = System.Single;
#endif
namespace Godot
{
[StructLayout(LayoutKind.Sequential)]
public struct Vector2 : IEquatable<Vector2>
{
public real_t x;
public real_t y;
public real_t this[int index]
{
get
{
switch (index)
{
case 0:
return x;
case 1:
return y;
default:
throw new IndexOutOfRangeException();
}
}
set
{
switch (index)
{
case 0:
x = value;
return;
case 1:
y = value;
return;
default:
throw new IndexOutOfRangeException();
}
}
}
internal void Normalize()
{
real_t length = x * x + y * y;
if (length != 0f)
{
length = Mathf.Sqrt(length);
x /= length;
y /= length;
}
}
public real_t Cross(Vector2 b)
{
return x * b.y - y * b.x;
}
public Vector2 Abs()
{
return new Vector2(Mathf.Abs(x), Mathf.Abs(y));
}
public real_t Angle()
{
return Mathf.Atan2(y, x);
}
public real_t AngleTo(Vector2 to)
{
return Mathf.Atan2(Cross(to), Dot(to));
}
public real_t AngleToPoint(Vector2 to)
{
return Mathf.Atan2(x - to.x, y - to.y);
}
public real_t Aspect()
{
return x / y;
}
public Vector2 Bounce(Vector2 n)
{
return -Reflect(n);
}
public Vector2 Ceil()
{
return new Vector2(Mathf.Ceil(x), Mathf.Ceil(y));
}
public Vector2 Clamped(real_t length)
{
var v = this;
real_t l = Length();
if (l > 0 && length < l)
{
v /= l;
v *= length;
}
return v;
}
public Vector2 CubicInterpolate(Vector2 b, Vector2 preA, Vector2 postB, real_t t)
{
var p0 = preA;
var p1 = this;
var p2 = b;
var p3 = postB;
real_t t2 = t * t;
real_t t3 = t2 * t;
return 0.5f * (p1 * 2.0f +
(-p0 + p2) * t +
(2.0f * p0 - 5.0f * p1 + 4 * p2 - p3) * t2 +
(-p0 + 3.0f * p1 - 3.0f * p2 + p3) * t3);
}
public real_t DistanceSquaredTo(Vector2 to)
{
return (x - to.x) * (x - to.x) + (y - to.y) * (y - to.y);
}
public real_t DistanceTo(Vector2 to)
{
return Mathf.Sqrt((x - to.x) * (x - to.x) + (y - to.y) * (y - to.y));
}
public real_t Dot(Vector2 with)
{
return x * with.x + y * with.y;
}
public Vector2 Floor()
{
return new Vector2(Mathf.Floor(x), Mathf.Floor(y));
}
public bool IsNormalized()
{
return Mathf.Abs(LengthSquared() - 1.0f) < Mathf.Epsilon;
}
public real_t Length()
{
return Mathf.Sqrt(x * x + y * y);
}
public real_t LengthSquared()
{
return x * x + y * y;
}
public Vector2 LinearInterpolate(Vector2 b, real_t t)
{
var res = this;
res.x += t * (b.x - x);
res.y += t * (b.y - y);
return res;
}
public Vector2 Normalized()
{
var result = this;
result.Normalize();
return result;
}
public Vector2 Project(Vector2 onNormal)
{
return onNormal * (Dot(onNormal) / onNormal.LengthSquared());
}
public Vector2 Reflect(Vector2 n)
{
return 2.0f * n * Dot(n) - this;
}
public Vector2 Rotated(real_t phi)
{
real_t rads = Angle() + phi;
return new Vector2(Mathf.Cos(rads), Mathf.Sin(rads)) * Length();
}
public Vector2 Round()
{
return new Vector2(Mathf.Round(x), Mathf.Round(y));
}
public void Set(real_t x, real_t y)
{
this.x = x;
this.y = y;
}
public void Set(Vector2 v)
{
x = v.x;
y = v.y;
}
public Vector2 Slerp(Vector2 b, real_t t)
{
real_t theta = AngleTo(b);
return Rotated(theta * t);
}
public Vector2 Slide(Vector2 n)
{
return this - n * Dot(n);
}
public Vector2 Snapped(Vector2 by)
{
return new Vector2(Mathf.Stepify(x, by.x), Mathf.Stepify(y, by.y));
}
public Vector2 Tangent()
{
return new Vector2(y, -x);
}
// Constants
private static readonly Vector2 _zero = new Vector2(0, 0);
private static readonly Vector2 _one = new Vector2(1, 1);
private static readonly Vector2 _negOne = new Vector2(-1, -1);
private static readonly Vector2 _inf = new Vector2(Mathf.Inf, Mathf.Inf);
private static readonly Vector2 _up = new Vector2(0, -1);
private static readonly Vector2 _down = new Vector2(0, 1);
private static readonly Vector2 _right = new Vector2(1, 0);
private static readonly Vector2 _left = new Vector2(-1, 0);
public static Vector2 Zero { get { return _zero; } }
public static Vector2 NegOne { get { return _negOne; } }
public static Vector2 One { get { return _one; } }
public static Vector2 Inf { get { return _inf; } }
public static Vector2 Up { get { return _up; } }
public static Vector2 Down { get { return _down; } }
public static Vector2 Right { get { return _right; } }
public static Vector2 Left { get { return _left; } }
// Constructors
public Vector2(real_t x, real_t y)
{
this.x = x;
this.y = y;
}
public Vector2(Vector2 v)
{
x = v.x;
y = v.y;
}
public static Vector2 operator +(Vector2 left, Vector2 right)
{
left.x += right.x;
left.y += right.y;
return left;
}
public static Vector2 operator -(Vector2 left, Vector2 right)
{
left.x -= right.x;
left.y -= right.y;
return left;
}
public static Vector2 operator -(Vector2 vec)
{
vec.x = -vec.x;
vec.y = -vec.y;
return vec;
}
public static Vector2 operator *(Vector2 vec, real_t scale)
{
vec.x *= scale;
vec.y *= scale;
return vec;
}
public static Vector2 operator *(real_t scale, Vector2 vec)
{
vec.x *= scale;
vec.y *= scale;
return vec;
}
public static Vector2 operator *(Vector2 left, Vector2 right)
{
left.x *= right.x;
left.y *= right.y;
return left;
}
public static Vector2 operator /(Vector2 vec, real_t scale)
{
vec.x /= scale;
vec.y /= scale;
return vec;
}
public static Vector2 operator /(Vector2 left, Vector2 right)
{
left.x /= right.x;
left.y /= right.y;
return left;
}
public static bool operator ==(Vector2 left, Vector2 right)
{
return left.Equals(right);
}
public static bool operator !=(Vector2 left, Vector2 right)
{
return !left.Equals(right);
}
public static bool operator <(Vector2 left, Vector2 right)
{
if (left.x.Equals(right.x))
{
return left.y < right.y;
}
return left.x < right.x;
}
public static bool operator >(Vector2 left, Vector2 right)
{
if (left.x.Equals(right.x))
{
return left.y > right.y;
}
return left.x > right.x;
}
public static bool operator <=(Vector2 left, Vector2 right)
{
if (left.x.Equals(right.x))
{
return left.y <= right.y;
}
return left.x <= right.x;
}
public static bool operator >=(Vector2 left, Vector2 right)
{
if (left.x.Equals(right.x))
{
return left.y >= right.y;
}
return left.x >= right.x;
}
public override bool Equals(object obj)
{
if (obj is Vector2)
{
return Equals((Vector2)obj);
}
return false;
}
public bool Equals(Vector2 other)
{
return x == other.x && y == other.y;
}
public override int GetHashCode()
{
return y.GetHashCode() ^ x.GetHashCode();
}
public override string ToString()
{
return String.Format("({0}, {1})", new object[]
{
x.ToString(),
y.ToString()
});
}
public string ToString(string format)
{
return String.Format("({0}, {1})", new object[]
{
x.ToString(format),
y.ToString(format)
});
}
}
}
| |
#if ASYNC
using System.Threading.Tasks;
#endif
using ZendeskApi_v2.Models.Macros;
namespace ZendeskApi_v2.Requests
{
public interface IMacros : ICore
{
#if SYNC
/// <summary>
/// Lists all shared and personal macros available to the current user
/// </summary>
/// <returns></returns>
GroupMacroResponse GetAllMacros();
IndividualMacroResponse GetMacroById(long id);
/// <summary>
/// Lists all active shared and personal macros available to the current user
/// </summary>
/// <returns></returns>
GroupMacroResponse GetActiveMacros();
IndividualMacroResponse CreateMacro(Macro macro);
IndividualMacroResponse UpdateMacro(Macro macro);
bool DeleteMacro(long id);
/// <summary>
/// Applies a macro to all applicable tickets.
/// </summary>
/// <param name="macroId"></param>
/// <returns></returns>
ApplyMacroResponse ApplyMacro(long macroId);
/// <summary>
/// Applies a macro to a specific ticket
/// </summary>
/// <param name="ticketId"></param>
/// <param name="macroId"></param>
/// <returns></returns>
ApplyMacroResponse ApplyMacroToTicket(long ticketId, long macroId);
#endif
#if ASYNC
/// <summary>
/// Lists all shared and personal macros available to the current user
/// </summary>
/// <returns></returns>
Task<GroupMacroResponse> GetAllMacrosAsync();
Task<IndividualMacroResponse> GetMacroByIdAsync(long id);
/// <summary>
/// Lists all active shared and personal macros available to the current user
/// </summary>
/// <returns></returns>
Task<GroupMacroResponse> GetActiveMacrosAsync();
Task<IndividualMacroResponse> CreateMacroAsync(Macro macro);
Task<IndividualMacroResponse> UpdateMacroAsync(Macro macro);
Task<bool> DeleteMacroAsync(long id);
/// <summary>
/// Applies a macro to all applicable tickets.
/// </summary>
/// <param name="macroId"></param>
/// <returns></returns>
Task<ApplyMacroResponse> ApplyMacroAsync(long macroId);
/// <summary>
/// Applies a macro to a specific ticket
/// </summary>
/// <param name="ticketId"></param>
/// <param name="macroId"></param>
/// <returns></returns>
Task<ApplyMacroResponse> ApplyMacroToTicketAsync(long ticketId, long macroId);
#endif
}
public class Macros : Core, IMacros
{
public Macros(string yourZendeskUrl, string user, string password, string apiToken, string p_OAuthToken)
: base(yourZendeskUrl, user, password, apiToken, p_OAuthToken)
{
}
#if SYNC
/// <summary>
/// Lists all shared and personal macros available to the current user
/// </summary>
/// <returns></returns>
public GroupMacroResponse GetAllMacros()
{
return GenericGet<GroupMacroResponse>(string.Format("macros.json"));
}
public IndividualMacroResponse GetMacroById(long id)
{
return GenericGet<IndividualMacroResponse>($"macros/{id}.json");
}
/// <summary>
/// Lists all active shared and personal macros available to the current user
/// </summary>
/// <returns></returns>
public GroupMacroResponse GetActiveMacros()
{
return GenericGet<GroupMacroResponse>(string.Format("macros/active.json"));
}
public IndividualMacroResponse CreateMacro(Macro macro)
{
var body = new {macro};
return GenericPost<IndividualMacroResponse>("macros.json", body);
}
public IndividualMacroResponse UpdateMacro(Macro macro)
{
var body = new { macro };
return GenericPut<IndividualMacroResponse>($"macros/{macro.Id}.json", body);
}
public bool DeleteMacro(long id)
{
return GenericDelete($"macros/{id}.json");
}
/// <summary>
/// Applies a macro to all applicable tickets.
/// </summary>
/// <param name="macroId"></param>
/// <returns></returns>
public ApplyMacroResponse ApplyMacro(long macroId)
{
return GenericGet<ApplyMacroResponse>($"macros/{macroId}/apply.json");
}
/// <summary>
/// Applies a macro to a specific ticket
/// </summary>
/// <param name="ticketId"></param>
/// <param name="macroId"></param>
/// <returns></returns>
public ApplyMacroResponse ApplyMacroToTicket(long ticketId, long macroId)
{
return GenericGet<ApplyMacroResponse>($"tickets/{ticketId}/macros/{macroId}/apply.json");
}
#endif
#if ASYNC
/// <summary>
/// Lists all shared and personal macros available to the current user
/// </summary>
/// <returns></returns>
public async Task<GroupMacroResponse> GetAllMacrosAsync()
{
return await GenericGetAsync<GroupMacroResponse>(string.Format("macros.json"));
}
public async Task<IndividualMacroResponse> GetMacroByIdAsync(long id)
{
return await GenericGetAsync<IndividualMacroResponse>($"macros/{id}.json");
}
/// <summary>
/// Lists all active shared and personal macros available to the current user
/// </summary>
/// <returns></returns>
public async Task<GroupMacroResponse> GetActiveMacrosAsync()
{
return await GenericGetAsync<GroupMacroResponse>(string.Format("macros/active.json"));
}
public async Task<IndividualMacroResponse> CreateMacroAsync(Macro macro)
{
var body = new { macro };
return await GenericPostAsync<IndividualMacroResponse>("macros.json", body);
}
public async Task<IndividualMacroResponse> UpdateMacroAsync(Macro macro)
{
var body = new { macro };
return await GenericPutAsync<IndividualMacroResponse>($"macros/{macro.Id}.json", body);
}
public async Task<bool> DeleteMacroAsync(long id)
{
return await GenericDeleteAsync($"macros/{id}.json");
}
/// <summary>
/// Applies a macro to all applicable tickets.
/// </summary>
/// <param name="macroId"></param>
/// <returns></returns>
public async Task<ApplyMacroResponse> ApplyMacroAsync(long macroId)
{
return await GenericGetAsync<ApplyMacroResponse>($"macros/{macroId}/apply.json");
}
/// <summary>
/// Applies a macro to a specific ticket
/// </summary>
/// <param name="ticketId"></param>
/// <param name="macroId"></param>
/// <returns></returns>
public async Task<ApplyMacroResponse> ApplyMacroToTicketAsync(long ticketId, long macroId)
{
return await GenericGetAsync<ApplyMacroResponse>($"tickets/{ticketId}/macros/{macroId}/apply.json");
}
#endif
}
}
| |
// Reference: Facepunch.ID
// Reference: Google.ProtocolBuffers
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
namespace Oxide.Plugins
{
[Info("Hooks Test", "Oxide Team", 0.1)]
public class HooksTest : RustLegacyPlugin
{
int hookCount = 0;
int hooksVerified;
Dictionary<string, bool> hooksRemaining = new Dictionary<string, bool>();
public void HookCalled(string name)
{
if (!hooksRemaining.ContainsKey(name)) return;
hookCount--;
hooksVerified++;
PrintWarning("{0} is working. {1} hooks verified!", name, hooksVerified);
hooksRemaining.Remove(name);
if (hookCount == 0)
PrintWarning("All hooks verified!");
else
PrintWarning("{0} hooks remaining: " + string.Join(", ", hooksRemaining.Keys.ToArray()), hookCount);
}
private void Init()
{
hookCount = hooks.Count;
hooksRemaining = hooks.Keys.ToDictionary(k => k, k => true);
PrintWarning("{0} hook to test!", hookCount);
HookCalled("Init");
}
public void Loaded()
{
HookCalled("Loaded");
}
protected override void LoadDefaultConfig()
{
HookCalled("LoadDefaultConfig");
}
private void Unloaded()
{
HookCalled("Unloaded");
}
private void OnFrame()
{
HookCalled("OnFrame");
}
private void ModifyTags(string oldtags)
{
HookCalled("ModifyTags");
}
private void BuildServerTags(IList<string> tags)
{
HookCalled("BuildServerTags");
}
int ResourceCounter = 1;
private void OnResourceNodeLoaded(ResourceTarget resource)
{
HookCalled("OnResourceNodeLoaded");
// Print resource
if (ResourceCounter <= 10)
{
Puts(resource.name + " loaded at " + resource.transform.position.ToString());
ResourceCounter++;
}
}
private void OnDatablocksInitialized()
{
HookCalled("OnDatablocksInitialized");
}
private void OnServerInitialized()
{
HookCalled("OnServerInitialized");
}
private void OnServerSave()
{
HookCalled("OnServerSave");
}
private void OnServerShutdown()
{
HookCalled("OnServerShutdown");
}
private void OnRunCommand(ConsoleSystem.Arg arg)
{
HookCalled("OnRunCommand");
var name = arg.argUser?.displayName;
if (name == null) name = "server console";
var cmd = arg.Class + "." + arg.Function;
var args = arg.ArgsStr;
Puts("The command '" + cmd + "' was used by " + name + " with the following arguments: " + args);
}
private void OnUserApprove(ClientConnection connection, uLink.NetworkPlayerApproval approval, ConnectionAcceptor acceptor)
{
HookCalled("OnUserApprove");
}
private void CanClientLogin(ClientConnection connection)
{
HookCalled("CanClientLogin");
}
private void OnPlayerConnected(NetUser netuser)
{
HookCalled("OnPlayerConnected");
// Print player connected in in-game chat
PrintToChat($"The player {netuser.displayName} has connected");
}
private void OnPlayerDisconnected(uLink.NetworkPlayer player)
{
HookCalled("OnPlayerDisconnected");
// Print player disconnected in in-game chat
var netUser = player.GetLocalData<NetUser>();
PrintToChat($"The player {netUser.displayName} has disconnected");
}
private void OnPlayerSpawn(PlayerClient client, bool useCamp, RustProto.Avatar avatar)
{
HookCalled("OnPlayerSpawn");
// Print spawn location in console
Puts("Player " + client.netUser.displayName + " spawned at " + client.lastKnownPosition + ".");
Puts("Player did " + (useCamp ? "" : "not ") + "select a sleepingbag to spawn at.");
// Doing stuff with the player needs to wait until the next frame
NextTick(() =>
{
// Print start metabolism values in console
var player = client.controllable;
var character = player.character;
var metabolism = character.GetComponent<Metabolism>();
Puts(client.netUser.displayName + " currently has the following Metabolism values:");
Puts(" Health: " + character.health.ToString());
Puts(" Calories: " + metabolism.GetCalorieLevel().ToString());
Puts(" Radiation: " + metabolism.GetRadLevel().ToString());
// Give admin items for testing
if (client.netUser.CanAdmin())
{
var inventory = player.GetComponent<Inventory>();
var pref = Inventory.Slot.Preference.Define(Inventory.Slot.Kind.Belt, false, Inventory.Slot.KindFlags.Belt);
var item = DatablockDictionary.GetByName("Uber Hatchet");
inventory.AddItemAmount(item, 1, pref);
}
});
}
private void OnItemCraft(CraftingInventory inventory, BlueprintDataBlock blueprint, int amount, ulong startTime)
{
HookCalled("OnItemCraft");
// Print item crafting
var netUser = inventory.GetComponent<Character>().netUser;
Puts(netUser.displayName + " started crafting " + blueprint.resultItem.name + " x " + amount.ToString());
}
private void OnItemDeployed(DeployableObject component, NetUser netUser)
{
HookCalled("OnItemDeployed");
// Print item deployed
Puts(netUser.displayName + " deployed a " + component.name);
}
private void OnItemAdded(Inventory inventory, int slot, IInventoryItem item)
{
HookCalled("OnItemAdded");
// Print item added
var netUser = inventory.GetComponent<Character>()?.netUser;
if (netUser == null) return;
Puts(item.datablock.name + " was added to inventory slot " + slot.ToString() + " owned by " + netUser.displayName);
}
private void OnItemRemoved(Inventory inventory, int slot, IInventoryItem item)
{
HookCalled("OnItemRemoved");
// Print item removed
var netUser = inventory.GetComponent<Character>()?.netUser;
if (netUser == null) return;
Puts(item.datablock.name + " was removed from inventory slot " + slot.ToString() + " owned by " + netUser.displayName);
}
private void OnDoorToggle(BasicDoor door, ulong timestamp, Controllable controllable)
{
HookCalled("OnDoorToggle");
// Print door used
Puts(controllable.netUser.displayName + " used the door " + door.GetInstanceID() + " owned by the player with SteamID " + door.GetComponent<DeployableObject>().ownerID);
}
private void ModifyDamage(TakeDamage takedamage, DamageEvent damage)
{
HookCalled("ModifyDamage");
}
private void OnHurt(TakeDamage takedamage, DamageEvent damage)
{
HookCalled("OnHurt");
// Print damage taken
var netUser = damage.victim.client.netUser;
if (netUser == null) return;
Puts("Player " + netUser.displayName + " took " + damage.amount + " damage!");
}
private void OnKilled(TakeDamage takedamage, DamageEvent damage)
{
HookCalled("OnKilled");
// Print death message
var netUser = damage.victim.client.netUser;
if (netUser == null) return;
Puts("Player " + netUser.displayName + " has died!");
}
private void OnStructureBuilt(StructureComponent component, NetUser netUser)
{
HookCalled("OnStructureBuilt");
// Print structure built
Puts(netUser.displayName + " build a " + component.name);
}
private void OnPlayerChat(NetUser netUser, string message)
{
HookCalled("OnPlayerChat");
// Print chat
Puts(netUser.displayName + " : " + message);
}
private void OnPlayerVoice(NetUser netUser, List<uLink.NetworkPlayer> listeners)
{
HookCalled("OnPlayerVoice");
// Print player using voice chat.
Puts(netUser.displayName + " is currently using voice chat.");
}
private void OnAirDrop(Vector3 dropLocation)
{
HookCalled("OnAirDrop");
// Print airdrop location
Puts("An airdrop is being called at location " + dropLocation.ToString());
}
bool OnStructureDecayCalled = false;
private void OnStructureDecay(StructureMaster master)
{
HookCalled("OnStructureDecay");
// Print structure info
if (!OnStructureDecayCalled)
{
Puts("Structure at " + master.transform.position.ToString() + " owned by player with SteamID " + master.ownerID + " took decay damage.");
OnStructureDecayCalled = true;
}
}
private void OnResearchItem(ResearchToolItem<ResearchToolDataBlock> tool, IInventoryItem item)
{
HookCalled("OnResearchItem");
// TODO: Complete parameters
//var netUser = item.inventory.GetComponent<Character>()?.netUser;
var netUser = item.inventory.GetComponent<Character>()?.netUser;
if (netUser == null) return;
Puts(netUser.displayName + " used " + tool.datablock.name + " on the item " + item.datablock.name);
}
private void OnBlueprintUse(BlueprintDataBlock bp, IBlueprintItem item)
{
HookCalled("OnBlueprintUse");
// TODO: Complete parameters
var netUser = item.inventory.GetComponent<Character>()?.netUser;
if (netUser == null) return;
Puts(netUser.displayName + " used the blueprint " + item.datablock.name + " to learn how to craft " + bp.resultItem.name);
}
}
}
| |
using System;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
namespace WeifenLuo.WinFormsUI.Docking
{
/// <summary>
/// Visual Studio 2012 Light theme.
/// </summary>
public class VS2012DarkTheme : ThemeBase
{
/// <summary>
/// Applies the specified theme to the dock panel.
/// </summary>
/// <param name="dockPanel">The dock panel.</param>
public override void Apply(DockPanel dockPanel)
{
if (dockPanel == null)
{
throw new NullReferenceException("dockPanel");
}
Measures.SplitterSize = 6;
dockPanel.Extender.DockPaneCaptionFactory = new VS2012DarkDockPaneCaptionFactory();
dockPanel.Extender.AutoHideStripFactory = new VS2012DarkAutoHideStripFactory();
dockPanel.Extender.AutoHideWindowFactory = new VS2012DarkAutoHideWindowFactory();
dockPanel.Extender.DockPaneStripFactory = new VS2012DarkDockPaneStripFactory();
dockPanel.Extender.DockPaneSplitterControlFactory = new VS2012DarkDockPaneSplitterControlFactory();
dockPanel.Extender.DockWindowSplitterControlFactory = new VS2012DarkDockWindowSplitterControlFactory();
dockPanel.Extender.DockWindowFactory = new VS2012DarkDockWindowFactory();
dockPanel.Extender.PaneIndicatorFactory = new VS2012DarkPaneIndicatorFactory();
dockPanel.Extender.PanelIndicatorFactory = new VS2012DarkPanelIndicatorFactory();
dockPanel.Extender.DockOutlineFactory = new VS2012DarkDockOutlineFactory();
dockPanel.Skin = CreateVisualStudio2012Dark();
}
private class VS2012DarkDockOutlineFactory : DockPanelExtender.IDockOutlineFactory
{
public DockOutlineBase CreateDockOutline()
{
return new VS2012DarkDockOutline();
}
private class VS2012DarkDockOutline : DockOutlineBase
{
public VS2012DarkDockOutline()
{
m_dragForm = new DragForm();
SetDragForm(Rectangle.Empty);
DragForm.BackColor = Color.FromArgb(0xff, 91, 173, 255);
DragForm.Opacity = 0.5;
DragForm.Show(false);
}
DragForm m_dragForm;
private DragForm DragForm
{
get { return m_dragForm; }
}
protected override void OnShow()
{
CalculateRegion();
}
protected override void OnClose()
{
DragForm.Close();
}
private void CalculateRegion()
{
if (SameAsOldValue)
return;
if (!FloatWindowBounds.IsEmpty)
SetOutline(FloatWindowBounds);
else if (DockTo is DockPanel)
SetOutline(DockTo as DockPanel, Dock, (ContentIndex != 0));
else if (DockTo is DockPane)
SetOutline(DockTo as DockPane, Dock, ContentIndex);
else
SetOutline();
}
private void SetOutline()
{
SetDragForm(Rectangle.Empty);
}
private void SetOutline(Rectangle floatWindowBounds)
{
SetDragForm(floatWindowBounds);
}
private void SetOutline(DockPanel dockPanel, DockStyle dock, bool fullPanelEdge)
{
Rectangle rect = fullPanelEdge ? dockPanel.DockArea : dockPanel.DocumentWindowBounds;
rect.Location = dockPanel.PointToScreen(rect.Location);
if (dock == DockStyle.Top)
{
int height = dockPanel.GetDockWindowSize(DockState.DockTop);
rect = new Rectangle(rect.X, rect.Y, rect.Width, height);
}
else if (dock == DockStyle.Bottom)
{
int height = dockPanel.GetDockWindowSize(DockState.DockBottom);
rect = new Rectangle(rect.X, rect.Bottom - height, rect.Width, height);
}
else if (dock == DockStyle.Left)
{
int width = dockPanel.GetDockWindowSize(DockState.DockLeft);
rect = new Rectangle(rect.X, rect.Y, width, rect.Height);
}
else if (dock == DockStyle.Right)
{
int width = dockPanel.GetDockWindowSize(DockState.DockRight);
rect = new Rectangle(rect.Right - width, rect.Y, width, rect.Height);
}
else if (dock == DockStyle.Fill)
{
rect = dockPanel.DocumentWindowBounds;
rect.Location = dockPanel.PointToScreen(rect.Location);
}
SetDragForm(rect);
}
private void SetOutline(DockPane pane, DockStyle dock, int contentIndex)
{
if (dock != DockStyle.Fill)
{
Rectangle rect = pane.DisplayingRectangle;
if (dock == DockStyle.Right)
rect.X += rect.Width / 2;
if (dock == DockStyle.Bottom)
rect.Y += rect.Height / 2;
if (dock == DockStyle.Left || dock == DockStyle.Right)
rect.Width -= rect.Width / 2;
if (dock == DockStyle.Top || dock == DockStyle.Bottom)
rect.Height -= rect.Height / 2;
rect.Location = pane.PointToScreen(rect.Location);
SetDragForm(rect);
}
else if (contentIndex == -1)
{
Rectangle rect = pane.DisplayingRectangle;
rect.Location = pane.PointToScreen(rect.Location);
SetDragForm(rect);
}
else
{
using (GraphicsPath path = pane.TabStripControl.GetOutline(contentIndex))
{
RectangleF rectF = path.GetBounds();
Rectangle rect = new Rectangle((int)rectF.X, (int)rectF.Y, (int)rectF.Width, (int)rectF.Height);
using (Matrix matrix = new Matrix(rect, new Point[] { new Point(0, 0), new Point(rect.Width, 0), new Point(0, rect.Height) }))
{
path.Transform(matrix);
}
Region region = new Region(path);
SetDragForm(rect, region);
}
}
}
private void SetDragForm(Rectangle rect)
{
DragForm.Bounds = rect;
if (rect == Rectangle.Empty)
{
if (DragForm.Region != null)
{
DragForm.Region.Dispose();
}
DragForm.Region = new Region(Rectangle.Empty);
}
else if (DragForm.Region != null)
{
DragForm.Region.Dispose();
DragForm.Region = null;
}
}
private void SetDragForm(Rectangle rect, Region region)
{
DragForm.Bounds = rect;
if (DragForm.Region != null)
{
DragForm.Region.Dispose();
}
DragForm.Region = region;
}
}
}
private class VS2012DarkPanelIndicatorFactory : DockPanelExtender.IPanelIndicatorFactory
{
public DockPanel.IPanelIndicator CreatePanelIndicator(DockStyle style)
{
return new VS2012DarkPanelIndicator( style );
}
private class VS2012DarkPanelIndicator : PictureBox, DockPanel.IPanelIndicator
{
private static Image _imagePanelLeft = Resources.DockIndicator_PanelLeft_VS2012;
private static Image _imagePanelRight = Resources.DockIndicator_PanelRight_VS2012;
private static Image _imagePanelTop = Resources.DockIndicator_PanelTop_VS2012;
private static Image _imagePanelBottom = Resources.DockIndicator_PanelBottom_VS2012;
private static Image _imagePanelFill = Resources.DockIndicator_PanelFill_VS2012;
private static Image _imagePanelLeftActive = Resources.DockIndicator_PanelLeft_VS2012;
private static Image _imagePanelRightActive = Resources.DockIndicator_PanelRight_VS2012;
private static Image _imagePanelTopActive = Resources.DockIndicator_PanelTop_VS2012;
private static Image _imagePanelBottomActive = Resources.DockIndicator_PanelBottom_VS2012;
private static Image _imagePanelFillActive = Resources.DockIndicator_PanelFill_VS2012;
public VS2012DarkPanelIndicator( DockStyle dockStyle )
{
m_dockStyle = dockStyle;
SizeMode = PictureBoxSizeMode.AutoSize;
Image = ImageInactive;
}
private DockStyle m_dockStyle;
private DockStyle DockStyle
{
get { return m_dockStyle; }
}
private DockStyle m_status;
public DockStyle Status
{
get { return m_status; }
set
{
if (value != DockStyle && value != DockStyle.None)
throw new InvalidEnumArgumentException();
if (m_status == value)
return;
m_status = value;
IsActivated = (m_status != DockStyle.None);
}
}
private Image ImageInactive
{
get
{
if (DockStyle == DockStyle.Left)
return _imagePanelLeft;
else if (DockStyle == DockStyle.Right)
return _imagePanelRight;
else if (DockStyle == DockStyle.Top)
return _imagePanelTop;
else if (DockStyle == DockStyle.Bottom)
return _imagePanelBottom;
else if (DockStyle == DockStyle.Fill)
return _imagePanelFill;
else
return null;
}
}
private Image ImageActive
{
get
{
if (DockStyle == DockStyle.Left)
return _imagePanelLeftActive;
else if (DockStyle == DockStyle.Right)
return _imagePanelRightActive;
else if (DockStyle == DockStyle.Top)
return _imagePanelTopActive;
else if (DockStyle == DockStyle.Bottom)
return _imagePanelBottomActive;
else if (DockStyle == DockStyle.Fill)
return _imagePanelFillActive;
else
return null;
}
}
private bool m_isActivated = false;
private bool IsActivated
{
get { return m_isActivated; }
set
{
m_isActivated = value;
Image = IsActivated ? ImageActive : ImageInactive;
}
}
public DockStyle HitTest(Point pt)
{
return this.Visible && ClientRectangle.Contains(PointToClient(pt)) ? DockStyle : DockStyle.None;
}
}
}
private class VS2012DarkPaneIndicatorFactory : DockPanelExtender.IPaneIndicatorFactory
{
public DockPanel.IPaneIndicator CreatePaneIndicator()
{
return new VS2012DarkPaneIndicator();
}
private class VS2012DarkPaneIndicator : PictureBox, DockPanel.IPaneIndicator
{
private static Bitmap _bitmapPaneDiamond = Resources.Dockindicator_PaneDiamond_VS2012;
private static Bitmap _bitmapPaneDiamondLeft = Resources.Dockindicator_PaneDiamond_Fill_VS2012;
private static Bitmap _bitmapPaneDiamondRight = Resources.Dockindicator_PaneDiamond_Fill_VS2012;
private static Bitmap _bitmapPaneDiamondTop = Resources.Dockindicator_PaneDiamond_Fill_VS2012;
private static Bitmap _bitmapPaneDiamondBottom = Resources.Dockindicator_PaneDiamond_Fill_VS2012;
private static Bitmap _bitmapPaneDiamondFill = Resources.Dockindicator_PaneDiamond_Fill_VS2012;
private static Bitmap _bitmapPaneDiamondHotSpot = Resources.Dockindicator_PaneDiamond_Hotspot_VS2012;
private static Bitmap _bitmapPaneDiamondHotSpotIndex = Resources.DockIndicator_PaneDiamond_HotspotIndex_VS2012;
private static DockPanel.HotSpotIndex[] _hotSpots = new[]
{
new DockPanel.HotSpotIndex(1, 0, DockStyle.Top),
new DockPanel.HotSpotIndex(0, 1, DockStyle.Left),
new DockPanel.HotSpotIndex(1, 1, DockStyle.Fill),
new DockPanel.HotSpotIndex(2, 1, DockStyle.Right),
new DockPanel.HotSpotIndex(1, 2, DockStyle.Bottom)
};
private GraphicsPath _displayingGraphicsPath = DrawHelper.CalculateGraphicsPathFromBitmap(_bitmapPaneDiamond);
public VS2012DarkPaneIndicator()
{
SizeMode = PictureBoxSizeMode.AutoSize;
Image = _bitmapPaneDiamond;
Region = new Region(DisplayingGraphicsPath);
}
public GraphicsPath DisplayingGraphicsPath
{
get { return _displayingGraphicsPath; }
}
public DockStyle HitTest(Point pt)
{
if (!Visible)
return DockStyle.None;
pt = PointToClient(pt);
if (!ClientRectangle.Contains(pt))
return DockStyle.None;
for (int i = _hotSpots.GetLowerBound(0); i <= _hotSpots.GetUpperBound(0); i++)
{
if (_bitmapPaneDiamondHotSpot.GetPixel(pt.X, pt.Y) == _bitmapPaneDiamondHotSpotIndex.GetPixel(_hotSpots[i].X, _hotSpots[i].Y))
return _hotSpots[i].DockStyle;
}
return DockStyle.None;
}
private DockStyle m_status = DockStyle.None;
public DockStyle Status
{
get { return m_status; }
set
{
m_status = value;
if (m_status == DockStyle.None)
Image = _bitmapPaneDiamond;
else if (m_status == DockStyle.Left)
Image = _bitmapPaneDiamondLeft;
else if (m_status == DockStyle.Right)
Image = _bitmapPaneDiamondRight;
else if (m_status == DockStyle.Top)
Image = _bitmapPaneDiamondTop;
else if (m_status == DockStyle.Bottom)
Image = _bitmapPaneDiamondBottom;
else if (m_status == DockStyle.Fill)
Image = _bitmapPaneDiamondFill;
}
}
}
}
private class VS2012DarkAutoHideWindowFactory : DockPanelExtender.IAutoHideWindowFactory
{
public DockPanel.AutoHideWindowControl CreateAutoHideWindow(DockPanel panel)
{
return new VS2012LightAutoHideWindowControl(panel);
}
}
private class VS2012DarkDockPaneSplitterControlFactory : DockPanelExtender.IDockPaneSplitterControlFactory
{
public DockPane.SplitterControlBase CreateSplitterControl(DockPane pane)
{
return new VS2012DarkSplitterControl(pane);
}
}
private class VS2012DarkDockWindowSplitterControlFactory : DockPanelExtender.IDockWindowSplitterControlFactory
{
public SplitterBase CreateSplitterControl()
{
return new VS2012LightDockWindow.VS2012DarkDockWindowSplitterControl();
}
}
private class VS2012DarkDockPaneStripFactory : DockPanelExtender.IDockPaneStripFactory
{
public DockPaneStripBase CreateDockPaneStrip(DockPane pane)
{
return new VS2012DarkDockPaneStrip(pane);
}
}
private class VS2012DarkAutoHideStripFactory : DockPanelExtender.IAutoHideStripFactory
{
public AutoHideStripBase CreateAutoHideStrip(DockPanel panel)
{
var strip = new VS2012LightAutoHideStrip(panel);
strip.BackColor = Color.FromArgb(255, 45, 45, 48);
strip.BackgroundBrush = new SolidBrush(strip.BackColor);
return strip;
}
}
private class VS2012DarkDockPaneCaptionFactory : DockPanelExtender.IDockPaneCaptionFactory
{
public DockPaneCaptionBase CreateDockPaneCaption(DockPane pane)
{
return new VS2012LightDockPaneCaption(pane);
}
}
private class VS2012DarkDockWindowFactory : DockPanelExtender.IDockWindowFactory
{
public DockWindow CreateDockWindow(DockPanel dockPanel, DockState dockState)
{
return new VS2012LightDockWindow(dockPanel, dockState);
}
}
public static DockPanelSkin CreateVisualStudio2012Dark()
{
var back = Color.FromArgb(255, 45, 45, 48);
var specialBlue = Color.FromArgb(0xFF, 0x00, 0x7A, 0xCC);
var darkdot = Color.FromArgb(255, 70, 70, 74);
var bluedot = Color.FromArgb(255, 89, 168, 222);
var activeTab = specialBlue;
var mouseHoverTab = Color.FromArgb(0xFF, 28, 151, 234);
var toolActiveTab = Color.FromArgb(255, 30, 30, 30);
var inactiveTab = back;
var lostFocusTab = Color.FromArgb(0xFF, 63, 63, 70);
var inactiveText = Color.FromArgb(255, 241, 241, 241);
var darkText = Color.FromArgb(255, 208, 208, 208);
var skin = new DockPanelSkin();
skin.AutoHideStripSkin.DockStripGradient.StartColor = specialBlue;
skin.AutoHideStripSkin.DockStripGradient.EndColor = lostFocusTab;
skin.AutoHideStripSkin.TabGradient.TextColor = darkText;
skin.DockPaneStripSkin.DocumentGradient.DockStripGradient.StartColor = back;
skin.DockPaneStripSkin.DocumentGradient.DockStripGradient.EndColor = back;
skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.StartColor = activeTab;
skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.EndColor = lostFocusTab;
skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.TextColor = Color.White;
skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient.StartColor = inactiveTab;
skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient.EndColor = mouseHoverTab;
skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient.TextColor = inactiveText;
skin.DockPaneStripSkin.ToolWindowGradient.DockStripGradient.StartColor = back;
skin.DockPaneStripSkin.ToolWindowGradient.DockStripGradient.EndColor = back;
skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.StartColor = toolActiveTab;
skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.EndColor = toolActiveTab;
skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.TextColor = specialBlue;
skin.DockPaneStripSkin.ToolWindowGradient.InactiveTabGradient.StartColor = back;
skin.DockPaneStripSkin.ToolWindowGradient.InactiveTabGradient.EndColor = back;
skin.DockPaneStripSkin.ToolWindowGradient.InactiveTabGradient.TextColor = darkText;
skin.DockPaneStripSkin.ToolWindowGradient.ActiveCaptionGradient.StartColor = specialBlue;
skin.DockPaneStripSkin.ToolWindowGradient.ActiveCaptionGradient.EndColor = bluedot;
skin.DockPaneStripSkin.ToolWindowGradient.ActiveCaptionGradient.LinearGradientMode = LinearGradientMode.Vertical;
skin.DockPaneStripSkin.ToolWindowGradient.ActiveCaptionGradient.TextColor = Color.White;
skin.DockPaneStripSkin.ToolWindowGradient.InactiveCaptionGradient.StartColor = inactiveTab;
skin.DockPaneStripSkin.ToolWindowGradient.InactiveCaptionGradient.EndColor = darkdot;
skin.DockPaneStripSkin.ToolWindowGradient.InactiveCaptionGradient.LinearGradientMode = LinearGradientMode.Vertical;
skin.DockPaneStripSkin.ToolWindowGradient.InactiveCaptionGradient.TextColor = inactiveText;
return skin;
}
}
}
| |
// 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.ComponentModel;
using System.Globalization;
using System.Runtime.Serialization;
namespace System.Drawing.Printing
{
/// <summary>
/// Specifies the margins of a printed page.
/// </summary>
#if netcoreapp || netcoreapp30
[TypeConverter("System.Drawing.Printing.MarginsConverter, System.Windows.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51")]
#endif
public partial class Margins : ICloneable
{
private int _left;
private int _right;
private int _bottom;
private int _top;
[OptionalField]
private double _doubleLeft;
[OptionalField]
private double _doubleRight;
[OptionalField]
private double _doubleTop;
[OptionalField]
private double _doubleBottom;
/// <summary>
/// Initializes a new instance of a the <see cref='Margins'/> class with one-inch margins.
/// </summary>
public Margins() : this(100, 100, 100, 100)
{
}
/// <summary>
/// Initializes a new instance of a the <see cref='Margins'/> class with the specified left, right, top, and bottom margins.
/// </summary>
public Margins(int left, int right, int top, int bottom)
{
CheckMargin(left, nameof(left));
CheckMargin(right, nameof(right));
CheckMargin(top, nameof(top));
CheckMargin(bottom, nameof(bottom));
_left = left;
_right = right;
_top = top;
_bottom = bottom;
_doubleLeft = (double)left;
_doubleRight = (double)right;
_doubleTop = (double)top;
_doubleBottom = (double)bottom;
}
/// <summary>
/// Gets or sets the left margin, in hundredths of an inch.
/// </summary>
public int Left
{
get { return _left; }
set
{
CheckMargin(value, "Left");
_left = value;
_doubleLeft = (double)value;
}
}
/// <summary>
/// Gets or sets the right margin, in hundredths of an inch.
/// </summary>
public int Right
{
get { return _right; }
set
{
CheckMargin(value, "Right");
_right = value;
_doubleRight = (double)value;
}
}
/// <summary>
/// Gets or sets the top margin, in hundredths of an inch.
/// </summary>
public int Top
{
get { return _top; }
set
{
CheckMargin(value, "Top");
_top = value;
_doubleTop = (double)value;
}
}
/// <summary>
/// Gets or sets the bottom margin, in hundredths of an inch.
/// </summary>
public int Bottom
{
get { return _bottom; }
set
{
CheckMargin(value, "Bottom");
_bottom = value;
_doubleBottom = (double)value;
}
}
/// <summary>
/// Gets or sets the left margin with double value, in hundredths of an inch.
/// When use the setter, the ranger of setting double value should between
/// 0 to Int.MaxValue;
/// </summary>
internal double DoubleLeft
{
get { return _doubleLeft; }
set
{
Left = (int)Math.Round(value);
_doubleLeft = value;
}
}
/// <summary>
/// Gets or sets the right margin with double value, in hundredths of an inch.
/// When use the setter, the ranger of setting double value should between
/// 0 to Int.MaxValue;
/// </summary>
internal double DoubleRight
{
get { return _doubleRight; }
set
{
Right = (int)Math.Round(value);
_doubleRight = value;
}
}
/// <summary>
/// Gets or sets the top margin with double value, in hundredths of an inch.
/// When use the setter, the ranger of setting double value should between
/// 0 to Int.MaxValue;
/// </summary>
internal double DoubleTop
{
get { return _doubleTop; }
set
{
Top = (int)Math.Round(value);
_doubleTop = value;
}
}
/// <summary>
/// Gets or sets the bottom margin with double value, in hundredths of an inch.
/// When use the setter, the ranger of setting double value should between
/// 0 to Int.MaxValue;
/// </summary>
internal double DoubleBottom
{
get { return _doubleBottom; }
set
{
Bottom = (int)Math.Round(value);
_doubleBottom = value;
}
}
private void CheckMargin(int margin, string name)
{
if (margin < 0)
throw new ArgumentException(SR.Format(SR.InvalidLowBoundArgumentEx, name, margin, "0"));
}
/// <summary>
/// Retrieves a duplicate of this object, member by member.
/// </summary>
public object Clone()
{
return MemberwiseClone();
}
/// <summary>
/// Compares this <see cref='Margins'/> to a specified <see cref='Margins'/> to see whether they
/// are equal.
/// </summary>
public override bool Equals(object obj)
{
Margins margins = obj as Margins;
if (margins == this)
return true;
if (margins == null)
return false;
return margins.Left == Left
&& margins.Right == Right
&& margins.Top == Top
&& margins.Bottom == Bottom;
}
/// <summary>
/// Calculates and retrieves a hash code based on the left, right, top, and bottom margins.
/// </summary>
public override int GetHashCode()
{
// return HashCodes.Combine(left, right, top, bottom);
uint left = (uint)Left;
uint right = (uint)Right;
uint top = (uint)Top;
uint bottom = (uint)Bottom;
uint result = left ^
((right << 13) | (right >> 19)) ^
((top << 26) | (top >> 6)) ^
((bottom << 7) | (bottom >> 25));
return unchecked((int)result);
}
/// <summary>
/// Tests whether two <see cref='Margins'/> objects are identical.
/// </summary>
public static bool operator ==(Margins m1, Margins m2)
{
if (object.ReferenceEquals(m1, null) != object.ReferenceEquals(m2, null))
{
return false;
}
if (!object.ReferenceEquals(m1, null))
{
return m1.Left == m2.Left && m1.Top == m2.Top && m1.Right == m2.Right && m1.Bottom == m2.Bottom;
}
return true;
}
/// <summary>
/// Tests whether two <see cref='Margins'/> objects are different.
/// </summary>
public static bool operator !=(Margins m1, Margins m2)
{
return !(m1 == m2);
}
/// <summary>
/// Provides some interesting information for the Margins in String form.
/// </summary>
public override string ToString()
{
return "[Margins"
+ " Left=" + Left.ToString(CultureInfo.InvariantCulture)
+ " Right=" + Right.ToString(CultureInfo.InvariantCulture)
+ " Top=" + Top.ToString(CultureInfo.InvariantCulture)
+ " Bottom=" + Bottom.ToString(CultureInfo.InvariantCulture)
+ "]";
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using gov.va.medora.mdo.exceptions;
using System.Data;
namespace gov.va.medora.mdo.dao.sql.cdw
{
public class CdwPatientDao : IPatientDao
{
CdwConnection _cxn;
public CdwPatientDao(AbstractConnection cxn)
{
_cxn = cxn as CdwConnection;
}
public Patient[] match(string target)
{
if (!SocSecNum.isValid(target))
{
throw new NotImplementedException("non-SSN matches are currently not supported by CDW");
}
SqlCommand cmd = new SqlCommand("SELECT * FROM SPatient.SPatient WHERE PatientSSN=@target;");
SqlParameter targetParam = new SqlParameter("@target", System.Data.SqlDbType.VarChar, 9);
targetParam.Value = target;
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.SelectCommand = new SqlCommand(cmd.CommandText);
adapter.SelectCommand.Parameters.Add(targetParam);
IDataReader reader = (IDataReader)_cxn.query(adapter);
IDictionary<string, Patient> patients = new Dictionary<string, Patient>();
//if (!reader..HasRows)
//{
// return new Patient[0];
//}
while (reader.Read())
{
Patient p = new Patient();
p.LocalSiteId = (reader.GetInt16(reader.GetOrdinal("Sta3n"))).ToString();
p.LocalPid = reader.GetString(reader.GetOrdinal("PatientIEN"));
p.Name = new PersonName(reader.GetString(reader.GetOrdinal("PatientName")));
if (!reader.IsDBNull(reader.GetOrdinal("PatientSSN")))
{
p.SSN = new SocSecNum(reader.GetString(reader.GetOrdinal("PatientSSN")));
}
if (!reader.IsDBNull(reader.GetOrdinal("Gender")))
{
p.Gender = reader.GetString(reader.GetOrdinal("Gender"));
}
else
{
p.Gender = "";
}
if (!reader.IsDBNull(reader.GetOrdinal("DateOfBirthText")))
{
p.DOB = reader.GetString(reader.GetOrdinal("DateOfBirthText"));
}
if (!reader.IsDBNull(reader.GetOrdinal("PatientICN")))
{
p.MpiPid = (reader.GetString(reader.GetOrdinal("PatientICN"))).ToString();
}
else
{
// use SSN for patient ICN
if (p.SSN == null || String.IsNullOrEmpty(p.SSN.toString()))
{
throw new MdoException(MdoExceptionCode.DATA_MISSING_REQUIRED, "Unable to process results for " + target + " - CDW record contains no ICN and no SSN");
}
p.MpiPid = p.SSN.toString();
}
p.Demographics = new Dictionary<string, DemographicSet>();
DemographicSet demogs = new DemographicSet();
demogs.PhoneNumbers = new List<PhoneNum>();
demogs.EmailAddresses = new List<EmailAddress>();
demogs.StreetAddresses = new List<Address>();
if (!reader.IsDBNull(reader.GetOrdinal("PhoneResidence")))
{
demogs.PhoneNumbers.Add(new PhoneNum(reader.GetString(reader.GetOrdinal("PhoneResidence"))));
}
if (!reader.IsDBNull(reader.GetOrdinal("PhoneWork")))
{
demogs.PhoneNumbers.Add(new PhoneNum(reader.GetString(reader.GetOrdinal("PhoneWork"))));
}
Address address = new Address();
if (!reader.IsDBNull(reader.GetOrdinal("StreetAddress1")))
{
address.Street1 = reader.GetString(reader.GetOrdinal("StreetAddress1"));
}
if (!reader.IsDBNull(reader.GetOrdinal("StreetAddress2")))
{
address.Street2 = reader.GetString(reader.GetOrdinal("StreetAddress2"));
}
if (!reader.IsDBNull(reader.GetOrdinal("StreetAddress3")))
{
address.Street3 = reader.GetString(reader.GetOrdinal("StreetAddress3"));
}
if (!reader.IsDBNull(reader.GetOrdinal("City")))
{
address.City = reader.GetString(reader.GetOrdinal("City"));
}
if (!reader.IsDBNull(reader.GetOrdinal("county")))
{
address.County = reader.GetString(reader.GetOrdinal("county"));
}
if (!reader.IsDBNull(reader.GetOrdinal("State")))
{
address.State = reader.GetString(reader.GetOrdinal("State"));
}
if (!reader.IsDBNull(reader.GetOrdinal("Zip")))
{
address.Zipcode = reader.GetString(reader.GetOrdinal("Zip"));
}
demogs.StreetAddresses.Add(address);
p.Demographics.Add(p.LocalSiteId, demogs);
if (!patients.ContainsKey(p.MpiPid))
{
p.SitePids = new System.Collections.Specialized.StringDictionary();
p.SitePids.Add(p.LocalSiteId, p.LocalPid);
patients.Add(p.MpiPid, p);
}
else
{
if (!(patients[p.MpiPid].SitePids.ContainsKey(p.LocalSiteId)))
{
patients[p.MpiPid].SitePids.Add(p.LocalSiteId, p.LocalPid);
}
patients[p.MpiPid].Demographics.Add(p.LocalSiteId, p.Demographics[p.LocalSiteId]);
}
}
// cleanup - need to set all temp ICNs back to null
foreach (string key in patients.Keys)
{
if (!(patients[key].SSN == null) && !String.IsNullOrEmpty(patients[key].SSN.toString()) &&
!String.IsNullOrEmpty(patients[key].MpiPid) && String.Equals(patients[key].MpiPid, patients[key].SSN.toString()))
{
patients[key].MpiPid = null;
}
}
Patient[] result = new Patient[patients.Count];
patients.Values.CopyTo(result, 0);
return result;
}
public Dictionary<string, string> getTreatingFacilityIds(string pid)
{
SqlDataAdapter request = buildGetTreatingFacilityIdsRequest(pid);
IDataReader rdr = (IDataReader)_cxn.query(request);
return toPatientIds(rdr);
}
internal SqlDataAdapter buildGetTreatingFacilityIdsRequest(string icn)
{
string sql = "SELECT Sta3n, PatientIEN FROM SPatient.SPatient WHERE PatientICN=@icn;";
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = new SqlCommand(sql);
SqlParameter patientIdParam = new SqlParameter("@icn", System.Data.SqlDbType.VarChar, 50);
patientIdParam.Value = icn;
adapter.SelectCommand.Parameters.Add(patientIdParam);
adapter.SelectCommand.CommandTimeout = 600; // allow query to run for up to 10 minutes
return adapter;
}
internal Dictionary<string, string> toPatientIds(IDataReader rdr)
{
Dictionary<string, string> ids = new Dictionary<string, string>();
while (rdr.Read())
{
ids.Add(Convert.ToString(rdr.GetInt16(0)), rdr.GetString(1));
}
return ids;
}
#region Not implemented members
public Patient[] getPatientsByWard(string wardId)
{
throw new NotImplementedException();
}
public Patient[] getPatientsByClinic(string clinicId)
{
throw new NotImplementedException();
}
public Patient[] getPatientsByClinic(string clinicId, string fromDate, string toDate)
{
throw new NotImplementedException();
}
public Patient[] getPatientsBySpecialty(string specialtyId)
{
throw new NotImplementedException();
}
public Patient[] getPatientsByTeam(string teamId)
{
throw new NotImplementedException();
}
public Patient[] getPatientsByProvider(string providerId)
{
throw new NotImplementedException();
}
public Patient[] matchByNameCityState(string name, string city, string stateAbbr)
{
throw new NotImplementedException();
}
public Patient select(string pid)
{
_cxn.Pid = pid;
return new Patient() { LocalPid = pid };
}
public Patient select()
{
throw new NotImplementedException();
}
public Patient selectBySSN(string ssn)
{
throw new NotImplementedException();
}
public string getLocalPid(string mpiPID)
{
throw new NotImplementedException();
}
public bool isTestPatient()
{
throw new NotImplementedException();
}
public KeyValuePair<int, string> getConfidentiality()
{
throw new NotImplementedException();
}
public string issueConfidentialityBulletin()
{
throw new NotImplementedException();
}
public System.Collections.Specialized.StringDictionary getRemoteSiteIds(string pid)
{
throw new NotImplementedException();
}
public Site[] getRemoteSites(string pid)
{
throw new NotImplementedException();
}
public OEF_OIF[] getOefOif()
{
throw new NotImplementedException();
}
public void addHomeData(Patient patient)
{
throw new NotImplementedException();
}
public PatientAssociate[] getPatientAssociates(string pid)
{
throw new NotImplementedException();
}
public System.Collections.Specialized.StringDictionary getPatientTypes()
{
throw new NotImplementedException();
}
public string patientInquiry(string pid)
{
throw new NotImplementedException();
}
public RatedDisability[] getRatedDisabilities()
{
throw new NotImplementedException();
}
public RatedDisability[] getRatedDisabilities(string pid)
{
throw new NotImplementedException();
}
public KeyValuePair<string, string> getPcpForPatient(string dfn)
{
throw new NotImplementedException();
}
#endregion
public TextReport getMOSReport(Patient patient)
{
throw new NotImplementedException();
}
public DemographicSet getDemographics()
{
throw new NotImplementedException();
}
public bool isIdentityProofed(Patient patient)
{
throw new NotImplementedException();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using LibGit2Sharp.Core;
using LibGit2Sharp.Tests.TestHelpers;
using Xunit;
using Xunit.Extensions;
namespace LibGit2Sharp.Tests
{
public class CommitFixture : BaseFixture
{
private const string sha = "8496071c1b46c854b31185ea97743be6a8774479";
private readonly List<string> expectedShas = new List<string> { "a4a7d", "c4780", "9fd73", "4a202", "5b5b0", "84960" };
[Fact]
public void CanCountCommits()
{
string path = SandboxBareTestRepo();
using (var repo = new Repository(path))
{
Assert.Equal(7, repo.Commits.Count());
}
}
[Fact]
public void CanCorrectlyCountCommitsWhenSwitchingToAnotherBranch()
{
string path = SandboxStandardTestRepo();
using (var repo = new Repository(path))
{
// Hard reset and then remove untracked files
repo.Reset(ResetMode.Hard);
repo.RemoveUntrackedFiles();
repo.Checkout("test");
Assert.Equal(2, repo.Commits.Count());
Assert.Equal("e90810b8df3e80c413d903f631643c716887138d", repo.Commits.First().Id.Sha);
repo.Checkout("master");
Assert.Equal(9, repo.Commits.Count());
Assert.Equal("32eab9cb1f450b5fe7ab663462b77d7f4b703344", repo.Commits.First().Id.Sha);
}
}
[Fact]
public void CanEnumerateCommits()
{
int count = 0;
string path = SandboxBareTestRepo();
using (var repo = new Repository(path))
{
foreach (Commit commit in repo.Commits)
{
Assert.NotNull(commit);
count++;
}
}
Assert.Equal(7, count);
}
[Fact]
public void CanEnumerateCommitsInDetachedHeadState()
{
string path = SandboxBareTestRepo();
using (var repo = new Repository(path))
{
ObjectId parentOfHead = repo.Head.Tip.Parents.First().Id;
repo.Refs.Add("HEAD", parentOfHead.Sha, true);
Assert.Equal(true, repo.Info.IsHeadDetached);
Assert.Equal(6, repo.Commits.Count());
}
}
[Fact]
public void DefaultOrderingWhenEnumeratingCommitsIsTimeBased()
{
string path = SandboxBareTestRepo();
using (var repo = new Repository(path))
{
Assert.Equal(CommitSortStrategies.Time, repo.Commits.SortedBy);
}
}
[Fact]
public void CanEnumerateCommitsFromSha()
{
int count = 0;
string path = SandboxBareTestRepo();
using (var repo = new Repository(path))
{
foreach (Commit commit in repo.Commits.QueryBy(new CommitFilter { Since = "a4a7dce85cf63874e984719f4fdd239f5145052f" }))
{
Assert.NotNull(commit);
count++;
}
}
Assert.Equal(6, count);
}
[Fact]
public void QueryingTheCommitHistoryWithUnknownShaOrInvalidEntryPointThrows()
{
string path = SandboxBareTestRepo();
using (var repo = new Repository(path))
{
Assert.Throws<NotFoundException>(() => repo.Commits.QueryBy(new CommitFilter { Since = Constants.UnknownSha }).Count());
Assert.Throws<NotFoundException>(() => repo.Commits.QueryBy(new CommitFilter { Since = "refs/heads/deadbeef" }).Count());
Assert.Throws<ArgumentNullException>(() => repo.Commits.QueryBy(new CommitFilter { Since = null }).Count());
}
}
[Fact]
public void QueryingTheCommitHistoryFromACorruptedReferenceThrows()
{
string path = SandboxBareTestRepo();
using (var repo = new Repository(path))
{
CreateCorruptedDeadBeefHead(repo.Info.Path);
Assert.Throws<NotFoundException>(() => repo.Commits.QueryBy(new CommitFilter { Since = repo.Branches["deadbeef"] }).Count());
Assert.Throws<NotFoundException>(() => repo.Commits.QueryBy(new CommitFilter { Since = repo.Refs["refs/heads/deadbeef"] }).Count());
}
}
[Fact]
public void QueryingTheCommitHistoryWithBadParamsThrows()
{
string path = SandboxBareTestRepo();
using (var repo = new Repository(path))
{
Assert.Throws<ArgumentException>(() => repo.Commits.QueryBy(new CommitFilter { Since = string.Empty }));
Assert.Throws<ArgumentNullException>(() => repo.Commits.QueryBy(new CommitFilter { Since = null }));
Assert.Throws<ArgumentNullException>(() => repo.Commits.QueryBy(default(CommitFilter)));
}
}
[Fact]
public void CanEnumerateCommitsWithReverseTimeSorting()
{
var reversedShas = new List<string>(expectedShas);
reversedShas.Reverse();
int count = 0;
string path = SandboxBareTestRepo();
using (var repo = new Repository(path))
{
foreach (Commit commit in repo.Commits.QueryBy(new CommitFilter
{
Since = "a4a7dce85cf63874e984719f4fdd239f5145052f",
SortBy = CommitSortStrategies.Time | CommitSortStrategies.Reverse
}))
{
Assert.NotNull(commit);
Assert.True(commit.Sha.StartsWith(reversedShas[count]));
count++;
}
}
Assert.Equal(6, count);
}
[Fact]
public void CanEnumerateCommitsWithReverseTopoSorting()
{
string path = SandboxBareTestRepo();
using (var repo = new Repository(path))
{
List<Commit> commits = repo.Commits.QueryBy(new CommitFilter
{
Since = "a4a7dce85cf63874e984719f4fdd239f5145052f",
SortBy = CommitSortStrategies.Time | CommitSortStrategies.Reverse
}).ToList();
foreach (Commit commit in commits)
{
Assert.NotNull(commit);
foreach (Commit p in commit.Parents)
{
Commit parent = commits.Single(x => x.Id == p.Id);
Assert.True(commits.IndexOf(commit) > commits.IndexOf(parent));
}
}
}
}
[Fact]
public void CanSimplifyByFirstParent()
{
AssertEnumerationOfCommits(
repo => new CommitFilter { Since = repo.Head, FirstParentOnly = true },
new[]
{
"4c062a6", "be3563a", "9fd738e",
"4a202b3", "5b5b025", "8496071",
});
}
[Fact]
public void CanGetParentsCount()
{
string path = SandboxBareTestRepo();
using (var repo = new Repository(path))
{
Assert.Equal(1, repo.Commits.First().Parents.Count());
}
}
[Fact]
public void CanEnumerateCommitsWithTimeSorting()
{
int count = 0;
string path = SandboxBareTestRepo();
using (var repo = new Repository(path))
{
foreach (Commit commit in repo.Commits.QueryBy(new CommitFilter
{
Since = "a4a7dce85cf63874e984719f4fdd239f5145052f",
SortBy = CommitSortStrategies.Time
}))
{
Assert.NotNull(commit);
Assert.True(commit.Sha.StartsWith(expectedShas[count]));
count++;
}
}
Assert.Equal(6, count);
}
[Fact]
public void CanEnumerateCommitsWithTopoSorting()
{
string path = SandboxBareTestRepo();
using (var repo = new Repository(path))
{
List<Commit> commits = repo.Commits.QueryBy(new CommitFilter
{
Since = "a4a7dce85cf63874e984719f4fdd239f5145052f",
SortBy = CommitSortStrategies.Topological
}).ToList();
foreach (Commit commit in commits)
{
Assert.NotNull(commit);
foreach (Commit p in commit.Parents)
{
Commit parent = commits.Single(x => x.Id == p.Id);
Assert.True(commits.IndexOf(commit) < commits.IndexOf(parent));
}
}
}
}
[Fact]
public void CanEnumerateFromHead()
{
AssertEnumerationOfCommits(
repo => new CommitFilter { Since = repo.Head },
new[]
{
"4c062a6", "be3563a", "c47800c", "9fd738e",
"4a202b3", "5b5b025", "8496071",
});
}
[Fact]
public void CanEnumerateFromDetachedHead()
{
string path = SandboxStandardTestRepo();
using (var repoClone = new Repository(path))
{
// Hard reset and then remove untracked files
repoClone.Reset(ResetMode.Hard);
repoClone.RemoveUntrackedFiles();
string headSha = repoClone.Head.Tip.Sha;
repoClone.Checkout(headSha);
AssertEnumerationOfCommitsInRepo(repoClone,
repo => new CommitFilter { Since = repo.Head },
new[]
{
"32eab9c", "592d3c8", "4c062a6",
"be3563a", "c47800c", "9fd738e",
"4a202b3", "5b5b025", "8496071",
});
}
}
[Fact]
public void CanEnumerateUsingTwoHeadsAsBoundaries()
{
AssertEnumerationOfCommits(
repo => new CommitFilter { Since = "HEAD", Until = "refs/heads/br2" },
new[] { "4c062a6", "be3563a" }
);
}
[Fact]
public void CanEnumerateUsingImplicitHeadAsSinceBoundary()
{
AssertEnumerationOfCommits(
repo => new CommitFilter { Until = "refs/heads/br2" },
new[] { "4c062a6", "be3563a" }
);
}
[Fact]
public void CanEnumerateUsingTwoAbbreviatedShasAsBoundaries()
{
AssertEnumerationOfCommits(
repo => new CommitFilter { Since = "a4a7dce", Until = "4a202b3" },
new[] { "a4a7dce", "c47800c", "9fd738e" }
);
}
[Fact]
public void CanEnumerateCommitsFromTwoHeads()
{
AssertEnumerationOfCommits(
repo => new CommitFilter { Since = new[] { "refs/heads/br2", "refs/heads/master" } },
new[]
{
"4c062a6", "a4a7dce", "be3563a", "c47800c",
"9fd738e", "4a202b3", "5b5b025", "8496071",
});
}
[Fact]
public void CanEnumerateCommitsFromMixedStartingPoints()
{
AssertEnumerationOfCommits(
repo => new CommitFilter { Since = new object[] { repo.Branches["br2"],
"refs/heads/master",
new ObjectId("e90810b8df3e80c413d903f631643c716887138d") } },
new[]
{
"4c062a6", "e90810b", "6dcf9bf", "a4a7dce",
"be3563a", "c47800c", "9fd738e", "4a202b3",
"5b5b025", "8496071",
});
}
[Fact]
public void CanEnumerateCommitsUsingGlob()
{
AssertEnumerationOfCommits(
repo => new CommitFilter { Since = repo.Refs.FromGlob("refs/heads/*") },
new[]
{
"4c062a6", "e90810b", "6dcf9bf", "a4a7dce", "be3563a", "c47800c", "9fd738e", "4a202b3", "41bc8c6", "5001298", "5b5b025", "8496071"
});
}
[Fact]
public void CanHideCommitsUsingGlob()
{
AssertEnumerationOfCommits(
repo => new CommitFilter { Since = "refs/heads/packed-test", Until = repo.Refs.FromGlob("*/packed") },
new[]
{
"4a202b3", "5b5b025", "8496071"
});
}
[Fact]
public void CanEnumerateCommitsFromAnAnnotatedTag()
{
CanEnumerateCommitsFromATag(t => t);
}
[Fact]
public void CanEnumerateCommitsFromATagAnnotation()
{
CanEnumerateCommitsFromATag(t => t.Annotation);
}
private void CanEnumerateCommitsFromATag(Func<Tag, object> transformer)
{
AssertEnumerationOfCommits(
repo => new CommitFilter { Since = transformer(repo.Tags["test"]) },
new[] { "e90810b", "6dcf9bf", }
);
}
[Fact]
public void CanEnumerateAllCommits()
{
AssertEnumerationOfCommits(
repo => new CommitFilter
{
Since = repo.Refs.OrderBy(r => r.CanonicalName, StringComparer.Ordinal),
},
new[]
{
"44d5d18", "bb65291", "532740a", "503a16f", "3dfd6fd",
"4409de1", "902c60b", "4c062a6", "e90810b", "6dcf9bf",
"a4a7dce", "be3563a", "c47800c", "9fd738e", "4a202b3",
"41bc8c6", "5001298", "5b5b025", "8496071",
});
}
[Fact]
public void CanEnumerateCommitsFromATagWhichPointsToABlob()
{
AssertEnumerationOfCommits(
repo => new CommitFilter { Since = repo.Tags["point_to_blob"] },
new string[] { });
}
[Fact]
public void CanEnumerateCommitsFromATagWhichPointsToATree()
{
string path = SandboxBareTestRepo();
using (var repo = new Repository(path))
{
string headTreeSha = repo.Head.Tip.Tree.Sha;
Tag tag = repo.ApplyTag("point_to_tree", headTreeSha);
AssertEnumerationOfCommitsInRepo(repo,
r => new CommitFilter { Since = tag },
new string[] { });
}
}
private void AssertEnumerationOfCommits(Func<IRepository, CommitFilter> filterBuilder, IEnumerable<string> abbrevIds)
{
string path = SandboxBareTestRepo();
using (var repo = new Repository(path))
{
AssertEnumerationOfCommitsInRepo(repo, filterBuilder, abbrevIds);
}
}
private static void AssertEnumerationOfCommitsInRepo(IRepository repo, Func<IRepository, CommitFilter> filterBuilder, IEnumerable<string> abbrevIds)
{
ICommitLog commits = repo.Commits.QueryBy(filterBuilder(repo));
IEnumerable<string> commitShas = commits.Select(c => c.Id.ToString(7)).ToArray();
Assert.Equal(abbrevIds, commitShas);
}
[Fact]
public void CanLookupCommitGeneric()
{
string path = SandboxBareTestRepo();
using (var repo = new Repository(path))
{
var commit = repo.Lookup<Commit>(sha);
Assert.Equal("testing\n", commit.Message);
Assert.Equal("testing", commit.MessageShort);
Assert.Equal(sha, commit.Sha);
}
}
[Fact]
public void CanReadCommitData()
{
string path = SandboxBareTestRepo();
using (var repo = new Repository(path))
{
GitObject obj = repo.Lookup(sha);
Assert.NotNull(obj);
Assert.Equal(typeof(Commit), obj.GetType());
var commit = (Commit)obj;
Assert.Equal("testing\n", commit.Message);
Assert.Equal("testing", commit.MessageShort);
Assert.Equal("UTF-8", commit.Encoding);
Assert.Equal(sha, commit.Sha);
Assert.NotNull(commit.Author);
Assert.Equal("Scott Chacon", commit.Author.Name);
Assert.Equal("schacon@gmail.com", commit.Author.Email);
Assert.Equal(1273360386, commit.Author.When.ToSecondsSinceEpoch());
Assert.NotNull(commit.Committer);
Assert.Equal("Scott Chacon", commit.Committer.Name);
Assert.Equal("schacon@gmail.com", commit.Committer.Email);
Assert.Equal(1273360386, commit.Committer.When.ToSecondsSinceEpoch());
Assert.Equal("181037049a54a1eb5fab404658a3a250b44335d7", commit.Tree.Sha);
Assert.Equal(0, commit.Parents.Count());
}
}
[Fact]
public void CanReadCommitWithMultipleParents()
{
string path = SandboxBareTestRepo();
using (var repo = new Repository(path))
{
var commit = repo.Lookup<Commit>("a4a7dce85cf63874e984719f4fdd239f5145052f");
Assert.Equal(2, commit.Parents.Count());
}
}
[Fact]
public void CanDirectlyAccessABlobOfTheCommit()
{
string path = SandboxBareTestRepo();
using (var repo = new Repository(path))
{
var commit = repo.Lookup<Commit>("4c062a6");
var blob = commit["1/branch_file.txt"].Target as Blob;
Assert.NotNull(blob);
Assert.Equal("hi\n", blob.GetContentText());
}
}
[Fact]
public void CanDirectlyAccessATreeOfTheCommit()
{
string path = SandboxBareTestRepo();
using (var repo = new Repository(path))
{
var commit = repo.Lookup<Commit>("4c062a6");
var tree1 = commit["1"].Target as Tree;
Assert.NotNull(tree1);
}
}
[Fact]
public void DirectlyAccessingAnUnknownTreeEntryOfTheCommitReturnsNull()
{
string path = SandboxBareTestRepo();
using (var repo = new Repository(path))
{
var commit = repo.Lookup<Commit>("4c062a6");
Assert.Null(commit["I-am-not-here"]);
}
}
[Theory]
[InlineData(null, "x@example.com")]
[InlineData("", "x@example.com")]
[InlineData("X", null)]
[InlineData("X", "")]
public void CommitWithInvalidSignatureConfigThrows(string name, string email)
{
string repoPath = InitNewRepository();
string configPath = CreateConfigurationWithDummyUser(name, email);
var options = new RepositoryOptions { GlobalConfigurationLocation = configPath };
using (var repo = new Repository(repoPath, options))
{
Assert.Equal(name, repo.Config.GetValueOrDefault<string>("user.name"));
Assert.Equal(email, repo.Config.GetValueOrDefault<string>("user.email"));
Assert.Throws<LibGit2SharpException>(
() => repo.Commit("Initial egotistic commit", new CommitOptions { AllowEmptyCommit = true }));
}
}
[Fact]
public void CanCommitWithSignatureFromConfig()
{
string repoPath = InitNewRepository();
string configPath = CreateConfigurationWithDummyUser(Constants.Signature);
var options = new RepositoryOptions { GlobalConfigurationLocation = configPath };
using (var repo = new Repository(repoPath, options))
{
string dir = repo.Info.Path;
Assert.True(Path.IsPathRooted(dir));
Assert.True(Directory.Exists(dir));
const string relativeFilepath = "new.txt";
string filePath = Touch(repo.Info.WorkingDirectory, relativeFilepath, "null");
repo.Stage(relativeFilepath);
File.AppendAllText(filePath, "token\n");
repo.Stage(relativeFilepath);
Assert.Null(repo.Head[relativeFilepath]);
Commit commit = repo.Commit("Initial egotistic commit");
AssertBlobContent(repo.Head[relativeFilepath], "nulltoken\n");
AssertBlobContent(commit[relativeFilepath], "nulltoken\n");
AssertCommitSignaturesAre(commit, Constants.Signature);
}
}
[Fact]
public void CommitParentsAreMergeHeads()
{
string path = SandboxStandardTestRepo();
using (var repo = new Repository(path))
{
repo.Reset(ResetMode.Hard, "c47800");
CreateAndStageANewFile(repo);
Touch(repo.Info.Path, "MERGE_HEAD", "9fd738e8f7967c078dceed8190330fc8648ee56a\n");
Assert.Equal(CurrentOperation.Merge, repo.Info.CurrentOperation);
Commit newMergedCommit = repo.Commit("Merge commit", Constants.Signature, Constants.Signature);
Assert.Equal(CurrentOperation.None, repo.Info.CurrentOperation);
Assert.Equal(2, newMergedCommit.Parents.Count());
Assert.Equal(newMergedCommit.Parents.First().Sha, "c47800c7266a2be04c571c04d5a6614691ea99bd");
Assert.Equal(newMergedCommit.Parents.Skip(1).First().Sha, "9fd738e8f7967c078dceed8190330fc8648ee56a");
// Assert reflog entry is created
var reflogEntry = repo.Refs.Log(repo.Refs.Head).First();
Assert.Equal(repo.Head.Tip.Id, reflogEntry.To);
Assert.NotNull(reflogEntry.Committer.Email);
Assert.NotNull(reflogEntry.Committer.Name);
Assert.Equal(string.Format("commit (merge): {0}", newMergedCommit.MessageShort), reflogEntry.Message);
}
}
[Fact]
public void CommitCleansUpMergeMetadata()
{
string repoPath = InitNewRepository();
using (var repo = new Repository(repoPath))
{
string dir = repo.Info.Path;
Assert.True(Path.IsPathRooted(dir));
Assert.True(Directory.Exists(dir));
const string relativeFilepath = "new.txt";
Touch(repo.Info.WorkingDirectory, relativeFilepath, "this is a new file");
repo.Stage(relativeFilepath);
string mergeHeadPath = Touch(repo.Info.Path, "MERGE_HEAD", "abcdefabcdefabcdefabcdefabcdefabcdefabcd");
string mergeMsgPath = Touch(repo.Info.Path, "MERGE_MSG", "This is a dummy merge.\n");
string mergeModePath = Touch(repo.Info.Path, "MERGE_MODE", "no-ff");
string origHeadPath = Touch(repo.Info.Path, "ORIG_HEAD", "beefbeefbeefbeefbeefbeefbeefbeefbeefbeef");
Assert.True(File.Exists(mergeHeadPath));
Assert.True(File.Exists(mergeMsgPath));
Assert.True(File.Exists(mergeModePath));
Assert.True(File.Exists(origHeadPath));
var author = Constants.Signature;
repo.Commit("Initial egotistic commit", author, author);
Assert.False(File.Exists(mergeHeadPath));
Assert.False(File.Exists(mergeMsgPath));
Assert.False(File.Exists(mergeModePath));
Assert.True(File.Exists(origHeadPath));
}
}
[Fact]
public void CanCommitALittleBit()
{
string repoPath = InitNewRepository();
var identity = Constants.Identity;
using (var repo = new Repository(repoPath, new RepositoryOptions { Identity = identity }))
{
string dir = repo.Info.Path;
Assert.True(Path.IsPathRooted(dir));
Assert.True(Directory.Exists(dir));
const string relativeFilepath = "new.txt";
string filePath = Touch(repo.Info.WorkingDirectory, relativeFilepath, "null");
repo.Stage(relativeFilepath);
File.AppendAllText(filePath, "token\n");
repo.Stage(relativeFilepath);
Assert.Null(repo.Head[relativeFilepath]);
var author = Constants.Signature;
const string shortMessage = "Initial egotistic commit";
const string commitMessage = shortMessage + "\n\nOnly the coolest commits from us";
var before = DateTimeOffset.Now.TruncateMilliseconds();
Commit commit = repo.Commit(commitMessage, author, author);
AssertBlobContent(repo.Head[relativeFilepath], "nulltoken\n");
AssertBlobContent(commit[relativeFilepath], "nulltoken\n");
Assert.Equal(0, commit.Parents.Count());
Assert.False(repo.Info.IsHeadUnborn);
// Assert a reflog entry is created on HEAD
Assert.Equal(1, repo.Refs.Log("HEAD").Count());
var reflogEntry = repo.Refs.Log("HEAD").First();
Assert.Equal(identity.Name, reflogEntry.Committer.Name);
Assert.Equal(identity.Email, reflogEntry.Committer.Email);
var now = DateTimeOffset.Now;
Assert.InRange(reflogEntry.Committer.When, before, now);
Assert.Equal(commit.Id, reflogEntry.To);
Assert.Equal(ObjectId.Zero, reflogEntry.From);
Assert.Equal(string.Format("commit (initial): {0}", shortMessage), reflogEntry.Message);
// Assert a reflog entry is created on HEAD target
var targetCanonicalName = repo.Refs.Head.TargetIdentifier;
Assert.Equal(1, repo.Refs.Log(targetCanonicalName).Count());
Assert.Equal(commit.Id, repo.Refs.Log(targetCanonicalName).First().To);
File.WriteAllText(filePath, "nulltoken commits!\n");
repo.Stage(relativeFilepath);
var author2 = new Signature(author.Name, author.Email, author.When.AddSeconds(5));
Commit commit2 = repo.Commit("Are you trying to fork me?", author2, author2);
AssertBlobContent(repo.Head[relativeFilepath], "nulltoken commits!\n");
AssertBlobContent(commit2[relativeFilepath], "nulltoken commits!\n");
Assert.Equal(1, commit2.Parents.Count());
Assert.Equal(commit.Id, commit2.Parents.First().Id);
// Assert the reflog is shifted
Assert.Equal(2, repo.Refs.Log("HEAD").Count());
Assert.Equal(reflogEntry.To, repo.Refs.Log("HEAD").First().From);
Branch firstCommitBranch = repo.CreateBranch("davidfowl-rules", commit);
repo.Checkout(firstCommitBranch);
File.WriteAllText(filePath, "davidfowl commits!\n");
var author3 = new Signature("David Fowler", "david.fowler@microsoft.com", author.When.AddSeconds(2));
repo.Stage(relativeFilepath);
Commit commit3 = repo.Commit("I'm going to branch you backwards in time!", author3, author3);
AssertBlobContent(repo.Head[relativeFilepath], "davidfowl commits!\n");
AssertBlobContent(commit3[relativeFilepath], "davidfowl commits!\n");
Assert.Equal(1, commit3.Parents.Count());
Assert.Equal(commit.Id, commit3.Parents.First().Id);
AssertBlobContent(firstCommitBranch[relativeFilepath], "nulltoken\n");
}
}
private static void AssertBlobContent(TreeEntry entry, string expectedContent)
{
Assert.Equal(TreeEntryTargetType.Blob, entry.TargetType);
Assert.Equal(expectedContent, ((Blob)(entry.Target)).GetContentText());
}
private static void AddCommitToRepo(string path)
{
using (var repo = new Repository(path))
{
const string relativeFilepath = "test.txt";
Touch(repo.Info.WorkingDirectory, relativeFilepath, "test\n");
repo.Stage(relativeFilepath);
var author = new Signature("nulltoken", "emeric.fermas@gmail.com", DateTimeOffset.Parse("Wed, Dec 14 2011 08:29:03 +0100"));
repo.Commit("Initial commit", author, author);
}
}
[Fact]
public void CanGeneratePredictableObjectShas()
{
string repoPath = InitNewRepository();
AddCommitToRepo(repoPath);
using (var repo = new Repository(repoPath))
{
Commit commit = repo.Commits.Single();
Assert.Equal("1fe3126578fc4eca68c193e4a3a0a14a0704624d", commit.Sha);
Tree tree = commit.Tree;
Assert.Equal("2b297e643c551e76cfa1f93810c50811382f9117", tree.Sha);
GitObject blob = tree.Single().Target;
Assert.IsAssignableFrom<Blob>(blob);
Assert.Equal("9daeafb9864cf43055ae93beb0afd6c7d144bfa4", blob.Sha);
}
}
[Fact]
public void CanAmendARootCommit()
{
string repoPath = InitNewRepository();
AddCommitToRepo(repoPath);
using (var repo = new Repository(repoPath))
{
Assert.Equal(1, repo.Head.Commits.Count());
Commit originalCommit = repo.Head.Tip;
Assert.Equal(0, originalCommit.Parents.Count());
CreateAndStageANewFile(repo);
Commit amendedCommit = repo.Commit("I'm rewriting the history!", Constants.Signature, Constants.Signature,
new CommitOptions { AmendPreviousCommit = true });
Assert.Equal(1, repo.Head.Commits.Count());
AssertCommitHasBeenAmended(repo, amendedCommit, originalCommit);
}
}
[Fact]
public void CanAmendACommitWithMoreThanOneParent()
{
string path = SandboxStandardTestRepo();
using (var repo = new Repository(path, new RepositoryOptions { Identity = Constants.Identity }))
{
var mergedCommit = repo.Lookup<Commit>("be3563a");
Assert.NotNull(mergedCommit);
Assert.Equal(2, mergedCommit.Parents.Count());
repo.Reset(ResetMode.Soft, mergedCommit.Sha);
CreateAndStageANewFile(repo);
const string commitMessage = "I'm rewriting the history!";
var before = DateTimeOffset.Now.TruncateMilliseconds();
Commit amendedCommit = repo.Commit(commitMessage, Constants.Signature, Constants.Signature,
new CommitOptions { AmendPreviousCommit = true });
AssertCommitHasBeenAmended(repo, amendedCommit, mergedCommit);
AssertRefLogEntry(repo, "HEAD",
string.Format("commit (amend): {0}", commitMessage),
mergedCommit.Id,
amendedCommit.Id,
Constants.Identity, before);
}
}
private static void CreateAndStageANewFile(IRepository repo)
{
string relativeFilepath = string.Format("new-file-{0}.txt", Path.GetRandomFileName());
Touch(repo.Info.WorkingDirectory, relativeFilepath, "brand new content\n");
repo.Stage(relativeFilepath);
}
private static void AssertCommitHasBeenAmended(IRepository repo, Commit amendedCommit, Commit originalCommit)
{
Commit headCommit = repo.Head.Tip;
Assert.Equal(amendedCommit, headCommit);
Assert.NotEqual(originalCommit.Sha, amendedCommit.Sha);
Assert.Equal(originalCommit.Parents, amendedCommit.Parents);
}
[Fact]
public void CanNotAmendAnEmptyRepository()
{
string repoPath = InitNewRepository();
using (var repo = new Repository(repoPath))
{
Assert.Throws<UnbornBranchException>(() =>
repo.Commit("I can not amend anything !:(", Constants.Signature, Constants.Signature, new CommitOptions { AmendPreviousCommit = true }));
}
}
[Fact]
public void CanRetrieveChildrenOfASpecificCommit()
{
string path = SandboxStandardTestRepo();
using (var repo = new Repository(path))
{
const string parentSha = "5b5b025afb0b4c913b4c338a42934a3863bf3644";
var filter = new CommitFilter
{
/* Revwalk from all the refs (git log --all) ... */
Since = repo.Refs,
/* ... and stop when the parent is reached */
Until = parentSha
};
var commits = repo.Commits.QueryBy(filter);
var children = from c in commits
from p in c.Parents
let pId = p.Id
where pId.Sha == parentSha
select c;
var expectedChildren = new[] { "c47800c7266a2be04c571c04d5a6614691ea99bd",
"4a202b346bb0fb0db7eff3cffeb3c70babbd2045" };
Assert.Equal(expectedChildren, children.Select(c => c.Id.Sha));
}
}
[Fact]
public void CanCorrectlyDistinguishAuthorFromCommitter()
{
string path = SandboxStandardTestRepo();
using (var repo = new Repository(path))
{
var author = new Signature("Wilbert van Dolleweerd", "getit@xs4all.nl",
Epoch.ToDateTimeOffset(1244187936, 120));
var committer = new Signature("Henk Westhuis", "Henk_Westhuis@hotmail.com",
Epoch.ToDateTimeOffset(1244286496, 120));
Commit c = repo.Commit("I can haz an author and a committer!", author, committer);
Assert.Equal(author, c.Author);
Assert.Equal(committer, c.Committer);
}
}
[Fact]
public void CanCommitOnOrphanedBranch()
{
string newBranchName = "refs/heads/newBranch";
string repoPath = InitNewRepository();
using (var repo = new Repository(repoPath))
{
// Set Head to point to branch other than master
repo.Refs.UpdateTarget("HEAD", newBranchName);
Assert.Equal(newBranchName, repo.Head.CanonicalName);
const string relativeFilepath = "test.txt";
Touch(repo.Info.WorkingDirectory, relativeFilepath, "test\n");
repo.Stage(relativeFilepath);
repo.Commit("Initial commit", Constants.Signature, Constants.Signature);
Assert.Equal(1, repo.Head.Commits.Count());
}
}
[Fact]
public void CanNotCommitAnEmptyCommit()
{
string path = SandboxStandardTestRepo();
using (var repo = new Repository(path))
{
repo.Reset(ResetMode.Hard);
repo.RemoveUntrackedFiles();
Assert.Throws<EmptyCommitException>(() => repo.Commit("Empty commit!", Constants.Signature, Constants.Signature));
}
}
[Fact]
public void CanCommitAnEmptyCommitWhenForced()
{
string path = SandboxStandardTestRepo();
using (var repo = new Repository(path))
{
repo.Reset(ResetMode.Hard);
repo.RemoveUntrackedFiles();
repo.Commit("Empty commit!", Constants.Signature, Constants.Signature,
new CommitOptions { AllowEmptyCommit = true });
}
}
[Fact]
public void CanNotAmendAnEmptyCommit()
{
string path = SandboxStandardTestRepo();
using (var repo = new Repository(path))
{
repo.Reset(ResetMode.Hard);
repo.RemoveUntrackedFiles();
repo.Commit("Empty commit!", Constants.Signature, Constants.Signature,
new CommitOptions { AllowEmptyCommit = true });
Assert.Throws<EmptyCommitException>(() => repo.Commit("Empty commit!", Constants.Signature, Constants.Signature,
new CommitOptions { AmendPreviousCommit = true }));
}
}
[Fact]
public void CanAmendAnEmptyCommitWhenForced()
{
string path = SandboxStandardTestRepo();
using (var repo = new Repository(path))
{
repo.Reset(ResetMode.Hard);
repo.RemoveUntrackedFiles();
Commit emptyCommit = repo.Commit("Empty commit!", Constants.Signature, Constants.Signature,
new CommitOptions { AllowEmptyCommit = true });
Commit amendedCommit = repo.Commit("I'm rewriting the history!", Constants.Signature, Constants.Signature,
new CommitOptions { AmendPreviousCommit = true, AllowEmptyCommit = true });
AssertCommitHasBeenAmended(repo, amendedCommit, emptyCommit);
}
}
[Fact]
public void CanCommitAnEmptyCommitWhenMerging()
{
string path = SandboxStandardTestRepo();
using (var repo = new Repository(path))
{
repo.Reset(ResetMode.Hard);
repo.RemoveUntrackedFiles();
Touch(repo.Info.Path, "MERGE_HEAD", "f705abffe7015f2beacf2abe7a36583ebee3487e\n");
Assert.Equal(CurrentOperation.Merge, repo.Info.CurrentOperation);
Commit newMergedCommit = repo.Commit("Merge commit", Constants.Signature, Constants.Signature);
Assert.Equal(2, newMergedCommit.Parents.Count());
Assert.Equal(newMergedCommit.Parents.First().Sha, "32eab9cb1f450b5fe7ab663462b77d7f4b703344");
Assert.Equal(newMergedCommit.Parents.Skip(1).First().Sha, "f705abffe7015f2beacf2abe7a36583ebee3487e");
}
}
[Fact]
public void CanAmendAnEmptyMergeCommit()
{
string path = SandboxStandardTestRepo();
using (var repo = new Repository(path))
{
repo.Reset(ResetMode.Hard);
repo.RemoveUntrackedFiles();
Touch(repo.Info.Path, "MERGE_HEAD", "f705abffe7015f2beacf2abe7a36583ebee3487e\n");
Commit newMergedCommit = repo.Commit("Merge commit", Constants.Signature, Constants.Signature);
Commit amendedCommit = repo.Commit("I'm rewriting the history!", Constants.Signature, Constants.Signature,
new CommitOptions { AmendPreviousCommit = true });
AssertCommitHasBeenAmended(repo, amendedCommit, newMergedCommit);
}
}
[Fact]
public void CanNotAmendACommitInAWayThatWouldLeadTheNewCommitToBecomeEmpty()
{
string repoPath = InitNewRepository();
using (var repo = new Repository(repoPath))
{
Touch(repo.Info.WorkingDirectory, "test.txt", "test\n");
repo.Stage("test.txt");
repo.Commit("Initial commit", Constants.Signature, Constants.Signature);
Touch(repo.Info.WorkingDirectory, "new.txt", "content\n");
repo.Stage("new.txt");
repo.Commit("One commit", Constants.Signature, Constants.Signature);
repo.Remove("new.txt");
Assert.Throws<EmptyCommitException>(() => repo.Commit("Oops", Constants.Signature, Constants.Signature,
new CommitOptions { AmendPreviousCommit = true }));
}
}
}
}
| |
// Copyright (c) MOSA Project. Licensed under the New BSD License.
using Mosa.Compiler.Framework;
using Mosa.Compiler.Framework.Stages;
using Mosa.Compiler.Linker;
using Mosa.Compiler.MosaTypeSystem;
using System.IO;
using System.Text;
namespace Mosa.Platform.x86.Stages
{
/// <summary>
/// Writes a multiboot v0.6.95 header into the generated binary.
/// </summary>
/// <remarks>
/// This compiler stage writes a multiboot header into the
/// the data section of the binary file and also creates a multiboot
/// compliant entry point into the binary.<para/>
/// The header and entry point written by this stage is compliant with
/// the specification at
/// http://www.gnu.org/software/grub/manual/multiboot/multiboot.html.
/// </remarks>
public sealed class Multiboot0695Stage : BaseCompilerStage
{
#region Constants
/// <summary>
/// Magic value in the multiboot header.
/// </summary>
private const uint HEADER_MB_MAGIC = 0x1BADB002U;
/// <summary>
/// Multiboot flag, which indicates that additional modules must be
/// loaded on page boundaries.
/// </summary>
private const uint HEADER_MB_FLAG_MODULES_PAGE_ALIGNED = 0x00000001U;
/// <summary>
/// Multiboot flag, which indicates if memory information must be
/// provided in the boot information structure.
/// </summary>
private const uint HEADER_MB_FLAG_MEMORY_INFO_REQUIRED = 0x00000002U;
/// <summary>
/// Multiboot flag, which indicates that the supported video mode
/// table must be provided in the boot information structure.
/// </summary>
private const uint HEADER_MB_FLAG_VIDEO_MODES_REQUIRED = 0x00000004U;
/// <summary>
/// Multiboot flag, which indicates a non-elf binary to boot and that
/// settings for the executable file should be read From the boot header
/// instead of the executable header.
/// </summary>
private const uint HEADER_MB_FLAG_NON_ELF_BINARY = 0x00010000U;
/// <summary>
/// This address is the top of the initial kernel stack.
/// </summary>
private const uint STACK_ADDRESS = 0x003FFFFC;
#endregion Constants
#region Data members
/// <summary>
/// The multiboot method
/// </summary>
private MosaMethod multibootMethod;
/// <summary>
/// The multiboot header
/// </summary>
private LinkerSymbol multibootHeader;
#endregion Data members
public bool HasVideo { get; set; }
public int Width { get; set; }
public int Height { get; set; }
public int Depth { get; set; }
protected override void Setup()
{
HasVideo = CompilerOptions.GetCustomOptionAsBoolean("multiboot.video", false);
Width = CompilerOptions.GetCustomOptionAsInteger("multiboot.width", 0);
Height = CompilerOptions.GetCustomOptionAsInteger("multiboot.height", 0);
Depth = CompilerOptions.GetCustomOptionAsInteger("multiboot.depth", 0);
}
protected override void RunPreCompile()
{
multibootHeader = Linker.CreateSymbol(MultibootHeaderSymbolName, SectionKind.Text, 1, 0x30);
multibootMethod = Compiler.CreateLinkerMethod("MultibootInit");
Linker.CreateSymbol(MultibootEAX, SectionKind.BSS, Architecture.NativeAlignment, Architecture.NativePointerSize);
Linker.CreateSymbol(MultibootEBX, SectionKind.BSS, Architecture.NativeAlignment, Architecture.NativePointerSize);
var startUpType = TypeSystem.GetTypeByName("Mosa.Runtime", "StartUp");
var startUpMethod = startUpType.FindMethodByName("Stage1");
Compiler.PlugSystem.CreatePlug(multibootMethod, startUpMethod);
}
protected override void RunPostCompile()
{
WriteMultibootHeader();
var typeInitializerSchedulerStage = Compiler.CompilePipeline.FindFirst<TypeInitializerSchedulerStage>();
var eax = Operand.CreateCPURegister(TypeSystem.BuiltIn.I4, GeneralPurposeRegister.EAX);
var ebx = Operand.CreateCPURegister(TypeSystem.BuiltIn.I4, GeneralPurposeRegister.EBX);
var ebp = Operand.CreateCPURegister(TypeSystem.BuiltIn.I4, GeneralPurposeRegister.EBP);
var esp = Operand.CreateCPURegister(TypeSystem.BuiltIn.I4, GeneralPurposeRegister.ESP);
var multibootEAX = Operand.CreateUnmanagedSymbolPointer(TypeSystem, Multiboot0695Stage.MultibootEAX);
var multibootEBX = Operand.CreateUnmanagedSymbolPointer(TypeSystem, Multiboot0695Stage.MultibootEBX);
var zero = Operand.CreateConstant(TypeSystem.BuiltIn.I4, 0);
var stackTop = Operand.CreateConstant(TypeSystem.BuiltIn.I4, STACK_ADDRESS);
var basicBlocks = new BasicBlocks();
var block = basicBlocks.CreateBlock();
basicBlocks.AddHeadBlock(block);
var ctx = new Context(block);
// Setup the stack and place the sentinel on the stack to indicate the start of the stack
ctx.AppendInstruction(X86.MovStore, InstructionSize.Size32, null, esp, zero, stackTop);
ctx.AppendInstruction(X86.MovStore, InstructionSize.Size32, null, ebp, zero, zero);
// Place the multiboot address into a static field
ctx.AppendInstruction(X86.MovStore, InstructionSize.Size32, null, multibootEAX, zero, eax);
ctx.AppendInstruction(X86.MovStore, InstructionSize.Size32, null, multibootEBX, zero, ebx);
// should never get here
ctx.AppendInstruction(X86.Ret);
Compiler.CompileMethod(multibootMethod, basicBlocks);
Linker.SetFirst(multibootHeader);
}
#region Internals
private const string MultibootHeaderSymbolName = @"<$>mosa-multiboot-header";
public const string MultibootEAX = @"<$>mosa-multiboot-eax";
public const string MultibootEBX = @"<$>mosa-multiboot-ebx";
/// <summary>
/// Writes the multiboot header.
/// </summary>
/// <param name="entryPoint">The virtualAddress of the multiboot compliant entry point.</param>
private void WriteMultibootHeader()
{
// HACK: According to the multiboot specification this header must be within the first 8K of the
// kernel binary. Since the text section is always first, this should take care of the problem.
LinkerSymbol entryPoint = Linker.EntryPoint;
//entryPoint = Linker.GetSymbol(MultibootHeaderSymbolName, SectionKind.Text);
var stream = multibootHeader.Stream;
var writer = new BinaryWriter(stream, Encoding.ASCII);
// flags - multiboot flags
uint flags = HEADER_MB_FLAG_MEMORY_INFO_REQUIRED | HEADER_MB_FLAG_MODULES_PAGE_ALIGNED;
if (HasVideo)
flags |= HEADER_MB_FLAG_VIDEO_MODES_REQUIRED;
uint load_addr = 0;
// magic
writer.Write(HEADER_MB_MAGIC);
// flags
writer.Write(flags);
// checksum
writer.Write(unchecked(0U - HEADER_MB_MAGIC - flags));
// header_addr - load address of the multiboot header
Linker.Link(LinkType.AbsoluteAddress, PatchType.I4, multibootHeader, (int)stream.Position, 0, multibootHeader, 0);
writer.Write(0);
// load_addr - address of the binary in memory
writer.Write(load_addr);
// load_end_addr - address past the last byte to load from the image
writer.Write(0);
// bss_end_addr - address of the last byte to be zeroed out
writer.Write(0);
// entry_addr - address of the entry point to invoke
Linker.Link(LinkType.AbsoluteAddress, PatchType.I4, multibootHeader, (int)stream.Position, 0, entryPoint, 0);
writer.Write(0);
// Write video settings if video has been specified, otherwise pad
if (HasVideo)
{
writer.Write(0); // Mode, 0 = linear
writer.Write(Width); // Width, 1280px
writer.Write(Height); // Height, 720px
writer.Write(Depth); // Depth, 24px
}
else
{
writer.Write(0);
writer.Write(0);
writer.Write(0);
writer.Write(0);
}
}
#endregion Internals
}
}
| |
#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: SampleTwime.SampleTwimePublic
File: MainWindow.xaml.cs
Created: 2015, 11, 11, 2:32 PM
Copyright 2010 by StockSharp, LLC
*******************************************************************************************/
#endregion S# License
namespace SampleTwime
{
using System;
using System.ComponentModel;
using System.Windows;
using Ecng.Common;
using Ecng.Xaml;
using StockSharp.Messages;
using StockSharp.BusinessEntities;
using StockSharp.Logging;
using StockSharp.Localization;
using StockSharp.Plaza;
using StockSharp.Twime;
public partial class MainWindow
{
private bool _isInitialized;
public TwimeTrader Trader = new TwimeTrader();
private readonly SecuritiesWindow _securitiesWindow = new SecuritiesWindow();
private readonly TradesWindow _tradesWindow = new TradesWindow();
private readonly MyTradesWindow _myTradesWindow = new MyTradesWindow();
private readonly OrdersWindow _ordersWindow = new OrdersWindow();
private readonly PortfoliosWindow _portfoliosWindow = new PortfoliosWindow();
private readonly LogManager _logManager = new LogManager();
public MainWindow()
{
InitializeComponent();
Title = Title.Put("TWIME");
_ordersWindow.MakeHideable();
_myTradesWindow.MakeHideable();
_tradesWindow.MakeHideable();
_securitiesWindow.MakeHideable();
_portfoliosWindow.MakeHideable();
var mdAdapter = new PlazaMessageAdapter(Trader.TransactionIdGenerator)
{
IsCGate = true,
};
mdAdapter.RemoveTransactionalSupport();
Trader.Adapter.InnerAdapters.Add(mdAdapter);
Instance = this;
Trader.LogLevel = LogLevels.Debug;
_logManager.Sources.Add(Trader);
_logManager.Listeners.Add(new FileLogListener { LogDirectory = "StockSharp_Twime" });
TransactionAddress.EndPoint = Trader.TransactionAddress;
RecoveryAddress.EndPoint = Trader.RecoveryAddress;
Login.Text = Trader.Login;
}
protected override void OnClosing(CancelEventArgs e)
{
_ordersWindow.DeleteHideable();
_myTradesWindow.DeleteHideable();
_tradesWindow.DeleteHideable();
_securitiesWindow.DeleteHideable();
_portfoliosWindow.DeleteHideable();
_securitiesWindow.Close();
_tradesWindow.Close();
_myTradesWindow.Close();
_ordersWindow.Close();
_portfoliosWindow.Close();
Trader.Dispose();
base.OnClosing(e);
}
public static MainWindow Instance { get; private set; }
private void ConnectClick(object sender, RoutedEventArgs e)
{
if (!_isInitialized)
{
_isInitialized = true;
Trader.Restored += () => this.GuiAsync(() =>
{
// update gui labes
ChangeConnectStatus(true);
MessageBox.Show(this, LocalizedStrings.Str2958);
});
// subscribe on connection successfully event
Trader.Connected += () =>
{
this.GuiAsync(() => ChangeConnectStatus(true));
};
Trader.Disconnected += () => this.GuiAsync(() => ChangeConnectStatus(false));
// subscribe on connection error event
Trader.ConnectionError += error => this.GuiAsync(() =>
{
// update gui labes
ChangeConnectStatus(false);
MessageBox.Show(this, error.ToString(), LocalizedStrings.Str2959);
});
// subscribe on error event
Trader.Error += error => this.GuiAsync(() => MessageBox.Show(this, error.ToString(), LocalizedStrings.Str2955));
// subscribe on error of market data subscription event
Trader.MarketDataSubscriptionFailed += (security, msg, error) =>
this.GuiAsync(() => MessageBox.Show(this, error.ToString(), LocalizedStrings.Str2956Params.Put(msg.DataType, security)));
Trader.NewSecurity += security => _securitiesWindow.SecurityPicker.Securities.Add(security);
Trader.NewMyTrade += trade => _myTradesWindow.TradeGrid.Trades.Add(trade);
Trader.NewTrade += trade => _tradesWindow.TradeGrid.Trades.Add(trade);
Trader.NewOrder += order => _ordersWindow.OrderGrid.Orders.Add(order);
Trader.NewPortfolio += portfolio =>
{
// subscribe on portfolio updates
//portfolios.ForEach(Trader.RegisterPortfolio);
_portfoliosWindow.PortfolioGrid.Portfolios.Add(portfolio);
};
Trader.NewPosition += position => _portfoliosWindow.PortfolioGrid.Positions.Add(position);
// subscribe on error of order registration event
Trader.OrderRegisterFailed += _ordersWindow.OrderGrid.AddRegistrationFail;
// subscribe on error of order cancelling event
Trader.OrderCancelFailed += OrderFailed;
// subscribe on error of stop-order registration event
Trader.StopOrderRegisterFailed += _ordersWindow.OrderGrid.AddRegistrationFail;
// subscribe on error of stop-order cancelling event
Trader.StopOrderCancelFailed += OrderFailed;
Trader.MassOrderCancelFailed += (transId, error) =>
this.GuiAsync(() => MessageBox.Show(this, error.ToString(), LocalizedStrings.Str716));
// set market data provider
_securitiesWindow.SecurityPicker.MarketDataProvider = Trader;
ShowSecurities.IsEnabled = ShowTrades.IsEnabled = ShowMyTrades.IsEnabled = ShowOrders.IsEnabled = ShowPortfolios.IsEnabled = true;
}
switch (Trader.ConnectionState)
{
case ConnectionStates.Failed:
case ConnectionStates.Disconnected:
Trader.TransactionAddress = TransactionAddress.EndPoint;
Trader.RecoveryAddress = RecoveryAddress.EndPoint;
Trader.Login = Login.Text;
Trader.PortfolioName = PortfolioName.Text;
((PlazaMessageAdapter)Trader.MarketDataAdapter).IsDemo = IsDemo.IsChecked == true;
Trader.Connect();
break;
case ConnectionStates.Connected:
Trader.Disconnect();
break;
}
}
private void OrderFailed(OrderFail fail)
{
this.GuiAsync(() =>
{
MessageBox.Show(this, fail.Error.ToString(), LocalizedStrings.Str153);
});
}
private void ChangeConnectStatus(bool isConnected)
{
ConnectBtn.Content = isConnected ? LocalizedStrings.Disconnect : LocalizedStrings.Connect;
}
private void ShowSecuritiesClick(object sender, RoutedEventArgs e)
{
ShowOrHide(_securitiesWindow);
}
private void ShowTradesClick(object sender, RoutedEventArgs e)
{
ShowOrHide(_tradesWindow);
}
private void ShowMyTradesClick(object sender, RoutedEventArgs e)
{
ShowOrHide(_myTradesWindow);
}
private void ShowOrdersClick(object sender, RoutedEventArgs e)
{
ShowOrHide(_ordersWindow);
}
private void ShowPortfoliosClick(object sender, RoutedEventArgs e)
{
ShowOrHide(_portfoliosWindow);
}
private static void ShowOrHide(Window window)
{
if (window == null)
throw new ArgumentNullException(nameof(window));
if (window.Visibility == Visibility.Visible)
window.Hide();
else
window.Show();
}
}
}
| |
using System;
using System.Linq;
using System.Numerics;
using System.Runtime.InteropServices;
using hw.DebugFormatter;
using hw.Helper;
using hw.UnitTest;
using JetBrains.Annotations;
using Reni.Runtime;
namespace Reni.Basics
{
[DumpToString]
public sealed class BitsConst : DumpableObject
{
[UnitTest]
public sealed class Test
{
[UnitTest]
public void All()
{
"Position of method tested".FlaggedLine(FilePositionTag.Test);
(Convert(0).ToInt64() == 0).Assert();
(Convert(11).ToInt64() == 11).Assert();
(Convert(-111).ToInt64() == -111).Assert();
((Convert(10) + Convert(1)).ToInt64() == 11).Assert();
((Convert(10) + Convert(-1)).ToInt64() == 9).Assert();
((Convert(1) + Convert(-10)).ToInt64() == -9).Assert();
((Convert(1111) + Convert(-10)).ToInt64() == 1101).Assert();
((Convert(1111) + Convert(-1110)).ToInt64() == 1).Assert();
((Convert(1111) + Convert(-1112)).ToInt64() == -1).Assert();
(Convert("0").ToString(10) == "0").Assert(() => Convert("0").ToString(10));
(Convert("1").ToString(10) == "1").Assert(() => Convert("1").ToString(10));
(Convert("21").ToString(10) == "21").Assert(() => Convert("21").ToString(10));
(Convert("321").ToString(10) == "321").Assert();
(Convert("4321").ToString(10) == "4321").Assert();
(Convert("54321").ToString(10) == "54321").Assert();
(Convert("654321").ToString(10) == "654321").Assert();
(Convert("-1").ToString(10) == "-1").Assert();
(Convert("-21").ToString(10) == "-21").Assert();
(Convert("-321").ToString(10) == "-321").Assert();
(Convert("-4321").ToString(10) == "-4321").Assert();
(Convert("-54321").ToString(10) == "-54321").Assert();
(Convert("-654321").ToString(10) == "-654321").Assert();
}
[UnitTest]
public void Resize()
{
"Position of method tested".FlaggedLine(FilePositionTag.Test);
(Convert("100").Resize(Size.Create(6)).ToString(10) == "-28").Assert();
(Convert("1").Resize(Size.Create(1)).ToString(10) == "-1").Assert();
(Convert("1").Resize(Size.Create(2)).ToString(10) == "1").Assert();
(Convert("1").Resize(Size.Create(3)).ToString(10) == "1").Assert();
(Convert("2").Resize(Size.Create(1)).ToString(10) == "0").Assert();
(Convert("2").Resize(Size.Create(2)).ToString(10) == "-2").Assert
(() => Convert("2").Resize(Size.Create(2)).ToString(10));
(Convert("2").Resize(Size.Create(3)).ToString(10) == "2").Assert();
(Convert("-4").Resize(Size.Create(32)).ToString(10) == "-4").Assert
(() => Convert("-4").Resize(Size.Create(32)).ToString(10));
(Convert("-4095").Resize(Size.Create(8)).ToString(10) == "1").Assert
(() => Convert("-4095").Resize(Size.Create(32)).ToString(10));
}
}
sealed class MissingMethodException : Exception
{
[EnableDump]
readonly string Operation;
public MissingMethodException(string operation)
{
Operation = operation;
Tracer.ThrowAssertionFailed("", () => Tracer.Dump(this), 1);
}
}
internal const int SegmentAlignBits = 3;
const string Digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
static int NextObjectId;
public Size Size { get; }
readonly byte[] Data;
readonly ValueCache<BigInteger> DataCache;
BitsConst(Size size)
: base(NextObjectId++)
{
Size = size;
Data = CreateDataArray();
DataCache = new ValueCache<BigInteger>(() => new BigInteger(Data));
StopByObjectIds(-7);
}
BitsConst(long value, Size size)
: this(new BitsConst(value), size) { }
BitsConst(long value)
: this(Size.AutoSize(value))
=> DataHandler.MoveBytes(DataSize(Size), Data, 0, value);
BitsConst(BitsConst value, Size size)
: this(size)
=> MoveData(Data, Size, value.Data, value.Size);
BitsConst(int bytes, byte[] value, int start)
: this(Size.Create(bytes * 8))
=> DataHandler.MoveBytes(DataSize(Size), Data, 0, value, start);
public bool IsEmpty => Size.IsZero;
public int ByteCount => DataSize(Size);
public bool IsZero => Data.All(t => t == 0);
static Size SegmentBits => Size.Create(1 << SegmentAlignBits);
static int SegmentValues => 1 << SegmentBits.ToInt();
[PublicAPI]
static int MaxSegmentValue => SegmentValues - 1;
bool IsNegative
{
get
{
if(Size.IsZero)
return false;
return GetBit(Size - 1) != 0;
}
}
[DisableDump]
BigInteger AsInteger => DataCache.Value;
public static int BitSize(System.Type t) => Marshal.SizeOf(t) << SegmentAlignBits;
public byte[] ToByteArray() => (byte[])Data.Clone();
public byte Byte(int index)
{
if(index < Data.Length)
return Data[index];
if(Data.Length == 0 || Data[Data.Length - 1] < 0x80)
return 0;
return 0xff;
}
public static BitsConst Convert(int bytes, byte[] data, int position)
=> new BitsConst(bytes, data, position);
public static BitsConst None() => new BitsConst(Size.Zero);
public static BitsConst Convert(long value) => new BitsConst(value);
public static BitsConst Convert(string value)
=> new BitsConst(System.Convert.ToInt64(value));
public static BitsConst ConvertAsText(string value)
{
(Marshal.SizeOf(value[0].GetType()) == 1).Assert();
return new BitsConst(value.Length, value.Select(c => (byte)c).ToArray(), 0);
}
public static BitsConst Convert(string target, int @base)
{
long result = 0;
for(var i = 0; i < target.Length; i++)
{
var digit = Digits.IndexOf
(target.Substring(i, 1), StringComparison.InvariantCultureIgnoreCase);
(digit >= 0 && digit < @base).Assert();
result = result * @base + digit;
}
return Convert(result);
}
public static int PlusSize(int left, int right) => Math.Max(left, right) + 1;
public static int MultiplySize(int left, int right) => left + right - 1;
public BitsConst Resize(Size size) => new BitsConst(this, size);
public BitsConst ByteResize(int size) => Resize(SegmentBits * size);
public BitsConst ShiftDown(Size size)
{
SlagBits(Size).IsZero.Assert
(() => "Size of object is not byte aligned: " + Dump());
SlagBits(size).IsZero.Assert
(() => "Binary size is not byte aligned: " + size.Dump());
var bytes = size.ByteCount;
return Convert(Data.Length - bytes, Data, bytes);
}
public BitsConst Multiply(BitsConst right, Size size)
{
if(!(Marshal.SizeOf(typeof(long)) * 8 >= size.ToInt()))
Tracer.AssertionFailed
(
@"sizeof(Int64)*8 >= size.ToInt()",
() => "right=" + right + ";size=" + size.Dump());
return Convert(ToInt64() * right.ToInt64()).Resize(size);
}
public BitsConst Multiply(int right, Size size) => Convert(ToInt64() * right).Resize(size);
[UsedImplicitly]
public BitsConst Star(BitsConst right, Size size) => Multiply(right, size);
[UsedImplicitly]
public BitsConst Slash(BitsConst right, Size size) => Divide(right, size);
public BitsConst Divide(BitsConst right, Size size)
{
if(!(Marshal.SizeOf(typeof(long)) * 8 >= size.ToInt()))
Tracer.AssertionFailed
(
@"sizeof(Int64)*8 >= size.ToInt()",
() => "right=" + right + ";size=" + size.Dump());
return Convert(ToInt64() / right.ToInt64()).Resize(size);
}
public BitsConst BytePlus(BitsConst left, int bytes) => Plus(left, SegmentBits * bytes);
public BitsConst Plus(BitsConst right, Size size)
{
var xResult = new BitsConst(this, size);
var yResult = new BitsConst(right, size);
xResult.AddAndKeepSize(yResult);
return xResult;
}
[UsedImplicitly]
public BitsConst Minus(BitsConst right, Size size) => Plus(right * -1, size);
[UsedImplicitly]
public BitsConst Equal(BitsConst right, Size size)
=> ToBitsConst(AsInteger == right.AsInteger, size);
[UsedImplicitly]
public BitsConst Greater(BitsConst right, Size size)
=> ToBitsConst(AsInteger > right.AsInteger, size);
[UsedImplicitly]
public BitsConst GreaterEqual(BitsConst right, Size size)
=> ToBitsConst(AsInteger >= right.AsInteger, size);
[UsedImplicitly]
public BitsConst Less(BitsConst right, Size size)
=> ToBitsConst(AsInteger < right.AsInteger, size);
[UsedImplicitly]
public BitsConst LessEqual(BitsConst right, Size size)
=> ToBitsConst(AsInteger <= right.AsInteger, size);
[UsedImplicitly]
public BitsConst LessGreater(BitsConst right, Size size)
=> ToBitsConst(AsInteger != right.AsInteger, size);
[UsedImplicitly]
public BitsConst MinusPrefix(Size size) => Multiply(-1, size);
public BitsConst Concat(BitsConst other)
{
Size.AssertAlignedSize(SegmentAlignBits);
var result = new BitsConst(Size + other.Size);
DataHandler.MoveBytes(DataSize(Size), result.Data, 0, Data, 0);
DataHandler.MoveBytes
(DataSize(other.Size), result.Data, DataSize(Size), other.Data, 0);
return result;
}
public void PrintNumber(BitsConst radix, IOutStream outStream)
{
var r = radix.ToInt64();
if(radix.Size.IsZero)
r = 10;
var left = ToString((int)r);
outStream.AddData(left);
}
public void PrintNumber(IOutStream outStream) => PrintNumber(None(), outStream);
public void PrintText(Size itemSize, IOutStream outStream)
=> outStream.AddData(ToString(itemSize));
public string ToString(Size itemSize)
{
(itemSize == SegmentBits).Assert();
return new string(Data.Select(c => (char)c).ToArray());
}
public override string ToString() => DumpValue();
public unsafe long ToInt64()
{
var sizeInt64 = Marshal.SizeOf(typeof(long));
if(!(64 >= Size.ToInt()))
Tracer.AssertionFailed(@"64 >= _size.ToInt()", () => "size=" + Size.Dump());
var x64 = ByteResize(sizeInt64);
fixed(byte* dataPtr = &x64.Data[0])
{
return *(long*)dataPtr;
}
}
public unsafe int ToInt32()
{
var sizeInt32 = Marshal.SizeOf(typeof(int));
if(!(64 >= Size.ToInt()))
Tracer.AssertionFailed(@"64 >= _size.ToInt()", () => "size=" + Size.Dump());
var x32 = ByteResize(sizeInt32);
fixed(byte* dataPtr = &x32.Data[0])
{
return *(int*)dataPtr;
}
}
public string DumpValue()
{
if(Size.IsZero)
return "0[0]";
var digits = Size.ToInt() < 8? ToBitString() : ToHexString();
var result = digits.Quote() + "[";
result += Size.Dump();
result += "]";
return result;
}
public static BitsConst operator +(BitsConst left, BitsConst right)
=> left.Plus(right, PlusSize(left.Size, right.Size));
public static BitsConst Add(BitsConst left, BitsConst right)
=> left.Plus(right, PlusSize(left.Size, right.Size));
public static BitsConst operator -(BitsConst left, BitsConst right)
=> left.Plus(right * -1, PlusSize(left.Size, right.Size));
public static BitsConst operator -(int left, BitsConst right) => Convert(left) - right;
public static BitsConst Subtract(BitsConst left, BitsConst right)
=> left.Plus(right * -1, PlusSize(left.Size, right.Size));
public static BitsConst Subtract(int left, BitsConst right) => Convert(left) - right;
public static BitsConst operator *(BitsConst left, BitsConst right)
=> left.Multiply(right, MultiplySize(left.Size, right.Size));
public static BitsConst operator *(BitsConst left, int right) => left * Convert(right);
public static BitsConst Multiply(BitsConst left, BitsConst right)
=> left.Multiply(right, MultiplySize(left.Size, right.Size));
public static BitsConst Multiply(BitsConst left, int right) => left * Convert(right);
public static BitsConst operator /(BitsConst left, BitsConst right)
=> left.Divide(right, DivideSize(left.Size, right.Size));
public static BitsConst operator /(BitsConst left, int right) => left / Convert(right);
public static BitsConst Divide(BitsConst left, BitsConst right)
=> left.Divide(right, DivideSize(left.Size, right.Size));
public static BitsConst Divide(BitsConst left, int right) => left / Convert(right);
public override bool Equals(object obj)
{
var left = obj as BitsConst;
if(left == null)
return false;
if(Size != left.Size)
return false;
return Data == left.Data;
}
public override int GetHashCode() => Data.GetHashCode();
public BitsConst Access(Size start, Size size)
{
NotImplementedMethod(start, size);
return this;
}
public bool? Access(Size start)
{
if(start.IsNegative)
return null;
if(start >= Size)
return null;
return GetBit(start) != 0;
}
public void CopyTo(byte[] data, int index) => Data.CopyTo(data, index);
public static BitsConst Convert(byte[] value) => new BitsConst(value.Length, value, 0);
public string CodeDump() => ToInt64().ToString();
protected override string GetNodeDump() => base.GetNodeDump() + " " + ToString();
internal static int DivideSize(int left, int right) => Math.Max(0, left - right) + 2;
internal string ByteSequence(Size size = null)
{
var result = "";
for(var i = 0; i < (size ?? Size).ByteCount; i++)
{
result += ", ";
result += Byte(i);
}
return result;
}
internal BitsConst BitArrayBinaryOp(string operation, Size size, BitsConst right)
{
var methodInfo = typeof(BitsConst).GetMethod(operation);
if(methodInfo == null)
throw new MissingMethodException(operation);
return (BitsConst)methodInfo.Invoke(this, new object[] {right, size});
}
internal BitsConst BitArrayPrefixOp(string operation, Size size)
{
var methodInfo = typeof(BitsConst).GetMethod(operation + "Prefix");
if(methodInfo == null)
throw new MissingMethodException(operation);
return (BitsConst)methodInfo.Invoke(this, new object[] {size});
}
static Size SlagBits(Size size) => SegmentBits * DataSize(size) - size;
byte[] CreateDataArray() => new byte[DataSize(Size)];
static void MoveData(byte[] data, Size size, byte[] source, Size sourceSize)
{
var i = 0;
var n = size.Min(sourceSize).ToInt() >> SegmentAlignBits;
for(; i < n; i++)
data[i] = source[i];
var sizeEnd = size - Size.Byte * i;
var sourceSizeEnd = sourceSize - Size.Byte * i;
if(sourceSizeEnd.IsZero)
i--;
else if(sizeEnd.IsZero)
return;
else
{
var bitsToByte = (Size.Byte - sizeEnd.Min(sourceSizeEnd)).ToInt();
data[i] = (byte)((sbyte)((sbyte)source[i] << bitsToByte) >> bitsToByte);
}
if(i == -1)
return;
if((sbyte)data[i] >= 0)
return;
for(i++; i < size.ByteCount; i++)
unchecked
{
data[i] = (byte)-1;
}
}
static int DataSize(Size size)
{
if(size.IsZero)
return 0;
return (size - 1) / SegmentBits + 1;
}
static BitsConst ToBitsConst(bool value, Size size) => new BitsConst(value? -1 : 0, size);
string ToString(int radix)
{
if(radix <= 0 || radix > Digits.Length)
Tracer.AssertionFailed("radix <= 0 || radix > " + Digits.Length, radix.ToString);
if(IsZero)
return "0";
if(IsNegative)
return "-" + (0 - this).ToString(radix);
var left = this / radix;
var right = this - left * radix;
var digit = Digits[(int)right.ToInt64()].ToString();
if(left.IsZero)
return digit;
return left.ToString(radix) + digit;
}
string ToHexString()
{
var value = "";
var n = Data.Length;
for(var i = 0; i < n; i++)
if(i < 2 || i >= n - 2 || n == 5)
value = HexDump(Data[i]) + value;
else if(i == 3)
value = "..." + value;
return value;
}
static string HexDump(byte left)
{
var result = "";
result += Digits[(left >> 4) & 0xf];
result += Digits[left & 0xf];
return result;
}
string ToBitString()
{
var result = "";
for(var i = Size.Zero; i < Size; i += 1)
result = "01"[GetBit(i)] + result;
return result;
}
int GetBit(Size i)
{
var b = i / SegmentBits;
var p = (i % SegmentBits).ToInt();
return (Data[b] >> p) & 1;
}
static Size PlusSize(Size size, Size size1)
=> Size.Create(PlusSize(size.ToInt(), size1.ToInt()));
static Size MultiplySize(Size left, Size right)
=> Size.Create(MultiplySize(left.ToInt(), right.ToInt()));
static Size DivideSize(Size left, Size right)
=> Size.Create(DivideSize(left.ToInt(), right.ToInt()));
void AddAndKeepSize(BitsConst left)
{
short carry = 0;
for(var i = 0; i < Data.Length; i++)
{
carry += Data[i];
carry += left.Data[i];
Data[i] = (byte)carry;
carry /= (short)SegmentValues;
}
}
}
}
| |
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
using System.Linq;
namespace Pathfinding {
/** Handles update checking for the A* Pathfinding Project */
[InitializeOnLoad]
public static class AstarUpdateChecker {
/** Used for downloading new version information */
static WWW updateCheckDownload;
static System.DateTime _lastUpdateCheck;
static bool _lastUpdateCheckRead;
static System.Version _latestVersion;
static System.Version _latestBetaVersion;
/** Description of the latest update of the A* Pathfinding Project */
static string _latestVersionDescription;
static bool hasParsedServerMessage;
/** Number of days between update checks */
const double updateCheckRate = 1F;
/** URL to the version file containing the latest version number. */
const string updateURL = "http://www.arongranberg.com/astar/version.php";
/** Last time an update check was made */
public static System.DateTime lastUpdateCheck {
get {
try {
// Reading from EditorPrefs is relatively slow, avoid it
if (_lastUpdateCheckRead) return _lastUpdateCheck;
_lastUpdateCheck = System.DateTime.Parse(EditorPrefs.GetString("AstarLastUpdateCheck", "1/1/1971 00:00:01"), System.Globalization.CultureInfo.InvariantCulture);
_lastUpdateCheckRead = true;
}
catch (System.FormatException) {
lastUpdateCheck = System.DateTime.UtcNow;
Debug.LogWarning("Invalid DateTime string encountered when loading from preferences");
}
return _lastUpdateCheck;
}
private set {
_lastUpdateCheck = value;
EditorPrefs.SetString("AstarLastUpdateCheck", _lastUpdateCheck.ToString(System.Globalization.CultureInfo.InvariantCulture));
}
}
/** Latest version of the A* Pathfinding Project */
public static System.Version latestVersion {
get {
RefreshServerMessage();
return _latestVersion ?? AstarPath.Version;
}
private set {
_latestVersion = value;
}
}
/** Latest beta version of the A* Pathfinding Project */
public static System.Version latestBetaVersion {
get {
RefreshServerMessage();
return _latestBetaVersion ?? AstarPath.Version;
}
private set {
_latestBetaVersion = value;
}
}
/** Summary of the latest update */
public static string latestVersionDescription {
get {
RefreshServerMessage();
return _latestVersionDescription ?? "";
}
private set {
_latestVersionDescription = value;
}
}
/** Holds various URLs and text for the editor.
* This info can be updated when a check for new versions is done to ensure that there are no invalid links.
*/
static Dictionary<string, string> astarServerData = new Dictionary<string, string> {
{ "URL:modifiers", "http://www.arongranberg.com/astar/docs/modifiers.php" },
{ "URL:astarpro", "http://arongranberg.com/unity/a-pathfinding/astarpro/" },
{ "URL:documentation", "http://arongranberg.com/astar/docs/" },
{ "URL:findoutmore", "http://arongranberg.com/astar" },
{ "URL:download", "http://arongranberg.com/unity/a-pathfinding/download" },
{ "URL:changelog", "http://arongranberg.com/astar/docs/changelog.php" },
{ "URL:tags", "http://arongranberg.com/astar/docs/tags.php" },
{ "URL:homepage", "http://arongranberg.com/astar/" }
};
static AstarUpdateChecker() {
// Add a callback so that we can parse the message when it has been downloaded
EditorApplication.update += UpdateCheckLoop;
}
static void RefreshServerMessage () {
if (!hasParsedServerMessage) {
var serverMessage = EditorPrefs.GetString("AstarServerMessage");
if (!string.IsNullOrEmpty(serverMessage)) {
ParseServerMessage(serverMessage);
ShowUpdateWindowIfRelevant();
}
}
}
public static string GetURL (string tag) {
RefreshServerMessage();
string url;
astarServerData.TryGetValue("URL:"+tag, out url);
return url ?? "";
}
/** Initiate a check for updates now, regardless of when the last check was done */
public static void CheckForUpdatesNow () {
lastUpdateCheck = System.DateTime.UtcNow.AddDays(-5);
// Remove the callback if it already exists
EditorApplication.update -= UpdateCheckLoop;
// Add a callback so that we can parse the message when it has been downloaded
EditorApplication.update += UpdateCheckLoop;
}
/**
* Checking for updates...
* Should be called from EditorApplication.update
*/
static void UpdateCheckLoop () {
// Go on until the update check has been completed
if (!CheckForUpdates()) {
EditorApplication.update -= UpdateCheckLoop;
}
}
/** Checks for updates if there was some time since last check.
* It must be called repeatedly to ensure that the result is processed.
* \returns True if an update check is progressing (WWW request)
*/
static bool CheckForUpdates () {
if (updateCheckDownload != null && updateCheckDownload.isDone) {
if (!string.IsNullOrEmpty(updateCheckDownload.error)) {
Debug.LogWarning("There was an error checking for updates to the A* Pathfinding Project\n" +
"The error might disappear if you switch build target from Webplayer to Standalone because of the webplayer security emulation\nError: " +
updateCheckDownload.error);
updateCheckDownload = null;
return false;
}
UpdateCheckCompleted(updateCheckDownload.text);
updateCheckDownload = null;
}
// Check if it is time to check for updates
// Check for updates a bit earlier if we are in play mode or have the AstarPath object in the scene
// as then the collected statistics will be a bit more accurate
var offsetMinutes = (Application.isPlaying && Time.time > 60) || AstarPath.active != null ? -20 : 20;
var minutesUntilUpdate = lastUpdateCheck.AddDays(updateCheckRate).AddMinutes(offsetMinutes).Subtract(System.DateTime.UtcNow).TotalMinutes;
if (minutesUntilUpdate < 0) {
DownloadVersionInfo();
}
return updateCheckDownload != null || minutesUntilUpdate < 10;
}
static void DownloadVersionInfo () {
var script = AstarPath.active != null ? AstarPath.active : GameObject.FindObjectOfType(typeof(AstarPath)) as AstarPath;
if (script != null) {
script.ConfigureReferencesInternal();
if ((!Application.isPlaying && (script.data.graphs == null || script.data.graphs.Length == 0)) || script.data.graphs == null) {
script.data.DeserializeGraphs();
}
}
bool mecanim = GameObject.FindObjectOfType(typeof(Animator)) != null;
string query = updateURL+
"?v="+AstarPath.Version+
"&pro=0"+
"&check="+updateCheckRate+"&distr="+AstarPath.Distribution+
"&unitypro="+(Application.HasProLicense() ? "1" : "0")+
"&inscene="+(script != null ? "1" : "0")+
"&targetplatform="+EditorUserBuildSettings.activeBuildTarget+
"&devplatform="+Application.platform+
"&mecanim="+(mecanim ? "1" : "0")+
"&hasNavmesh=" + (script != null && script.data.graphs.Any(g => g.GetType().Name == "NavMeshGraph") ? 1 : 0) +
"&hasPoint=" + (script != null && script.data.graphs.Any(g => g.GetType().Name == "PointGraph") ? 1 : 0) +
"&hasGrid=" + (script != null && script.data.graphs.Any(g => g.GetType().Name == "GridGraph") ? 1 : 0) +
"&hasLayered=" + (script != null && script.data.graphs.Any(g => g.GetType().Name == "LayerGridGraph") ? 1 : 0) +
"&hasRecast=" + (script != null && script.data.graphs.Any(g => g.GetType().Name == "RecastGraph") ? 1 : 0) +
"&hasGrid=" + (script != null && script.data.graphs.Any(g => g.GetType().Name == "GridGraph") ? 1 : 0) +
"&hasCustom=" + (script != null && script.data.graphs.Any(g => g != null && !g.GetType().FullName.Contains("Pathfinding.")) ? 1 : 0) +
"&graphCount=" + (script != null ? script.data.graphs.Count(g => g != null) : 0) +
"&unityversion="+Application.unityVersion +
"&branch="+AstarPath.Branch;
updateCheckDownload = new WWW(query);
lastUpdateCheck = System.DateTime.UtcNow;
}
/** Handles the data from the update page */
static void UpdateCheckCompleted (string result) {
EditorPrefs.SetString("AstarServerMessage", result);
ParseServerMessage(result);
ShowUpdateWindowIfRelevant();
}
static void ParseServerMessage (string result) {
if (string.IsNullOrEmpty(result)) {
return;
}
hasParsedServerMessage = true;
string[] splits = result.Split('|');
latestVersionDescription = splits.Length > 1 ? splits[1] : "";
if (splits.Length > 4) {
// First 4 are just compatibility fields
var fields = splits.Skip(4).ToArray();
// Take all pairs of fields
for (int i = 0; i < (fields.Length/2)*2; i += 2) {
string key = fields[i];
string val = fields[i+1];
astarServerData[key] = val;
}
}
try {
latestVersion = new System.Version(astarServerData["VERSION:branch"]);
} catch (System.Exception ex) {
Debug.LogWarning("Could not parse version\n"+ex);
}
try {
latestBetaVersion = new System.Version(astarServerData["VERSION:beta"]);
} catch (System.Exception ex) {
Debug.LogWarning("Could not parse version\n"+ex);
}
}
static void ShowUpdateWindowIfRelevant () {
try {
System.DateTime remindDate;
var remindVersion = new System.Version(EditorPrefs.GetString("AstarRemindUpdateVersion", "0.0.0.0"));
if (latestVersion == remindVersion && System.DateTime.TryParse(EditorPrefs.GetString("AstarRemindUpdateDate", "1/1/1971 00:00:01"), out remindDate)) {
if (System.DateTime.UtcNow < remindDate) {
// Don't remind yet
return;
}
} else {
EditorPrefs.DeleteKey("AstarRemindUpdateDate");
EditorPrefs.DeleteKey("AstarRemindUpdateVersion");
}
} catch {
Debug.LogError("Invalid AstarRemindUpdateVersion or AstarRemindUpdateDate");
}
var skipVersion = new System.Version(EditorPrefs.GetString("AstarSkipUpToVersion", AstarPath.Version.ToString()));
if (AstarPathEditor.FullyDefinedVersion(latestVersion) != AstarPathEditor.FullyDefinedVersion(skipVersion) && AstarPathEditor.FullyDefinedVersion(latestVersion) > AstarPathEditor.FullyDefinedVersion(AstarPath.Version)) {
EditorPrefs.DeleteKey("AstarSkipUpToVersion");
EditorPrefs.DeleteKey("AstarRemindUpdateDate");
EditorPrefs.DeleteKey("AstarRemindUpdateVersion");
AstarUpdateWindow.Init(latestVersion, latestVersionDescription);
}
}
}
}
| |
//
// 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 System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Management.SiteRecovery.Models;
namespace Microsoft.Azure.Management.SiteRecovery
{
/// <summary>
/// Definition of fabric operations for the Site Recovery extension.
/// </summary>
public partial interface IFabricOperations
{
/// <summary>
/// Creates a Fabric
/// </summary>
/// <param name='fabricName'>
/// Fabric Name.
/// </param>
/// <param name='input'>
/// Input to create fabric
/// </param>
/// <param name='customRequestHeaders'>
/// Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
Task<LongRunningOperationResponse> BeginCreatingAsync(string fabricName, FabricCreationInput input, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken);
/// <summary>
/// Deletes a Fabric
/// </summary>
/// <param name='fabricName'>
/// Fabric Name.
/// </param>
/// <param name='customRequestHeaders'>
/// Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
Task<LongRunningOperationResponse> BeginDeletingAsync(string fabricName, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken);
/// <summary>
/// Deploy a Process Server.
/// </summary>
/// <param name='fabricName'>
/// Fabric Name.
/// </param>
/// <param name='input'>
/// Input to deploy a Process Server.
/// </param>
/// <param name='customRequestHeaders'>
/// Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
Task<LongRunningOperationResponse> BeginDeployProcessServerAsync(string fabricName, DeployProcessServerRequest input, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken);
/// <summary>
/// Purges a Fabric
/// </summary>
/// <param name='fabricName'>
/// Fabric Name.
/// </param>
/// <param name='customRequestHeaders'>
/// Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
Task<LongRunningOperationResponse> BeginPurgingAsync(string fabricName, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken);
/// <summary>
/// Performs reassociate gateway operation on a fabric.
/// </summary>
/// <param name='fabricName'>
/// Fabric Name.
/// </param>
/// <param name='input'>
/// Input to reassociate a gateway.
/// </param>
/// <param name='customRequestHeaders'>
/// Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
Task<LongRunningOperationResponse> BeginReassociateGatewayAsync(string fabricName, FailoverProcessServerRequest input, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken);
/// <summary>
/// Renews certificates of a Fabric
/// </summary>
/// <param name='fabricName'>
/// Fabric Name.
/// </param>
/// <param name='customRequestHeaders'>
/// Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
Task<LongRunningOperationResponse> BeginRenewCertificateAsync(string fabricName, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken);
/// <summary>
/// Creates a fabric
/// </summary>
/// <param name='fabricName'>
/// Fabric Name.
/// </param>
/// <param name='input'>
/// Input to create fabric
/// </param>
/// <param name='customRequestHeaders'>
/// Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
Task<LongRunningOperationResponse> CreateAsync(string fabricName, FabricCreationInput input, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken);
/// <summary>
/// Deletes a fabric
/// </summary>
/// <param name='fabricName'>
/// Fabric Name.
/// </param>
/// <param name='customRequestHeaders'>
/// Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
Task<LongRunningOperationResponse> DeleteAsync(string fabricName, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken);
/// <summary>
/// Deploy a Process Server.
/// </summary>
/// <param name='fabricName'>
/// Fabric Name.
/// </param>
/// <param name='input'>
/// Input to deploy a Process Server.
/// </param>
/// <param name='customRequestHeaders'>
/// Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
Task<LongRunningOperationResponse> DeployProcessServerAsync(string fabricName, DeployProcessServerRequest input, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken);
/// <summary>
/// Get the server object by Id.
/// </summary>
/// <param name='fabricName'>
/// Fabric Name.
/// </param>
/// <param name='customRequestHeaders'>
/// Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the fabric object
/// </returns>
Task<FabricResponse> GetAsync(string fabricName, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken);
/// <summary>
/// The Get Operation Status operation returns the status of the
/// specified operation. After calling an asynchronous operation, you
/// can call Get Operation Status to determine whether the operation
/// has succeeded, failed, or is still in progress.
/// </summary>
/// <param name='operationStatusLink'>
/// Location value returned by the Begin operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for fabric long running operations.
/// </returns>
Task<FabricOperationResponse> GetCreateStatusAsync(string operationStatusLink, CancellationToken cancellationToken);
/// <summary>
/// The Get Operation Status operation returns the status of the
/// specified operation. After calling an asynchronous operation, you
/// can call Get Operation Status to determine whether the operation
/// has succeeded, failed, or is still in progress.
/// </summary>
/// <param name='operationStatusLink'>
/// Location value returned by the Begin operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
Task<LongRunningOperationResponse> GetDeleteStatusAsync(string operationStatusLink, CancellationToken cancellationToken);
/// <summary>
/// The Get Operation Status operation returns the status of the
/// specified operation. After calling an asynchronous operation, you
/// can call Get Operation Status to determine whether the operation
/// has succeeded, failed, or is still in progress.
/// </summary>
/// <param name='operationStatusLink'>
/// Location value returned by the Begin operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
Task<DeployProcessServerOperationResponse> GetDeployProcessServerStatusAsync(string operationStatusLink, CancellationToken cancellationToken);
/// <summary>
/// The Get Operation Status operation returns the status of the
/// specified operation. After calling an asynchronous operation, you
/// can call Get Operation Status to determine whether the operation
/// has succeeded, failed, or is still in progress.
/// </summary>
/// <param name='operationStatusLink'>
/// Location value returned by the Begin operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
Task<LongRunningOperationResponse> GetPurgeStatusAsync(string operationStatusLink, CancellationToken cancellationToken);
/// <summary>
/// The Get Operation Status operation returns the status of the
/// specified operation. After calling an asynchronous operation, you
/// can call Get Operation Status to determine whether the operation
/// has succeeded, failed, or is still in progress.
/// </summary>
/// <param name='operationStatusLink'>
/// Location value returned by the Begin operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
Task<ReassociateGatewayOperationResponse> GetReassociateGatewayStatusAsync(string operationStatusLink, CancellationToken cancellationToken);
/// <summary>
/// The Get Operation Status operation returns the status of the
/// specified operation. After calling an asynchronous operation, you
/// can call Get Operation Status to determine whether the operation
/// has succeeded, failed, or is still in progress.
/// </summary>
/// <param name='operationStatusLink'>
/// Location value returned by the Begin operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for fabric long running operations.
/// </returns>
Task<FabricOperationResponse> GetRenewCertificateStatusAsync(string operationStatusLink, CancellationToken cancellationToken);
/// <summary>
/// Get the list of all fabrics under the vault.
/// </summary>
/// <param name='customRequestHeaders'>
/// Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the list servers operation.
/// </returns>
Task<FabricListResponse> ListAsync(CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken);
/// <summary>
/// Purges a fabric
/// </summary>
/// <param name='fabricName'>
/// Fabric Name.
/// </param>
/// <param name='customRequestHeaders'>
/// Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
Task<LongRunningOperationResponse> PurgeAsync(string fabricName, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken);
/// <summary>
/// Performs reassociate gateway operation on a fabric.
/// </summary>
/// <param name='fabricName'>
/// Fabric Name.
/// </param>
/// <param name='input'>
/// Input to reassociate a gateway.
/// </param>
/// <param name='customRequestHeaders'>
/// Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
Task<LongRunningOperationResponse> ReassociateGatewayAsync(string fabricName, FailoverProcessServerRequest input, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken);
/// <summary>
/// Renews certificates of a Fabric
/// </summary>
/// <param name='fabricName'>
/// Fabric Name.
/// </param>
/// <param name='customRequestHeaders'>
/// Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
Task<LongRunningOperationResponse> RenewCertificateAsync(string fabricName, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken);
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using BenchmarkDotNet.Attributes;
using HandlebarsDotNet;
using HandlebarsDotNet.Helpers;
using HandlebarsDotNet.PathStructure;
namespace HandlebarsNet.Benchmark
{
public class EndToEnd
{
private object _data;
private HandlebarsTemplate<TextWriter, object, object> _default;
[Params(5)]
public int N { get; set; }
[Params("object", "dictionary")]
public string DataType { get; set; }
[GlobalSetup]
public void Setup()
{
const string template = @"
childCount={{level1.Count}}
{{#each level1}}
id={{id}}
childCount={{level2.Count}}
index=[{{@../../index}}:{{@../index}}:{{@index}}]
pow1=[{{pow1 @index}}]
pow2=[{{pow2 @index}}]
pow3=[{{pow3 @index}}]
pow4=[{{pow4 @index}}]
pow5=[{{#pow5 @index}}empty{{/pow5}}]
{{#each level2}}
id={{id}}
childCount={{level3.Count}}
index=[{{@../../index}}:{{@../index}}:{{@index}}]
pow1=[{{pow1 @index}}]
pow2=[{{pow2 @index}}]
pow3=[{{pow3 @index}}]
pow4=[{{pow4 @index}}]
pow5=[{{#pow5 @index}}empty{{/pow5}}]
{{#each level3}}
id={{id}}
index=[{{@../../index}}:{{@../index}}:{{@index}}]
pow1=[{{pow1 @index}}]
pow2=[{{pow2 @index}}]
pow3=[{{pow3 @index}}]
pow4=[{{pow4 @index}}]
pow5=[{{#pow5 @index}}empty{{/pow5}}]
{{/each}}
{{/each}}
{{/each}}";
switch (DataType)
{
case "object":
_data = new { level1 = ObjectLevel1Generator()};
break;
case "dictionary":
_data = new Dictionary<string, object>{["level1"] = DictionaryLevel1Generator()};
break;
}
var handlebars = Handlebars.Create();
using(handlebars.Configure())
{
handlebars.RegisterHelper(new PowHelper("pow1"));
handlebars.RegisterHelper(new PowHelper("pow2"));
handlebars.RegisterHelper(new BlockPowHelper("pow5"));
}
using (var reader = new StringReader(template))
{
_default = handlebars.Compile(reader);
}
using(handlebars.Configure())
{
handlebars.RegisterHelper(new PowHelper("pow3"));
handlebars.RegisterHelper(new PowHelper("pow4"));
}
List<object> ObjectLevel1Generator()
{
var level = new List<object>();
for (int i = 0; i < N; i++)
{
level.Add(new
{
id = $"{i}",
level2 = ObjectLevel2Generator(i)
});
}
return level;
}
List<object> ObjectLevel2Generator(int id1)
{
var level = new List<object>();
for (int i = 0; i < N; i++)
{
level.Add(new
{
id = $"{id1}-{i}",
level3 = ObjectLevel3Generator(id1, i)
});
}
return level;
}
List<object> ObjectLevel3Generator(int id1, int id2)
{
var level = new List<object>();
for (int i = 0; i < N; i++)
{
level.Add(new
{
id = $"{id1}-{id2}-{i}"
});
}
return level;
}
List<Dictionary<string, object>> DictionaryLevel1Generator()
{
var level = new List<Dictionary<string, object>>();
for (int i = 0; i < N; i++)
{
level.Add(new Dictionary<string, object>()
{
["id"] = $"{i}",
["level2"] = DictionaryLevel2Generator(i)
});
}
return level;
}
List<Dictionary<string, object>> DictionaryLevel2Generator(int id1)
{
var level = new List<Dictionary<string, object>>();
for (int i = 0; i < N; i++)
{
level.Add(new Dictionary<string, object>()
{
["id"] = $"{id1}-{i}",
["level3"] = DictionaryLevel3Generator(id1, i)
});
}
return level;
}
List<Dictionary<string, object>> DictionaryLevel3Generator(int id1, int id2)
{
var level = new List<Dictionary<string, object>>();
for (int i = 0; i < N; i++)
{
level.Add(new Dictionary<string, object>()
{
["id"] = $"{id1}-{id2}-{i}"
});
}
return level;
}
}
private class PowHelper : IHelperDescriptor<HelperOptions>
{
public PowHelper(PathInfo name) => Name = name;
public PathInfo Name { get; }
public object Invoke(in HelperOptions options, in Context context, in Arguments arguments)
{
return ((int)arguments[0] * (int)arguments[0]).ToString();
}
public void Invoke(in EncodedTextWriter output, in HelperOptions options, in Context context, in Arguments arguments)
{
output.WriteSafeString(((int)arguments[0] * (int)arguments[0]).ToString());
}
}
private class BlockPowHelper : IHelperDescriptor<BlockHelperOptions>
{
public BlockPowHelper(PathInfo name) => Name = name;
public PathInfo Name { get; }
public object Invoke(in BlockHelperOptions options, in Context context, in Arguments arguments)
{
return ((int)arguments[0] * (int)arguments[0]).ToString();
}
public void Invoke(in EncodedTextWriter output, in BlockHelperOptions options, in Context context, in Arguments arguments)
{
output.WriteSafeString(((int)arguments[0] * (int)arguments[0]).ToString());
}
}
[Benchmark]
public void Default() => _default(TextWriter.Null, _data);
}
}
| |
/* ====================================================================
Copyright (C) 2004-2008 fyiReporting Software, LLC
Copyright (C) 2011 Peter Gill <peter@majorsilence.com>
This file is part of the fyiReporting RDL project.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
For additional information, email info@fyireporting.com or visit
the website www.fyiReporting.com.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Globalization;
using System.Xml;
using System.Reflection;
using RdlEngine.Resources;
using fyiReporting.RDL;
namespace fyiReporting.RDL
{
/// <summary>
/// <p>Language parser. Recursive descent parser. Precedence of operators
/// is handled by starting with lowest precedence and calling down recursively
/// to the highest.</p>
/// AND/OR
/// NOT
/// relational operators, eq, ne, lt, lte, gt, gte
/// +, -
/// *, /, %
/// ^ (exponentiation)
/// unary +, -
/// parenthesis (...)
/// <p>
/// In BNF the language grammar is:</p>
/// <code>
/// Expr: Term ExprRhs
/// ExprRhs: PlusMinusOperator Term ExprRhs
/// Term: Factor TermRhs
/// TermRhs: MultDivOperator Factor TermRhs
/// Factor: ( Expr ) | BaseType | - BaseType | - ( Expr )
/// BaseType: FuncIdent | NUMBER | QUOTE
/// FuncIDent: IDENTIFIER ( [Expr] [, Expr]*) | IDENTIFIER
/// PlusMinusOperator: + | -
/// MultDivOperator: * | /
/// </code>
///
/// </summary>
internal class Parser
{
static internal long Counter; // counter used for unique expression count
private TokenList tokens;
private Stack operandStack = new Stack();
private Stack operatorStack = new Stack();
private Token curToken=null;
private NameLookup idLookup=null;
private List<ICacheData> _DataCache;
private bool _InAggregate;
private DataSetDefn inAggregateDataSet = null;
private bool _NoAggregate=false;
/// <summary>
/// Parse an expression.
/// </summary>
internal Parser(List<ICacheData> c)
{
_DataCache = c;
}
/// <summary>
/// Returns a parsed Expression
/// </summary>
/// <param name="lu">The NameLookUp class used to resolve names.</param>
/// <param name="expr">The expression to be parsed.</param>
/// <returns>An expression that can be run after validation and binding.</returns>
internal IExpr Parse(NameLookup lu, string expr)
{
_InAggregate = false;
if (expr.Substring(0,1) != "=") // if 1st char not '='
return new Constant(expr); // this is a constant value
idLookup = lu;
IExpr e = this.ParseExpr(new StringReader(expr));
if (e == null) // Didn't get an expression?
e = new Constant(expr); // then provide a constant
return e;
}
internal bool NoAggregateFunctions
{ // marked true when in an aggregate function
get {return _NoAggregate;}
set {_NoAggregate = value;}
}
private static string GetLocationInfo(Token token)
{
return string.Format(Strings.Parser_ErrorP_AtColumn, token.StartCol);
}
private static string GetLocationInfoWithValue(Token token)
{
return string.Format(Strings.Parser_ErrorP_FoundValue, token.Value) + GetLocationInfo(token);
}
/// <summary>
/// Returns a parsed DPL instance.
/// </summary>
/// <param name="reader">The TextReader value to be parsed.</param>
/// <returns>A parsed Program instance.</returns>
private IExpr ParseExpr(TextReader reader)
{
IExpr result=null;
Lexer lexer = new Lexer(reader);
tokens = lexer.Lex();
if (tokens.Peek().Type == TokenTypes.EQUAL)
{
tokens.Extract(); // skip over the equal
curToken = tokens.Extract(); // set up the first token
MatchExprAndOr(out result); // start with lowest precedence and work up
}
if (curToken.Type != TokenTypes.EOF)
throw new ParserException(Strings.Parser_ErrorP_EndExpressionExpected + GetLocationInfo(curToken));
return result;
}
// ExprAndOr:
private void MatchExprAndOr(out IExpr result)
{
TokenTypes t; // remember the type
IExpr lhs;
MatchExprNot(out lhs);
result = lhs; // in case we get no matches
while ((t = curToken.Type) == TokenTypes.AND || t == TokenTypes.OR)
{
curToken = tokens.Extract();
IExpr rhs;
MatchExprNot(out rhs);
bool bBool = (rhs.GetTypeCode() == TypeCode.Boolean &&
lhs.GetTypeCode() == TypeCode.Boolean);
if (!bBool)
throw new ParserException(Strings.Parser_ErrorP_AND_OR_RequiresBoolean + GetLocationInfo(curToken));
switch(t)
{
case TokenTypes.AND:
result = new FunctionAnd(lhs, rhs);
break;
case TokenTypes.OR:
result = new FunctionOr(lhs, rhs);
break;
}
lhs = result; // in case we have more AND/OR s
}
}
private void MatchExprNot(out IExpr result)
{
TokenTypes t; // remember the type
t = curToken.Type;
if (t == TokenTypes.NOT)
{
curToken = tokens.Extract();
}
MatchExprRelop(out result);
if (t == TokenTypes.NOT)
{
if (result.GetTypeCode() != TypeCode.Boolean)
throw new ParserException(Strings.Parser_ErrorP_NOTRequiresBoolean + GetLocationInfo(curToken));
result = new FunctionNot(result);
}
}
// ExprRelop:
private void MatchExprRelop(out IExpr result)
{
TokenTypes t; // remember the type
IExpr lhs;
MatchExprAddSub(out lhs);
result = lhs; // in case we get no matches
while ((t = curToken.Type) == TokenTypes.EQUAL ||
t == TokenTypes.NOTEQUAL ||
t == TokenTypes.GREATERTHAN ||
t == TokenTypes.GREATERTHANOREQUAL ||
t == TokenTypes.LESSTHAN ||
t == TokenTypes.LESSTHANOREQUAL)
{
curToken = tokens.Extract();
IExpr rhs;
MatchExprAddSub(out rhs);
switch(t)
{
case TokenTypes.EQUAL:
result = new FunctionRelopEQ(lhs, rhs);
break;
case TokenTypes.NOTEQUAL:
result = new FunctionRelopNE(lhs, rhs);
break;
case TokenTypes.GREATERTHAN:
result = new FunctionRelopGT(lhs, rhs);
break;
case TokenTypes.GREATERTHANOREQUAL:
result = new FunctionRelopGTE(lhs, rhs);
break;
case TokenTypes.LESSTHAN:
result = new FunctionRelopLT(lhs, rhs);
break;
case TokenTypes.LESSTHANOREQUAL:
result = new FunctionRelopLTE(lhs, rhs);
break;
}
lhs = result; // in case we continue the loop
}
}
// ExprAddSub: PlusMinusOperator Term ExprRhs
private void MatchExprAddSub(out IExpr result)
{
TokenTypes t; // remember the type
IExpr lhs;
MatchExprMultDiv(out lhs);
result = lhs; // in case we get no matches
while ((t = curToken.Type) == TokenTypes.PLUS || t == TokenTypes.PLUSSTRING || t == TokenTypes.MINUS)
{
curToken = tokens.Extract();
IExpr rhs;
MatchExprMultDiv(out rhs);
TypeCode lt = lhs.GetTypeCode();
TypeCode rt = rhs.GetTypeCode();
bool bDecimal = (rt == TypeCode.Decimal &&
lt == TypeCode.Decimal);
bool bInt32 = (rt == TypeCode.Int32 &&
lt == TypeCode.Int32);
bool bString = (rt == TypeCode.String ||
lt == TypeCode.String);
switch(t)
{
case TokenTypes.PLUSSTRING:
result = new FunctionPlusString(lhs, rhs);
break;
case TokenTypes.PLUS:
if (bDecimal)
result = new FunctionPlusDecimal(lhs, rhs);
else if (bString)
result = new FunctionPlusString(lhs, rhs);
else if (bInt32)
result = new FunctionPlusInt32(lhs, rhs);
else
result = new FunctionPlus(lhs, rhs);
break;
case TokenTypes.MINUS:
if (bDecimal)
result = new FunctionMinusDecimal(lhs, rhs);
else if (bString)
throw new ParserException(Strings.Parser_ErrorP_MinusNeedNumbers + GetLocationInfo(curToken));
else if (bInt32)
result = new FunctionMinusInt32(lhs, rhs);
else
result = new FunctionMinus(lhs, rhs);
break;
}
lhs = result; // in case continue in the loop
}
}
// TermRhs: MultDivOperator Factor TermRhs
private void MatchExprMultDiv(out IExpr result)
{
TokenTypes t; // remember the type
IExpr lhs;
MatchExprExp(out lhs);
result = lhs; // in case we get no matches
while ((t = curToken.Type) == TokenTypes.FORWARDSLASH ||
t == TokenTypes.STAR ||
t == TokenTypes.MODULUS)
{
curToken = tokens.Extract();
IExpr rhs;
MatchExprExp(out rhs);
bool bDecimal = (rhs.GetTypeCode() == TypeCode.Decimal &&
lhs.GetTypeCode() == TypeCode.Decimal);
switch (t)
{
case TokenTypes.FORWARDSLASH:
if (bDecimal)
result = new FunctionDivDecimal(lhs, rhs);
else
result = new FunctionDiv(lhs, rhs);
break;
case TokenTypes.STAR:
if (bDecimal)
result = new FunctionMultDecimal(lhs, rhs);
else
result = new FunctionMult(lhs, rhs);
break;
case TokenTypes.MODULUS:
result = new FunctionModulus(lhs, rhs);
break;
}
lhs = result; // in case continue in the loop
}
}
// TermRhs: ExpOperator Factor TermRhs
private void MatchExprExp(out IExpr result)
{
IExpr lhs;
MatchExprUnary(out lhs);
if (curToken.Type == TokenTypes.EXP)
{
curToken = tokens.Extract();
IExpr rhs;
MatchExprUnary(out rhs);
result = new FunctionExp(lhs, rhs);
}
else
result = lhs;
}
private void MatchExprUnary(out IExpr result)
{
TokenTypes t; // remember the type
t = curToken.Type;
if (t == TokenTypes.PLUS || t == TokenTypes.MINUS)
{
curToken = tokens.Extract();
}
MatchExprParen(out result);
if (t == TokenTypes.MINUS)
{
if (result.GetTypeCode() == TypeCode.Decimal)
result = new FunctionUnaryMinusDecimal(result);
else if (result.GetTypeCode() == TypeCode.Int32)
result = new FunctionUnaryMinusInteger(result);
else
result = new FunctionUnaryMinus(result);
}
}
// Factor: ( Expr ) | BaseType | - BaseType | - ( Expr )
private void MatchExprParen(out IExpr result)
{
// Match- ( Expr )
if (curToken.Type == TokenTypes.LPAREN)
{ // trying to match ( Expr )
curToken = tokens.Extract();
MatchExprAndOr(out result);
if (curToken.Type != TokenTypes.RPAREN)
throw new ParserException(Strings.Parser_ErrorP_BracketExpected + GetLocationInfoWithValue(curToken));
curToken = tokens.Extract();
}
else
MatchBaseType(out result);
}
// BaseType: FuncIdent | NUMBER | QUOTE - note certain types are restricted in expressions
private void MatchBaseType(out IExpr result)
{
if (MatchFuncIDent(out result))
return;
switch (curToken.Type)
{
case TokenTypes.NUMBER:
result = new ConstantDecimal(curToken.Value);
break;
case TokenTypes.DATETIME:
result = new ConstantDateTime(curToken.Value);
break;
case TokenTypes.DOUBLE:
result = new ConstantDouble(curToken.Value);
break;
case TokenTypes.INTEGER:
result = new ConstantInteger(curToken.Value);
break;
case TokenTypes.QUOTE:
result = new ConstantString(curToken.Value);
break;
default:
throw new ParserException(Strings.Parser_ErrorP_IdentifierExpected + GetLocationInfoWithValue(curToken));
}
curToken = tokens.Extract();
return;
}
// FuncIDent: IDENTIFIER ( [Expr] [, Expr]*) | IDENTIFIER
private bool MatchFuncIDent(out IExpr result)
{
IExpr e;
string fullname; // will hold the full name
string method; // will hold method name or second part of name
string firstPart; // will hold the collection name
string thirdPart; // will hold third part of name
bool bOnePart; // simple name: no ! or . in name
result = null;
if (curToken.Type != TokenTypes.IDENTIFIER)
return false;
// Disentangle method calls from collection references
method = fullname = curToken.Value;
curToken = tokens.Extract();
// Break the name into parts
char[] breakChars = new char[] {'!', '.'};
int posBreak = method.IndexOfAny(breakChars);
if (posBreak > 0)
{
bOnePart = false;
firstPart = method.Substring(0, posBreak);
method = method.Substring(posBreak+1); // rest of expression
}
else
{
bOnePart = true;
firstPart = method;
}
posBreak = method.IndexOf('.');
if (posBreak > 0)
{
thirdPart = method.Substring(posBreak + 1); // rest of expression
method = method.Substring(0, posBreak);
}
else
{
thirdPart = null;
}
if (curToken.Type != TokenTypes.LPAREN) switch (firstPart)
{
case "Fields":
Field f = null;
if (inAggregateDataSet != null)
{
f = inAggregateDataSet.Fields == null ? null : inAggregateDataSet.Fields[method];
if (f == null)
throw new ParserException(string.Format(Strings.Parser_ErrorP_FieldNotInDataSet, method, inAggregateDataSet.Name.Nm));
}
else
{
f = idLookup.LookupField(method);
if (f == null)
{
throw new ParserException(string.Format(Strings.Parser_ErrorP_FieldNotFound, method));
}
}
if (thirdPart == null || thirdPart == "Value")
{
result = new FunctionField(f);
}
else if (thirdPart == "IsMissing")
{
result = new FunctionFieldIsMissing(f);
}
else
throw new ParserException(string.Format(Strings.Parser_ErrorP_FieldSupportsValueAndIsMissing, method));
return true;
case "Parameters": // see ResolveParametersMethod for resolution of MultiValue parameter function reference
ReportParameter p = idLookup.LookupParameter(method);
if (p == null)
throw new ParserException(string.Format(Strings.Parser_ErrorP_ParameterNotFound, method));
int ci = thirdPart == null? -1: thirdPart.IndexOf(".Count");
if (ci > 0)
thirdPart = thirdPart.Substring(0, ci);
FunctionReportParameter r;
if (thirdPart == null || thirdPart == "Value")
r = new FunctionReportParameter(p);
else if (thirdPart == "Label")
r = new FunctionReportParameterLabel(p);
else
throw new ParserException(string.Format(Strings.Parser_ErrorP_ParameterSupportsValueAndLabel, method));
if (ci > 0)
r.SetParameterMethod("Count", null);
result = r;
return true;
case "ReportItems":
Textbox t = idLookup.LookupReportItem(method);
if (t == null)
throw new ParserException(string.Format(Strings.Parser_ErrorP_ItemNotFound, method));
if (thirdPart != null && thirdPart != "Value")
throw new ParserException(string.Format(Strings.Parser_ErrorP_ItemSupportsValue, method));
result = new FunctionTextbox(t, idLookup.ExpressionName);
return true;
case "Globals":
e = idLookup.LookupGlobal(method);
if (e == null)
throw new ParserException(string.Format(Strings.Parser_ErrorP_GlobalsNotFound, method));
result = e;
return true;
case "User":
e = idLookup.LookupUser(method);
if (e == null)
throw new ParserException(string.Format(Strings.Parser_ErrorP_UserVarNotFound, method));
result = e;
return true;
case "Recursive": // Only valid for some aggregate functions
result = new IdentifierKey(IdentifierKeyEnum.Recursive);
return true;
case "Simple": // Only valid for some aggregate functions
result = new IdentifierKey(IdentifierKeyEnum.Simple);
return true;
default:
if (!bOnePart)
throw new ParserException(string.Format(Strings.Parser_ErrorP_UnknownIdentifer, fullname));
switch (method.ToLower()) // lexer should probably mark these
{
case "true":
case "false":
result = new ConstantBoolean(method.ToLower());
break;
default:
// usually this is enum that will be used in an aggregate
result = new Identifier(method);
break;
}
return true;
}
// We've got an function reference
curToken = tokens.Extract(); // get rid of '('
// Got a function now obtain the arguments
int argCount=0;
bool isAggregate = IsAggregate(method, bOnePart);
if (_NoAggregate && isAggregate)
throw new ParserException(string.Format(Strings.Parser_ErrorP_AggregateCannotUsedWithinGrouping, method));
if (_InAggregate && isAggregate)
throw new ParserException(string.Format(Strings.Parser_ErrorP_AggregateCannotNestedInAnotherAggregate, method));
_InAggregate = isAggregate;
if (_InAggregate)
{
int level = 0;
bool nextScope = false;
Token scopeToken = null;
foreach(Token tok in tokens)
{
if(nextScope)
{
scopeToken = tok;
break;
}
if(level == 0 && tok.Type == TokenTypes.COMMA)
{
nextScope = true;
continue;
}
if (tok.Type == TokenTypes.RPAREN)
level--;
if (tok.Type == TokenTypes.LPAREN)
level++;
}
if (scopeToken != null)
{
if (scopeToken.Type != TokenTypes.QUOTE)
throw new ParserException(string.Format(Strings.Parser_ErrorP_ScopeMustConstant, scopeToken.Value));
inAggregateDataSet = this.idLookup.ScopeDataSet(scopeToken.Value);
if (inAggregateDataSet == null)
throw new ParserException(string.Format(Strings.Parser_ErrorP_ScopeNotKnownDataSet, scopeToken.Value));
}
}
List<IExpr> largs = new List<IExpr>();
while(true)
{
if (curToken.Type == TokenTypes.RPAREN)
{ // We've got our function
curToken = tokens.Extract();
break;
}
if (argCount == 0)
{
// don't need to do anything
}
else if (curToken.Type == TokenTypes.COMMA)
{
curToken = tokens.Extract();
}
else
throw new ParserException(Strings.Parser_ErrorP_Invalid_function_arguments + GetLocationInfoWithValue(curToken));
MatchExprAndOr(out e);
if (e == null)
throw new ParserException(Strings.Parser_ErrorP_ExpectingComma + GetLocationInfoWithValue(curToken));
largs.Add(e);
argCount++;
}
if (_InAggregate)
{
inAggregateDataSet = null;
_InAggregate = false;
}
IExpr[] args = largs.ToArray();
object scope;
bool bSimple;
if (!bOnePart)
{
result = (firstPart == "Parameters")?
ResolveParametersMethod(method, thirdPart, args):
ResolveMethodCall(fullname, args); // throw exception when fails
}
else switch(method.ToLower())
{
case "iif":
if (args.Length != 3)
throw new ParserException(Strings.Parser_ErrorP_iff_function_requires_3_arguments + GetLocationInfo(curToken));
// We allow any type for the first argument; it will get converted to boolean at runtime
// if (args[0].GetTypeCode() != TypeCode.Boolean)
// throw new ParserException("First argument to iif function must be boolean." + GetLocationInfo(curToken));
result = new FunctionIif(args[0], args[1], args[2]);
break;
case "choose":
if (args.Length <= 2)
throw new ParserException(Strings.Parser_ErrorP_ChooseRequires2Arguments + GetLocationInfo(curToken));
switch (args[0].GetTypeCode())
{
case TypeCode.Double:
case TypeCode.Single:
case TypeCode.Int32:
case TypeCode.Decimal:
case TypeCode.Int16:
case TypeCode.Int64:
case TypeCode.UInt16:
case TypeCode.UInt32:
case TypeCode.UInt64:
break;
default:
throw new ParserException(Strings.Parser_ErrorP_ChooseFirstArgumentMustNumeric + GetLocationInfo(curToken));
}
result = new FunctionChoose(args);
break;
case "switch":
if (args.Length <= 2)
throw new ParserException(Strings.Parser_ErrorP_SwitchRequires2Arguments + GetLocationInfo(curToken));
if (args.Length % 2 != 0)
throw new ParserException(Strings.Parser_ErrorP_SwitchMustEvenArguments + GetLocationInfo(curToken));
for (int i=0; i < args.Length; i = i+2)
{
if (args[i].GetTypeCode() != TypeCode.Boolean)
throw new ParserException(Strings.Parser_ErrorP_SwitchMustBoolean + GetLocationInfo(curToken));
}
result = new FunctionSwitch(args);
break;
case "format":
if (args.Length > 2 || args.Length < 1)
throw new ParserException(Strings.Parser_ErrorP_FormatRequires2Arguments + GetLocationInfo(curToken));
if (args.Length == 1)
{
result = new FunctionFormat(args[0], new ConstantString(""));
}
else
{
if (args[1].GetTypeCode() != TypeCode.String)
throw new ParserException(Strings.Parser_ErrorP_SecondMustString + GetLocationInfo(curToken));
result = new FunctionFormat(args[0], args[1]);
}
break;
case "fields":
if (args.Length != 1)
throw new ParserException(Strings.Parser_ErrorP_FieldsRequires1Argument + GetLocationInfo(curToken));
result = new FunctionFieldCollection(idLookup.Fields, args[0]);
if (curToken.Type == TokenTypes.DOT)
{ // user placed "." TODO: generalize this code
curToken = tokens.Extract(); // skip past dot operator
if (curToken.Type == TokenTypes.IDENTIFIER && curToken.Value.ToLowerInvariant() == "value")
curToken = tokens.Extract(); // only support "value" property for now
else
throw new ParserException(string.Format(Strings.Parser_ErrorP_UnknownProperty, curToken.Value, "Fields") + GetLocationInfo(curToken));
}
break;
case "parameters":
if (args.Length != 1)
throw new ParserException(Strings.Parser_ErrorP_ParametersRequires1Argument + GetLocationInfo(curToken));
result = new FunctionParameterCollection(idLookup.Parameters, args[0]);
if (curToken.Type == TokenTypes.DOT)
{ // user placed "."
curToken = tokens.Extract(); // skip past dot operator
if (curToken.Type == TokenTypes.IDENTIFIER && curToken.Value.ToLowerInvariant() == "value")
curToken = tokens.Extract(); // only support "value" property for now
else
throw new ParserException((string.Format(Strings.Parser_ErrorP_UnknownProperty, curToken.Value, "Parameters") + GetLocationInfo(curToken)));
}
break;
case "reportitems":
if (args.Length != 1)
throw new ParserException(Strings.Parser_ErrorP_ReportItemsRequires1Argument + GetLocationInfo(curToken));
result = new FunctionReportItemCollection(idLookup.ReportItems, args[0]);
if (curToken.Type == TokenTypes.DOT)
{ // user placed "."
curToken = tokens.Extract(); // skip past dot operator
if (curToken.Type == TokenTypes.IDENTIFIER && curToken.Value.ToLowerInvariant() == "value")
curToken = tokens.Extract(); // only support "value" property for now
else
throw new ParserException((string.Format(Strings.Parser_ErrorP_UnknownProperty, curToken.Value, "ReportItems") + GetLocationInfo(curToken)));
}
break;
case "globals":
if (args.Length != 1)
throw new ParserException(Strings.Parser_ErrorP_GlobalsRequires1Argument + GetLocationInfo(curToken));
result = new FunctionGlobalCollection(idLookup.Globals, args[0]);
break;
case "user":
if (args.Length != 1)
throw new ParserException(Strings.Parser_ErrorP_UserRequires1Argument + GetLocationInfo(curToken));
result = new FunctionUserCollection(idLookup.User, args[0]);
break;
case "sum":
scope = ResolveAggrScope(args, 2, out bSimple);
FunctionAggrSum aggrFS = new FunctionAggrSum(_DataCache, args[0], scope);
aggrFS.LevelCheck = bSimple;
result = aggrFS;
break;
case "avg":
scope = ResolveAggrScope(args, 2, out bSimple);
FunctionAggrAvg aggrFA = new FunctionAggrAvg(_DataCache, args[0], scope);
aggrFA.LevelCheck = bSimple;
result = aggrFA;
break;
case "min":
scope = ResolveAggrScope(args, 2, out bSimple);
FunctionAggrMin aggrFMin = new FunctionAggrMin(_DataCache, args[0], scope);
aggrFMin.LevelCheck = bSimple;
result = aggrFMin;
break;
case "max":
scope = ResolveAggrScope(args, 2, out bSimple);
FunctionAggrMax aggrFMax = new FunctionAggrMax(_DataCache, args[0], scope);
aggrFMax.LevelCheck = bSimple;
result = aggrFMax;
break;
case "first":
scope = ResolveAggrScope(args, 2, out bSimple);
result = new FunctionAggrFirst(_DataCache, args[0], scope);
break;
case "last":
scope = ResolveAggrScope(args, 2, out bSimple);
result = new FunctionAggrLast(_DataCache, args[0], scope);
break;
case "next":
scope = ResolveAggrScope(args, 2, out bSimple);
result = new FunctionAggrNext(_DataCache, args[0], scope);
break;
case "previous":
scope = ResolveAggrScope(args, 2, out bSimple);
result = new FunctionAggrPrevious(_DataCache, args[0], scope);
break;
case "level":
scope = ResolveAggrScope(args, 1, out bSimple);
result = new FunctionAggrLevel(scope);
break;
case "aggregate":
scope = ResolveAggrScope(args, 2, out bSimple);
FunctionAggrArray aggr = new FunctionAggrArray(_DataCache, args[0], scope);
aggr.LevelCheck = bSimple;
result = aggr;
break;
case "count":
scope = ResolveAggrScope(args, 2, out bSimple);
FunctionAggrCount aggrFC = new FunctionAggrCount(_DataCache, args[0], scope);
aggrFC.LevelCheck = bSimple;
result = aggrFC;
break;
case "countrows":
scope = ResolveAggrScope(args, 1, out bSimple);
FunctionAggrCountRows aggrFCR = new FunctionAggrCountRows(scope);
aggrFCR.LevelCheck = bSimple;
result = aggrFCR;
break;
case "countdistinct":
scope = ResolveAggrScope(args, 2, out bSimple);
FunctionAggrCountDistinct aggrFCD = new FunctionAggrCountDistinct(_DataCache, args[0], scope);
aggrFCD.LevelCheck = bSimple;
result = aggrFCD;
break;
case "rownumber":
scope = ResolveAggrScope(args, 1, out bSimple);
IExpr texpr = new ConstantDouble("0");
result = new FunctionAggrRvCount(_DataCache, texpr, scope);
break;
case "runningvalue":
if (args.Length < 2 || args.Length > 3)
throw new ParserException(Strings.Parser_ErrorP_RunningValue_takes_2_or_3_arguments + GetLocationInfo(curToken));
string aggrFunc = args[1].EvaluateString(null, null);
if (aggrFunc == null)
throw new ParserException(Strings.Parser_ErrorP_RunningValueArgumentInvalid + GetLocationInfo(curToken));
scope = ResolveAggrScope(args, 3, out bSimple);
switch(aggrFunc.ToLower())
{
case "sum":
result = new FunctionAggrRvSum(_DataCache, args[0], scope);
break;
case "avg":
result = new FunctionAggrRvAvg(_DataCache, args[0], scope);
break;
case "count":
result = new FunctionAggrRvCount(_DataCache, args[0], scope);
break;
case "max":
result = new FunctionAggrRvMax(_DataCache, args[0], scope);
break;
case "min":
result = new FunctionAggrRvMin(_DataCache, args[0], scope);
break;
case "stdev":
result = new FunctionAggrRvStdev(_DataCache, args[0], scope);
break;
case "stdevp":
result = new FunctionAggrRvStdevp(_DataCache, args[0], scope);
break;
case "var":
result = new FunctionAggrRvVar(_DataCache, args[0], scope);
break;
case "varp":
result = new FunctionAggrRvVarp(_DataCache, args[0], scope);
break;
default:
throw new ParserException(string.Format(Strings.Parser_ErrorP_RunningValueNotSupported, aggrFunc) + GetLocationInfo(curToken));
}
break;
case "stdev":
scope = ResolveAggrScope(args, 2, out bSimple);
FunctionAggrStdev aggrSDev = new FunctionAggrStdev(_DataCache, args[0], scope);
aggrSDev.LevelCheck = bSimple;
result = aggrSDev;
break;
case "stdevp":
scope = ResolveAggrScope(args, 2, out bSimple);
FunctionAggrStdevp aggrSDevP = new FunctionAggrStdevp(_DataCache, args[0], scope);
aggrSDevP.LevelCheck = bSimple;
result = aggrSDevP;
break;
case "var":
scope = ResolveAggrScope(args, 2, out bSimple);
FunctionAggrVar aggrVar = new FunctionAggrVar(_DataCache, args[0], scope);
aggrVar.LevelCheck = bSimple;
result = aggrVar;
break;
case "varp":
scope = ResolveAggrScope(args, 2, out bSimple);
FunctionAggrVarp aggrVarP = new FunctionAggrVarp(_DataCache, args[0], scope);
aggrVarP.LevelCheck = bSimple;
result = aggrVarP;
break;
default:
result = ResolveMethodCall(fullname, args); // through exception when fails
break;
}
return true;
}
private bool IsAggregate(string method, bool onePart)
{
if (!onePart)
return false;
bool rc;
switch(method.ToLower())
{ // this needs to include all aggregate functions
case "sum":
case "avg":
case "min":
case "max":
case "first":
case "last":
case "next":
case "previous":
case "aggregate":
case "count":
case "countrows":
case "countdistinct":
case "stdev":
case "stdevp":
case "var":
case "varp":
case "rownumber":
case "runningvalue":
rc = true;
break;
default:
rc = false;
break;
}
return rc;
}
private object ResolveAggrScope(IExpr[] args, int indexOfScope, out bool bSimple)
{
object scope;
bSimple = true;
if (args.Length == 0 && indexOfScope > 1)
throw new ParserException(Strings.Parser_ErrorP_AggregateMust1Argument);
if (args.Length >= indexOfScope)
{
string n = args[indexOfScope-1].EvaluateString(null, null);
if (idLookup.IsPageScope)
throw new ParserException(string.Format(Strings.Parser_ErrorP_ScopeNotSpecifiedInHeaderOrFooter,n));
scope = idLookup.LookupScope(n);
if (scope == null)
{
Identifier ie = args[indexOfScope-1] as Identifier;
if (ie == null || ie.IsNothing == false) // check for "nothing" identifier
throw new ParserException(string.Format(Strings.Parser_ErrorP_ScopeNotKnownGrouping,n));
}
if (args.Length > indexOfScope) // has recursive/simple been specified
{
IdentifierKey k = args[indexOfScope] as IdentifierKey;
if (k == null)
throw new ParserException(Strings.Parser_ErrorP_ScopeIdentifer + GetLocationInfo(curToken));
if (k.Value == IdentifierKeyEnum.Recursive)
bSimple = false;
}
}
else if (idLookup.IsPageScope)
{
scope = "pghf"; // indicates page header or footer
}
else
{
scope = idLookup.LookupGrouping();
if (scope == null)
{
scope = idLookup.LookupMatrix();
if (scope == null)
scope = idLookup.ScopeDataSet(null);
}
}
return scope;
}
private IExpr ResolveParametersMethod(string pname, string vf, IExpr[] args)
{
FunctionReportParameter result;
ReportParameter p = idLookup.LookupParameter(pname);
if (p == null)
throw new ParserException(string.Format(Strings.Parser_ErrorP_ParameterNotFound, pname));
string arrayMethod;
int posBreak = vf.IndexOf('.');
if (posBreak > 0)
{
arrayMethod = vf.Substring(posBreak + 1); // rest of expression
vf = vf.Substring(0, posBreak);
}
else
arrayMethod = null;
if (vf == null || vf == "Value")
result = new FunctionReportParameter(p);
else if (vf == "Label")
result = new FunctionReportParameterLabel(p);
else
throw new ParserException(string.Format(Strings.Parser_ErrorP_ParameterSupportsValueAndLabel, pname));
result.SetParameterMethod(arrayMethod, args);
return result;
}
private IExpr ResolveMethodCall(string fullname, IExpr[] args)
{
string cls, method;
int idx = fullname.LastIndexOf('.');
if (idx > 0)
{
cls = fullname.Substring(0, idx);
method = fullname.Substring(idx+1);
}
else
{
cls = "";
method = fullname;
}
// Fill out the argument types
Type[] argTypes = new Type[args.Length];
for (int i=0; i < args.Length; i++)
{
argTypes[i] = XmlUtil.GetTypeFromTypeCode(args[i].GetTypeCode());
}
// See if this is a function within the Code element
Type cType=null;
bool bCodeFunction = false;
if (cls == "" || cls.ToLower() == "code")
{
cType = idLookup.CodeClassType; // get the code class type
if (cType != null)
{
if (XmlUtil.GetMethod(cType, method, argTypes) == null)
cType = null; // try for the method in the instance
else
bCodeFunction = true;
}
if (cls != "" && !bCodeFunction)
throw new ParserException(string.Format(Strings.Parser_ErrorP_NotCodeMethod, method));
}
// See if this is a function within the instance classes
ReportClass rc=null;
if (cType == null)
{
rc = idLookup.LookupInstance(cls); // is this an instance variable name?
if (rc == null)
{
cType=idLookup.LookupType(cls); // no, must be a static class reference
}
else
{
cType= idLookup.LookupType(rc.ClassName); // yes, use the classname of the ReportClass
}
}
string syscls=null;
if (cType == null)
{ // ok try for some of the system functions
switch(cls)
{
case "Math":
syscls = "System.Math";
break;
case "String":
syscls = "System.String";
break;
case "Convert":
syscls = "System.Convert";
break;
case "Financial":
syscls = "fyiReporting.RDL.Financial";
break;
default:
syscls = "fyiReporting.RDL.VBFunctions";
break;
}
if (syscls != null)
{
cType = Type.GetType(syscls, false, true);
}
}
if (cType == null)
{
string err;
if (cls == null || cls.Length == 0)
err = String.Format(Strings.Parser_ErrorP_FunctionUnknown, method);
else
err = String.Format(Strings.Parser_ErrorP_ClassUnknown, cls);
throw new ParserException(err);
}
IExpr result=null;
MethodInfo mInfo = XmlUtil.GetMethod(cType, method, argTypes);
if (mInfo == null)
{
string err;
if (cls == null || cls.Length == 0)
err = String.Format(Strings.Parser_ErrorP_FunctionUnknown, method);
else
err = String.Format(Strings.Parser_ErrorP_FunctionOfClassUnknown, method, cls);
throw new ParserException(err);
}
// when nullable object (e.g. DateTime?, int?,...)
// we need to get the underlying type
Type t = mInfo.ReturnType;
if (Type.GetTypeCode(t) == TypeCode.Object)
{
try
{
t = Nullable.GetUnderlyingType(t);
}
catch { } // ok if it fails; must not be nullable object
}
// obtain the TypeCode
TypeCode tc = Type.GetTypeCode(t);
if (bCodeFunction)
result = new FunctionCode(method, args, tc);
else if (syscls != null)
result = new FunctionSystem(syscls, method, args, tc);
else if (rc == null)
result = new FunctionCustomStatic(idLookup.CMS, cls, method, args, tc);
else
result = new FunctionCustomInstance(rc, method, args, tc);
return result;
}
}
}
| |
//---------------------------------------------------------------------
// <copyright file="Exceptions.cs" company="Microsoft Corporation">
// Copyright (c) 1999, Microsoft Corporation. All rights reserved.
// </copyright>
// <summary>
// Exceptions for the Microsoft.Deployment.WindowsInstaller namespace.
// </summary>
//---------------------------------------------------------------------
namespace Microsoft.PackageManagement.Msi.Internal.Deployment.WindowsInstaller
{
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Runtime.Serialization;
using System.Security.Permissions;
using System.Text;
/// <summary>
/// Base class for Windows Installer exceptions.
/// </summary>
[Serializable]
internal class InstallerException : SystemException
{
private int errorCode;
private object[] errorData;
/// <summary>
/// Creates a new InstallerException with a specified error message and a reference to the
/// inner exception that is the cause of this exception.
/// </summary>
/// <param name="msg">The message that describes the error.</param>
/// <param name="innerException">The exception that is the cause of the current exception. If the
/// innerException parameter is not a null reference (Nothing in Visual Basic), the current exception
/// is raised in a catch block that handles the inner exception.</param>
public InstallerException(string msg, Exception innerException)
: this(0, msg, innerException)
{
}
/// <summary>
/// Creates a new InstallerException with a specified error message.
/// </summary>
/// <param name="msg">The message that describes the error.</param>
public InstallerException(string msg)
: this(0, msg)
{
}
/// <summary>
/// Creates a new InstallerException.
/// </summary>
public InstallerException()
: this(0, null)
{
}
internal InstallerException(int errorCode, string msg, Exception innerException)
: base(msg, innerException)
{
this.errorCode = errorCode;
this.SaveErrorRecord();
}
internal InstallerException(int errorCode, string msg)
: this(errorCode, msg, null)
{
}
/// <summary>
/// Initializes a new instance of the InstallerException class with serialized data.
/// </summary>
/// <param name="info">The SerializationInfo that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The StreamingContext that contains contextual information about the source or destination.</param>
protected InstallerException(SerializationInfo info, StreamingContext context) : base(info, context)
{
if (info == null)
{
throw new ArgumentNullException("info");
}
this.errorCode = info.GetInt32("msiErrorCode");
}
/// <summary>
/// Gets the system error code that resulted in this exception, or 0 if not applicable.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public int ErrorCode
{
get
{
return this.errorCode;
}
}
/// <summary>
/// Gets a message that describes the exception. This message may contain detailed
/// formatted error data if it was available.
/// </summary>
public override String Message
{
get
{
string msg = base.Message;
using (Record errorRec = this.GetErrorRecord())
{
if (errorRec != null)
{
string errorMsg = Installer.GetErrorMessage(errorRec, CultureInfo.InvariantCulture);
msg = Combine(msg, errorMsg);
}
}
return msg;
}
}
/// <summary>
/// Sets the SerializationInfo with information about the exception.
/// </summary>
/// <param name="info">The SerializationInfo that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The StreamingContext that contains contextual information about the source or destination.</param>
[SecurityPermission(SecurityAction.Demand, SerializationFormatter=true)]
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
{
throw new ArgumentNullException("info");
}
info.AddValue("msiErrorCode", this.errorCode);
base.GetObjectData(info, context);
}
/// <summary>
/// Gets extended information about the error, or null if no further information
/// is available.
/// </summary>
/// <returns>A Record object. Field 1 of the Record contains the installer
/// message code. Other fields contain data specific to the particular error.</returns>
/// <remarks><p>
/// If the record is passed to <see cref="Session.Message"/>, it is formatted
/// by looking up the string in the current database. If there is no installation
/// session, the formatted error message may be obtained by a query on the Error table using
/// the error code, followed by a call to <see cref="Record.ToString()"/>.
/// Alternatively, the standard MSI message can by retrieved by calling the
/// <see cref="Installer.GetErrorMessage(Record,CultureInfo)"/> method.
/// </p><p>
/// The following methods and properties may report extended error data:
/// <list type="bullet">
/// <item><see cref="Database"/> (constructor)</item>
/// <item><see cref="Database"/>.<see cref="Database.ApplyTransform(string,TransformErrors)"/></item>
/// <item><see cref="Database"/>.<see cref="Database.Commit"/></item>
/// <item><see cref="Database"/>.<see cref="Database.Execute(string,object[])"/></item>
/// <item><see cref="Database"/>.<see cref="Database.ExecuteQuery(string,object[])"/></item>
/// <item><see cref="Database"/>.<see cref="Database.ExecuteIntegerQuery(string,object[])"/></item>
/// <item><see cref="Database"/>.<see cref="Database.ExecuteStringQuery(string,object[])"/></item>
/// <item><see cref="Database"/>.<see cref="Database.Export"/></item>
/// <item><see cref="Database"/>.<see cref="Database.ExportAll"/></item>
/// <item><see cref="Database"/>.<see cref="Database.GenerateTransform"/></item>
/// <item><see cref="Database"/>.<see cref="Database.Import"/></item>
/// <item><see cref="Database"/>.<see cref="Database.ImportAll"/></item>
/// <item><see cref="Database"/>.<see cref="Database.Merge(Database,string)"/></item>
/// <item><see cref="Database"/>.<see cref="Database.OpenView"/></item>
/// <item><see cref="Database"/>.<see cref="Database.SummaryInfo"/></item>
/// <item><see cref="Database"/>.<see cref="Database.ViewTransform"/></item>
/// <item><see cref="View"/>.<see cref="View.Assign"/></item>
/// <item><see cref="View"/>.<see cref="View.Delete"/></item>
/// <item><see cref="View"/>.<see cref="View.Execute(Record)"/></item>
/// <item><see cref="View"/>.<see cref="View.Insert"/></item>
/// <item><see cref="View"/>.<see cref="View.InsertTemporary"/></item>
/// <item><see cref="View"/>.<see cref="View.Merge"/></item>
/// <item><see cref="View"/>.<see cref="View.Modify"/></item>
/// <item><see cref="View"/>.<see cref="View.Refresh"/></item>
/// <item><see cref="View"/>.<see cref="View.Replace"/></item>
/// <item><see cref="View"/>.<see cref="View.Seek"/></item>
/// <item><see cref="View"/>.<see cref="View.Update"/></item>
/// <item><see cref="View"/>.<see cref="View.Validate"/></item>
/// <item><see cref="View"/>.<see cref="View.ValidateFields"/></item>
/// <item><see cref="View"/>.<see cref="View.ValidateDelete"/></item>
/// <item><see cref="View"/>.<see cref="View.ValidateNew"/></item>
/// <item><see cref="SummaryInfo"/> (constructor)</item>
/// <item><see cref="Record"/>.<see cref="Record.SetStream(int,string)"/></item>
/// <item><see cref="Session"/>.<see cref="Session.SetInstallLevel"/></item>
/// <item><see cref="Session"/>.<see cref="Session.GetSourcePath"/></item>
/// <item><see cref="Session"/>.<see cref="Session.GetTargetPath"/></item>
/// <item><see cref="Session"/>.<see cref="Session.SetTargetPath"/></item>
/// <item><see cref="ComponentInfo"/>.<see cref="ComponentInfo.CurrentState"/></item>
/// <item><see cref="FeatureInfo"/>.<see cref="FeatureInfo.CurrentState"/></item>
/// <item><see cref="FeatureInfo"/>.<see cref="FeatureInfo.ValidStates"/></item>
/// <item><see cref="FeatureInfo"/>.<see cref="FeatureInfo.GetCost"/></item>
/// </list>
/// </p><p>
/// The Record object should be <see cref="InstallerHandle.Close"/>d after use.
/// It is best that the handle be closed manually as soon as it is no longer
/// needed, as leaving lots of unused handles open can degrade performance.
/// </p><p>
/// Win32 MSI API:
/// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msigetlasterrorrecord.asp">MsiGetLastErrorRecord</a>
/// </p></remarks>
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
public Record GetErrorRecord()
{
return this.errorData != null ? new Record(this.errorData) : null;
}
internal static Exception ExceptionFromReturnCode(uint errorCode)
{
return ExceptionFromReturnCode(errorCode, null);
}
internal static Exception ExceptionFromReturnCode(uint errorCode, string msg)
{
msg = Combine(GetSystemMessage(errorCode), msg);
switch (errorCode)
{
case (uint) NativeMethods.Error.FILE_NOT_FOUND:
case (uint) NativeMethods.Error.PATH_NOT_FOUND: return new FileNotFoundException(msg);
case (uint) NativeMethods.Error.INVALID_PARAMETER:
case (uint) NativeMethods.Error.DIRECTORY:
case (uint) NativeMethods.Error.UNKNOWN_PROPERTY:
case (uint) NativeMethods.Error.UNKNOWN_PRODUCT:
case (uint) NativeMethods.Error.UNKNOWN_FEATURE:
case (uint) NativeMethods.Error.UNKNOWN_COMPONENT: return new ArgumentException(msg);
case (uint) NativeMethods.Error.BAD_QUERY_SYNTAX: return new BadQuerySyntaxException(msg);
case (uint) NativeMethods.Error.INVALID_HANDLE_STATE:
case (uint) NativeMethods.Error.INVALID_HANDLE:
InvalidHandleException ihex = new InvalidHandleException(msg);
ihex.errorCode = (int) errorCode;
return ihex;
case (uint) NativeMethods.Error.INSTALL_USEREXIT: return new InstallCanceledException(msg);
case (uint) NativeMethods.Error.CALL_NOT_IMPLEMENTED: return new NotImplementedException(msg);
default: return new InstallerException((int) errorCode, msg);
}
}
internal static string GetSystemMessage(uint errorCode)
{
const uint FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200;
const uint FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000;
StringBuilder buf = new StringBuilder(1024);
uint formatCount = NativeMethods.FormatMessage(
FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
IntPtr.Zero,
(uint) errorCode,
0,
buf,
(uint) buf.Capacity,
IntPtr.Zero);
if (formatCount != 0)
{
return buf.ToString().Trim();
}
else
{
return null;
}
}
internal void SaveErrorRecord()
{
// TODO: pass an affinity handle here?
int recordHandle = RemotableNativeMethods.MsiGetLastErrorRecord(0);
if (recordHandle != 0)
{
using (Record errorRec = new Record((IntPtr) recordHandle, true, null))
{
this.errorData = new object[errorRec.FieldCount];
for (int i = 0; i < this.errorData.Length; i++)
{
this.errorData[i] = errorRec[i + 1];
}
}
}
else
{
this.errorData = null;
}
}
private static string Combine(string msg1, string msg2)
{
if (msg1 == null) return msg2;
if (msg2 == null) return msg1;
return msg1 + " " + msg2;
}
}
/// <summary>
/// User Canceled the installation.
/// </summary>
[Serializable]
internal class InstallCanceledException : InstallerException
{
/// <summary>
/// Creates a new InstallCanceledException with a specified error message and a reference to the
/// inner exception that is the cause of this exception.
/// </summary>
/// <param name="msg">The message that describes the error.</param>
/// <param name="innerException">The exception that is the cause of the current exception. If the
/// innerException parameter is not a null reference (Nothing in Visual Basic), the current exception
/// is raised in a catch block that handles the inner exception.</param>
public InstallCanceledException(string msg, Exception innerException)
: base((int) NativeMethods.Error.INSTALL_USEREXIT, msg, innerException)
{
}
/// <summary>
/// Creates a new InstallCanceledException with a specified error message.
/// </summary>
/// <param name="msg">The message that describes the error.</param>
public InstallCanceledException(string msg)
: this(msg, null)
{
}
/// <summary>
/// Creates a new InstallCanceledException.
/// </summary>
public InstallCanceledException()
: this(null, null)
{
}
/// <summary>
/// Initializes a new instance of the InstallCanceledException class with serialized data.
/// </summary>
/// <param name="info">The SerializationInfo that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The StreamingContext that contains contextual information about the source or destination.</param>
protected InstallCanceledException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
}
/// <summary>
/// A bad SQL query string was passed to <see cref="Database.OpenView"/> or <see cref="Database.Execute(string,object[])"/>.
/// </summary>
[Serializable]
internal class BadQuerySyntaxException : InstallerException
{
/// <summary>
/// Creates a new BadQuerySyntaxException with a specified error message and a reference to the
/// inner exception that is the cause of this exception.
/// </summary>
/// <param name="msg">The message that describes the error.</param>
/// <param name="innerException">The exception that is the cause of the current exception. If the
/// innerException parameter is not a null reference (Nothing in Visual Basic), the current exception
/// is raised in a catch block that handles the inner exception.</param>
public BadQuerySyntaxException(string msg, Exception innerException)
: base((int) NativeMethods.Error.BAD_QUERY_SYNTAX, msg, innerException)
{
}
/// <summary>
/// Creates a new BadQuerySyntaxException with a specified error message.
/// </summary>
/// <param name="msg">The message that describes the error.</param>
public BadQuerySyntaxException(string msg)
: this(msg, null)
{
}
/// <summary>
/// Creates a new BadQuerySyntaxException.
/// </summary>
public BadQuerySyntaxException()
: this(null, null)
{
}
/// <summary>
/// Initializes a new instance of the BadQuerySyntaxException class with serialized data.
/// </summary>
/// <param name="info">The SerializationInfo that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The StreamingContext that contains contextual information about the source or destination.</param>
protected BadQuerySyntaxException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
}
/// <summary>
/// A method was called on an invalid installer handle. The handle may have been already closed.
/// </summary>
[Serializable]
internal class InvalidHandleException : InstallerException
{
/// <summary>
/// Creates a new InvalidHandleException with a specified error message and a reference to the
/// inner exception that is the cause of this exception.
/// </summary>
/// <param name="msg">The message that describes the error.</param>
/// <param name="innerException">The exception that is the cause of the current exception. If the
/// innerException parameter is not a null reference (Nothing in Visual Basic), the current exception
/// is raised in a catch block that handles the inner exception.</param>
public InvalidHandleException(string msg, Exception innerException)
: base((int) NativeMethods.Error.INVALID_HANDLE, msg, innerException)
{
}
/// <summary>
/// Creates a new InvalidHandleException with a specified error message.
/// </summary>
/// <param name="msg">The message that describes the error.</param>
public InvalidHandleException(string msg)
: this(msg, null)
{
}
/// <summary>
/// Creates a new InvalidHandleException.
/// </summary>
public InvalidHandleException()
: this(null, null)
{
}
/// <summary>
/// Initializes a new instance of the InvalidHandleException class with serialized data.
/// </summary>
/// <param name="info">The SerializationInfo that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The StreamingContext that contains contextual information about the source or destination.</param>
protected InvalidHandleException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
}
/// <summary>
/// A failure occurred when executing <see cref="Database.Merge(Database,string)"/>. The exception may contain
/// details about the merge conflict.
/// </summary>
[Serializable]
internal class MergeException : InstallerException
{
private IList<string> conflictTables;
private IList<int> conflictCounts;
/// <summary>
/// Creates a new MergeException with a specified error message and a reference to the
/// inner exception that is the cause of this exception.
/// </summary>
/// <param name="msg">The message that describes the error.</param>
/// <param name="innerException">The exception that is the cause of the current exception. If the
/// innerException parameter is not a null reference (Nothing in Visual Basic), the current exception
/// is raised in a catch block that handles the inner exception.</param>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public MergeException(string msg, Exception innerException)
: base(msg, innerException)
{
}
/// <summary>
/// Creates a new MergeException with a specified error message.
/// </summary>
/// <param name="msg">The message that describes the error.</param>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public MergeException(string msg)
: base(msg)
{
}
/// <summary>
/// Creates a new MergeException.
/// </summary>
public MergeException()
: base()
{
}
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal MergeException(Database db, string conflictsTableName)
: base("Merge failed.")
{
if (conflictsTableName != null)
{
IList<string> conflictTableList = new List<string>();
IList<int> conflictCountList = new List<int>();
using (View view = db.OpenView("SELECT `Table`, `NumRowMergeConflicts` FROM `" + conflictsTableName + "`"))
{
view.Execute();
foreach (Record rec in view) using (rec)
{
conflictTableList.Add(rec.GetString(1));
conflictCountList.Add((int) rec.GetInteger(2));
}
}
this.conflictTables = conflictTableList;
this.conflictCounts = conflictCountList;
}
}
/// <summary>
/// Initializes a new instance of the MergeException class with serialized data.
/// </summary>
/// <param name="info">The SerializationInfo that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The StreamingContext that contains contextual information about the source or destination.</param>
protected MergeException(SerializationInfo info, StreamingContext context) : base(info, context)
{
if (info == null)
{
throw new ArgumentNullException("info");
}
this.conflictTables = (string[]) info.GetValue("mergeConflictTables", typeof(string[]));
this.conflictCounts = (int[]) info.GetValue("mergeConflictCounts", typeof(int[]));
}
/// <summary>
/// Gets the number of merge conflicts in each table, corresponding to the tables returned by
/// <see cref="ConflictTables"/>.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public IList<int> ConflictCounts
{
get
{
return new List<int>(this.conflictCounts);
}
}
/// <summary>
/// Gets the list of tables containing merge conflicts.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public IList<string> ConflictTables
{
get
{
return new List<string>(this.conflictTables);
}
}
/// <summary>
/// Gets a message that describes the merge conflits.
/// </summary>
public override String Message
{
get
{
StringBuilder msg = new StringBuilder(base.Message);
if (this.conflictTables != null)
{
for (int i = 0; i < this.conflictTables.Count; i++)
{
msg.Append(i == 0 ? " Conflicts: " : ", ");
msg.Append(this.conflictTables[i]);
msg.Append('(');
msg.Append(this.conflictCounts[i]);
msg.Append(')');
}
}
return msg.ToString();
}
}
/// <summary>
/// Sets the SerializationInfo with information about the exception.
/// </summary>
/// <param name="info">The SerializationInfo that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The StreamingContext that contains contextual information about the source or destination.</param>
[SecurityPermission(SecurityAction.Demand, SerializationFormatter=true)]
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
{
throw new ArgumentNullException("info");
}
info.AddValue("mergeConflictTables", this.conflictTables);
info.AddValue("mergeConflictCounts", this.conflictCounts);
base.GetObjectData(info, context);
}
}
}
| |
/*
* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace XenAPI
{
/// <summary>
/// a proxy connects a VM/VIF with a PVS site
/// First published in XenServer 7.1.
/// </summary>
public partial class PVS_proxy : XenObject<PVS_proxy>
{
public PVS_proxy()
{
}
public PVS_proxy(string uuid,
XenRef<PVS_site> site,
XenRef<VIF> VIF,
bool currently_attached,
pvs_proxy_status status)
{
this.uuid = uuid;
this.site = site;
this.VIF = VIF;
this.currently_attached = currently_attached;
this.status = status;
}
/// <summary>
/// Creates a new PVS_proxy from a Proxy_PVS_proxy.
/// </summary>
/// <param name="proxy"></param>
public PVS_proxy(Proxy_PVS_proxy proxy)
{
this.UpdateFromProxy(proxy);
}
/// <summary>
/// Updates each field of this instance with the value of
/// the corresponding field of a given PVS_proxy.
/// </summary>
public override void UpdateFrom(PVS_proxy update)
{
uuid = update.uuid;
site = update.site;
VIF = update.VIF;
currently_attached = update.currently_attached;
status = update.status;
}
internal void UpdateFromProxy(Proxy_PVS_proxy proxy)
{
uuid = proxy.uuid == null ? null : (string)proxy.uuid;
site = proxy.site == null ? null : XenRef<PVS_site>.Create(proxy.site);
VIF = proxy.VIF == null ? null : XenRef<VIF>.Create(proxy.VIF);
currently_attached = (bool)proxy.currently_attached;
status = proxy.status == null ? (pvs_proxy_status) 0 : (pvs_proxy_status)Helper.EnumParseDefault(typeof(pvs_proxy_status), (string)proxy.status);
}
public Proxy_PVS_proxy ToProxy()
{
Proxy_PVS_proxy result_ = new Proxy_PVS_proxy();
result_.uuid = uuid ?? "";
result_.site = site ?? "";
result_.VIF = VIF ?? "";
result_.currently_attached = currently_attached;
result_.status = pvs_proxy_status_helper.ToString(status);
return result_;
}
/// <summary>
/// Creates a new PVS_proxy from a Hashtable.
/// Note that the fields not contained in the Hashtable
/// will be created with their default values.
/// </summary>
/// <param name="table"></param>
public PVS_proxy(Hashtable table) : this()
{
UpdateFrom(table);
}
/// <summary>
/// Given a Hashtable with field-value pairs, it updates the fields of this PVS_proxy
/// with the values listed in the Hashtable. Note that only the fields contained
/// in the Hashtable will be updated and the rest will remain the same.
/// </summary>
/// <param name="table"></param>
public void UpdateFrom(Hashtable table)
{
if (table.ContainsKey("uuid"))
uuid = Marshalling.ParseString(table, "uuid");
if (table.ContainsKey("site"))
site = Marshalling.ParseRef<PVS_site>(table, "site");
if (table.ContainsKey("VIF"))
VIF = Marshalling.ParseRef<VIF>(table, "VIF");
if (table.ContainsKey("currently_attached"))
currently_attached = Marshalling.ParseBool(table, "currently_attached");
if (table.ContainsKey("status"))
status = (pvs_proxy_status)Helper.EnumParseDefault(typeof(pvs_proxy_status), Marshalling.ParseString(table, "status"));
}
public bool DeepEquals(PVS_proxy other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
return Helper.AreEqual2(this._uuid, other._uuid) &&
Helper.AreEqual2(this._site, other._site) &&
Helper.AreEqual2(this._VIF, other._VIF) &&
Helper.AreEqual2(this._currently_attached, other._currently_attached) &&
Helper.AreEqual2(this._status, other._status);
}
internal static List<PVS_proxy> ProxyArrayToObjectList(Proxy_PVS_proxy[] input)
{
var result = new List<PVS_proxy>();
foreach (var item in input)
result.Add(new PVS_proxy(item));
return result;
}
public override string SaveChanges(Session session, string opaqueRef, PVS_proxy server)
{
if (opaqueRef == null)
{
System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server");
return "";
}
else
{
throw new InvalidOperationException("This type has no read/write properties");
}
}
/// <summary>
/// Get a record containing the current state of the given PVS_proxy.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pvs_proxy">The opaque_ref of the given pvs_proxy</param>
public static PVS_proxy get_record(Session session, string _pvs_proxy)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pvs_proxy_get_record(session.opaque_ref, _pvs_proxy);
else
return new PVS_proxy((Proxy_PVS_proxy)session.proxy.pvs_proxy_get_record(session.opaque_ref, _pvs_proxy ?? "").parse());
}
/// <summary>
/// Get a reference to the PVS_proxy instance with the specified UUID.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_uuid">UUID of object to return</param>
public static XenRef<PVS_proxy> get_by_uuid(Session session, string _uuid)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pvs_proxy_get_by_uuid(session.opaque_ref, _uuid);
else
return XenRef<PVS_proxy>.Create(session.proxy.pvs_proxy_get_by_uuid(session.opaque_ref, _uuid ?? "").parse());
}
/// <summary>
/// Get the uuid field of the given PVS_proxy.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pvs_proxy">The opaque_ref of the given pvs_proxy</param>
public static string get_uuid(Session session, string _pvs_proxy)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pvs_proxy_get_uuid(session.opaque_ref, _pvs_proxy);
else
return (string)session.proxy.pvs_proxy_get_uuid(session.opaque_ref, _pvs_proxy ?? "").parse();
}
/// <summary>
/// Get the site field of the given PVS_proxy.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pvs_proxy">The opaque_ref of the given pvs_proxy</param>
public static XenRef<PVS_site> get_site(Session session, string _pvs_proxy)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pvs_proxy_get_site(session.opaque_ref, _pvs_proxy);
else
return XenRef<PVS_site>.Create(session.proxy.pvs_proxy_get_site(session.opaque_ref, _pvs_proxy ?? "").parse());
}
/// <summary>
/// Get the VIF field of the given PVS_proxy.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pvs_proxy">The opaque_ref of the given pvs_proxy</param>
public static XenRef<VIF> get_VIF(Session session, string _pvs_proxy)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pvs_proxy_get_vif(session.opaque_ref, _pvs_proxy);
else
return XenRef<VIF>.Create(session.proxy.pvs_proxy_get_vif(session.opaque_ref, _pvs_proxy ?? "").parse());
}
/// <summary>
/// Get the currently_attached field of the given PVS_proxy.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pvs_proxy">The opaque_ref of the given pvs_proxy</param>
public static bool get_currently_attached(Session session, string _pvs_proxy)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pvs_proxy_get_currently_attached(session.opaque_ref, _pvs_proxy);
else
return (bool)session.proxy.pvs_proxy_get_currently_attached(session.opaque_ref, _pvs_proxy ?? "").parse();
}
/// <summary>
/// Get the status field of the given PVS_proxy.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pvs_proxy">The opaque_ref of the given pvs_proxy</param>
public static pvs_proxy_status get_status(Session session, string _pvs_proxy)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pvs_proxy_get_status(session.opaque_ref, _pvs_proxy);
else
return (pvs_proxy_status)Helper.EnumParseDefault(typeof(pvs_proxy_status), (string)session.proxy.pvs_proxy_get_status(session.opaque_ref, _pvs_proxy ?? "").parse());
}
/// <summary>
/// Configure a VM/VIF to use a PVS proxy
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_site">PVS site that we proxy for</param>
/// <param name="_vif">VIF for the VM that needs to be proxied</param>
public static XenRef<PVS_proxy> create(Session session, string _site, string _vif)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pvs_proxy_create(session.opaque_ref, _site, _vif);
else
return XenRef<PVS_proxy>.Create(session.proxy.pvs_proxy_create(session.opaque_ref, _site ?? "", _vif ?? "").parse());
}
/// <summary>
/// Configure a VM/VIF to use a PVS proxy
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_site">PVS site that we proxy for</param>
/// <param name="_vif">VIF for the VM that needs to be proxied</param>
public static XenRef<Task> async_create(Session session, string _site, string _vif)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_pvs_proxy_create(session.opaque_ref, _site, _vif);
else
return XenRef<Task>.Create(session.proxy.async_pvs_proxy_create(session.opaque_ref, _site ?? "", _vif ?? "").parse());
}
/// <summary>
/// remove (or switch off) a PVS proxy for this VM
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pvs_proxy">The opaque_ref of the given pvs_proxy</param>
public static void destroy(Session session, string _pvs_proxy)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.pvs_proxy_destroy(session.opaque_ref, _pvs_proxy);
else
session.proxy.pvs_proxy_destroy(session.opaque_ref, _pvs_proxy ?? "").parse();
}
/// <summary>
/// remove (or switch off) a PVS proxy for this VM
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pvs_proxy">The opaque_ref of the given pvs_proxy</param>
public static XenRef<Task> async_destroy(Session session, string _pvs_proxy)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_pvs_proxy_destroy(session.opaque_ref, _pvs_proxy);
else
return XenRef<Task>.Create(session.proxy.async_pvs_proxy_destroy(session.opaque_ref, _pvs_proxy ?? "").parse());
}
/// <summary>
/// Return a list of all the PVS_proxys known to the system.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
public static List<XenRef<PVS_proxy>> get_all(Session session)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pvs_proxy_get_all(session.opaque_ref);
else
return XenRef<PVS_proxy>.Create(session.proxy.pvs_proxy_get_all(session.opaque_ref).parse());
}
/// <summary>
/// Get all the PVS_proxy Records at once, in a single XML RPC call
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
public static Dictionary<XenRef<PVS_proxy>, PVS_proxy> get_all_records(Session session)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pvs_proxy_get_all_records(session.opaque_ref);
else
return XenRef<PVS_proxy>.Create<Proxy_PVS_proxy>(session.proxy.pvs_proxy_get_all_records(session.opaque_ref).parse());
}
/// <summary>
/// Unique identifier/object reference
/// </summary>
public virtual string uuid
{
get { return _uuid; }
set
{
if (!Helper.AreEqual(value, _uuid))
{
_uuid = value;
Changed = true;
NotifyPropertyChanged("uuid");
}
}
}
private string _uuid = "";
/// <summary>
/// PVS site this proxy is part of
/// </summary>
[JsonConverter(typeof(XenRefConverter<PVS_site>))]
public virtual XenRef<PVS_site> site
{
get { return _site; }
set
{
if (!Helper.AreEqual(value, _site))
{
_site = value;
Changed = true;
NotifyPropertyChanged("site");
}
}
}
private XenRef<PVS_site> _site = new XenRef<PVS_site>("OpaqueRef:NULL");
/// <summary>
/// VIF of the VM using the proxy
/// </summary>
[JsonConverter(typeof(XenRefConverter<VIF>))]
public virtual XenRef<VIF> VIF
{
get { return _VIF; }
set
{
if (!Helper.AreEqual(value, _VIF))
{
_VIF = value;
Changed = true;
NotifyPropertyChanged("VIF");
}
}
}
private XenRef<VIF> _VIF = new XenRef<VIF>("OpaqueRef:NULL");
/// <summary>
/// true = VM is currently proxied
/// </summary>
public virtual bool currently_attached
{
get { return _currently_attached; }
set
{
if (!Helper.AreEqual(value, _currently_attached))
{
_currently_attached = value;
Changed = true;
NotifyPropertyChanged("currently_attached");
}
}
}
private bool _currently_attached = false;
/// <summary>
/// The run-time status of the proxy
/// </summary>
[JsonConverter(typeof(pvs_proxy_statusConverter))]
public virtual pvs_proxy_status status
{
get { return _status; }
set
{
if (!Helper.AreEqual(value, _status))
{
_status = value;
Changed = true;
NotifyPropertyChanged("status");
}
}
}
private pvs_proxy_status _status = pvs_proxy_status.stopped;
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using ToolKit.Data;
using Xunit;
namespace UnitTests.Data
{
public class MyOtherValueObject : ValueObject
{
public MyOtherValueObject(int value1, string value2)
{
MyValue1 = value1;
MyValue2 = value2;
}
public int MyValue1 { get; set; }
public string MyValue2 { get; set; }
protected override IEnumerable<object> GetPropertyValues()
{
yield return MyValue1;
yield return MyValue2;
}
}
[SuppressMessage(
"StyleCop.CSharp.DocumentationRules",
"SA1600:ElementsMustBeDocumented",
Justification = "Test Suites do not need XML Documentation.")]
public class ValueObjectTests
{
[Fact]
public void EqualOperator_Should_ReturnFalse_When_LeftIsNull()
{
// Arrange
var value1 = new MyValueObject(10, "Unit Tests");
// Act
var actual = MyValueObject.TestEqualOperator(null, value1);
// Assert
Assert.False(actual);
}
[Fact]
public void EqualOperator_Should_ReturnFalse_When_RightIsNull()
{
// Arrange
var value1 = new MyValueObject(10, "Unit Tests");
// Act
var actual = MyValueObject.TestEqualOperator(value1, null);
// Assert
Assert.False(actual);
}
[Fact]
public void EqualOperator_Should_ReturnTrue_When_BothAreNull()
{
// Arrange & Act
var actual = MyValueObject.TestEqualOperator(null, null);
// Assert
Assert.True(actual);
}
[Fact]
public void EqualOperator_Should_ReturnTrueWithSameValues()
{
// Arrange
var value1 = new MyValueObject(10, "Unit Tests");
var value2 = new MyValueObject(10, "Unit Tests");
// Act
var actual = MyValueObject.TestEqualOperator(value1, value2);
// Assert
Assert.True(actual);
}
[Fact]
public void Equals_Should_ReturnFalse_When_TwoDifferentTypesButSameProperties()
{
// Arrange
var value1 = new MyValueObject(10, "Unit Tests");
var value2 = new MyOtherValueObject(10, "Unit Tests");
// Act
var actual = value1.Equals(value2);
// Assert
Assert.False(actual);
}
[Fact]
public void Equals_Should_ReturnFalseWithDifferentValues()
{
// Arrange
var value1 = new MyValueObject(10, "Unit Tests");
var value2 = new MyValueObject(10, "Unit Tests For Life1");
// Act
var actual = value1.Equals(value2);
// Assert
Assert.False(actual);
}
[Fact]
public void Equals_Should_ReturnFalseWithNull()
{
// Arrange
var value1 = new MyValueObject(10, "Unit Tests");
// Act
var actual = value1.Equals(null);
// Assert
Assert.False(actual);
}
[Fact]
public void Equals_Should_ReturnTrue_When_BothHaveSameValuesButPassedasObject()
{
// Arrange
var value1 = new MyValueObject(10, "Unit Tests");
var value2 = new MyValueObject(10, "Unit Tests");
// Act
var actual = value1.Equals((object)value2);
// Assert
Assert.True(actual);
}
[Fact]
public void Equals_Should_ReturnTrue_When_OtherObjectIsSame()
{
// Arrange
var value1 = new MyValueObject(10, "Unit Tests");
// Act
var actual = value1.Equals(value1);
// Assert
Assert.True(actual);
}
[Fact]
public void Equals_Should_ReturnTrueWithSameValues()
{
// Arrange
var value1 = new MyValueObject(10, "Unit Tests");
var value2 = new MyValueObject(10, "Unit Tests");
// Act
var actual = value1.Equals(value2);
// Assert
Assert.True(actual);
}
[Fact]
public void GetCopy_Should_StillBeEqual()
{
// Arrange & Act
var value1 = new MyValueObject(10, "Unit Tests");
var value2 = value1.GetCopy();
// Assert
Assert.Equal(value1, value2);
}
[Fact]
public void GetHashCode_Should_ReturnSameValues()
{
// Arrange
var value1 = new MyValueObject(10, "Unit Tests");
var value2 = new MyValueObject(10, "Unit Tests");
// Act & Assert
Assert.Equal(value1.GetHashCode(), value2.GetHashCode());
}
[Fact]
public void GetHashCode_Should_ReturnValue_WhenItContainsNullProperties()
{
// Arrange
const int expected = 512;
var value1 = new MyValueObject(512, null);
// Act
var actual = value1.GetHashCode();
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void NotEqualExplicitOperator_Should_ReturnFalseWithSameValues()
{
// Arrange
var value1 = new MyValueObject(10, "Unit Tests");
var value2 = new MyValueObject(10, "Unit Tests");
// Act
var actual = value1 != value2;
// Assert
Assert.False(actual);
}
[Fact]
public void NotEqualOperator_Should_ReturnFalseWithSameValues()
{
// Arrange
var value1 = new MyValueObject(10, "Unit Tests");
var value2 = new MyValueObject(10, "Unit Tests");
// Act
var actual = MyValueObject.TestNotEqualOperator(value1, value2);
// Assert
Assert.False(actual);
}
public class MyValueObject : ValueObject
{
public MyValueObject(int value1, string value2)
{
MyValue1 = value1;
MyValue2 = value2;
}
public int MyValue1 { get; set; }
public string MyValue2 { get; set; }
public static bool TestEqualOperator(ValueObject left, ValueObject right)
=> ValueObject.EqualOperator(left, right);
public static bool TestNotEqualOperator(ValueObject left, ValueObject right)
=> ValueObject.NotEqualOperator(left, right);
protected override IEnumerable<object> GetPropertyValues()
{
yield return MyValue1;
yield return MyValue2;
}
}
}
}
| |
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Chutzpah.FrameworkDefinitions;
using Chutzpah.Models;
using Chutzpah.Wrappers;
using Moq;
using Xunit;
namespace Chutzpah.Facts
{
public class ReferenceProcessorFacts
{
private class TestableReferenceProcessor : Testable<ReferenceProcessor>
{
public IFrameworkDefinition FrameworkDefinition { get; set; }
public TestableReferenceProcessor()
{
var frameworkMock = Mock<IFrameworkDefinition>();
frameworkMock.Setup(x => x.FileUsesFramework(It.IsAny<string>(), It.IsAny<bool>(), It.IsAny<PathType>())).Returns(true);
frameworkMock.Setup(x => x.FrameworkKey).Returns("qunit");
frameworkMock.Setup(x => x.GetTestRunner(It.IsAny<ChutzpahTestSettingsFile>())).Returns("qunitRunner.js");
frameworkMock.Setup(x => x.GetTestHarness(It.IsAny<ChutzpahTestSettingsFile>())).Returns("qunit.html");
frameworkMock.Setup(x => x.GetFileDependencies(It.IsAny<ChutzpahTestSettingsFile>())).Returns(new[] { "qunit.js", "qunit.css" });
FrameworkDefinition = frameworkMock.Object;
Mock<IFileProbe>().Setup(x => x.FindFilePath(It.IsAny<string>())).Returns<string>(x => x);
Mock<IFileSystemWrapper>().Setup(x => x.GetText(It.IsAny<string>())).Returns(string.Empty);
}
}
public class SetupAmdFilePaths
{
[Fact]
public void Will_set_amd_path_for_reference_path()
{
var processor = new TestableReferenceProcessor();
var testHarnessDirectory = @"c:\some\path";
var referencedFile = new ReferencedFile {Path = @"C:\some\path\code\test.js"};
var referenceFiles = new List<ReferencedFile> { referencedFile };
processor.ClassUnderTest.SetupAmdFilePaths(referenceFiles,testHarnessDirectory, new ChutzpahTestSettingsFile().InheritFromDefault());
Assert.Equal("code/test",referencedFile.AmdFilePath);
Assert.Null(referencedFile.AmdGeneratedFilePath);
}
[Fact]
public void Will_make_amd_path_relative_to_amdbaseurl_if_no_amdappdirectory_if_given()
{
var processor = new TestableReferenceProcessor();
var testHarnessDirectory = @"c:\some\path";
var referencedFile = new ReferencedFile { Path = @"C:\some\path\code\test.js" };
var referenceFiles = new List<ReferencedFile> { referencedFile };
var settings = new ChutzpahTestSettingsFile { AMDBaseUrl = @"C:\some\other" };
processor.ClassUnderTest.SetupAmdFilePaths(referenceFiles, testHarnessDirectory, settings);
Assert.Equal("../path/code/test", referencedFile.AmdFilePath);
Assert.Null(referencedFile.AmdGeneratedFilePath);
}
[Fact]
public void Will_make_amd_path_relative_to_amdappdirectory_if_given()
{
var processor = new TestableReferenceProcessor();
var testHarnessDirectory = @"c:\some\path";
var referencedFile = new ReferencedFile { Path = @"C:\some\path\code\test.js" };
var referenceFiles = new List<ReferencedFile> { referencedFile };
var settings = new ChutzpahTestSettingsFile { AMDAppDirectory = @"C:\some\other" };
processor.ClassUnderTest.SetupAmdFilePaths(referenceFiles, testHarnessDirectory, settings);
Assert.Equal("../path/code/test", referencedFile.AmdFilePath);
Assert.Null(referencedFile.AmdGeneratedFilePath);
}
[Fact]
public void Will_make_amd_path_relative_to_amdbasepath_with_legacy_setting()
{
var processor = new TestableReferenceProcessor();
var testHarnessDirectory = @"c:\some\path";
var referencedFile = new ReferencedFile { Path = @"C:\some\path\code\test.js" };
var referenceFiles = new List<ReferencedFile> { referencedFile };
var settings = new ChutzpahTestSettingsFile {AMDBasePath = @"C:\some\other"};
processor.ClassUnderTest.SetupAmdFilePaths(referenceFiles, testHarnessDirectory, settings);
Assert.Equal("../path/code/test", referencedFile.AmdFilePath);
Assert.Null(referencedFile.AmdGeneratedFilePath);
}
[Fact]
public void Will_make_amd_path_relative_to_testHarnessLocation()
{
var processor = new TestableReferenceProcessor();
var testHarnessDirectory = @"c:\some\src\folder";
var referencedFile = new ReferencedFile { Path = @"C:\some\path\code\test.js" };
var referenceFiles = new List<ReferencedFile> { referencedFile };
var settings = new ChutzpahTestSettingsFile { };
processor.ClassUnderTest.SetupAmdFilePaths(referenceFiles, testHarnessDirectory, settings);
Assert.Equal("../../path/code/test", referencedFile.AmdFilePath);
Assert.Null(referencedFile.AmdGeneratedFilePath);
}
[Fact]
public void Will_make_amd_path_relative_to_testHarnessLocation_and_amdbasepath()
{
var processor = new TestableReferenceProcessor();
var testHarnessDirectory = @"c:\some\path\subFolder";
var referencedFile = new ReferencedFile { Path = @"C:\some\path\code\test.js" };
var referenceFiles = new List<ReferencedFile> { referencedFile };
var settings = new ChutzpahTestSettingsFile { AMDBasePath = @"C:\some\other" };
processor.ClassUnderTest.SetupAmdFilePaths(referenceFiles, testHarnessDirectory, settings);
Assert.Equal("../path/subFolder/../code/test", referencedFile.AmdFilePath);
Assert.Null(referencedFile.AmdGeneratedFilePath);
}
[Fact]
public void Will_set_amd_path_ignoring_the_case()
{
var processor = new TestableReferenceProcessor();
var testHarnessDirectory = @"C:\Some\Path";
var referencedFile = new ReferencedFile { Path = @"C:\some\path\code\test.js" };
var referenceFiles = new List<ReferencedFile> { referencedFile };
processor.ClassUnderTest.SetupAmdFilePaths(referenceFiles, testHarnessDirectory, new ChutzpahTestSettingsFile().InheritFromDefault());
Assert.Equal("code/test", referencedFile.AmdFilePath);
Assert.Null(referencedFile.AmdGeneratedFilePath);
}
[Fact]
public void Will_set_amd_path_for_reference_path_and_generated_path()
{
var processor = new TestableReferenceProcessor();
var testHarnessDirectory = @"C:\some\path";
var referencedFile = new ReferencedFile { Path = @"C:\some\path\code\test.ts", GeneratedFilePath = @"C:\some\path\code\_Chutzpah.1.test.js" };
var referenceFiles = new List<ReferencedFile> { referencedFile };
processor.ClassUnderTest.SetupAmdFilePaths(referenceFiles, testHarnessDirectory, new ChutzpahTestSettingsFile().InheritFromDefault());
Assert.Equal("code/test", referencedFile.AmdFilePath);
}
}
public class GetReferencedFiles
{
[Fact]
public void Will_add_reference_file_to_referenced_files()
{
var processor = new TestableReferenceProcessor();
var settings = new ChutzpahTestSettingsFile { }.InheritFromDefault();
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path\test.js", ExpandReferenceComments = true } };
var text = (@"/// <reference path=""lib.js"" />
some javascript code");
processor.Mock<IFileSystemWrapper>().Setup(x => x.GetText(@"path\test.js")).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
Assert.True(referenceFiles.Any(x => x.Path == @"path\lib.js" && x.IncludeInTestHarness));
}
[Fact]
public void Will_handle_multiple_test_files()
{
var processor = new TestableReferenceProcessor();
var settings = new ChutzpahTestSettingsFile { }.InheritFromDefault();
var referenceFiles = new List<ReferencedFile> {
new ReferencedFile { IsFileUnderTest = true, Path = @"path\test1.js", ExpandReferenceComments = true },
new ReferencedFile { IsFileUnderTest = true, Path = @"path\test2.js", ExpandReferenceComments = true }};
var text = (@"/// <reference path=""lib.js"" />
some javascript code");
processor.Mock<IFileSystemWrapper>().Setup(x => x.GetText(@"path\test1.js")).Returns(text);
processor.Mock<IFileSystemWrapper>().Setup(x => x.GetText(@"path\test2.js")).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
Assert.Equal(2, referenceFiles.Count(x => x.IsFileUnderTest));
}
[Fact]
public void Will_exclude_reference_from_harness_in_amd_mode()
{
var processor = new TestableReferenceProcessor();
var settings = new ChutzpahTestSettingsFile { }.InheritFromDefault();
settings.TestHarnessReferenceMode = TestHarnessReferenceMode.AMD;
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path\test.js", ExpandReferenceComments = true } };
var text = (@"/// <reference path=""lib.js"" />
some javascript code");
processor.Mock<IFileSystemWrapper>().Setup(x => x.GetText(@"path\test.js")).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
Assert.True(referenceFiles.Any(x => x.Path == @"path\lib.js" && !x.IncludeInTestHarness));
}
[Fact]
public void Will_change_path_root_given_SettingsFileDirectory_RootReferencePathMode()
{
var processor = new TestableReferenceProcessor();
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path1\test.js", ExpandReferenceComments = true } };
var settings = new ChutzpahTestSettingsFile
{
RootReferencePathMode = RootReferencePathMode.SettingsFileDirectory,
SettingsFileDirectory = @"C:\root"
};
var text = @"/// <reference path=""/this/file.js"" />
some javascript code
";
processor.Mock<IFileSystemWrapper>().Setup(x => x.GetText(@"path1\test.js")).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
Assert.True(referenceFiles.Any(x => x.Path.Equals(@"C:\root/this/file.js")));
}
[Fact]
public void Will_change_path_root_given_even_if_has_tilde()
{
var processor = new TestableReferenceProcessor();
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path1\test.js", ExpandReferenceComments = true } };
var settings = new ChutzpahTestSettingsFile
{
RootReferencePathMode = RootReferencePathMode.SettingsFileDirectory,
SettingsFileDirectory = @"C:\root"
};
var text = @"/// <reference path=""~/this/file.js"" />
some javascript code
";
processor.Mock<IFileSystemWrapper>().Setup(x => x.GetText(@"path1\test.js")).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
Assert.True(referenceFiles.Any(x => x.Path.Equals(@"C:\root/this/file.js")));
}
[Fact]
public void Will_not_change_path_root_given_SettingsFileDirectory_RootReferencePathMode()
{
var processor = new TestableReferenceProcessor();
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path1\test.js", ExpandReferenceComments = true } };
var settings = new ChutzpahTestSettingsFile {RootReferencePathMode = RootReferencePathMode.DriveRoot, SettingsFileDirectory = @"C:\root"};
var text = @"/// <reference path=""/this/file.js"" />
some javascript code
";
processor.Mock<IFileSystemWrapper>().Setup(x => x.GetText(@"path1\test.js")).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
Assert.True(referenceFiles.Any(x => x.Path.Equals(@"/this/file.js")));
}
[Fact]
public void Will_change_path_root_given_SettingsFileDirectory_RootReferencePathMode_for_html_file()
{
var processor = new TestableReferenceProcessor();
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path1\test.js", ExpandReferenceComments = true } };
var settings = new ChutzpahTestSettingsFile
{
RootReferencePathMode = RootReferencePathMode.SettingsFileDirectory,
SettingsFileDirectory = @"C:\root"
};
var text = @"/// <reference path=""/this/file.html"" />
some javascript code
";
processor.Mock<IFileSystemWrapper>().Setup(x => x.GetText(@"path1\test.js")).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
Assert.True(referenceFiles.Any(x => x.Path.Equals(@"C:\root/this/file.html")));
}
[Fact]
public void Will_not_add_referenced_file_if_it_is_excluded()
{
var processor = new TestableReferenceProcessor();
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path1\test.js", ExpandReferenceComments = true } };
var settings = new ChutzpahTestSettingsFile {};
var text = @"/// <reference path=""lib.js"" />
/// <reference path=""../../js/excluded.js"" chutzpah-exclude=""true"" />
/// <reference path=""../../js/doublenegative.js"" chutzpah-exclude=""false"" />
/// <reference path=""../../js/excluded.js"" chutzpahExclude=""true"" />
/// <reference path=""../../js/doublenegative.js"" chutzpahExclude=""false"" />
some javascript code
";
processor.Mock<IFileSystemWrapper>().Setup(x => x.GetText(@"path1\test.js")).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
Assert.False(referenceFiles.Any(x => x.Path.EndsWith("excluded.js")), "Test context contains excluded reference.");
Assert.True(referenceFiles.Any(x => x.Path.EndsWith("doublenegative.js")), "Test context does not contain negatively excluded reference.");
}
[Fact]
public void Will_put_recursively_referenced_files_before_parent_file()
{
var processor = new TestableReferenceProcessor();
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path\test.js", ExpandReferenceComments = true } };
var settings = new ChutzpahTestSettingsFile {};
processor.Mock<IFileProbe>()
.Setup(x => x.FindFilePath(Path.Combine(@"path\", @"../../js/references.js")))
.Returns(@"path\references.js");
processor.Mock<IFileSystemWrapper>()
.Setup(x => x.GetText(@"path\references.js"))
.Returns(@"/// <reference path=""lib.js"" />");
string text = @"/// <reference path=""../../js/references.js"" />
some javascript code
";
processor.Mock<IFileSystemWrapper>().Setup(x => x.GetText(@"path\test.js")).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
var ref1 = referenceFiles.First(x => x.Path == @"path\lib.js");
var ref2 = referenceFiles.First(x => x.Path == @"path\references.js");
var pos1 = referenceFiles.IndexOf(ref1);
var pos2 = referenceFiles.IndexOf(ref2);
Assert.True(pos1 < pos2);
}
[Fact(Timeout = 5000)]
public void Will_stop_infinite_loop_when_processing_referenced_files()
{
var processor = new TestableReferenceProcessor();
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path\test.js", ExpandReferenceComments = true } };
var settings = new ChutzpahTestSettingsFile {};
var text = @"/// <reference path=""../../js/references.js"" />
some javascript code
";
var loopText = @"/// <reference path=""../../js/references.js"" />";
processor.Mock<IFileSystemWrapper>().Setup(x => x.GetText(@"path\test.js")).Returns(text);
processor.Mock<IFileSystemWrapper>()
.Setup(x => x.GetText(@"path\references.js"))
.Returns(loopText);
processor.Mock<IFileProbe>()
.Setup(x => x.FindFilePath(Path.Combine(@"path\", @"../../js/references.js")))
.Returns(@"path\references.js");
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
Assert.True(referenceFiles.Any(x => x.Path == @"path\references.js"));
}
[Fact]
public void Will_process_all_files_in_folder_references()
{
var processor = new TestableReferenceProcessor();
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path\test.js", ExpandReferenceComments = true } };
var settings = new ChutzpahTestSettingsFile {};
processor.Mock<IFileProbe>()
.Setup(x => x.FindFilePath(Path.Combine(@"path\", @"../../js/somefolder")))
.Returns((string) null);
processor.Mock<IFileProbe>()
.Setup(x => x.FindFolderPath(Path.Combine(@"path\", @"../../js/somefolder")))
.Returns(@"path\someFolder");
processor.Mock<IFileSystemWrapper>()
.Setup(x => x.GetFiles(@"path\someFolder", "*.*", SearchOption.AllDirectories))
.Returns(new[] {@"path\subFile.js"});
var text = @"/// <reference path=""../../js/somefolder"" />
some javascript code
";
processor.Mock<IFileSystemWrapper>().Setup(x => x.GetText(@"path\test.js")).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
Assert.True(referenceFiles.Any(x => x.Path == @"path\subFile.js"));
}
[Fact]
public void Will_skip_chutzpah_temporary_files_in_folder_references()
{
var processor = new TestableReferenceProcessor();
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path\test.js", ExpandReferenceComments = true } };
var settings = new ChutzpahTestSettingsFile {};
processor.Mock<IFileProbe>()
.Setup(x => x.FindFilePath(Path.Combine(@"path\", @"../../js/somefolder")))
.Returns((string) null);
processor.Mock<IFileProbe>()
.Setup(x => x.FindFolderPath(Path.Combine(@"path\", @"../../js/somefolder")))
.Returns(@"path\someFolder");
processor.Mock<IFileSystemWrapper>()
.Setup(x => x.GetFiles(@"path\someFolder", "*.*", SearchOption.AllDirectories))
.Returns(new[] {@"path\subFile.js"});
var text = @"/// <reference path=""../../js/somefolder"" />
some javascript code
";
processor.Mock<IFileProbe>().Setup(x => x.IsTemporaryChutzpahFile(It.IsAny<string>())).Returns(true);
processor.Mock<IFileSystemWrapper>().Setup(x => x.GetText(@"path\test.js")).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
Assert.False(referenceFiles.Any(x => x.Path == @"path\subFile.js"));
}
[Fact]
public void Will_only_include_one_reference_with_mulitple_references_in_html_template()
{
var processor = new TestableReferenceProcessor();
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path\test.js", ExpandReferenceComments = true } };
var settings = new ChutzpahTestSettingsFile {};
var text = (@"/// <template path=""../../templates/file.html"" />
/// <template path=""../../templates/file.html"" />
some javascript code");
processor.Mock<IFileSystemWrapper>().Setup(x => x.GetText(@"path\test.js")).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
Assert.Equal(1, referenceFiles.Count(x => x.Path.EndsWith("file.html")));
}
[Fact]
public void Will_add_reference_url_to_referenced_files()
{
var processor = new TestableReferenceProcessor();
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path\test.js", ExpandReferenceComments = true } };
var settings = new ChutzpahTestSettingsFile {};
var text = (@"/// <reference path=""http://a.com/lib.js"" />
some javascript code");
processor.Mock<IFileSystemWrapper>().Setup(x => x.GetText(@"path\test.js")).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
Assert.True(referenceFiles.Any(x => x.Path == "http://a.com/lib.js"));
}
[Fact]
public void Will_add_chutzpah_reference_to_referenced_files()
{
var processor = new TestableReferenceProcessor();
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path\test.js", ExpandReferenceComments = true } };
var settings = new ChutzpahTestSettingsFile {};
var text = (@"/// <chutzpah_reference path=""lib.js"" />
some javascript code");
processor.Mock<IFileSystemWrapper>().Setup(x => x.GetText(@"path\test.js")).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
Assert.True(referenceFiles.Any(x => x.Path.EndsWith("lib.js")));
}
[Fact]
public void Will_add_file_from_settings_referenced_files()
{
var processor = new TestableReferenceProcessor();
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path\test.js" } };
var settings = new ChutzpahTestSettingsFile {};
processor.Mock<IFileSystemWrapper>().Setup(x => x.FolderExists(It.IsAny<string>())).Returns(true);
settings.SettingsFileDirectory = @"c:\dir";
settings.References.Add(
new SettingsFileReference
{
Path = "here.js",
SettingsFileDirectory = settings.SettingsFileDirectory
});
var text = (@"some javascript code");
processor.Mock<IFileSystemWrapper>().Setup(x => x.GetText(@"path\test.js")).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
Assert.True(referenceFiles.Any(x => x.Path == @"c:\dir\here.js" && x.IncludeInTestHarness));
}
[Fact]
public void Will_default_path_to_settings_folder_when_adding_from_settings_references()
{
var processor = new TestableReferenceProcessor();
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path\test.js" } };
var settings = new ChutzpahTestSettingsFile().InheritFromDefault();
processor.Mock<IFileSystemWrapper>().Setup(x => x.FolderExists(It.IsAny<string>())).Returns(true);
processor.Mock<IFileProbe>().Setup(x => x.FindFilePath(@"c:\settingsDir")).Returns<string>(null);
processor.Mock<IFileProbe>().Setup(x => x.FindFolderPath(@"c:\settingsDir")).Returns(@"c:\settingsDir");
processor.Mock<IFileSystemWrapper>()
.Setup(x => x.GetFiles(@"c:\settingsDir", "*.*", SearchOption.AllDirectories))
.Returns(new[] { @"settingsDir\subFile.js", @"settingsDir\newFile.js", @"other\subFile.js" });
settings.SettingsFileDirectory = @"c:\settingsDir";
settings.References.Add(
new SettingsFileReference
{
Path = null,
Include = "*subFile.js",
SettingsFileDirectory = settings.SettingsFileDirectory
});
var text = (@"some javascript code");
processor.Mock<IFileSystemWrapper>().Setup(x => x.GetText(@"path\test.js")).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
Assert.True(referenceFiles.Any(x => x.Path == @"settingsDir\subFile.js"));
Assert.False(referenceFiles.Any(x => x.Path == @"path\subFile.js"));
Assert.False(referenceFiles.Any(x => x.Path == @"path\newFile.js"));
}
[Fact]
public void Will_exclude_from_test_harness_given_setting()
{
var processor = new TestableReferenceProcessor();
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path\test.js" } };
var settings = new ChutzpahTestSettingsFile {};
processor.Mock<IFileSystemWrapper>().Setup(x => x.FolderExists(It.IsAny<string>())).Returns(true);
settings.SettingsFileDirectory = @"c:\dir";
settings.TestHarnessReferenceMode = TestHarnessReferenceMode.AMD;
settings.References.Add(
new SettingsFileReference
{
Path = "here.js",
IncludeInTestHarness = true,
SettingsFileDirectory = settings.SettingsFileDirectory
});
var text = (@"some javascript code");
processor.Mock<IFileSystemWrapper>().Setup(x => x.GetText(@"path\test.js")).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
Assert.True(referenceFiles.Any(x => x.Path == @"c:\dir\here.js" && x.IncludeInTestHarness));
}
[Fact]
public void Will_add_files_from_folder_from_settings_referenced_files()
{
var processor = new TestableReferenceProcessor();
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path\test.js" } };
var settings = new ChutzpahTestSettingsFile {};
processor.Mock<IFileSystemWrapper>().Setup(x => x.FolderExists(It.IsAny<string>())).Returns(true);
processor.Mock<IFileProbe>().Setup(x => x.FindFilePath(@"c:\dir\here")).Returns<string>(null);
processor.Mock<IFileProbe>().Setup(x => x.FindFolderPath(@"c:\dir\here")).Returns(@"c:\dir\here");
processor.Mock<IFileSystemWrapper>()
.Setup(x => x.GetFiles(@"c:\dir\here", "*.*", SearchOption.AllDirectories))
.Returns(new[] {@"path\subFile.js", @"path\newFile.js"});
settings.SettingsFileDirectory = @"c:\dir";
settings.References.Add(
new SettingsFileReference
{
Path = "here",
SettingsFileDirectory = settings.SettingsFileDirectory
});
var text = (@"some javascript code");
processor.Mock<IFileSystemWrapper>().Setup(x => x.GetText(@"path\test.js")).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
Assert.True(referenceFiles.Any(x => x.Path == @"path\subFile.js"));
Assert.True(referenceFiles.Any(x => x.Path == @"path\newFile.js"));
}
[Fact]
public void Will_exclude_files_from_folder_from_settings_referenced_files_if_match_exclude_path()
{
var processor = new TestableReferenceProcessor();
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path\test.js" } };
var settings = new ChutzpahTestSettingsFile {};
processor.Mock<IFileSystemWrapper>().Setup(x => x.FolderExists(It.IsAny<string>())).Returns(true);
processor.Mock<IFileProbe>().Setup(x => x.FindFilePath(@"c:\dir\here")).Returns<string>(null);
processor.Mock<IFileProbe>().Setup(x => x.FindFolderPath(@"c:\dir\here")).Returns(@"c:\dir\here");
processor.Mock<IFileSystemWrapper>()
.Setup(x => x.GetFiles(@"c:\dir\here", "*.*", SearchOption.AllDirectories))
.Returns(new[] {@"path\subFile.js", @"path\newFile.js"});
settings.SettingsFileDirectory = @"c:\dir";
settings.References.Add(
new SettingsFileReference
{
Path = "here",
Exclude = @"*path\sub*",
SettingsFileDirectory = settings.SettingsFileDirectory
});
var text = (@"some javascript code");
processor.Mock<IFileSystemWrapper>().Setup(x => x.GetText(@"path\test.js")).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
Assert.True(referenceFiles.Any(x => x.Path == @"path\newFile.js"));
Assert.False(referenceFiles.Any(x => x.Path == @"path\subFile.js"));
}
[Fact]
public void Will_exclude_files_from_folder_from_settings_referenced_files_if_they_dont_match_include_path()
{
var processor = new TestableReferenceProcessor();
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path\test.js" } };
var settings = new ChutzpahTestSettingsFile {};
processor.Mock<IFileSystemWrapper>().Setup(x => x.FolderExists(It.IsAny<string>())).Returns(true);
processor.Mock<IFileProbe>().Setup(x => x.FindFilePath(@"c:\dir\here")).Returns<string>(null);
processor.Mock<IFileProbe>().Setup(x => x.FindFolderPath(@"c:\dir\here")).Returns(@"c:\dir\here");
processor.Mock<IFileSystemWrapper>()
.Setup(x => x.GetFiles(@"c:\dir\here", "*.*", SearchOption.AllDirectories))
.Returns(new[] {@"path\subFile.js", @"path\newFile.js"});
settings.SettingsFileDirectory = @"c:\dir";
settings.References.Add(
new SettingsFileReference
{
Path = "here",
Include = @"*path\sub*",
SettingsFileDirectory = settings.SettingsFileDirectory
});
var text = (@"some javascript code");
processor.Mock<IFileSystemWrapper>().Setup(x => x.GetText(@"path\test.js")).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
Assert.False(referenceFiles.Any(x => x.Path == @"path\newFile.js"));
Assert.True(referenceFiles.Any(x => x.Path == @"path\subFile.js"));
}
[Fact]
public void Will_exclude_files_from_folder_from_settings_referenced_files_if_match_exclude_path_and_dont_match_include()
{
var processor = new TestableReferenceProcessor();
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path\test.js" } };
var settings = new ChutzpahTestSettingsFile {};
processor.Mock<IFileSystemWrapper>().Setup(x => x.FolderExists(It.IsAny<string>())).Returns(true);
processor.Mock<IFileProbe>().Setup(x => x.FindFilePath(@"c:\dir\here")).Returns<string>(null);
processor.Mock<IFileProbe>().Setup(x => x.FindFolderPath(@"c:\dir\here")).Returns(@"c:\dir\here");
processor.Mock<IFileSystemWrapper>()
.Setup(x => x.GetFiles(@"c:\dir\here", "*.*", SearchOption.AllDirectories))
.Returns(new[] {@"path\parentFile.js", @"other\newFile.js", @"path\sub\childFile.js"});
settings.SettingsFileDirectory = @"c:\dir";
settings.References.Add(
new SettingsFileReference
{
Path = "here",
Include = @"path\*",
Exclude = @"*path\pare*",
SettingsFileDirectory = settings.SettingsFileDirectory
});
var text = (@"some javascript code");
processor.Mock<IFileSystemWrapper>().Setup(x => x.GetText(@"path\test.js")).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
Assert.True(referenceFiles.Any(x => x.Path == @"path\sub\childFile.js"));
Assert.False(referenceFiles.Any(x => x.Path == @"path\parentFile.js"));
Assert.False(referenceFiles.Any(x => x.Path == @"other\newFile.js"));
}
[Fact]
public void Will_exclude_files_from_folder_from_settings_referenced_files_if_match_excludes_path_and_dont_match_include()
{
var processor = new TestableReferenceProcessor();
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path\test.js" } };
var settings = new ChutzpahTestSettingsFile { };
processor.Mock<IFileSystemWrapper>().Setup(x => x.FolderExists(It.IsAny<string>())).Returns(true);
processor.Mock<IFileProbe>().Setup(x => x.FindFilePath(@"c:\dir\here")).Returns<string>(null);
processor.Mock<IFileProbe>().Setup(x => x.FindFolderPath(@"c:\dir\here")).Returns(@"c:\dir\here");
processor.Mock<IFileSystemWrapper>()
.Setup(x => x.GetFiles(@"c:\dir\here", "*.*", SearchOption.AllDirectories))
.Returns(new[] { @"path\parentFile.js", @"other\newFile.js", @"path\sub\childFile.js" });
settings.SettingsFileDirectory = @"c:\dir";
settings.References.Add(
new SettingsFileReference
{
Path = "here",
Includes = new[] { @"path\*", @"other\*", },
Excludes = new []{ @"*path\pare*", @"other\new*" },
SettingsFileDirectory = settings.SettingsFileDirectory
});
var text = (@"some javascript code");
processor.Mock<IFileSystemWrapper>().Setup(x => x.GetText(@"path\test.js")).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
Assert.True(referenceFiles.Any(x => x.Path == @"path\sub\childFile.js"));
Assert.False(referenceFiles.Any(x => x.Path == @"path\parentFile.js"));
Assert.False(referenceFiles.Any(x => x.Path == @"other\newFile.js"));
}
[Fact]
public void Will_normlize_paths_for_case_and_slashes_for_path_include_exclude()
{
var processor = new TestableReferenceProcessor();
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path\test.js" } };
var settings = new ChutzpahTestSettingsFile { };
processor.Mock<IFileSystemWrapper>().Setup(x => x.FolderExists(It.IsAny<string>())).Returns(true);
processor.Mock<IFileProbe>().Setup(x => x.FindFilePath(@"c:\dir\here")).Returns<string>(null);
processor.Mock<IFileProbe>().Setup(x => x.FindFolderPath(@"c:\dir\here")).Returns(@"c:\dir\here");
processor.Mock<IFileSystemWrapper>()
.Setup(x => x.GetFiles(@"c:\dir\here", "*.*", SearchOption.AllDirectories))
.Returns(new[] { @"pAth/parentFile.js", @"Other/newFile.js", @"path\sub\childFile.js" });
settings.SettingsFileDirectory = @"c:\dir";
settings.References.Add(
new SettingsFileReference
{
Path = "here",
Include = @"PATH/*",
Exclude = @"*paTh/pAre*",
SettingsFileDirectory = settings.SettingsFileDirectory
});
var text = (@"some javascript code");
processor.Mock<IFileSystemWrapper>().Setup(x => x.GetText(@"path\test.js")).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
Assert.True(referenceFiles.Any(x => x.Path == @"path\sub\childFile.js"));
Assert.False(referenceFiles.Any(x => x.Path == @"path\parentFile.js"));
Assert.False(referenceFiles.Any(x => x.Path == @"other\newFile.js"));
}
}
}
}
| |
using UnityEditor;
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.IO;
namespace Pbtk
{
namespace TileMap2D
{
/// <summary>
/// A collection of utilities for making TileMap2D tile maps
/// </summary>
public static class ConverterUtility
{
/// <summary>
/// Gets the name of the sprite asset corresponding to a size and index
/// </summary>
/// <param name="size_x">The width of the sprite</param>
/// <param name="size_y">The height of the sprite</param>
/// <param name="index">The index of the sprite</param>
/// <returns>The name of the sprite asset</returns>
public static string MakeTileSpriteAssetName(int size_x, int size_y, int index)
{
return "tile_" + size_x + "x" + size_y + "_" + index;
}
/// <summary>
/// Parses the size and index from a sprite asset name
/// </summary>
/// <param name="asset_name">The name of the sprite asset</param>
/// <param name="size_x">The width of the sprite</param>
/// <param name="size_y">The height of the sprite</param>
/// <param name="index">The index of the sprite</param>
/// <returns>Whether the name was correctly parsed</returns>
public static bool ParseTileSpriteAssetName(string asset_name, out int size_x, out int size_y, out int index)
{
string[] coords = asset_name.Split(new char[] { 'x', '_' });
size_x = 0;
size_y = 0;
index = 0;
if (coords.Length != 4)
return false;
if (coords[0] != "tile")
return false;
if (!int.TryParse(coords[1], out size_x) || !int.TryParse(coords[2], out size_y) || !int.TryParse(coords[3], out index))
return false;
return true;
}
/// <summary>
/// Makes a new tile set from an image with the given parameters
/// </summary>
/// <param name="source_system_path">The path to the original image file</param>
/// <param name="tile_set_dir">Where to put the image and tile set and look for them (asset path)</param>
/// <param name="pixels_per_unit">The ratio between pixels and units</param>
/// <param name="margin_x">The number of pixels around the edge of the image to cut around horizontally</param>
/// <param name="margin_y">The number of pixels around the edge of the image to cut around vertically</param>
/// <param name="spacing_x">The number of pixels between each tile horizontally</param>
/// <param name="spacing_y">The number of pixels between each tile vertically</param>
/// <param name="slice_size_x">The width of each tile</param>
/// <param name="slice_size_y">The height of each tile</param>
/// <param name="offset_x">The drawing offset along the X axis</param>
/// <param name="offset_y">The drawing offset along the Y axis</param>
/// <param name="transparent_color">A color to set to transparent in the image or a color with an alpha of 0 to indicate no transparent color</param>
/// <param name="flip_x_indices">Whether to flip X indices from left to right</param>
/// <param name="flip_y_indices">Whether to flip Y indices from bottom to top</param>
/// <param name="force_rebuild">Whether to rebuild sprite metadata for sprites that already exist (usually false)</param>
/// <returns>The newly-created tile set</returns>
public static TileSet SliceTileSetFromImage(
string source_system_path,
string tile_set_dir,
float pixels_per_unit,
int margin_x, int margin_y,
int spacing_x, int spacing_y,
int slice_size_x, int slice_size_y,
float offset_x, float offset_y,
Color32 transparent_color,
bool flip_x_indices,
bool flip_y_indices,
bool force_rebuild
)
{
string image_path = Pb.Path.Combine(tile_set_dir, Path.GetFileName(source_system_path));
string image_system_path = Pb.Path.AssetPathToSystemPath(image_path);
string tile_set_name = Path.GetFileNameWithoutExtension(source_system_path) + "_" + slice_size_x + "x" + slice_size_y;
string tile_set_path = Pb.Path.Combine(tile_set_dir, tile_set_name + ".asset");
string tile_set_system_path = Pb.Path.AssetPathToSystemPath(tile_set_path);
if (File.Exists(tile_set_system_path) && !force_rebuild)
return AssetDatabase.LoadAssetAtPath(tile_set_path, typeof(TileSet)) as TileSet;
if (!File.Exists(image_system_path))
{
File.Copy(source_system_path, image_system_path, false);
AssetDatabase.Refresh();
AssetDatabase.ImportAsset(image_path);
}
TextureImporter importer = AssetImporter.GetAtPath(image_path) as TextureImporter;
importer.textureType = TextureImporterType.Sprite;
importer.textureFormat = (transparent_color.a > 0 ? TextureImporterFormat.ARGB32 : TextureImporterFormat.AutomaticTruecolor);
importer.spriteImportMode = SpriteImportMode.Multiple;
importer.filterMode = FilterMode.Point;
importer.spritePivot = Vector2.zero;
importer.spritePixelsToUnits = pixels_per_unit;
importer.isReadable = (transparent_color.a > 0);
AssetDatabase.ImportAsset(image_path);
Texture2D atlas = AssetDatabase.LoadAssetAtPath(image_path, typeof(Texture2D)) as Texture2D;
int tiles_x = (atlas.width - 2 * margin_x + spacing_x) / (slice_size_x + spacing_x);
int tiles_y = (atlas.height - 2 * margin_y + spacing_y) / (slice_size_y + spacing_y);
int tile_count = tiles_x * tiles_y;
int nudge_x = atlas.width + spacing_x - 2 * margin_x - tiles_x * (slice_size_x + spacing_x);
int nudge_y = atlas.height + spacing_y - 2 * margin_y - tiles_y * (slice_size_y + spacing_y);
TileSet tile_set = Pb.Utility.Asset.GetAndEdit<TileSet>(tile_set_path);
tile_set.draw_offset = new Vector2(offset_x, offset_y);
bool reimport_required = false;
importer = AssetImporter.GetAtPath(image_path) as TextureImporter;
importer.textureType = TextureImporterType.Sprite;
importer.textureFormat = (transparent_color.a > 0 ? TextureImporterFormat.ARGB32 : TextureImporterFormat.AutomaticTruecolor);
importer.spriteImportMode = SpriteImportMode.Multiple;
importer.filterMode = FilterMode.Point;
importer.spritePivot = Vector2.zero;
importer.spritePixelsToUnits = pixels_per_unit;
importer.isReadable = (transparent_color.a > 0);
bool[] skip_tiles = new bool[tile_count];
int add_tiles = tile_count;
int add_index = 0;
if (importer.spritesheet != null)
{
add_index = importer.spritesheet.Length;
foreach (SpriteMetaData meta in importer.spritesheet)
{
int size_x = 0;
int size_y = 0;
int index = 0;
if (!ParseTileSpriteAssetName(meta.name, out size_x, out size_y, out index))
continue;
if (size_x != slice_size_x || size_y != slice_size_y)
continue;
skip_tiles[index] = true;
--add_tiles;
}
}
if (add_tiles > 0)
{
SpriteMetaData[] new_spritesheet = new SpriteMetaData[add_index + add_tiles];
System.Array.Copy(importer.spritesheet, new_spritesheet, add_index);
for (int i = 0; i < tile_count; ++i)
{
if (skip_tiles[i])
continue;
int x = i % tiles_x;
if (flip_x_indices)
x = tiles_x - x - 1;
int y = i / tiles_x;
if (flip_y_indices)
y = tiles_y - y - 1;
SpriteMetaData new_meta = new SpriteMetaData();
new_meta.alignment = (int)SpriteAlignment.Center;
new_meta.name = MakeTileSpriteAssetName(slice_size_x, slice_size_y, i);
new_meta.pivot = Vector2.zero;
new_meta.rect =
new Rect(
margin_x + x * (slice_size_x + spacing_x) + nudge_x,
margin_y + y * (slice_size_y + spacing_y) + nudge_y,
slice_size_x,
slice_size_y
);
new_spritesheet[add_index++] = new_meta;
}
importer.spritesheet = new_spritesheet;
reimport_required = true;
}
if (reimport_required)
AssetDatabase.ImportAsset(image_path);
if (transparent_color.a > 0)
{
Color32[] pixels = atlas.GetPixels32();
for (int i = 0; i < pixels.Length; ++i)
{
if (pixels[i].r == transparent_color.r && pixels[i].g == transparent_color.g && pixels[i].b == transparent_color.b && pixels[i].a == transparent_color.a)
pixels[i] = new Color32(0, 0, 0, 0);
}
atlas.SetPixels32(pixels);
atlas.Apply();
File.WriteAllBytes(image_path, atlas.EncodeToPNG());
importer.isReadable = false;
AssetDatabase.ImportAsset(image_path);
}
while (tile_set.tiles.Count < tile_count)
tile_set.tiles.Add(new TileInfo());
Object[] assets = AssetDatabase.LoadAllAssetRepresentationsAtPath(image_path);
foreach (Object asset in assets)
{
int size_x = 0;
int size_y = 0;
int index = 0;
if (!ParseTileSpriteAssetName(asset.name, out size_x, out size_y, out index))
continue;
if (size_x != slice_size_x || size_y != slice_size_y)
continue;
tile_set.tiles[index].sprite = asset as Sprite;
}
return tile_set;
}
/// <summary>
/// Builds a number of chunks in the Resources directory from the given data
/// </summary>
/// <param name="map_width">The width of the map</param>
/// <param name="map_height">The height of the map</param>
/// <param name="layers">The layers of IDs</param>
/// <param name="chunk_size_x">The size of each chunk along the X axis</param>
/// <param name="chunk_size_y">The size of each chunk along the Y axis</param>
/// <param name="resources_name">The name (or path) of the folder to make inside the Resources directory</param>
/// <returns>A StaticChunkManager that can load the newly-created chunks</returns>
public static StaticChunkManager BuildStaticChunks(
int map_width,
int map_height,
List<int[]> layers,
int chunk_size_x,
int chunk_size_y,
string resources_name
)
{
string resources_dir = Pb.Path.Combine("Assets/Resources", resources_name);
string resources_system_dir = Pb.Path.AssetPathToSystemPath(resources_dir);
if (Directory.Exists(resources_system_dir))
Directory.Delete(resources_system_dir, true);
Directory.CreateDirectory(resources_system_dir);
int chunks_x = Pb.Math.CeilDivide(map_width, chunk_size_x);
int chunks_y = Pb.Math.CeilDivide(map_height, chunk_size_y);
int count = 0;
for (int chunk_y = 0; chunk_y < chunks_y; ++chunk_y)
{
int pos_y = chunk_y * chunk_size_y;
for (int chunk_x = 0; chunk_x < chunks_x; ++chunk_x)
{
string chunk_path = Pb.Path.Combine(resources_dir, "chunk_" + chunk_x + "_" + chunk_y + ".asset");
Chunk chunk = Pb.Utility.Asset.GetAndEdit<Chunk>(chunk_path);
chunk.index = new Pb.Collections.IVector2(chunk_x, chunk_y);
chunk.ids = new int[layers.Count * chunk_size_y * chunk_size_x];
int pos_x = chunk_x * chunk_size_x;
int index = 0;
for (int l = 0; l < layers.Count; ++l)
{
for (int y = 0; y < chunk_size_y; ++y)
{
for (int x = 0; x < chunk_size_x; ++x, ++index)
{
if (pos_x + x >= map_width || pos_y + y >= map_height)
chunk.ids[index] = 0;
else
chunk.ids[index] = layers[l][(pos_y + y) * map_width + pos_x + x];
}
}
}
++count;
}
}
AssetDatabase.Refresh();
string chunk_manager_path = Pb.Path.Combine(resources_dir, "chunk_manager.asset");
StaticChunkManager chunk_manager = Pb.Utility.Asset.GetAndEdit<StaticChunkManager>(chunk_manager_path);
chunk_manager.chunk_size = new Pb.Collections.IVector2(chunk_size_x, chunk_size_y);
chunk_manager.chunk_least = Pb.Collections.IVector2.zero;
chunk_manager.chunk_greatest = new Pb.Collections.IVector2(chunks_x - 1, chunks_y - 1);
chunk_manager.resources_path = resources_name;
return chunk_manager;
}
}
}
}
| |
// 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.Runtime.CompilerServices;
using Xunit;
namespace System.SpanTests
{
public static partial class SpanTests
{
[Fact]
public static void TryCopyTo()
{
int[] src = { 1, 2, 3 };
int[] dst = { 99, 100, 101 };
Span<int> srcSpan = new Span<int>(src);
bool success = srcSpan.TryCopyTo(dst);
Assert.True(success);
Assert.Equal<int>(src, dst);
}
[Fact]
public static void TryCopyToSingle()
{
int[] src = { 1 };
int[] dst = { 99 };
Span<int> srcSpan = new Span<int>(src);
bool success = srcSpan.TryCopyTo(dst);
Assert.True(success);
Assert.Equal<int>(src, dst);
}
[Fact]
public static void TryCopyToArraySegmentImplicit()
{
int[] src = { 1, 2, 3 };
int[] dst = { 5, 99, 100, 101, 10 };
var segment = new ArraySegment<int>(dst, 1, 3);
Span<int> srcSpan = new Span<int>(src);
bool success = srcSpan.TryCopyTo(segment);
Assert.True(success);
Assert.Equal<int>(src, segment);
}
[Fact]
public static void TryCopyToEmpty()
{
int[] src = { };
int[] dst = { 99, 100, 101 };
Span<int> srcSpan = new Span<int>(src);
bool success = srcSpan.TryCopyTo(dst);
Assert.True(success);
int[] expected = { 99, 100, 101 };
Assert.Equal<int>(expected, dst);
}
[Fact]
public static void TryCopyToLonger()
{
int[] src = { 1, 2, 3 };
int[] dst = { 99, 100, 101, 102 };
Span<int> srcSpan = new Span<int>(src);
bool success = srcSpan.TryCopyTo(dst);
Assert.True(success);
int[] expected = { 1, 2, 3, 102 };
Assert.Equal<int>(expected, dst);
}
[Fact]
public static void TryCopyToShorter()
{
int[] src = { 1, 2, 3 };
int[] dst = { 99, 100 };
Span<int> srcSpan = new Span<int>(src);
bool success = srcSpan.TryCopyTo(dst);
Assert.False(success);
int[] expected = { 99, 100 };
Assert.Equal<int>(expected, dst); // TryCopyTo() checks for sufficient space before doing any copying.
}
[Fact]
public static void CopyToShorter()
{
int[] src = { 1, 2, 3 };
int[] dst = { 99, 100 };
Span<int> srcSpan = new Span<int>(src);
TestHelpers.AssertThrows<ArgumentException, int>(srcSpan, (_srcSpan) => _srcSpan.CopyTo(dst));
int[] expected = { 99, 100 };
Assert.Equal<int>(expected, dst); // CopyTo() checks for sufficient space before doing any copying.
}
[Fact]
public static void Overlapping1()
{
int[] a = { 90, 91, 92, 93, 94, 95, 96, 97 };
Span<int> src = new Span<int>(a, 1, 6);
Span<int> dst = new Span<int>(a, 2, 6);
src.CopyTo(dst);
int[] expected = { 90, 91, 91, 92, 93, 94, 95, 96 };
Assert.Equal<int>(expected, a);
}
[Fact]
public static void Overlapping2()
{
int[] a = { 90, 91, 92, 93, 94, 95, 96, 97 };
Span<int> src = new Span<int>(a, 2, 6);
Span<int> dst = new Span<int>(a, 1, 6);
src.CopyTo(dst);
int[] expected = { 90, 92, 93, 94, 95, 96, 97, 97 };
Assert.Equal<int>(expected, a);
}
[Fact]
public static void CopyToArray()
{
int[] src = { 1, 2, 3 };
Span<int> dst = new int[3] { 99, 100, 101 };
src.CopyTo(dst);
Assert.Equal<int>(src, dst.ToArray());
}
[Fact]
public static void CopyToSingleArray()
{
int[] src = { 1 };
Span<int> dst = new int[1] { 99 };
src.CopyTo(dst);
Assert.Equal<int>(src, dst.ToArray());
}
[Fact]
public static void CopyToEmptyArray()
{
int[] src = { };
Span<int> dst = new int[3] { 99, 100, 101 };
src.CopyTo(dst);
int[] expected = { 99, 100, 101 };
Assert.Equal<int>(expected, dst.ToArray());
Span<int> dstEmpty = new int[0] { };
src.CopyTo(dstEmpty);
int[] expectedEmpty = { };
Assert.Equal<int>(expectedEmpty, dstEmpty.ToArray());
}
[Fact]
public static void CopyToLongerArray()
{
int[] src = { 1, 2, 3 };
Span<int> dst = new int[4] { 99, 100, 101, 102 };
src.CopyTo(dst);
int[] expected = { 1, 2, 3, 102 };
Assert.Equal<int>(expected, dst.ToArray());
}
[Fact]
public static void CopyToShorterArray()
{
int[] src = { 1, 2, 3 };
int[] dst = new int[2] { 99, 100 };
TestHelpers.AssertThrows<ArgumentException, int>(src, (_src) => _src.CopyTo(dst));
int[] expected = { 99, 100 };
Assert.Equal<int>(expected, dst); // CopyTo() checks for sufficient space before doing any copying.
}
[Fact]
public static void CopyToCovariantArray()
{
string[] src = new string[] { "Hello" };
Span<object> dst = new object[] { "world" };
src.CopyTo<object>(dst);
Assert.Equal("Hello", dst[0]);
}
// This test case tests the Span.CopyTo method for large buffers of size 4GB or more. In the fast path,
// the CopyTo method performs copy in chunks of size 4GB (uint.MaxValue) with final iteration copying
// the residual chunk of size (bufferSize % 4GB). The inputs sizes to this method, 4GB and 4GB+256B,
// test the two size selection paths in CoptyTo method - memory size that is multiple of 4GB or,
// a multiple of 4GB + some more size.
[ActiveIssue(25254)]
[Theory]
[OuterLoop]
[PlatformSpecific(TestPlatforms.Windows | TestPlatforms.OSX)]
[InlineData(4L * 1024L * 1024L * 1024L)]
[InlineData((4L * 1024L * 1024L * 1024L) + 256)]
public static void CopyToLargeSizeTest(long bufferSize)
{
// If this test is run in a 32-bit process, the large allocation will fail.
if (Unsafe.SizeOf<IntPtr>() != sizeof(long))
{
return;
}
int GuidCount = (int)(bufferSize / Unsafe.SizeOf<Guid>());
bool allocatedFirst = false;
bool allocatedSecond = false;
IntPtr memBlockFirst = IntPtr.Zero;
IntPtr memBlockSecond = IntPtr.Zero;
unsafe
{
try
{
allocatedFirst = AllocationHelper.TryAllocNative((IntPtr)bufferSize, out memBlockFirst);
allocatedSecond = AllocationHelper.TryAllocNative((IntPtr)bufferSize, out memBlockSecond);
if (allocatedFirst && allocatedSecond)
{
ref Guid memoryFirst = ref Unsafe.AsRef<Guid>(memBlockFirst.ToPointer());
var spanFirst = new Span<Guid>(memBlockFirst.ToPointer(), GuidCount);
ref Guid memorySecond = ref Unsafe.AsRef<Guid>(memBlockSecond.ToPointer());
var spanSecond = new Span<Guid>(memBlockSecond.ToPointer(), GuidCount);
Guid theGuid = Guid.Parse("900DBAD9-00DB-AD90-00DB-AD900DBADBAD");
for (int count = 0; count < GuidCount; ++count)
{
Unsafe.Add(ref memoryFirst, count) = theGuid;
}
spanFirst.CopyTo(spanSecond);
for (int count = 0; count < GuidCount; ++count)
{
Guid guidfirst = Unsafe.Add(ref memoryFirst, count);
Guid guidSecond = Unsafe.Add(ref memorySecond, count);
Assert.Equal(guidfirst, guidSecond);
}
}
}
finally
{
if (allocatedFirst)
AllocationHelper.ReleaseNative(ref memBlockFirst);
if (allocatedSecond)
AllocationHelper.ReleaseNative(ref memBlockSecond);
}
}
}
[Fact]
public static void CopyToVaryingSizes()
{
const int MaxLength = 2048;
var rng = new Random();
byte[] inputArray = new byte[MaxLength];
Span<byte> inputSpan = inputArray;
Span<byte> outputSpan = new byte[MaxLength];
Span<byte> allZerosSpan = new byte[MaxLength];
// Test all inputs from size 0 .. MaxLength (inclusive) to make sure we don't have
// gaps in our Memmove logic.
for (int i = 0; i <= MaxLength; i++)
{
// Arrange
rng.NextBytes(inputArray);
outputSpan.Clear();
// Act
inputSpan.Slice(0, i).CopyTo(outputSpan);
// Assert
Assert.True(inputSpan.Slice(0, i).SequenceEqual(outputSpan.Slice(0, i))); // src successfully copied to dst
Assert.True(outputSpan.Slice(i).SequenceEqual(allZerosSpan.Slice(i))); // no other part of dst was overwritten
}
}
}
}
| |
/********************************************************************
The Multiverse Platform is made available under the MIT License.
Copyright (c) 2012 The Multiverse Foundation
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify,
merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
OR OTHER DEALINGS IN THE SOFTWARE.
*********************************************************************/
namespace TUVienna.CS_CUP
{
using System;
using System.Collections;
using System.IO;
/** This class serves as the main driver for the JavaCup system.
* It accepts user options and coordinates overall control flow.
* The main flow of control includes the following activities:
* <ul>
* <li> Parse user supplied arguments and options.
* <li> Open output files.
* <li> Parse the specification from standard input.
* <li> Check for unused terminals, non-terminals, and productions.
* <li> Build the state machine, tables, etc.
* <li> Output the generated code.
* <li> Close output files.
* <li> Print a summary if requested.
* </ul>
*
* Options to the main program include: <dl>
* <dt> -package name
* <dd> specify package generated classes go in [default none]
* <dt> -parser name
* <dd> specify parser class name [default "parser"]
* <dt> -symbols name
* <dd> specify name for symbol constant class [default "sym"]
* <dt> -interface
* <dd> emit symbol constant <i>interface</i>, rather than class
* <dt> -nonterms
* <dd> put non terminals in symbol constant class
* <dt> -expect #
* <dd> number of conflicts expected/allowed [default 0]
* <dt> -compact_red
* <dd> compact tables by defaulting to most frequent reduce
* <dt> -nowarn
* <dd> don't warn about useless productions, etc.
* <dt> -nosummary
* <dd> don't print the usual summary of parse states, etc.
* <dt> -progress
* <dd> print messages to indicate progress of the system
* <dt> -time
* <dd> print time usage summary
* <dt> -dump_grammar
* <dd> produce a dump of the symbols and grammar
* <dt> -dump_states
* <dd> produce a dump of parse state machine
* <dt> -dump_tables
* <dd> produce a dump of the parse tables
* <dt> -dump
* <dd> produce a dump of all of the above
* <dt> -debug
* <dd> turn on debugging messages within JavaCup
* <dt> -nopositions
* <dd> don't generate the positions code
* <dt> -noscanner
* <dd> don't refer to java_cup.runtime.Scanner in the parser
* (for compatibility with old runtimes)
* <dt> -version
* <dd> print version information for JavaCUP and halt.
* </dl>
*
* @version last updated: 7/3/96
* @author Frank Flannery
* translated to C# 08.09.2003 by Samuel Imriska
*/
public class CSCup
{
/*-----------------------------------------------------------*/
/*--- Constructor(s) ----------------------------------------*/
/*-----------------------------------------------------------*/
/** Only constructor is private, so we do not allocate any instances of this
class. */
private CSCup() { }
/*-------------------------*/
/* Options Set by the user */
/*-------------------------*/
/** User option -- do we print progress messages. */
protected static bool print_progress = true;
/** User option -- do we produce a dump of the state machine */
protected static bool opt_dump_states = false;
/** User option -- do we produce a dump of the parse tables */
protected static bool opt_dump_tables = false;
/** User option -- do we produce a dump of the grammar */
protected static bool opt_dump_grammar = false;
/** User option -- do we show timing information as a part of the summary */
protected static bool opt_show_timing = false;
/** User option -- do we run produce extra debugging messages */
protected static bool opt_do_debug = false;
/** User option -- do we compact tables by making most common reduce the
default action */
protected static bool opt_compact_red = false;
/** User option -- should we include non terminal symbol numbers in the
symbol constant class. */
protected static bool include_non_terms = false;
/** User option -- do not print a summary. */
protected static bool no_summary = false;
/** User option -- number of conflicts to expect */
protected static int expect_conflicts = 0;
/* frankf added this 6/18/96 */
/** User option -- should generator generate code for left/right values? */
protected static bool lr_values = true;
/** User option -- should symbols be put in a class or an interface? [CSA]*/
protected static bool sym_interface = false;
/** User option -- should generator suppress references to
* java_cup.runtime.Scanner for compatibility with old runtimes? */
protected static bool suppress_scanner = false;
/*----------------------------------------------------------------------*/
/* Timing data (not all of these time intervals are mutually exclusive) */
/*----------------------------------------------------------------------*/
/** Timing data -- when did we start */
protected static long start_time = 0;
/** Timing data -- when did we end preliminaries */
protected static long prelim_end = 0;
/** Timing data -- when did we end parsing */
protected static long parse_end = 0;
/** Timing data -- when did we end checking */
protected static long check_end = 0;
/** Timing data -- when did we end dumping */
protected static long dump_end = 0;
/** Timing data -- when did we end state and table building */
protected static long build_end = 0;
/** Timing data -- when did we end nullability calculation */
protected static long nullability_end = 0;
/** Timing data -- when did we end first Set calculation */
protected static long first_end = 0;
/** Timing data -- when did we end state machine construction */
protected static long machine_end = 0;
/** Timing data -- when did we end table construction */
protected static long table_end = 0;
/** Timing data -- when did we end checking for non-reduced productions */
protected static long reduce_check_end = 0;
/** Timing data -- when did we finish emitting code */
protected static long emit_end = 0;
/** Timing data -- when were we completely done */
protected static long final_time = 0;
/* Additional timing information is also collected in emit */
/*-----------------------------------------------------------*/
/*--- Main Program ------------------------------------------*/
/*-----------------------------------------------------------*/
/** The main driver for the system.
* @param argv an array of strings containing command line arguments.
*/
public static void Main(string[] argv)
{
bool did_output = false;
try
{
//Test phase
start_time = DateTime.Now.Ticks;
/* process user options and arguments */
parse_args(argv);
/* frankf 6/18/96
hackish, yes, but works */
emit.set_lr_values(lr_values);
/* open output files */
if (print_progress) System.Console.Error.WriteLine("Opening files...");
/* use a buffered version of standard input */
// System.Console.SetIn(new StreamReader("c:\\parser.cup"));
input_file = System.Console.In;
prelim_end = DateTime.Now.Ticks;
/* parse spec into internal data structures */
if (print_progress)
System.Console.Error.WriteLine("Parsing specification from standard input...");
parse_grammar_spec();
parse_end = DateTime.Now.Ticks;
/* don't proceed unless we are error free */
if (lexer.error_count == 0)
{
/* check for unused bits */
if (print_progress) System.Console.Error.WriteLine("Checking specification...");
check_unused();
check_end = DateTime.Now.Ticks;
/* build the state machine and parse tables */
if (print_progress) System.Console.Error.WriteLine("Building parse tables...");
build_parser();
build_end = DateTime.Now.Ticks;
/* output the generated code, if # of conflicts permits */
if (lexer.error_count != 0)
{
// conflicts! don't emit code, don't dump tables.
opt_dump_tables = false;
}
else
{ // everything's okay, emit parser.
if (print_progress) System.Console.WriteLine("Writing parser...");
open_files();
emit_parser();
did_output = true;
}
}
/* fix up the times to make the summary easier */
emit_end = DateTime.Now.Ticks;
/* do requested dumps */
if (opt_dump_grammar) dump_grammar();
if (opt_dump_states) dump_machine();
if (opt_dump_tables) dump_tables();
dump_end = DateTime.Now.Ticks;
/* close input/output files */
if (print_progress) System.Console.Error.WriteLine("Closing files...");
close_files();
/* produce a summary if desired */
if (!no_summary) emit_summary(did_output);
/* If there were errors during the run,
* exit with non-zero status (makefile-friendliness). --CSA */
if (lexer.error_count != 0)
System.Environment.Exit(100);
}
catch(System.Exception e)
{
System.Console.WriteLine(e.Message);
}
}
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Print a "usage message" that described possible command line options,
* then exit.
* @param message a specific error message to preface the usage message by.
*/
protected static void usage(string message)
{
System.Console.Error.WriteLine();
System.Console.Error.WriteLine(message);
System.Console.Error.WriteLine();
System.Console.Error.WriteLine(
"Usage: " + version.program_name + " [options] [filename]\n" +
" and expects a specification file on standard input if no filename is given.\n" +
" Legal options include:\n" +
" -namespace name specify package generated classes go in [default none]\n" +
" -parser name specify parser class name [default \"parser\"]\n" +
" -symbols name specify name for symbol constant class [default \"sym\"]\n"+
" -interface put symbols in an interface, rather than a class\n" +
" -nonterms put non terminals in symbol constant class\n" +
" -expect # number of conflicts expected/allowed [default 0]\n" +
" -compact_red compact tables by defaulting to most frequent reduce\n" +
" -nowarn don't warn about useless productions, etc.\n" +
" -nosummary don't print the usual summary of parse states, etc.\n" +
" -nopositions don't propagate the left and right token position values\n" +
" -noscanner don't refer to java_cup.runtime.Scanner\n" +
" -progress print messages to indicate progress of the system\n" +
" -time print time usage summary\n" +
" -dump_grammar produce a human readable dump of the symbols and grammar\n"+
" -dump_states produce a dump of parse state machine\n"+
" -dump_tables produce a dump of the parse tables\n"+
" -dump produce a dump of all of the above\n"+
" -version print the version information for CUP and exit\n"
);
System.Environment.Exit(1);
}
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Parse command line options and arguments to Set various user-option
* flags and variables.
* @param argv the command line arguments to be parsed.
*/
protected static void parse_args(string[] argv)
{
int len = argv.Length;
int i;
/* parse the options */
for (i=0; i<len; i++)
{
/* try to get the various options */
if (argv[i].Equals("-namespace"))
{
/* must have an arg */
if (++i >= len || argv[i].StartsWith("-") ||
argv[i].EndsWith(".cup"))
usage("-package must have a name argument");
/* record the name */
emit.package_name = argv[i];
}
else if (argv[i].Equals("-parser"))
{
/* must have an arg */
if (++i >= len || argv[i].StartsWith("-") ||
argv[i].EndsWith(".cup"))
usage("-parser must have a name argument");
/* record the name */
emit.parser_class_name = argv[i];
}
else if (argv[i].Equals("-symbols"))
{
/* must have an arg */
if (++i >= len || argv[i].StartsWith("-") ||
argv[i].EndsWith(".cup"))
usage("-symbols must have a name argument");
/* record the name */
emit.symbol_const_class_name = argv[i];
}
else if (argv[i].Equals("-nonterms"))
{
include_non_terms = true;
}
else if (argv[i].Equals("-expect"))
{
/* must have an arg */
if (++i >= len || argv[i].StartsWith("-") ||
argv[i].EndsWith(".cup"))
usage("-expect must have a name argument");
/* record the number */
try
{
expect_conflicts = Int32.Parse(argv[i]);
}
catch
{
usage("-expect must be followed by a decimal integer");
}
}
else if (argv[i].Equals("-compact_red")) opt_compact_red = true;
else if (argv[i].Equals("-nosummary")) no_summary = true;
else if (argv[i].Equals("-nowarn")) emit.nowarn = true;
else if (argv[i].Equals("-dump_states")) opt_dump_states = true;
else if (argv[i].Equals("-dump_tables")) opt_dump_tables = true;
else if (argv[i].Equals("-progress")) print_progress = true;
else if (argv[i].Equals("-dump_grammar")) opt_dump_grammar = true;
else if (argv[i].Equals("-dump"))
opt_dump_states = opt_dump_tables = opt_dump_grammar = true;
else if (argv[i].Equals("-time")) opt_show_timing = true;
else if (argv[i].Equals("-debug")) opt_do_debug = true;
/* frankf 6/18/96 */
else if (argv[i].Equals("-nopositions")) lr_values = false;
/* CSA 12/21/97 */
else if (argv[i].Equals("-interface")) sym_interface = true;
/* CSA 23-Jul-1999 */
else if (argv[i].Equals("-noscanner")) suppress_scanner = true;
/* CSA 23-Jul-1999 */
else if (argv[i].Equals("-version"))
{
System.Console.WriteLine(version.title_str);
System.Environment.Exit(1);
}
/* CSA 24-Jul-1999; suggestion by Jean Vaucher */
else if (!argv[i].StartsWith("-") && i==len-1)
{
/* use input from file. */
try
{
input_redirected=true;
System.Console.SetIn(new StreamReader(argv[i]));
}
catch
{
usage("Unable to open \"" + argv[i] +"\" for input");
}
}
else
{
usage("Unrecognized option \"" + argv[i] + "\"");
}
}
}
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/*-------*/
/* Files */
/*-------*/
/** Input file. This is a buffered version of System.in. */
protected static TextReader input_file;
protected static bool input_redirected = false;
/** Output file for the parser class. */
protected static TextWriter parser_class_file;
/** Output file for the symbol constant class. */
protected static TextWriter symbol_class_file;
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Open various files used by the system. */
protected static void open_files()
{
string out_name;
/* open each of the output files */
/* parser class */
out_name = emit.parser_class_name + ".cs";
try
{
parser_class_file = new StreamWriter(out_name);
}
catch
{
System.Console.Error.WriteLine("Can't open \"" + out_name + "\" for output");
System.Environment.Exit(3);
}
/* symbol constants class */
out_name = emit.symbol_const_class_name + ".cs";
try
{
symbol_class_file = new StreamWriter(out_name);
}
catch
{
System.Console.Error.WriteLine("Can't open \"" + out_name + "\" for output");
System.Environment.Exit(4);
}
}
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Close various files used by the system. */
protected static void close_files()
{
if (input_redirected) input_file.Close();
if (parser_class_file != null)
{
parser_class_file.Flush();
parser_class_file.Close();
}
if (symbol_class_file != null)
{
symbol_class_file.Flush();
symbol_class_file.Close();
}
}
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Parse the grammar specification from standard input. This produces
* sets of terminal, non-terminals, and productions which can be accessed
* via static variables of the respective classes, as well as the setting
* of various variables (mostly in the emit class) for small user supplied
* items such as the code to scan with.
*/
protected static void parse_grammar_spec()
{
parser parser_obj;
// create a parser and parse with it
parser_obj = new parser();
try
{
if (opt_do_debug)
parser_obj.debug_parse();
else
parser_obj.parse();
}
catch (Exception e)
{
// something threw an exception. catch it and emit a message so we
// have a line number to work with, then re-throw it
lexer.emit_error("Internal error: Unexpected exception");
throw e;
}
}
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Check for unused symbols. Unreduced productions get checked when
* tables are created.
*/
protected static void check_unused()
{
terminal term;
non_terminal nt;
/* check for unused terminals */
IEnumerator t = terminal.all();
while ( t.MoveNext() )
{
term = (terminal)t.Current;
/* don't issue a message for EOF */
if (term == terminal.EOF) continue;
/* or error */
if (term == terminal.error) continue;
/* is this one unused */
if (term.use_count() == 0)
{
/* count it and warn if we are doing warnings */
emit.unused_term++;
if (!emit.nowarn)
{
System.Console.Error.WriteLine("Warning: Terminal \"" + term.name() +
"\" was declared but never used");
lexer.warning_count++;
}
}
}
/* check for unused non terminals */
IEnumerator n = non_terminal.all();
while ( n.MoveNext() )
{
nt = (non_terminal)n.Current;
/* is this one unused */
if (nt.use_count() == 0)
{
/* count and warn if we are doing warnings */
emit.unused_term++;
if (!emit.nowarn)
{
System.Console.Error.WriteLine("Warning: Non terminal \"" + nt.name() +
"\" was declared but never used");
lexer.warning_count++;
}
}
}
}
/* . . . . . . . . . . . . . . . . . . . . . . . . .*/
/* . . Internal Results of Generating the Parser . .*/
/* . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Start state in the overall state machine. */
protected static lalr_state start_state;
/** Resulting parse action table. */
protected static parse_action_table action_table;
/** Resulting reduce-goto table. */
protected static parse_reduce_table reduce_table;
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Build the (internal) parser from the previously parsed specification.
* This includes:<ul>
* <li> Computing nullability of non-terminals.
* <li> Computing first sets of non-terminals and productions.
* <li> Building the viable prefix recognizer machine.
* <li> Filling in the (internal) parse tables.
* <li> Checking for unreduced productions.
* </ul>
*/
protected static void build_parser()
{
/* compute nullability of all non terminals */
if (opt_do_debug || print_progress)
System.Console.Error.WriteLine(" Computing non-terminal nullability...");
non_terminal.compute_nullability();
nullability_end = DateTime.Now.Ticks;
/* compute first sets of all non terminals */
if (opt_do_debug || print_progress)
System.Console.Error.WriteLine(" Computing first sets...");
non_terminal.compute_first_sets();
first_end = DateTime.Now.Ticks;
/* build the LR viable prefix recognition machine */
if (opt_do_debug || print_progress)
System.Console.Error.WriteLine(" Building state machine...");
start_state = lalr_state.build_machine(emit.start_production);
machine_end = DateTime.Now.Ticks;
/* build the LR parser action and reduce-goto tables */
if (opt_do_debug || print_progress)
System.Console.Error.WriteLine(" Filling in tables...");
action_table = new parse_action_table();
reduce_table = new parse_reduce_table();
IEnumerator st = lalr_state.all();
while ( st.MoveNext() )
{
lalr_state lst = (lalr_state)st.Current;
lst.build_table_entries(
action_table, reduce_table);
}
table_end = DateTime.Now.Ticks;
/* check and warn for non-reduced productions */
if (opt_do_debug || print_progress)
System.Console.Error.WriteLine(" Checking for non-reduced productions...");
action_table.check_reductions();
reduce_check_end = DateTime.Now.Ticks;
/* if we have more conflicts than we expected issue a message and die */
if (emit.num_conflicts > expect_conflicts)
{
System.Console.Error.WriteLine("*** More conflicts encountered than expected " +
"-- parser generation aborted");
lexer.error_count++; // indicate the problem.
// we'll die on return, after clean up.
}
}
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Call the emit routines necessary to write out the generated parser. */
protected static void emit_parser()
{
emit.symbols(symbol_class_file, include_non_terms, sym_interface);
emit.parser(parser_class_file, action_table, reduce_table,
start_state.index(), emit.start_production, opt_compact_red,
suppress_scanner);
}
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Helper routine to optionally return a plural or non-plural ending.
* @param val the numerical value determining plurality.
*/
protected static string plural(int val)
{
if (val == 1)
return "";
else
return "s";
}
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Emit a long summary message to standard error (System.err) which
* summarizes what was found in the specification, how many states were
* produced, how many conflicts were found, etc. A detailed timing
* summary is also produced if it was requested by the user.
* @param output_produced did the system get far enough to generate code.
*/
protected static void emit_summary(bool output_produced)
{
final_time = DateTime.Now.Ticks;
if (no_summary) return;
System.Console.Error.WriteLine("------- " + version.title_str +
" Parser Generation Summary -------");
/* error and warning count */
System.Console.Error.WriteLine(" " + lexer.error_count + " error" +
plural(lexer.error_count) + " and " + lexer.warning_count +
" warning" + plural(lexer.warning_count));
/* basic stats */
System.Console.Error.Write(" " + terminal.number() + " terminal" +
plural(terminal.number()) + ", ");
System.Console.Error.Write(non_terminal.number() + " non-terminal" +
plural(non_terminal.number()) + ", and ");
System.Console.Error.WriteLine(production.number() + " production" +
plural(production.number()) + " declared, ");
System.Console.Error.WriteLine(" producing " + lalr_state.number() +
" unique parse states.");
/* unused symbols */
System.Console.Error.WriteLine(" " + emit.unused_term + " terminal" +
plural(emit.unused_term) + " declared but not used.");
System.Console.Error.WriteLine(" " + emit.unused_non_term + " non-terminal" +
plural(emit.unused_term) + " declared but not used.");
/* productions that didn't reduce */
System.Console.Error.WriteLine(" " + emit.not_reduced + " production" +
plural(emit.not_reduced) + " never reduced.");
/* conflicts */
System.Console.Error.WriteLine(" " + emit.num_conflicts + " conflict" +
plural(emit.num_conflicts) + " detected" +
" (" + expect_conflicts + " expected).");
/* code location */
if (output_produced)
System.Console.Error.WriteLine(" Code written to \"" + emit.parser_class_name +
".cs\", and \"" + emit.symbol_const_class_name + ".cs\".");
else
System.Console.Error.WriteLine(" No code produced.");
if (opt_show_timing) show_times();
System.Console.Error.WriteLine(
"---------------------------------------------------- (" +
version.version_str + ")");
}
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Produce the optional timing summary as part of an overall summary. */
protected static void show_times()
{
long total_time = final_time - start_time;
System.Console.Error.WriteLine(". . . . . . . . . . . . . . . . . . . . . . . . . ");
System.Console.Error.WriteLine(" Timing Summary");
System.Console.Error.WriteLine(" Total time "
+ timestr(final_time-start_time, total_time));
System.Console.Error.WriteLine(" Startup "
+ timestr(prelim_end-start_time, total_time));
System.Console.Error.WriteLine(" Parse "
+ timestr(parse_end-prelim_end, total_time) );
if (check_end != 0)
System.Console.Error.WriteLine(" Checking "
+ timestr(check_end-parse_end, total_time));
if (check_end != 0 && build_end != 0)
System.Console.Error.WriteLine(" Parser Build "
+ timestr(build_end-check_end, total_time));
if (nullability_end != 0 && check_end != 0)
System.Console.Error.WriteLine(" Nullability "
+ timestr(nullability_end-check_end, total_time));
if (first_end != 0 && nullability_end != 0)
System.Console.Error.WriteLine(" First sets "
+ timestr(first_end-nullability_end, total_time));
if (machine_end != 0 && first_end != 0)
System.Console.Error.WriteLine(" State build "
+ timestr(machine_end-first_end, total_time));
if (table_end != 0 && machine_end != 0)
System.Console.Error.WriteLine(" Table build "
+ timestr(table_end-machine_end, total_time));
if (reduce_check_end != 0 && table_end != 0)
System.Console.Error.WriteLine(" Checking "
+ timestr(reduce_check_end-table_end, total_time));
if (emit_end != 0 && build_end != 0)
System.Console.Error.WriteLine(" Code Output "
+ timestr(emit_end-build_end, total_time));
if (emit.symbols_time != 0)
System.Console.Error.WriteLine(" Symbols "
+ timestr(emit.symbols_time, total_time));
if (emit.parser_time != 0)
System.Console.Error.WriteLine(" Parser class "
+ timestr(emit.parser_time, total_time));
if (emit.action_code_time != 0)
System.Console.Error.WriteLine(" Actions "
+ timestr(emit.action_code_time, total_time));
if (emit.production_table_time != 0)
System.Console.Error.WriteLine(" Prod table "
+ timestr(emit.production_table_time, total_time));
if (emit.action_table_time != 0)
System.Console.Error.WriteLine(" Action tab "
+ timestr(emit.action_table_time, total_time));
if (emit.goto_table_time != 0)
System.Console.Error.WriteLine(" Reduce tab "
+ timestr(emit.goto_table_time, total_time));
System.Console.Error.WriteLine(" Dump Output "
+ timestr(dump_end-emit_end, total_time));
}
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Helper routine to format a decimal based display of seconds and
* percentage of total time given counts of milliseconds. Note: this
* is broken for use with some instances of negative time (since we don't
* use any negative time here, we let if be for now).
* @param time_val the value being formatted (in ms).
* @param total_time total time percentages are calculated against (in ms).
*/
protected static string timestr(long time_val, long total_time)
{
bool neg;
long ms = 0;
long sec = 0;
long percent10;
string pad;
/* work with positives only */
neg = time_val < 0;
if (neg) time_val = -time_val;
/* pull out seconds and ms */
ms = time_val % 1000;
sec = time_val / 1000;
/* construct a pad to blank fill seconds out to 4 places */
if (sec < 10)
pad = " ";
else if (sec < 100)
pad = " ";
else if (sec < 1000)
pad = " ";
else
pad = "";
/* calculate 10 times the percentage of total */
percent10 = (time_val*1000)/total_time;
/* build and return the output string */
return (neg ? "-" : "") + pad + sec + "." +
((ms%1000)/100) + ((ms%100)/10) + (ms%10) + "sec" +
" (" + percent10/10 + "." + percent10%10 + "%)";
}
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Produce a human readable dump of the grammar. */
public static void dump_grammar()
{
System.Console.Error.WriteLine("===== Terminals =====");
for (int tidx=0, cnt=0; tidx < terminal.number(); tidx++, cnt++)
{
System.Console.Error.Write("["+tidx+"]"+terminal.find(tidx).name()+" ");
if ((cnt+1) % 5 == 0) System.Console.Error.WriteLine();
}
System.Console.Error.WriteLine();
System.Console.Error.WriteLine();
System.Console.Error.WriteLine("===== Non terminals =====");
for (int nidx=0, cnt=0; nidx < non_terminal.number(); nidx++, cnt++)
{
System.Console.Error.Write("["+nidx+"]"+non_terminal.find(nidx).name()+" ");
if ((cnt+1) % 5 == 0) System.Console.Error.WriteLine();
}
System.Console.Error.WriteLine();
System.Console.Error.WriteLine();
System.Console.Error.WriteLine("===== Productions =====");
for (int pidx=0; pidx < production.number(); pidx++)
{
production prod = production.find(pidx);
System.Console.Error.Write("["+pidx+"] "+prod.lhs().the_symbol().name() + " ::= ");
for (int i=0; i<prod.rhs_length(); i++)
if (prod.rhs(i).is_action())
System.Console.Error.Write("{action} ");
else
System.Console.Error.Write(
((symbol_part)prod.rhs(i)).the_symbol().name() + " ");
System.Console.Error.WriteLine();
}
System.Console.Error.WriteLine();
}
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Produce a (semi-) human readable dump of the complete viable prefix
* recognition state machine.
*/
public static void dump_machine()
{
lalr_state[] ordered = new lalr_state[lalr_state.number()];
/* put the states in sorted order for a nicer display */
IEnumerator s = lalr_state.all();
while ( s.MoveNext() )
{
lalr_state st = (lalr_state)s.Current;
ordered[st.index()] = st;
}
System.Console.Error.WriteLine("===== Viable Prefix Recognizer =====");
for (int i = 0; i<lalr_state.number(); i++)
{
if (ordered[i] == start_state) System.Console.Error.Write("START ");
System.Console.Error.WriteLine(ordered[i]);
System.Console.Error.WriteLine("-------------------");
}
}
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Produce a (semi-) human readable dumps of the parse tables */
public static void dump_tables()
{
System.Console.Error.WriteLine(action_table);
System.Console.Error.WriteLine(reduce_table);
}
/*-----------------------------------------------------------*/
}
}
| |
#pragma warning disable 0168
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Xml;
using nHydrate.Generator.Common.GeneratorFramework;
using nHydrate.Generator.Common.Util;
namespace nHydrate.Generator.Models
{
public enum TypedTableConstants
{
None,
DatabaseTable,
EnumOnly,
}
public class Table : BaseModelObject, ICodeFacadeObject, INamedObject
{
#region Member Variables
protected const bool _def_associativeTable = false;
protected const bool _def_hasHistory = false;
protected const bool _def_modifiedAudit = true;
protected const bool _def_createAudit = true;
protected const bool _def_timestamp = true;
protected const TypedTableConstants _def_isTypeTable = TypedTableConstants.None;
protected const bool _def_fullIndexSearch = false;
protected const bool _def_immutable = false;
protected const string _def_dbSchema = "dbo";
protected const string _def_description = "";
protected const string _def_codeFacade = "";
protected const bool _def_generatesDoubleDerived = false;
protected const bool _def_isTenant = false;
protected RowEntryCollection _staticData = null;
private bool _immutable = _def_immutable;
#endregion
#region Constructors
public Table(INHydrateModelObject root)
: base(root)
{
this.Initialize();
}
public Table()
{
//Only needed for BaseModelCollection<T>
}
#endregion
private void Initialize()
{
_staticData = new RowEntryCollection(this.Root);
this.Columns = new ReferenceCollection(this.Root, this, ReferenceType.Column);
Columns.ResetKey(Guid.Empty.ToString());
Relationships = new ReferenceCollection(this.Root, this, ReferenceType.Relation);
Relationships.ResetKey(Guid.Empty.ToString());
Columns.ObjectPlural = "Fields";
Columns.ObjectSingular = "Field";
Columns.ImageIndex = ImageHelper.GetImageIndex(TreeIconConstants.FolderClose);
Columns.SelectedImageIndex = ImageHelper.GetImageIndex(TreeIconConstants.FolderOpen);
Relationships.ObjectPlural = "Relationships";
Relationships.ObjectSingular = "Relationship";
Relationships.ImageIndex = ImageHelper.GetImageIndex(TreeIconConstants.FolderClose);
Relationships.SelectedImageIndex = ImageHelper.GetImageIndex(TreeIconConstants.FolderOpen);
}
protected override void OnRootReset(System.EventArgs e)
{
this.Initialize();
}
#region Property Implementations
public bool IsTenant { get; set; } = _def_isTenant;
public List<TableIndex> TableIndexList { get; } = new List<TableIndex>();
public TypedTableConstants TypedTable { get; set; } = _def_isTypeTable;
public string DBSchema { get; set; } = _def_dbSchema;
public bool GeneratesDoubleDerived { get; set; } = _def_generatesDoubleDerived;
public string Description { get; set; } = _def_description;
public bool Immutable
{
get { return _immutable || this.TypedTable != TypedTableConstants.None; }
set { _immutable = value; }
}
public ReferenceCollection Relationships { get; private set; } = null;
public RelationCollection AllRelationships
{
get
{
var retval = new RelationCollection(this.Root);
var relationCollection = ((ModelRoot)this.Root).Database.Relations;
foreach (var r in relationCollection.AsEnumerable())
{
if ((r.ParentTableRef != null) && (r.ChildTableRef != null))
{
if ((r.ParentTableRef.Ref == this.Id) || (r.ChildTableRef.Ref == this.Id))
{
retval.Add(r);
}
}
}
return retval;
}
}
public ReferenceCollection Columns { get; private set; } = null;
public bool AllowModifiedAudit { get; set; } = _def_modifiedAudit;
public bool AllowCreateAudit { get; set; } = _def_createAudit;
public bool AllowTimestamp { get; set; } = _def_timestamp;
public bool FullIndexSearch { get; set; } = _def_fullIndexSearch;
public RowEntryCollection StaticData => _staticData;
public bool AssociativeTable { get; set; } = _def_associativeTable;
public bool HasHistory { get; set; } = _def_hasHistory;
#endregion
#region Methods
public override string ToString()
{
return this.Name;
}
protected internal System.Data.DataTable CreateDataTable()
{
var retval = new System.Data.DataSet();
var t = retval.Tables.Add(this.Name);
foreach (var column in this.GetColumns())
{
var c = t.Columns.Add(column.Name, typeof(string));
}
return retval.Tables[0];
}
public bool IsInheritedFrom(Table table)
{
return false;
}
public IEnumerable<Table> GetTablesInheritedFromHierarchy()
{
var retval = new List<Table>();
return retval;
}
public Table GetAbsoluteBaseTable()
{
var tableList = GetTableHierarchy().ToList();
if (!tableList.Any())
return this;
return tableList.First();
}
public IEnumerable<Table> GetTableHierarchy()
{
var retval = new List<Table>();
retval.Add(this);
return retval;
}
public ColumnCollection GetColumnsFullHierarchy()
{
try
{
var nameList = new List<string>();
var retval = new ColumnCollection(this.Root);
var t = this;
while (t != null)
{
foreach (var r in t.Columns.ToList())
{
var c = r.Object as Column;
if (!nameList.Contains(c.Name.ToLower()))
{
nameList.Add(c.Name.ToLower());
retval.Add(c);
}
}
//t = t.ParentTable;
t = null;
}
return retval;
}
catch (Exception ex)
{
throw;
}
}
public IEnumerable<Table> GetParentTables()
{
var retval = new List<Table>();
foreach (var r in this.AllRelationships.ToList())
{
if (r.ChildTableRef.Object == this)
{
retval.Add((Table)r.ParentTableRef.Object);
}
}
return retval;
}
public IEnumerable<Table> GetParentTablesFullHierarchy()
{
var retval = new List<Table>();
var curTable = this;
foreach (var r in curTable.AllRelationships.Where(x => x.IsInherited).ToList())
{
if (r.ChildTableRef.Object == curTable)
{
var parentTable = (Table)r.ParentTableRef.Object;
retval.Add(parentTable);
retval.AddRange(parentTable.GetParentTablesFullHierarchy());
}
}
return retval;
}
public IEnumerable<Column> GetColumns()
{
var list = new List<Column>();
foreach (var r in this.Columns.ToList())
{
var c = r.Object as Column;
if (c == null) System.Diagnostics.Debug.Write(string.Empty);
else list.Add(c);
}
return list.OrderBy(x => x.Name);
}
public IEnumerable<Column> GetColumnsByType(System.Data.SqlDbType type)
{
var retval = new List<Column>();
foreach (Column column in this.GetColumnsFullHierarchy())
{
if (column.DataType == type)
{
retval.Add(column);
}
}
return retval;
}
public RelationCollection GetRelations()
{
var retval = new RelationCollection(this.Root);
foreach (var r in this.Relationships.AsEnumerable())
{
var relation = r.Object as Relation;
if (relation != null)
{
retval.Add(relation);
}
}
return retval;
}
public IEnumerable<Relation> GetRelationsWhereChild(bool fullHierarchy = false)
{
return ((ModelRoot)_root).Database.GetRelationsWhereChild(this, fullHierarchy);
}
public bool IsColumnRelatedToTypeTable(Column column, out string roleName)
{
return (GetRelatedTypeTableByColumn(column, out roleName) != null);
}
public Table GetRelatedTypeTableByColumn(Column column, out string roleName)
{
return GetRelatedTypeTableByColumn(column, false, out roleName);
}
public Table GetRelatedTypeTableByColumn(Column column, bool fullHierarchy, out string roleName)
{
roleName = string.Empty;
foreach (var relation in this.GetRelationsWhereChild(fullHierarchy))
{
var parentTable = relation.ParentTableRef.Object as Table;
//Type tables have 1 PK
if (relation.ColumnRelationships.Count == 1)
{
var parentColumn = relation.ColumnRelationships[0].ParentColumnRef.Object as Column;
var childColumn = relation.ColumnRelationships[0].ChildColumnRef.Object as Column;
if ((column == childColumn) && parentTable.TypedTable != TypedTableConstants.None)
{
roleName = relation.PascalRoleName;
return parentTable;
}
}
}
return null;
}
public string GetSQLSchema()
{
if (string.IsNullOrEmpty(this.DBSchema)) return "dbo";
return this.DBSchema;
}
#endregion
#region IXMLable Members
public override void XmlAppend(XmlNode node)
{
var oDoc = node.OwnerDocument;
node.AddAttribute("key", this.Key);
node.AddAttribute("name", this.Name);
node.AddAttribute("dbschema", this.DBSchema, _def_dbSchema);
node.AddAttribute("codeFacade", this.CodeFacade, _def_codeFacade);
node.AddAttribute("description", this.Description, _def_description);
if (this.Relationships.Count > 0)
{
var relationshipsNode = oDoc.CreateElement("r");
this.Relationships.XmlAppend(relationshipsNode);
node.AppendChild(relationshipsNode);
}
var tableIndexListNode = oDoc.CreateElement("til");
TableIndexList.XmlAppend(tableIndexListNode);
node.AppendChild(tableIndexListNode);
var columnsNode = oDoc.CreateElement("c");
this.Columns.XmlAppend(columnsNode);
node.AppendChild(columnsNode);
node.AddAttribute("isTenant", this.IsTenant, _def_isTenant);
node.AddAttribute("immutable", this.Immutable, _def_immutable);
node.AddAttribute("modifiedAudit", this.AllowModifiedAudit, _def_modifiedAudit);
node.AddAttribute("typedTable", this.TypedTable.ToString("d"), _def_isTypeTable.ToString("d"));
node.AddAttribute("createAudit", this.AllowCreateAudit, _def_createAudit);
node.AddAttribute("timestamp", this.AllowTimestamp, _def_timestamp);
node.AddAttribute("generatesDoubleDerived", this.GeneratesDoubleDerived, _def_generatesDoubleDerived);
node.AddAttribute("id", this.Id);
if (this.StaticData.Count > 0)
{
var staticDataNode = oDoc.CreateElement("staticData");
this.StaticData.XmlAppend(staticDataNode);
node.AppendChild(staticDataNode);
}
node.AddAttribute("associativeTable", this.AssociativeTable, _def_associativeTable);
node.AddAttribute("hasHistory", this.HasHistory, _def_hasHistory);
node.AddAttribute("fullIndexSearch", this.FullIndexSearch, _def_fullIndexSearch);
}
public override void XmlLoad(XmlNode node)
{
var relationshipsNode = node.SelectSingleNode("relationships"); //deprecated, use "r"
if (relationshipsNode == null) relationshipsNode = node.SelectSingleNode("r");
if (relationshipsNode != null)
this.Relationships.XmlLoad(relationshipsNode);
var columnsNode = node.SelectSingleNode("columns"); //deprecated, use "c"
if (columnsNode == null) columnsNode = node.SelectSingleNode("c");
if (columnsNode != null)
this.Columns.XmlLoad(columnsNode);
var tableIndexListNode = node.SelectSingleNode("til");
if (tableIndexListNode != null)
TableIndexList.XmlLoad(tableIndexListNode, this.Root);
this.Immutable = XmlHelper.GetAttributeValue(node, "immutable", _def_immutable);
this.IsTenant = XmlHelper.GetAttributeValue(node, "isTenant", _def_isTenant);
this.ResetId(XmlHelper.GetAttributeValue(node, "id", this.Id));
var staticDataNode = node.SelectSingleNode("staticData");
if (staticDataNode != null)
this.StaticData.XmlLoad(staticDataNode);
this.AssociativeTable = XmlHelper.GetAttributeValue(node, "associativeTable", AssociativeTable);
this.HasHistory = XmlHelper.GetAttributeValue(node, "hasHistory", HasHistory);
this.FullIndexSearch = XmlHelper.GetAttributeValue(node, "fullIndexSearch", _def_fullIndexSearch);
this.Key = XmlHelper.GetAttributeValue(node, "key", string.Empty);
this.Name = XmlHelper.GetAttributeValue(node, "name", string.Empty);
this.DBSchema = XmlHelper.GetAttributeValue(node, "dbschema", _def_dbSchema);
this.CodeFacade = XmlHelper.GetAttributeValue(node, "codeFacade", _def_codeFacade);
this.Description = XmlHelper.GetAttributeValue(node, "description", _def_description);
this.AllowModifiedAudit = XmlHelper.GetAttributeValue(node, "modifiedAudit", AllowModifiedAudit);
this.AllowCreateAudit = XmlHelper.GetAttributeValue(node, "createAudit", _def_createAudit);
this.TypedTable = (TypedTableConstants) XmlHelper.GetAttributeValue(node, "typedTable", int.Parse(TypedTable.ToString("d")));
this.AllowTimestamp = XmlHelper.GetAttributeValue(node, "timestamp", AllowTimestamp);
this.GeneratesDoubleDerived = XmlHelper.GetAttributeValue(node, "generatesDoubleDerived", _def_generatesDoubleDerived);
}
#endregion
#region Helpers
public Reference CreateRef()
{
return CreateRef(Guid.NewGuid().ToString());
}
public Reference CreateRef(string key)
{
var returnVal = new Reference(this.Root);
returnVal.ResetKey(key);
returnVal.Ref = this.Id;
returnVal.RefType = ReferenceType.Table;
return returnVal;
}
public string CamelName => StringHelper.DatabaseNameToCamelCase(this.PascalName);
public string PascalName
{
get
{
if (!string.IsNullOrEmpty(this.CodeFacade)) return this.CodeFacade;
else return this.Name;
}
}
public string DatabaseName => this.Name;
public ReadOnlyCollection<Relation> ParentRoleRelations
{
get
{
try
{
var retval = new List<Relation>();
foreach (Relation relation in ((ModelRoot)this.Root).Database.Relations)
{
if ((relation.ParentTableRef.Object != null) && (relation.ParentTableRef.Ref == this.Id))
retval.Add(relation);
}
return retval.AsReadOnly();
}
catch (Exception ex)
{
throw;
}
}
}
public ReadOnlyCollection<Relation> ChildRoleRelations
{
get
{
var retval = new List<Relation>();
foreach (Relation relation in ((ModelRoot)this.Root).Database.Relations)
{
if ((relation.ChildTableRef.Object != null) && (relation.ChildTableRef.Ref == this.Id))
retval.Add(relation);
}
return retval.AsReadOnly();
}
}
public IList<Column> PrimaryKeyColumns
{
get
{
var primaryKeyColumns = new List<Column>();
foreach (Reference columnRef in this.Columns)
{
var column = (Column)columnRef.Object;
if (column.PrimaryKey) primaryKeyColumns.Add(column);
}
return primaryKeyColumns.AsReadOnly();
}
}
#endregion
#region ICodeFacadeObject Members
public string CodeFacade { get; set; } = _def_codeFacade;
public string GetCodeFacade()
{
if (string.IsNullOrEmpty(this.CodeFacade))
return this.Name;
else
return this.CodeFacade;
}
#endregion
}
}
| |
#region License
//
// Copyright (c) 2018, Fluent Migrator Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using System;
using System.Linq;
using FluentMigrator.Runner.Generators.SqlServer;
using NUnit.Framework;
using Shouldly;
namespace FluentMigrator.Tests.Unit.Generators.SqlServer2005
{
[TestFixture]
public class SqlServer2005ColumnTests : BaseColumnTests
{
protected SqlServer2005Generator Generator;
[SetUp]
public void Setup()
{
Generator = new SqlServer2005Generator();
}
[Test]
public override void CanCreateNullableColumnWithCustomDomainTypeAndCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateColumnExpressionWithNullableCustomType();
expression.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE [TestSchema].[TestTable1] ADD [TestColumn1] MyDomainType NULL");
}
[Test]
public override void CanCreateNullableColumnWithCustomDomainTypeAndDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateColumnExpressionWithNullableCustomType();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE [dbo].[TestTable1] ADD [TestColumn1] MyDomainType NULL");
}
[Test]
public override void CanAlterColumnWithCustomSchema()
{
//TODO: This will fail if there are any keys attached
var expression = GeneratorTestHelper.GetAlterColumnExpression();
expression.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE [TestSchema].[TestTable1] ALTER COLUMN [TestColumn1] NVARCHAR(20) NOT NULL");
}
[Test]
public override void CanAlterColumnWithDefaultSchema()
{
//TODO: This will fail if there are any keys attached
var expression = GeneratorTestHelper.GetAlterColumnExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE [dbo].[TestTable1] ALTER COLUMN [TestColumn1] NVARCHAR(20) NOT NULL");
}
[Test]
public override void CanCreateAutoIncrementColumnWithCustomSchema()
{
var expression = GeneratorTestHelper.GetAlterColumnAddAutoIncrementExpression();
expression.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE [TestSchema].[TestTable1] ALTER COLUMN [TestColumn1] INT NOT NULL IDENTITY(1,1)");
}
[Test]
public override void CanCreateAutoIncrementColumnWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetAlterColumnAddAutoIncrementExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE [dbo].[TestTable1] ALTER COLUMN [TestColumn1] INT NOT NULL IDENTITY(1,1)");
}
[Test]
public override void CanCreateColumnWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateColumnExpression();
expression.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE [TestSchema].[TestTable1] ADD [TestColumn1] NVARCHAR(5) NOT NULL");
}
[Test]
public override void CanCreateColumnWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateColumnExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE [dbo].[TestTable1] ADD [TestColumn1] NVARCHAR(5) NOT NULL");
}
[Test]
public override void CanCreateColumnWithSystemMethodAndCustomSchema()
{
var expressions = GeneratorTestHelper.GetCreateColumnWithSystemMethodExpression("TestSchema");
var result = string.Join(Environment.NewLine, expressions.Select(x => (string)Generator.Generate((dynamic)x)));
result.ShouldBe(
@"ALTER TABLE [TestSchema].[TestTable1] ADD [TestColumn1] DATETIME" + Environment.NewLine +
"UPDATE [TestSchema].[TestTable1] SET [TestColumn1] = GETDATE() WHERE 1 = 1");
}
[Test]
public override void CanCreateColumnWithSystemMethodAndDefaultSchema()
{
var expressions = GeneratorTestHelper.GetCreateColumnWithSystemMethodExpression();
var result = string.Join(Environment.NewLine, expressions.Select(x => (string)Generator.Generate((dynamic)x)));
result.ShouldBe(
@"ALTER TABLE [dbo].[TestTable1] ADD [TestColumn1] DATETIME" + Environment.NewLine +
"UPDATE [dbo].[TestTable1] SET [TestColumn1] = GETDATE() WHERE 1 = 1");
}
[Test]
public override void CanCreateDecimalColumnWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateDecimalColumnExpression();
expression.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE [TestSchema].[TestTable1] ADD [TestColumn1] DECIMAL(19,2) NOT NULL");
}
[Test]
public override void CanCreateDecimalColumnWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateDecimalColumnExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE [dbo].[TestTable1] ADD [TestColumn1] DECIMAL(19,2) NOT NULL");
}
[Test]
public override void CanDropColumnWithCustomSchema()
{
//This does not work if it is a primary key
var expression = GeneratorTestHelper.GetDeleteColumnExpression();
expression.SchemaName = "TestSchema";
var expected = "DECLARE @default sysname, @sql nvarchar(max);" + Environment.NewLine + Environment.NewLine +
"-- get name of default constraint" + Environment.NewLine +
"SELECT @default = name" + Environment.NewLine +
"FROM sys.default_constraints" + Environment.NewLine +
"WHERE parent_object_id = object_id('[TestSchema].[TestTable1]')" + Environment.NewLine +
"AND type = 'D'" + Environment.NewLine +
"AND parent_column_id = (" + Environment.NewLine +
"SELECT column_id" + Environment.NewLine +
"FROM sys.columns" + Environment.NewLine +
"WHERE object_id = object_id('[TestSchema].[TestTable1]')" + Environment.NewLine +
"AND name = 'TestColumn1'" + Environment.NewLine +
");" + Environment.NewLine + Environment.NewLine +
"-- create alter table command to drop constraint as string and run it" + Environment.NewLine +
"SET @sql = N'ALTER TABLE [TestSchema].[TestTable1] DROP CONSTRAINT ' + QUOTENAME(@default);" + Environment.NewLine +
"EXEC sp_executesql @sql;" + Environment.NewLine + Environment.NewLine +
"-- now we can finally drop column" + Environment.NewLine +
"ALTER TABLE [TestSchema].[TestTable1] DROP COLUMN [TestColumn1];" + Environment.NewLine;
var result = Generator.Generate(expression);
result.ShouldBe(expected);
}
[Test]
public override void CanDropColumnWithDefaultSchema()
{
//This does not work if it is a primary key
var expression = GeneratorTestHelper.GetDeleteColumnExpression();
var expected = "DECLARE @default sysname, @sql nvarchar(max);" + Environment.NewLine + Environment.NewLine +
"-- get name of default constraint" + Environment.NewLine +
"SELECT @default = name" + Environment.NewLine +
"FROM sys.default_constraints" + Environment.NewLine +
"WHERE parent_object_id = object_id('[dbo].[TestTable1]')" + Environment.NewLine +
"AND type = 'D'" + Environment.NewLine +
"AND parent_column_id = (" + Environment.NewLine +
"SELECT column_id" + Environment.NewLine +
"FROM sys.columns" + Environment.NewLine +
"WHERE object_id = object_id('[dbo].[TestTable1]')" + Environment.NewLine +
"AND name = 'TestColumn1'" + Environment.NewLine +
");" + Environment.NewLine + Environment.NewLine +
"-- create alter table command to drop constraint as string and run it" + Environment.NewLine +
"SET @sql = N'ALTER TABLE [dbo].[TestTable1] DROP CONSTRAINT ' + QUOTENAME(@default);" + Environment.NewLine +
"EXEC sp_executesql @sql;" + Environment.NewLine + Environment.NewLine +
"-- now we can finally drop column" + Environment.NewLine +
"ALTER TABLE [dbo].[TestTable1] DROP COLUMN [TestColumn1];" + Environment.NewLine;
var result = Generator.Generate(expression);
result.ShouldBe(expected);
}
[Test]
public override void CanDropMultipleColumnsWithCustomSchema()
{
//This does not work if it is a primary key
var expression = GeneratorTestHelper.GetDeleteColumnExpression(new [] { "TestColumn1", "TestColumn2" });
expression.SchemaName = "TestSchema";
var expected = "DECLARE @default sysname, @sql nvarchar(max);" + Environment.NewLine + Environment.NewLine +
"-- get name of default constraint" + Environment.NewLine +
"SELECT @default = name" + Environment.NewLine +
"FROM sys.default_constraints" + Environment.NewLine +
"WHERE parent_object_id = object_id('[TestSchema].[TestTable1]')" + Environment.NewLine +
"AND type = 'D'" + Environment.NewLine +
"AND parent_column_id = (" + Environment.NewLine +
"SELECT column_id" + Environment.NewLine +
"FROM sys.columns" + Environment.NewLine +
"WHERE object_id = object_id('[TestSchema].[TestTable1]')" + Environment.NewLine +
"AND name = 'TestColumn1'" + Environment.NewLine +
");" + Environment.NewLine + Environment.NewLine +
"-- create alter table command to drop constraint as string and run it" + Environment.NewLine +
"SET @sql = N'ALTER TABLE [TestSchema].[TestTable1] DROP CONSTRAINT ' + QUOTENAME(@default);" + Environment.NewLine +
"EXEC sp_executesql @sql;" + Environment.NewLine + Environment.NewLine +
"-- now we can finally drop column" + Environment.NewLine +
"ALTER TABLE [TestSchema].[TestTable1] DROP COLUMN [TestColumn1];" + Environment.NewLine +
"GO" + Environment.NewLine +
"DECLARE @default sysname, @sql nvarchar(max);" + Environment.NewLine + Environment.NewLine +
"-- get name of default constraint" + Environment.NewLine +
"SELECT @default = name" + Environment.NewLine +
"FROM sys.default_constraints" + Environment.NewLine +
"WHERE parent_object_id = object_id('[TestSchema].[TestTable1]')" + Environment.NewLine +
"AND type = 'D'" + Environment.NewLine +
"AND parent_column_id = (" + Environment.NewLine +
"SELECT column_id" + Environment.NewLine +
"FROM sys.columns" + Environment.NewLine +
"WHERE object_id = object_id('[TestSchema].[TestTable1]')" + Environment.NewLine +
"AND name = 'TestColumn2'" + Environment.NewLine +
");" + Environment.NewLine + Environment.NewLine +
"-- create alter table command to drop constraint as string and run it" + Environment.NewLine +
"SET @sql = N'ALTER TABLE [TestSchema].[TestTable1] DROP CONSTRAINT ' + QUOTENAME(@default);" + Environment.NewLine +
"EXEC sp_executesql @sql;" + Environment.NewLine + Environment.NewLine +
"-- now we can finally drop column" + Environment.NewLine +
"ALTER TABLE [TestSchema].[TestTable1] DROP COLUMN [TestColumn2];" + Environment.NewLine;
var result = Generator.Generate(expression);
result.ShouldBe(expected);
}
[Test]
public override void CanDropMultipleColumnsWithDefaultSchema()
{
//This does not work if it is a primary key
var expression = GeneratorTestHelper.GetDeleteColumnExpression(new [] { "TestColumn1", "TestColumn2" });
var expected = "DECLARE @default sysname, @sql nvarchar(max);" + Environment.NewLine + Environment.NewLine +
"-- get name of default constraint" + Environment.NewLine +
"SELECT @default = name" + Environment.NewLine +
"FROM sys.default_constraints" + Environment.NewLine +
"WHERE parent_object_id = object_id('[dbo].[TestTable1]')" + Environment.NewLine + "" +
"AND type = 'D'" + Environment.NewLine +
"AND parent_column_id = (" + Environment.NewLine +
"SELECT column_id" + Environment.NewLine +
"FROM sys.columns" + Environment.NewLine +
"WHERE object_id = object_id('[dbo].[TestTable1]')" + Environment.NewLine +
"AND name = 'TestColumn1'" + Environment.NewLine +
");" + Environment.NewLine + Environment.NewLine +
"-- create alter table command to drop constraint as string and run it" + Environment.NewLine +
"SET @sql = N'ALTER TABLE [dbo].[TestTable1] DROP CONSTRAINT ' + QUOTENAME(@default);" + Environment.NewLine +
"EXEC sp_executesql @sql;" + Environment.NewLine + Environment.NewLine +
"-- now we can finally drop column" + Environment.NewLine +
"ALTER TABLE [dbo].[TestTable1] DROP COLUMN [TestColumn1];" + Environment.NewLine +
"GO" + Environment.NewLine +
"DECLARE @default sysname, @sql nvarchar(max);" + Environment.NewLine + Environment.NewLine +
"-- get name of default constraint" + Environment.NewLine +
"SELECT @default = name" + Environment.NewLine +
"FROM sys.default_constraints" + Environment.NewLine +
"WHERE parent_object_id = object_id('[dbo].[TestTable1]')" + Environment.NewLine + "" +
"AND type = 'D'" + Environment.NewLine +
"AND parent_column_id = (" + Environment.NewLine +
"SELECT column_id" + Environment.NewLine +
"FROM sys.columns" + Environment.NewLine +
"WHERE object_id = object_id('[dbo].[TestTable1]')" + Environment.NewLine +
"AND name = 'TestColumn2'" + Environment.NewLine +
");" + Environment.NewLine + Environment.NewLine +
"-- create alter table command to drop constraint as string and run it" + Environment.NewLine +
"SET @sql = N'ALTER TABLE [dbo].[TestTable1] DROP CONSTRAINT ' + QUOTENAME(@default);" + Environment.NewLine +
"EXEC sp_executesql @sql;" + Environment.NewLine + Environment.NewLine +
"-- now we can finally drop column" + Environment.NewLine +
"ALTER TABLE [dbo].[TestTable1] DROP COLUMN [TestColumn2];" + Environment.NewLine;
var result = Generator.Generate(expression);
result.ShouldBe(expected);
}
[Test]
public override void CanRenameColumnWithCustomSchema()
{
var expression = GeneratorTestHelper.GetRenameColumnExpression();
expression.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("sp_rename N'[TestSchema].[TestTable1].[TestColumn1]', N'TestColumn2'");
}
[Test]
public override void CanRenameColumnWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetRenameColumnExpression();
var result = Generator.Generate(expression);
result.ShouldBe("sp_rename N'[dbo].[TestTable1].[TestColumn1]', N'TestColumn2'");
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.DataLake.Store
{
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Azure.OData;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// AccountOperations operations.
/// </summary>
public partial interface IAccountOperations
{
/// <summary>
/// Deletes the specified firewall rule from the specified Data Lake
/// Store account
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake
/// Store account.
/// </param>
/// <param name='accountName'>
/// The name of the Data Lake Store account from which to delete the
/// firewall rule.
/// </param>
/// <param name='firewallRuleName'>
/// The name of the firewall rule to delete.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> DeleteFirewallRuleWithHttpMessagesAsync(string resourceGroupName, string accountName, string firewallRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the specified Data Lake Store firewall rule.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake
/// Store account.
/// </param>
/// <param name='accountName'>
/// The name of the Data Lake Store account from which to get the
/// firewall rule.
/// </param>
/// <param name='firewallRuleName'>
/// The name of the firewall rule to retrieve.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<FirewallRule>> GetFirewallRuleWithHttpMessagesAsync(string resourceGroupName, string accountName, string firewallRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists the Data Lake Store firewall rules within the specified Data
/// Lake Store account.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake
/// Store account.
/// </param>
/// <param name='accountName'>
/// The name of the Data Lake Store account from which to get the
/// firewall rules.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<FirewallRule>>> ListFirewallRulesWithHttpMessagesAsync(string resourceGroupName, string accountName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or updates the specified firewall rule.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake
/// Store account.
/// </param>
/// <param name='accountName'>
/// The name of the Data Lake Store account to which to add the
/// firewall rule.
/// </param>
/// <param name='name'>
/// The name of the firewall rule to create or update.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to create the create firewall rule.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<FirewallRule>> CreateOrUpdateFirewallRuleWithHttpMessagesAsync(string resourceGroupName, string accountName, string name, FirewallRule parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates the specified Data Lake Store account.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake
/// Store account.
/// </param>
/// <param name='name'>
/// The name of the Data Lake Store account to create.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to create the Data Lake Store account.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<DataLakeStoreAccount>> CreateWithHttpMessagesAsync(string resourceGroupName, string name, DataLakeStoreAccount parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates the specified Data Lake Store account.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake
/// Store account.
/// </param>
/// <param name='name'>
/// The name of the Data Lake Store account to create.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to create the Data Lake Store account.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<DataLakeStoreAccount>> BeginCreateWithHttpMessagesAsync(string resourceGroupName, string name, DataLakeStoreAccount parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Updates the specified Data Lake Store account information.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake
/// Store account.
/// </param>
/// <param name='name'>
/// The name of the Data Lake Store account to update.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to update the Data Lake Store account.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<DataLakeStoreAccount>> UpdateWithHttpMessagesAsync(string resourceGroupName, string name, DataLakeStoreAccount parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Updates the specified Data Lake Store account information.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake
/// Store account.
/// </param>
/// <param name='name'>
/// The name of the Data Lake Store account to update.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to update the Data Lake Store account.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<DataLakeStoreAccount>> BeginUpdateWithHttpMessagesAsync(string resourceGroupName, string name, DataLakeStoreAccount parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes the specified Data Lake Store account.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake
/// Store account.
/// </param>
/// <param name='accountName'>
/// The name of the Data Lake Store account to delete.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string accountName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes the specified Data Lake Store account.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake
/// Store account.
/// </param>
/// <param name='accountName'>
/// The name of the Data Lake Store account to delete.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string accountName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the specified Data Lake Store account.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake
/// Store account.
/// </param>
/// <param name='accountName'>
/// The name of the Data Lake Store account to retrieve.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<DataLakeStoreAccount>> GetWithHttpMessagesAsync(string resourceGroupName, string accountName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists the Data Lake Store accounts within a specific resource
/// group. The response includes a link to the next page of results,
/// if any.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake
/// Store account(s).
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='select'>
/// OData Select statement. Limits the properties on each entry to
/// just those requested, e.g.
/// Categories?$select=CategoryName,Description. Optional.
/// </param>
/// <param name='count'>
/// A Boolean value of true or false to request a count of the
/// matching resources included with the resources in the response,
/// e.g. Categories?$count=true. Optional.
/// </param>
/// <param name='search'>
/// A free form search. A free-text search expression to match for
/// whether a particular entry should be included in the feed, e.g.
/// Categories?$search=blue OR green. Optional.
/// </param>
/// <param name='format'>
/// The desired return format. Return the response in particular
/// formatxii without access to request headers for standard
/// content-type negotiation (e.g Orders?$format=json). Optional.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<DataLakeStoreAccount>>> ListByResourceGroupWithHttpMessagesAsync(string resourceGroupName, ODataQuery<DataLakeStoreAccount> odataQuery = default(ODataQuery<DataLakeStoreAccount>), string select = default(string), bool? count = default(bool?), string search = default(string), string format = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists the Data Lake Store accounts within the subscription. The
/// response includes a link to the next page of results, if any.
/// </summary>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='select'>
/// OData Select statement. Limits the properties on each entry to
/// just those requested, e.g.
/// Categories?$select=CategoryName,Description. Optional.
/// </param>
/// <param name='count'>
/// The Boolean value of true or false to request a count of the
/// matching resources included with the resources in the response,
/// e.g. Categories?$count=true. Optional.
/// </param>
/// <param name='search'>
/// A free form search. A free-text search expression to match for
/// whether a particular entry should be included in the feed, e.g.
/// Categories?$search=blue OR green. Optional.
/// </param>
/// <param name='format'>
/// The desired return format. Return the response in particular
/// formatxii without access to request headers for standard
/// content-type negotiation (e.g Orders?$format=json). Optional.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<DataLakeStoreAccount>>> ListWithHttpMessagesAsync(ODataQuery<DataLakeStoreAccount> odataQuery = default(ODataQuery<DataLakeStoreAccount>), string select = default(string), bool? count = default(bool?), string search = default(string), string format = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists the Data Lake Store firewall rules within the specified Data
/// Lake Store account.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<FirewallRule>>> ListFirewallRulesNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists the Data Lake Store accounts within a specific resource
/// group. The response includes a link to the next page of results,
/// if any.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<DataLakeStoreAccount>>> ListByResourceGroupNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists the Data Lake Store accounts within the subscription. The
/// response includes a link to the next page of results, if any.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<DataLakeStoreAccount>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.IO;
using System.Linq;
using System.Security.Claims;
namespace Microsoft.AspNetCore.Authentication
{
// This MUST be kept in sync with Microsoft.Owin.Security.Interop.AspNetTicketSerializer
/// <summary>
/// Serializes and deserializes <see cref="AuthenticationTicket"/> instances.
/// </summary>
public class TicketSerializer : IDataSerializer<AuthenticationTicket>
{
private const string DefaultStringPlaceholder = "\0";
private const int FormatVersion = 5;
/// <summary>
/// Gets the default implementation for <see cref="TicketSerializer"/>.
/// </summary>
public static TicketSerializer Default { get; } = new TicketSerializer();
/// <inheritdoc/>
public virtual byte[] Serialize(AuthenticationTicket ticket)
{
using (var memory = new MemoryStream())
{
using (var writer = new BinaryWriter(memory))
{
Write(writer, ticket);
}
return memory.ToArray();
}
}
/// <inheritdoc/>
public virtual AuthenticationTicket? Deserialize(byte[] data)
{
using (var memory = new MemoryStream(data))
{
using (var reader = new BinaryReader(memory))
{
return Read(reader);
}
}
}
/// <summary>
/// Writes the <paramref name="ticket"/> using the specified <paramref name="writer"/>.
/// </summary>
/// <param name="writer">The <see cref="BinaryWriter"/>.</param>
/// <param name="ticket">The <see cref="AuthenticationTicket"/>.</param>
public virtual void Write(BinaryWriter writer, AuthenticationTicket ticket)
{
if (writer == null)
{
throw new ArgumentNullException(nameof(writer));
}
if (ticket == null)
{
throw new ArgumentNullException(nameof(ticket));
}
writer.Write(FormatVersion);
writer.Write(ticket.AuthenticationScheme);
// Write the number of identities contained in the principal.
var principal = ticket.Principal;
writer.Write(principal.Identities.Count());
foreach (var identity in principal.Identities)
{
WriteIdentity(writer, identity);
}
PropertiesSerializer.Default.Write(writer, ticket.Properties);
}
/// <summary>
/// Writes the specified <paramref name="identity" />.
/// </summary>
/// <param name="writer">The <see cref="BinaryWriter" />.</param>
/// <param name="identity">The <see cref="ClaimsIdentity" />.</param>
protected virtual void WriteIdentity(BinaryWriter writer, ClaimsIdentity identity)
{
if (writer == null)
{
throw new ArgumentNullException(nameof(writer));
}
if (identity == null)
{
throw new ArgumentNullException(nameof(identity));
}
var authenticationType = identity.AuthenticationType ?? string.Empty;
writer.Write(authenticationType);
WriteWithDefault(writer, identity.NameClaimType, ClaimsIdentity.DefaultNameClaimType);
WriteWithDefault(writer, identity.RoleClaimType, ClaimsIdentity.DefaultRoleClaimType);
// Write the number of claims contained in the identity.
writer.Write(identity.Claims.Count());
foreach (var claim in identity.Claims)
{
WriteClaim(writer, claim);
}
var bootstrap = identity.BootstrapContext as string;
if (!string.IsNullOrEmpty(bootstrap))
{
writer.Write(true);
writer.Write(bootstrap);
}
else
{
writer.Write(false);
}
if (identity.Actor != null)
{
writer.Write(true);
WriteIdentity(writer, identity.Actor);
}
else
{
writer.Write(false);
}
}
/// <inheritdoc/>
protected virtual void WriteClaim(BinaryWriter writer, Claim claim)
{
if (writer == null)
{
throw new ArgumentNullException(nameof(writer));
}
if (claim == null)
{
throw new ArgumentNullException(nameof(claim));
}
WriteWithDefault(writer, claim.Type, claim.Subject?.NameClaimType ?? ClaimsIdentity.DefaultNameClaimType);
writer.Write(claim.Value);
WriteWithDefault(writer, claim.ValueType, ClaimValueTypes.String);
WriteWithDefault(writer, claim.Issuer, ClaimsIdentity.DefaultIssuer);
WriteWithDefault(writer, claim.OriginalIssuer, claim.Issuer);
// Write the number of properties contained in the claim.
writer.Write(claim.Properties.Count);
foreach (var property in claim.Properties)
{
writer.Write(property.Key ?? string.Empty);
writer.Write(property.Value ?? string.Empty);
}
}
/// <summary>
/// Reads an <see cref="AuthenticationTicket"/>.
/// </summary>
/// <param name="reader">The <see cref="BinaryReader"/>.</param>
/// <returns>The <see cref="AuthenticationTicket"/> if the format is supported, otherwise <see langword="null"/>.</returns>
public virtual AuthenticationTicket? Read(BinaryReader reader)
{
if (reader == null)
{
throw new ArgumentNullException(nameof(reader));
}
if (reader.ReadInt32() != FormatVersion)
{
return null;
}
var scheme = reader.ReadString();
// Read the number of identities stored
// in the serialized payload.
var count = reader.ReadInt32();
if (count < 0)
{
return null;
}
var identities = new ClaimsIdentity[count];
for (var index = 0; index != count; ++index)
{
identities[index] = ReadIdentity(reader);
}
var properties = PropertiesSerializer.Default.Read(reader);
return new AuthenticationTicket(new ClaimsPrincipal(identities), properties, scheme);
}
/// <summary>
/// Reads a <see cref="ClaimsIdentity"/> from a <see cref="BinaryReader"/>.
/// </summary>
/// <param name="reader">The <see cref="BinaryReader"/>.</param>
/// <returns>The read <see cref="ClaimsIdentity"/>.</returns>
protected virtual ClaimsIdentity ReadIdentity(BinaryReader reader)
{
if (reader == null)
{
throw new ArgumentNullException(nameof(reader));
}
var authenticationType = reader.ReadString();
var nameClaimType = ReadWithDefault(reader, ClaimsIdentity.DefaultNameClaimType);
var roleClaimType = ReadWithDefault(reader, ClaimsIdentity.DefaultRoleClaimType);
// Read the number of claims contained
// in the serialized identity.
var count = reader.ReadInt32();
var identity = new ClaimsIdentity(authenticationType, nameClaimType, roleClaimType);
for (int index = 0; index != count; ++index)
{
var claim = ReadClaim(reader, identity);
identity.AddClaim(claim);
}
// Determine whether the identity
// has a bootstrap context attached.
if (reader.ReadBoolean())
{
identity.BootstrapContext = reader.ReadString();
}
// Determine whether the identity
// has an actor identity attached.
if (reader.ReadBoolean())
{
identity.Actor = ReadIdentity(reader);
}
return identity;
}
/// <summary>
/// Reads a <see cref="Claim"/> and adds it to the specified <paramref name="identity"/>.
/// </summary>
/// <param name="reader">The <see cref="BinaryReader"/>.</param>
/// <param name="identity">The <see cref="ClaimsIdentity"/> to add the claim to.</param>
/// <returns>The read <see cref="Claim"/>.</returns>
protected virtual Claim ReadClaim(BinaryReader reader, ClaimsIdentity identity)
{
if (reader == null)
{
throw new ArgumentNullException(nameof(reader));
}
if (identity == null)
{
throw new ArgumentNullException(nameof(identity));
}
var type = ReadWithDefault(reader, identity.NameClaimType);
var value = reader.ReadString();
var valueType = ReadWithDefault(reader, ClaimValueTypes.String);
var issuer = ReadWithDefault(reader, ClaimsIdentity.DefaultIssuer);
var originalIssuer = ReadWithDefault(reader, issuer);
var claim = new Claim(type, value, valueType, issuer, originalIssuer, identity);
// Read the number of properties stored in the claim.
var count = reader.ReadInt32();
for (var index = 0; index != count; ++index)
{
var key = reader.ReadString();
var propertyValue = reader.ReadString();
claim.Properties.Add(key, propertyValue);
}
return claim;
}
private static void WriteWithDefault(BinaryWriter writer, string value, string defaultValue)
{
if (string.Equals(value, defaultValue, StringComparison.Ordinal))
{
writer.Write(DefaultStringPlaceholder);
}
else
{
writer.Write(value);
}
}
private static string ReadWithDefault(BinaryReader reader, string defaultValue)
{
var value = reader.ReadString();
if (string.Equals(value, DefaultStringPlaceholder, StringComparison.Ordinal))
{
return defaultValue;
}
return value;
}
}
}
| |
/*
* UltraCart Rest API V2
*
* UltraCart REST API Version 2
*
* OpenAPI spec version: 2.0.0
* Contact: support@ultracart.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
using SwaggerDateConverter = com.ultracart.admin.v2.Client.SwaggerDateConverter;
namespace com.ultracart.admin.v2.Model
{
/// <summary>
/// AffiliateLedger
/// </summary>
[DataContract]
public partial class AffiliateLedger : IEquatable<AffiliateLedger>, IValidatableObject
{
/// <summary>
/// Transaction state
/// </summary>
/// <value>Transaction state</value>
[JsonConverter(typeof(StringEnumConverter))]
public enum TransactionStateEnum
{
/// <summary>
/// Enum Pending for value: Pending
/// </summary>
[EnumMember(Value = "Pending")]
Pending = 1,
/// <summary>
/// Enum Posted for value: Posted
/// </summary>
[EnumMember(Value = "Posted")]
Posted = 2,
/// <summary>
/// Enum Approved for value: Approved
/// </summary>
[EnumMember(Value = "Approved")]
Approved = 3,
/// <summary>
/// Enum Paid for value: Paid
/// </summary>
[EnumMember(Value = "Paid")]
Paid = 4,
/// <summary>
/// Enum Rejected for value: Rejected
/// </summary>
[EnumMember(Value = "Rejected")]
Rejected = 5,
/// <summary>
/// Enum PartiallyPaid for value: Partially Paid
/// </summary>
[EnumMember(Value = "Partially Paid")]
PartiallyPaid = 6
}
/// <summary>
/// Transaction state
/// </summary>
/// <value>Transaction state</value>
[DataMember(Name="transaction_state", EmitDefaultValue=false)]
public TransactionStateEnum? TransactionState { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="AffiliateLedger" /> class.
/// </summary>
/// <param name="affiliateClickOid">Unique object identifier for the click associated with this ledger entry.</param>
/// <param name="affiliateLedgerOid">Affiliate ledger object ID associated with this ledger.</param>
/// <param name="affiliateLinkOid">Unique object identifier for the link that this click is associated with.</param>
/// <param name="affiliateOid">Affiliate object ID associated with this transaction.</param>
/// <param name="assignedByUser">User that assigned the transaction if it was done manually.</param>
/// <param name="click">click.</param>
/// <param name="itemId">Item ID associated with this transaction.</param>
/// <param name="link">link.</param>
/// <param name="order">order.</param>
/// <param name="orderId">Order ID associated with this transaction.</param>
/// <param name="originalTransactionDts">Date/time of the original transaction for reversals.</param>
/// <param name="subId">Sub ID associated with transaction (from the click).</param>
/// <param name="tierNumber">Tier number that this transaction earned.</param>
/// <param name="transactionAmount">Transaction amount.</param>
/// <param name="transactionAmountPaid">Amount of the transaction that has been paid out..</param>
/// <param name="transactionDts">Date/time that the transaction was made.</param>
/// <param name="transactionMemo">Memo explaining the transaction.</param>
/// <param name="transactionPercentage">Percentage associated with this transaction.</param>
/// <param name="transactionState">Transaction state.</param>
public AffiliateLedger(int? affiliateClickOid = default(int?), int? affiliateLedgerOid = default(int?), int? affiliateLinkOid = default(int?), int? affiliateOid = default(int?), string assignedByUser = default(string), AffiliateClick click = default(AffiliateClick), string itemId = default(string), AffiliateLink link = default(AffiliateLink), Order order = default(Order), string orderId = default(string), string originalTransactionDts = default(string), string subId = default(string), int? tierNumber = default(int?), decimal? transactionAmount = default(decimal?), decimal? transactionAmountPaid = default(decimal?), string transactionDts = default(string), string transactionMemo = default(string), decimal? transactionPercentage = default(decimal?), TransactionStateEnum? transactionState = default(TransactionStateEnum?))
{
this.AffiliateClickOid = affiliateClickOid;
this.AffiliateLedgerOid = affiliateLedgerOid;
this.AffiliateLinkOid = affiliateLinkOid;
this.AffiliateOid = affiliateOid;
this.AssignedByUser = assignedByUser;
this.Click = click;
this.ItemId = itemId;
this.Link = link;
this.Order = order;
this.OrderId = orderId;
this.OriginalTransactionDts = originalTransactionDts;
this.SubId = subId;
this.TierNumber = tierNumber;
this.TransactionAmount = transactionAmount;
this.TransactionAmountPaid = transactionAmountPaid;
this.TransactionDts = transactionDts;
this.TransactionMemo = transactionMemo;
this.TransactionPercentage = transactionPercentage;
this.TransactionState = transactionState;
}
/// <summary>
/// Unique object identifier for the click associated with this ledger entry
/// </summary>
/// <value>Unique object identifier for the click associated with this ledger entry</value>
[DataMember(Name="affiliate_click_oid", EmitDefaultValue=false)]
public int? AffiliateClickOid { get; set; }
/// <summary>
/// Affiliate ledger object ID associated with this ledger
/// </summary>
/// <value>Affiliate ledger object ID associated with this ledger</value>
[DataMember(Name="affiliate_ledger_oid", EmitDefaultValue=false)]
public int? AffiliateLedgerOid { get; set; }
/// <summary>
/// Unique object identifier for the link that this click is associated with
/// </summary>
/// <value>Unique object identifier for the link that this click is associated with</value>
[DataMember(Name="affiliate_link_oid", EmitDefaultValue=false)]
public int? AffiliateLinkOid { get; set; }
/// <summary>
/// Affiliate object ID associated with this transaction
/// </summary>
/// <value>Affiliate object ID associated with this transaction</value>
[DataMember(Name="affiliate_oid", EmitDefaultValue=false)]
public int? AffiliateOid { get; set; }
/// <summary>
/// User that assigned the transaction if it was done manually
/// </summary>
/// <value>User that assigned the transaction if it was done manually</value>
[DataMember(Name="assigned_by_user", EmitDefaultValue=false)]
public string AssignedByUser { get; set; }
/// <summary>
/// Gets or Sets Click
/// </summary>
[DataMember(Name="click", EmitDefaultValue=false)]
public AffiliateClick Click { get; set; }
/// <summary>
/// Item ID associated with this transaction
/// </summary>
/// <value>Item ID associated with this transaction</value>
[DataMember(Name="item_id", EmitDefaultValue=false)]
public string ItemId { get; set; }
/// <summary>
/// Gets or Sets Link
/// </summary>
[DataMember(Name="link", EmitDefaultValue=false)]
public AffiliateLink Link { get; set; }
/// <summary>
/// Gets or Sets Order
/// </summary>
[DataMember(Name="order", EmitDefaultValue=false)]
public Order Order { get; set; }
/// <summary>
/// Order ID associated with this transaction
/// </summary>
/// <value>Order ID associated with this transaction</value>
[DataMember(Name="order_id", EmitDefaultValue=false)]
public string OrderId { get; set; }
/// <summary>
/// Date/time of the original transaction for reversals
/// </summary>
/// <value>Date/time of the original transaction for reversals</value>
[DataMember(Name="original_transaction_dts", EmitDefaultValue=false)]
public string OriginalTransactionDts { get; set; }
/// <summary>
/// Sub ID associated with transaction (from the click)
/// </summary>
/// <value>Sub ID associated with transaction (from the click)</value>
[DataMember(Name="sub_id", EmitDefaultValue=false)]
public string SubId { get; set; }
/// <summary>
/// Tier number that this transaction earned
/// </summary>
/// <value>Tier number that this transaction earned</value>
[DataMember(Name="tier_number", EmitDefaultValue=false)]
public int? TierNumber { get; set; }
/// <summary>
/// Transaction amount
/// </summary>
/// <value>Transaction amount</value>
[DataMember(Name="transaction_amount", EmitDefaultValue=false)]
public decimal? TransactionAmount { get; set; }
/// <summary>
/// Amount of the transaction that has been paid out.
/// </summary>
/// <value>Amount of the transaction that has been paid out.</value>
[DataMember(Name="transaction_amount_paid", EmitDefaultValue=false)]
public decimal? TransactionAmountPaid { get; set; }
/// <summary>
/// Date/time that the transaction was made
/// </summary>
/// <value>Date/time that the transaction was made</value>
[DataMember(Name="transaction_dts", EmitDefaultValue=false)]
public string TransactionDts { get; set; }
/// <summary>
/// Memo explaining the transaction
/// </summary>
/// <value>Memo explaining the transaction</value>
[DataMember(Name="transaction_memo", EmitDefaultValue=false)]
public string TransactionMemo { get; set; }
/// <summary>
/// Percentage associated with this transaction
/// </summary>
/// <value>Percentage associated with this transaction</value>
[DataMember(Name="transaction_percentage", EmitDefaultValue=false)]
public decimal? TransactionPercentage { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class AffiliateLedger {\n");
sb.Append(" AffiliateClickOid: ").Append(AffiliateClickOid).Append("\n");
sb.Append(" AffiliateLedgerOid: ").Append(AffiliateLedgerOid).Append("\n");
sb.Append(" AffiliateLinkOid: ").Append(AffiliateLinkOid).Append("\n");
sb.Append(" AffiliateOid: ").Append(AffiliateOid).Append("\n");
sb.Append(" AssignedByUser: ").Append(AssignedByUser).Append("\n");
sb.Append(" Click: ").Append(Click).Append("\n");
sb.Append(" ItemId: ").Append(ItemId).Append("\n");
sb.Append(" Link: ").Append(Link).Append("\n");
sb.Append(" Order: ").Append(Order).Append("\n");
sb.Append(" OrderId: ").Append(OrderId).Append("\n");
sb.Append(" OriginalTransactionDts: ").Append(OriginalTransactionDts).Append("\n");
sb.Append(" SubId: ").Append(SubId).Append("\n");
sb.Append(" TierNumber: ").Append(TierNumber).Append("\n");
sb.Append(" TransactionAmount: ").Append(TransactionAmount).Append("\n");
sb.Append(" TransactionAmountPaid: ").Append(TransactionAmountPaid).Append("\n");
sb.Append(" TransactionDts: ").Append(TransactionDts).Append("\n");
sb.Append(" TransactionMemo: ").Append(TransactionMemo).Append("\n");
sb.Append(" TransactionPercentage: ").Append(TransactionPercentage).Append("\n");
sb.Append(" TransactionState: ").Append(TransactionState).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public virtual string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as AffiliateLedger);
}
/// <summary>
/// Returns true if AffiliateLedger instances are equal
/// </summary>
/// <param name="input">Instance of AffiliateLedger to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(AffiliateLedger input)
{
if (input == null)
return false;
return
(
this.AffiliateClickOid == input.AffiliateClickOid ||
(this.AffiliateClickOid != null &&
this.AffiliateClickOid.Equals(input.AffiliateClickOid))
) &&
(
this.AffiliateLedgerOid == input.AffiliateLedgerOid ||
(this.AffiliateLedgerOid != null &&
this.AffiliateLedgerOid.Equals(input.AffiliateLedgerOid))
) &&
(
this.AffiliateLinkOid == input.AffiliateLinkOid ||
(this.AffiliateLinkOid != null &&
this.AffiliateLinkOid.Equals(input.AffiliateLinkOid))
) &&
(
this.AffiliateOid == input.AffiliateOid ||
(this.AffiliateOid != null &&
this.AffiliateOid.Equals(input.AffiliateOid))
) &&
(
this.AssignedByUser == input.AssignedByUser ||
(this.AssignedByUser != null &&
this.AssignedByUser.Equals(input.AssignedByUser))
) &&
(
this.Click == input.Click ||
(this.Click != null &&
this.Click.Equals(input.Click))
) &&
(
this.ItemId == input.ItemId ||
(this.ItemId != null &&
this.ItemId.Equals(input.ItemId))
) &&
(
this.Link == input.Link ||
(this.Link != null &&
this.Link.Equals(input.Link))
) &&
(
this.Order == input.Order ||
(this.Order != null &&
this.Order.Equals(input.Order))
) &&
(
this.OrderId == input.OrderId ||
(this.OrderId != null &&
this.OrderId.Equals(input.OrderId))
) &&
(
this.OriginalTransactionDts == input.OriginalTransactionDts ||
(this.OriginalTransactionDts != null &&
this.OriginalTransactionDts.Equals(input.OriginalTransactionDts))
) &&
(
this.SubId == input.SubId ||
(this.SubId != null &&
this.SubId.Equals(input.SubId))
) &&
(
this.TierNumber == input.TierNumber ||
(this.TierNumber != null &&
this.TierNumber.Equals(input.TierNumber))
) &&
(
this.TransactionAmount == input.TransactionAmount ||
(this.TransactionAmount != null &&
this.TransactionAmount.Equals(input.TransactionAmount))
) &&
(
this.TransactionAmountPaid == input.TransactionAmountPaid ||
(this.TransactionAmountPaid != null &&
this.TransactionAmountPaid.Equals(input.TransactionAmountPaid))
) &&
(
this.TransactionDts == input.TransactionDts ||
(this.TransactionDts != null &&
this.TransactionDts.Equals(input.TransactionDts))
) &&
(
this.TransactionMemo == input.TransactionMemo ||
(this.TransactionMemo != null &&
this.TransactionMemo.Equals(input.TransactionMemo))
) &&
(
this.TransactionPercentage == input.TransactionPercentage ||
(this.TransactionPercentage != null &&
this.TransactionPercentage.Equals(input.TransactionPercentage))
) &&
(
this.TransactionState == input.TransactionState ||
(this.TransactionState != null &&
this.TransactionState.Equals(input.TransactionState))
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.AffiliateClickOid != null)
hashCode = hashCode * 59 + this.AffiliateClickOid.GetHashCode();
if (this.AffiliateLedgerOid != null)
hashCode = hashCode * 59 + this.AffiliateLedgerOid.GetHashCode();
if (this.AffiliateLinkOid != null)
hashCode = hashCode * 59 + this.AffiliateLinkOid.GetHashCode();
if (this.AffiliateOid != null)
hashCode = hashCode * 59 + this.AffiliateOid.GetHashCode();
if (this.AssignedByUser != null)
hashCode = hashCode * 59 + this.AssignedByUser.GetHashCode();
if (this.Click != null)
hashCode = hashCode * 59 + this.Click.GetHashCode();
if (this.ItemId != null)
hashCode = hashCode * 59 + this.ItemId.GetHashCode();
if (this.Link != null)
hashCode = hashCode * 59 + this.Link.GetHashCode();
if (this.Order != null)
hashCode = hashCode * 59 + this.Order.GetHashCode();
if (this.OrderId != null)
hashCode = hashCode * 59 + this.OrderId.GetHashCode();
if (this.OriginalTransactionDts != null)
hashCode = hashCode * 59 + this.OriginalTransactionDts.GetHashCode();
if (this.SubId != null)
hashCode = hashCode * 59 + this.SubId.GetHashCode();
if (this.TierNumber != null)
hashCode = hashCode * 59 + this.TierNumber.GetHashCode();
if (this.TransactionAmount != null)
hashCode = hashCode * 59 + this.TransactionAmount.GetHashCode();
if (this.TransactionAmountPaid != null)
hashCode = hashCode * 59 + this.TransactionAmountPaid.GetHashCode();
if (this.TransactionDts != null)
hashCode = hashCode * 59 + this.TransactionDts.GetHashCode();
if (this.TransactionMemo != null)
hashCode = hashCode * 59 + this.TransactionMemo.GetHashCode();
if (this.TransactionPercentage != null)
hashCode = hashCode * 59 + this.TransactionPercentage.GetHashCode();
if (this.TransactionState != null)
hashCode = hashCode * 59 + this.TransactionState.GetHashCode();
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;
using Xunit;
namespace System.Linq.Expressions.Tests
{
public static class NewTests
{
#region Test methods
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckNewCustomTest(bool useInterpreter)
{
Expression<Func<C>> e =
Expression.Lambda<Func<C>>(
Expression.New(typeof(C)),
Enumerable.Empty<ParameterExpression>());
Func<C> f = e.Compile(useInterpreter);
Assert.Equal(new C(), f());
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckNewEnumTest(bool useInterpreter)
{
Expression<Func<E>> e =
Expression.Lambda<Func<E>>(
Expression.New(typeof(E)),
Enumerable.Empty<ParameterExpression>());
Func<E> f = e.Compile(useInterpreter);
Assert.Equal(new E(), f());
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckNewNullableEnumTest(bool useInterpreter)
{
Expression<Func<E?>> e =
Expression.Lambda<Func<E?>>(
Expression.New(typeof(E?)),
Enumerable.Empty<ParameterExpression>());
Func<E?> f = e.Compile(useInterpreter);
Assert.Equal(new E?(), f());
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckNewNullableIntTest(bool useInterpreter)
{
Expression<Func<int?>> e =
Expression.Lambda<Func<int?>>(
Expression.New(typeof(int?)),
Enumerable.Empty<ParameterExpression>());
Func<int?> f = e.Compile(useInterpreter);
Assert.Equal(new int?(), f());
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckNewStructTest(bool useInterpreter)
{
Expression<Func<S>> e =
Expression.Lambda<Func<S>>(
Expression.New(typeof(S)),
Enumerable.Empty<ParameterExpression>());
Func<S> f = e.Compile(useInterpreter);
Assert.Equal(new S(), f());
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckNewNullableStructTest(bool useInterpreter)
{
Expression<Func<S?>> e =
Expression.Lambda<Func<S?>>(
Expression.New(typeof(S?)),
Enumerable.Empty<ParameterExpression>());
Func<S?> f = e.Compile(useInterpreter);
Assert.Equal(new S?(), f());
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckNewStructWithStringTest(bool useInterpreter)
{
Expression<Func<Sc>> e =
Expression.Lambda<Func<Sc>>(
Expression.New(typeof(Sc)),
Enumerable.Empty<ParameterExpression>());
Func<Sc> f = e.Compile(useInterpreter);
Assert.Equal(new Sc(), f());
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckNewNullableStructWithStringTest(bool useInterpreter)
{
Expression<Func<Sc?>> e =
Expression.Lambda<Func<Sc?>>(
Expression.New(typeof(Sc?)),
Enumerable.Empty<ParameterExpression>());
Func<Sc?> f = e.Compile(useInterpreter);
Assert.Equal(new Sc?(), f());
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckNewStructWithStringAndFieldTest(bool useInterpreter)
{
Expression<Func<Scs>> e =
Expression.Lambda<Func<Scs>>(
Expression.New(typeof(Scs)),
Enumerable.Empty<ParameterExpression>());
Func<Scs> f = e.Compile(useInterpreter);
Assert.Equal(new Scs(), f());
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckNewNullableStructWithStringAndFieldTest(bool useInterpreter)
{
Expression<Func<Scs?>> e =
Expression.Lambda<Func<Scs?>>(
Expression.New(typeof(Scs?)),
Enumerable.Empty<ParameterExpression>());
Func<Scs?> f = e.Compile(useInterpreter);
Assert.Equal(new Scs?(), f());
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckNewStructWithTwoValuesTest(bool useInterpreter)
{
Expression<Func<Sp>> e =
Expression.Lambda<Func<Sp>>(
Expression.New(typeof(Sp)),
Enumerable.Empty<ParameterExpression>());
Func<Sp> f = e.Compile(useInterpreter);
Assert.Equal(new Sp(), f());
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckNewNullableStructWithTwoValuesTest(bool useInterpreter)
{
Expression<Func<Sp?>> e =
Expression.Lambda<Func<Sp?>>(
Expression.New(typeof(Sp?)),
Enumerable.Empty<ParameterExpression>());
Func<Sp?> f = e.Compile(useInterpreter);
Assert.Equal(new Sp?(), f());
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckNewGenericWithStructRestrictionWithEnumTest(bool useInterpreter)
{
CheckNewGenericWithStructRestrictionHelper<E>(useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckNewGenericWithStructRestrictionWithStructTest(bool useInterpreter)
{
CheckNewGenericWithStructRestrictionHelper<S>(useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckNewGenericWithStructRestrictionWithStructWithStringAndFieldTest(bool useInterpreter)
{
CheckNewGenericWithStructRestrictionHelper<Scs>(useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckNewNullableGenericWithStructRestrictionWithEnumTest(bool useInterpreter)
{
CheckNewNullableGenericWithStructRestrictionHelper<E>(useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckNewNullableGenericWithStructRestrictionWithStructTest(bool useInterpreter)
{
CheckNewNullableGenericWithStructRestrictionHelper<S>(useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckNewNullableGenericWithStructRestrictionWithStructWithStringAndFieldTest(bool useInterpreter)
{
CheckNewNullableGenericWithStructRestrictionHelper<Scs>(useInterpreter);
}
#endregion
#region Generic helpers
private static void CheckNewGenericWithStructRestrictionHelper<Ts>(bool useInterpreter) where Ts : struct
{
Expression<Func<Ts>> e =
Expression.Lambda<Func<Ts>>(
Expression.New(typeof(Ts)),
Enumerable.Empty<ParameterExpression>());
Func<Ts> f = e.Compile(useInterpreter);
Assert.Equal(new Ts(), f());
}
private static void CheckNewNullableGenericWithStructRestrictionHelper<Ts>(bool useInterpreter) where Ts : struct
{
Expression<Func<Ts?>> e =
Expression.Lambda<Func<Ts?>>(
Expression.New(typeof(Ts?)),
Enumerable.Empty<ParameterExpression>());
Func<Ts?> f = e.Compile(useInterpreter);
Assert.Equal(new Ts?(), f());
}
#endregion
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void PrivateDefaultConstructor(bool useInterpreter)
{
Assert.Equal("Test instance", TestPrivateDefaultConstructor.GetInstanceFunc(useInterpreter)().ToString());
}
class TestPrivateDefaultConstructor
{
private TestPrivateDefaultConstructor() { }
public static Func<TestPrivateDefaultConstructor> GetInstanceFunc(bool useInterpreter)
{
Expression<Func<TestPrivateDefaultConstructor>> lambda = Expression.Lambda<Func<TestPrivateDefaultConstructor>>(Expression.New(typeof(TestPrivateDefaultConstructor)), new ParameterExpression[] { });
return lambda.Compile(useInterpreter);
}
public override string ToString() => "Test instance";
}
[Fact]
public static void New_NullConstructor_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("constructor", () => Expression.New((ConstructorInfo)null));
AssertExtensions.Throws<ArgumentNullException>("constructor", () => Expression.New(null, new Expression[0]));
AssertExtensions.Throws<ArgumentNullException>("constructor", () => Expression.New(null, (IEnumerable<Expression>)new Expression[0]));
AssertExtensions.Throws<ArgumentNullException>("constructor", () => Expression.New(null, new Expression[0], new MemberInfo[0]));
AssertExtensions.Throws<ArgumentNullException>("constructor", () => Expression.New(null, new Expression[0], (IEnumerable<MemberInfo>)new MemberInfo[0]));
}
[Fact]
public static void StaticConstructor_ThrowsArgumentException()
{
ConstructorInfo cctor = typeof(StaticCtor).GetTypeInfo().DeclaredConstructors.Single(c => c.IsStatic);
AssertExtensions.Throws<ArgumentException>("constructor", () => Expression.New(cctor));
AssertExtensions.Throws<ArgumentException>("constructor", () => Expression.New(cctor, new Expression[0]));
AssertExtensions.Throws<ArgumentException>("constructor", () => Expression.New(cctor, (IEnumerable<Expression>)new Expression[0]));
AssertExtensions.Throws<ArgumentException>("constructor", () => Expression.New(cctor, new Expression[0], new MemberInfo[0]));
AssertExtensions.Throws<ArgumentException>("constructor", () => Expression.New(cctor, new Expression[0], (IEnumerable<MemberInfo>)new MemberInfo[0]));
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void Compile_AbstractCtor_ThrowsInvalidOperationException(bool useInterpretation)
{
ConstructorInfo ctor = typeof(AbstractCtor).GetTypeInfo().DeclaredConstructors.Single();
Expression<Func<AbstractCtor>> f = Expression.Lambda<Func<AbstractCtor>>(Expression.New(ctor));
Assert.Throws<InvalidOperationException>(() => f.Compile(useInterpretation));
}
[Fact]
public static void ConstructorDeclaringType_GenericTypeDefinition_ThrowsArgumentException()
{
ConstructorInfo constructor = typeof(GenericClass<>).GetConstructor(new Type[0]);
AssertExtensions.Throws<ArgumentException>("constructor", () => Expression.New(constructor));
AssertExtensions.Throws<ArgumentException>("constructor", () => Expression.New(constructor, new Expression[0]));
AssertExtensions.Throws<ArgumentException>("constructor", () => Expression.New(constructor, (IEnumerable<Expression>)new Expression[0]));
AssertExtensions.Throws<ArgumentException>("constructor", () => Expression.New(constructor, new Expression[0], new MemberInfo[0]));
AssertExtensions.Throws<ArgumentException>("constructor", () => Expression.New(constructor, new Expression[0], (IEnumerable<MemberInfo>)new MemberInfo[0]));
}
public static IEnumerable<object[]> ConstructorAndArguments_DifferentLengths_TestData()
{
yield return new object[] { typeof(ClassWithCtors).GetConstructor(new Type[0]), new Expression[2] };
yield return new object[] { typeof(ClassWithCtors).GetConstructor(new Type[] { typeof(string) }), new Expression[0] };
yield return new object[] { typeof(ClassWithCtors).GetConstructor(new Type[] { typeof(string) }), new Expression[2] };
}
[Theory]
[MemberData(nameof(ConstructorAndArguments_DifferentLengths_TestData))]
public static void ConstructorAndArguments_DifferentLengths_ThrowsArgumentException(ConstructorInfo constructor, Expression[] expressions)
{
if (expressions.Length == 0)
{
AssertExtensions.Throws<ArgumentException>(null, () => Expression.New(constructor));
}
AssertExtensions.Throws<ArgumentException>(null, () => Expression.New(constructor, expressions));
AssertExtensions.Throws<ArgumentException>(null, () => Expression.New(constructor, (IEnumerable<Expression>)expressions));
AssertExtensions.Throws<ArgumentException>(null, () => Expression.New(constructor, expressions, new MemberInfo[expressions.Length]));
AssertExtensions.Throws<ArgumentException>(null, () => Expression.New(constructor, expressions, (IEnumerable<MemberInfo>)new MemberInfo[expressions.Length]));
}
[Fact]
public static void Arguments_ExpressionNotReadable_ThrowsArgumentException()
{
ConstructorInfo constructor = typeof(ClassWithCtors).GetConstructor(new Type[] { typeof(string) });
Expression[] expressions = new Expression[] { Expression.Property(null, typeof(Unreachable<string>), nameof(Unreachable<string>.WriteOnly)) };
AssertExtensions.Throws<ArgumentException>("arguments[0]", () => Expression.New(constructor, expressions));
AssertExtensions.Throws<ArgumentException>("arguments[0]", () => Expression.New(constructor, (IEnumerable<Expression>)expressions));
AssertExtensions.Throws<ArgumentException>("arguments[0]", () => Expression.New(constructor, expressions, new MemberInfo[1]));
AssertExtensions.Throws<ArgumentException>("arguments[0]", () => Expression.New(constructor, expressions, (IEnumerable<MemberInfo>)new MemberInfo[1]));
}
[Fact]
public static void ConstructorAndArguments_IncompatibleTypes_ThrowsArgumentException()
{
ConstructorInfo constructor = typeof(ClassWithCtors).GetConstructor(new Type[] { typeof(string) });
Expression[] expressions = new Expression[] { Expression.Constant(5) };
AssertExtensions.Throws<ArgumentException>("arguments[0]", () => Expression.New(constructor, expressions));
AssertExtensions.Throws<ArgumentException>("arguments[0]", () => Expression.New(constructor, (IEnumerable<Expression>)expressions));
MemberInfo[] members = new MemberInfo[] { typeof(ClassWithCtors).GetProperty(nameof(ClassWithCtors.IntProperty)) };
AssertExtensions.Throws<ArgumentException>("arguments[0]", () => Expression.New(constructor, expressions, members));
AssertExtensions.Throws<ArgumentException>("arguments[0]", () => Expression.New(constructor, expressions, members));
}
public static IEnumerable<object[]> ArgumentsAndMembers_DifferentLengths_TestData()
{
yield return new object[] { typeof(ClassWithCtors).GetConstructor(new Type[0]), new Expression[0], new MemberInfo[1] };
yield return new object[] { typeof(ClassWithCtors).GetConstructor(new Type[] { typeof(string) }), new Expression[1], new MemberInfo[0] };
yield return new object[] { typeof(ClassWithCtors).GetConstructor(new Type[] { typeof(string) }), new Expression[1], new MemberInfo[2] };
}
[Theory]
[MemberData(nameof(ArgumentsAndMembers_DifferentLengths_TestData))]
public static void ArgumentsAndMembers_DifferentLengths_ThrowsArgumentException(ConstructorInfo constructor, Expression[] arguments, MemberInfo[] members)
{
AssertExtensions.Throws<ArgumentException>(null, () => Expression.New(constructor, arguments, members));
AssertExtensions.Throws<ArgumentException>(null, () => Expression.New(constructor, arguments, (IEnumerable<MemberInfo>)members));
}
[Fact]
public static void Members_MemberNotOnDeclaringType_ThrowsArgumentException()
{
ConstructorInfo constructor = typeof(ClassWithCtors).GetConstructor(new Type[] { typeof(string) });
Expression[] arguments = new Expression[] { Expression.Constant("hello") };
MemberInfo[] members = new MemberInfo[] { typeof(Unreachable<string>).GetProperty(nameof(Unreachable<string>.WriteOnly)) };
AssertExtensions.Throws<ArgumentException>("members[0]", () => Expression.New(constructor, arguments, members));
AssertExtensions.Throws<ArgumentException>("members[0]", () => Expression.New(constructor, arguments, (IEnumerable<MemberInfo>)members));
}
[Theory]
[InlineData(nameof(ClassWithCtors.s_field))]
[InlineData(nameof(ClassWithCtors.StaticProperty))]
[InlineData(nameof(ClassWithCtors.StaticMethod))]
public static void Members_StaticMember_ThrowsArgumentException(string memberName)
{
ConstructorInfo constructor = typeof(ClassWithCtors).GetConstructor(new Type[] { typeof(string) });
Expression[] arguments = new Expression[] { Expression.Constant("hello") };
MemberInfo[] members = new MemberInfo[] { typeof(ClassWithCtors).GetMember(memberName).First() };
AssertExtensions.Throws<ArgumentException>("members[0]", () => Expression.New(constructor, arguments, members));
AssertExtensions.Throws<ArgumentException>("members[0]", () => Expression.New(constructor, arguments, (IEnumerable<MemberInfo>)members));
}
[Fact]
public static void Members_MemberWriteOnly_ThrowsArgumentException()
{
ConstructorInfo constructor = typeof(ClassWithCtors).GetConstructor(new Type[] { typeof(string) });
Expression[] arguments = new Expression[] { Expression.Constant("hello") };
MemberInfo[] members = new MemberInfo[] { typeof(ClassWithCtors).GetProperty(nameof(ClassWithCtors.WriteOnlyProperty)) };
AssertExtensions.Throws<ArgumentException>("members[0]", () => Expression.New(constructor, arguments, members));
AssertExtensions.Throws<ArgumentException>("members[0]", () => Expression.New(constructor, arguments, (IEnumerable<MemberInfo>)members));
}
[Fact]
public static void Members_MemberNotPropertyAccessor_ThrowsArgumentException()
{
ConstructorInfo constructor = typeof(ClassWithCtors).GetConstructor(new Type[] { typeof(string) });
Expression[] arguments = new Expression[] { Expression.Constant("hello") };
MemberInfo[] members = new MemberInfo[] { typeof(ClassWithCtors).GetMethod(nameof(ClassWithCtors.InstanceMethod)) };
AssertExtensions.Throws<ArgumentException>("members[0]", () => Expression.New(constructor, arguments, members));
AssertExtensions.Throws<ArgumentException>("members[0]", () => Expression.New(constructor, arguments, (IEnumerable<MemberInfo>)members));
}
[Fact]
public static void Members_MemberNotFieldPropertyOrMethod_ThrowsArgumentException()
{
ConstructorInfo constructor = typeof(ClassWithCtors).GetConstructor(new Type[] { typeof(string) });
Expression[] arguments = new Expression[] { Expression.Constant("hello") };
MemberInfo[] members = new MemberInfo[] { constructor };
AssertExtensions.Throws<ArgumentException>("members[0]", () => Expression.New(constructor, arguments, members));
AssertExtensions.Throws<ArgumentException>("members[0]", () => Expression.New(constructor, arguments, (IEnumerable<MemberInfo>)members));
}
[Fact]
public static void Members_ArgumentTypeAndMemberTypeDontMatch_ThrowsArgumentException()
{
ConstructorInfo constructor = typeof(ClassWithCtors).GetConstructor(new Type[] { typeof(string) });
Expression[] arguments = new Expression[] { Expression.Constant("hello") };
MemberInfo[] members = new MemberInfo[] { typeof(ClassWithCtors).GetField(nameof(ClassWithCtors._field)) };
AssertExtensions.Throws<ArgumentException>("arguments[0]", () => Expression.New(constructor, arguments, members));
AssertExtensions.Throws<ArgumentException>("arguments[0]", () => Expression.New(constructor, arguments, (IEnumerable<MemberInfo>)members));
}
[Fact]
public static void Type_Null_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("type", () => Expression.New((Type)null));
}
[Fact]
public static void ToStringTest()
{
NewExpression e1 = Expression.New(typeof(Bar).GetConstructor(Type.EmptyTypes));
Assert.Equal("new Bar()", e1.ToString());
NewExpression e2 = Expression.New(typeof(Bar).GetConstructor(new[] { typeof(int) }), Expression.Parameter(typeof(int), "foo"));
Assert.Equal("new Bar(foo)", e2.ToString());
NewExpression e3 = Expression.New(typeof(Bar).GetConstructor(new[] { typeof(int), typeof(int) }), Expression.Parameter(typeof(int), "foo"), Expression.Parameter(typeof(int), "qux"));
Assert.Equal("new Bar(foo, qux)", e3.ToString());
NewExpression e4 = Expression.New(typeof(Bar).GetConstructor(new[] { typeof(int), typeof(int) }), new[] { Expression.Parameter(typeof(int), "foo"), Expression.Parameter(typeof(int), "qux") }, new[] { typeof(Bar).GetProperty(nameof(Bar.Foo)), typeof(Bar).GetProperty(nameof(Bar.Qux)) });
Assert.Equal("new Bar(Foo = foo, Qux = qux)", e4.ToString());
}
[Fact]
public static void NullUpdateValidForEmptyParameters()
{
NewExpression newExp = Expression.New(typeof(Bar).GetConstructor(Type.EmptyTypes));
Assert.Same(newExp, newExp.Update(null));
}
public static IEnumerable<object[]> Type_InvalidType_TestData()
{
yield return new object[] { typeof(void) };
yield return new object[] { typeof(int).MakeByRefType() };
yield return new object[] { typeof(StaticCtor) };
yield return new object[] { typeof(ClassWithNoDefaultCtor) };
yield return new object[] { typeof(int).MakePointerType() };
Type listType = typeof(List<>);
yield return new object[] { listType };
yield return new object[] { listType.MakeGenericType(listType) };
}
[Theory]
[MemberData(nameof(Type_InvalidType_TestData))]
public static void Type_InvalidType_ThrowsArgumentException(Type type)
{
AssertExtensions.Throws<ArgumentException>("type", () => Expression.New(type));
}
public static IEnumerable<object[]> OpenGenericConstructors()
{
Type listType = typeof(List<>);
foreach (Type t in new[] {listType, listType.MakeGenericType(listType)})
{
foreach (ConstructorInfo ctor in t.GetConstructors())
{
IEnumerable<Type> types = ctor.GetParameters().Select(p => p.ParameterType);
if (!types.Any(pt => pt.ContainsGenericParameters))
{
yield return new object[] {ctor, types.Select(pt => Expression.Default(pt))};
}
}
}
}
[Theory, MemberData(nameof(OpenGenericConstructors))]
public static void OpenGenericConstructorsInvalid(ConstructorInfo ctor, Expression[] arguments)
{
AssertExtensions.Throws<ArgumentException>("constructor", () => Expression.New(ctor, arguments));
if (arguments.Length == 0)
{
AssertExtensions.Throws<ArgumentException>("constructor", () => Expression.New(ctor));
}
}
#if FEATURE_COMPILE
[Fact]
public static void GlobalMethodInMembers()
{
ModuleBuilder module = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("Name"), AssemblyBuilderAccess.RunAndCollect).DefineDynamicModule("Module");
MethodBuilder globalMethod = module.DefineGlobalMethod("GlobalMethod", MethodAttributes.Public | MethodAttributes.Static, typeof(int), Type.EmptyTypes);
globalMethod.GetILGenerator().Emit(OpCodes.Ret);
module.CreateGlobalFunctions();
MethodInfo globalMethodInfo = module.GetMethod(globalMethod.Name);
ConstructorInfo constructor = typeof(ClassWithCtors).GetConstructor(new Type[] { typeof(string) });
Expression[] arguments = { Expression.Constant(5) };
MemberInfo[] members = { globalMethodInfo };
AssertExtensions.Throws<ArgumentException>("members[0]", () => Expression.New(constructor, arguments, members));
}
[Fact]
public static void GlobalFieldInMembers()
{
ModuleBuilder module = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("Name"), AssemblyBuilderAccess.RunAndCollect).DefineDynamicModule("Module");
FieldBuilder fieldBuilder = module.DefineInitializedData("GlobalField", new byte[1], FieldAttributes.Public);
module.CreateGlobalFunctions();
FieldInfo globalField = module.GetField(fieldBuilder.Name);
ConstructorInfo constructor = typeof(ClassWithCtors).GetConstructor(new Type[] { typeof(string) });
Expression[] arguments = { Expression.Constant(5) };
MemberInfo[] members = { globalField };
AssertExtensions.Throws<ArgumentException>("members[0]", () => Expression.New(constructor, arguments, members));
}
#endif
static class StaticCtor
{
static StaticCtor() { }
}
abstract class AbstractCtor
{
public AbstractCtor() { }
}
class GenericClass<T>
{
public GenericClass() { }
}
class ClassWithCtors
{
public ClassWithCtors() { }
public ClassWithCtors(string obj) { }
public string StringProperty { get; set; }
public int IntProperty { get; set; }
public int WriteOnlyProperty { set { } }
#pragma warning disable 0649
public int _field;
public static int s_field;
#pragma warning restore 0649
public static string StaticProperty { get; set; }
public static void StaticMethod() { }
public void InstanceMethod() { }
}
class ClassWithNoDefaultCtor
{
public ClassWithNoDefaultCtor(string s) { }
}
static class Unreachable<T>
{
public static T WriteOnly { set { } }
}
class Bar
{
public Bar()
{
}
public Bar(int foo)
{
}
public Bar(int foo, int qux)
{
}
public int Foo { get; set; }
public int Qux { get; set; }
}
}
}
| |
/*
* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using CookComputing.XmlRpc;
namespace XenAPI
{
/// <summary>
/// VM Snapshot Schedule
/// First published in XenServer 7.2.
/// </summary>
public partial class VMSS : XenObject<VMSS>
{
public VMSS()
{
}
public VMSS(string uuid,
string name_label,
string name_description,
bool enabled,
vmss_type type,
long retained_snapshots,
vmss_frequency frequency,
Dictionary<string, string> schedule,
DateTime last_run_time,
List<XenRef<VM>> VMs)
{
this.uuid = uuid;
this.name_label = name_label;
this.name_description = name_description;
this.enabled = enabled;
this.type = type;
this.retained_snapshots = retained_snapshots;
this.frequency = frequency;
this.schedule = schedule;
this.last_run_time = last_run_time;
this.VMs = VMs;
}
/// <summary>
/// Creates a new VMSS from a Proxy_VMSS.
/// </summary>
/// <param name="proxy"></param>
public VMSS(Proxy_VMSS proxy)
{
this.UpdateFromProxy(proxy);
}
public override void UpdateFrom(VMSS update)
{
uuid = update.uuid;
name_label = update.name_label;
name_description = update.name_description;
enabled = update.enabled;
type = update.type;
retained_snapshots = update.retained_snapshots;
frequency = update.frequency;
schedule = update.schedule;
last_run_time = update.last_run_time;
VMs = update.VMs;
}
internal void UpdateFromProxy(Proxy_VMSS proxy)
{
uuid = proxy.uuid == null ? null : (string)proxy.uuid;
name_label = proxy.name_label == null ? null : (string)proxy.name_label;
name_description = proxy.name_description == null ? null : (string)proxy.name_description;
enabled = (bool)proxy.enabled;
type = proxy.type == null ? (vmss_type) 0 : (vmss_type)Helper.EnumParseDefault(typeof(vmss_type), (string)proxy.type);
retained_snapshots = proxy.retained_snapshots == null ? 0 : long.Parse((string)proxy.retained_snapshots);
frequency = proxy.frequency == null ? (vmss_frequency) 0 : (vmss_frequency)Helper.EnumParseDefault(typeof(vmss_frequency), (string)proxy.frequency);
schedule = proxy.schedule == null ? null : Maps.convert_from_proxy_string_string(proxy.schedule);
last_run_time = proxy.last_run_time;
VMs = proxy.VMs == null ? null : XenRef<VM>.Create(proxy.VMs);
}
public Proxy_VMSS ToProxy()
{
Proxy_VMSS result_ = new Proxy_VMSS();
result_.uuid = (uuid != null) ? uuid : "";
result_.name_label = (name_label != null) ? name_label : "";
result_.name_description = (name_description != null) ? name_description : "";
result_.enabled = enabled;
result_.type = vmss_type_helper.ToString(type);
result_.retained_snapshots = retained_snapshots.ToString();
result_.frequency = vmss_frequency_helper.ToString(frequency);
result_.schedule = Maps.convert_to_proxy_string_string(schedule);
result_.last_run_time = last_run_time;
result_.VMs = (VMs != null) ? Helper.RefListToStringArray(VMs) : new string[] {};
return result_;
}
/// <summary>
/// Creates a new VMSS from a Hashtable.
/// </summary>
/// <param name="table"></param>
public VMSS(Hashtable table)
{
uuid = Marshalling.ParseString(table, "uuid");
name_label = Marshalling.ParseString(table, "name_label");
name_description = Marshalling.ParseString(table, "name_description");
enabled = Marshalling.ParseBool(table, "enabled");
type = (vmss_type)Helper.EnumParseDefault(typeof(vmss_type), Marshalling.ParseString(table, "type"));
retained_snapshots = Marshalling.ParseLong(table, "retained_snapshots");
frequency = (vmss_frequency)Helper.EnumParseDefault(typeof(vmss_frequency), Marshalling.ParseString(table, "frequency"));
schedule = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "schedule"));
last_run_time = Marshalling.ParseDateTime(table, "last_run_time");
VMs = Marshalling.ParseSetRef<VM>(table, "VMs");
}
public bool DeepEquals(VMSS other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
return Helper.AreEqual2(this._uuid, other._uuid) &&
Helper.AreEqual2(this._name_label, other._name_label) &&
Helper.AreEqual2(this._name_description, other._name_description) &&
Helper.AreEqual2(this._enabled, other._enabled) &&
Helper.AreEqual2(this._type, other._type) &&
Helper.AreEqual2(this._retained_snapshots, other._retained_snapshots) &&
Helper.AreEqual2(this._frequency, other._frequency) &&
Helper.AreEqual2(this._schedule, other._schedule) &&
Helper.AreEqual2(this._last_run_time, other._last_run_time) &&
Helper.AreEqual2(this._VMs, other._VMs);
}
public override string SaveChanges(Session session, string opaqueRef, VMSS server)
{
if (opaqueRef == null)
{
Proxy_VMSS p = this.ToProxy();
return session.proxy.vmss_create(session.uuid, p).parse();
}
else
{
if (!Helper.AreEqual2(_name_label, server._name_label))
{
VMSS.set_name_label(session, opaqueRef, _name_label);
}
if (!Helper.AreEqual2(_name_description, server._name_description))
{
VMSS.set_name_description(session, opaqueRef, _name_description);
}
if (!Helper.AreEqual2(_enabled, server._enabled))
{
VMSS.set_enabled(session, opaqueRef, _enabled);
}
if (!Helper.AreEqual2(_type, server._type))
{
VMSS.set_type(session, opaqueRef, _type);
}
if (!Helper.AreEqual2(_retained_snapshots, server._retained_snapshots))
{
VMSS.set_retained_snapshots(session, opaqueRef, _retained_snapshots);
}
if (!Helper.AreEqual2(_frequency, server._frequency))
{
VMSS.set_frequency(session, opaqueRef, _frequency);
}
if (!Helper.AreEqual2(_schedule, server._schedule))
{
VMSS.set_schedule(session, opaqueRef, _schedule);
}
return null;
}
}
/// <summary>
/// Get a record containing the current state of the given VMSS.
/// First published in XenServer 7.2.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmss">The opaque_ref of the given vmss</param>
public static VMSS get_record(Session session, string _vmss)
{
return new VMSS((Proxy_VMSS)session.proxy.vmss_get_record(session.uuid, (_vmss != null) ? _vmss : "").parse());
}
/// <summary>
/// Get a reference to the VMSS instance with the specified UUID.
/// First published in XenServer 7.2.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_uuid">UUID of object to return</param>
public static XenRef<VMSS> get_by_uuid(Session session, string _uuid)
{
return XenRef<VMSS>.Create(session.proxy.vmss_get_by_uuid(session.uuid, (_uuid != null) ? _uuid : "").parse());
}
/// <summary>
/// Create a new VMSS instance, and return its handle.
/// First published in XenServer 7.2.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_record">All constructor arguments</param>
public static XenRef<VMSS> create(Session session, VMSS _record)
{
return XenRef<VMSS>.Create(session.proxy.vmss_create(session.uuid, _record.ToProxy()).parse());
}
/// <summary>
/// Create a new VMSS instance, and return its handle.
/// First published in XenServer 7.2.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_record">All constructor arguments</param>
public static XenRef<Task> async_create(Session session, VMSS _record)
{
return XenRef<Task>.Create(session.proxy.async_vmss_create(session.uuid, _record.ToProxy()).parse());
}
/// <summary>
/// Destroy the specified VMSS instance.
/// First published in XenServer 7.2.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmss">The opaque_ref of the given vmss</param>
public static void destroy(Session session, string _vmss)
{
session.proxy.vmss_destroy(session.uuid, (_vmss != null) ? _vmss : "").parse();
}
/// <summary>
/// Destroy the specified VMSS instance.
/// First published in XenServer 7.2.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmss">The opaque_ref of the given vmss</param>
public static XenRef<Task> async_destroy(Session session, string _vmss)
{
return XenRef<Task>.Create(session.proxy.async_vmss_destroy(session.uuid, (_vmss != null) ? _vmss : "").parse());
}
/// <summary>
/// Get all the VMSS instances with the given label.
/// First published in XenServer 7.2.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_label">label of object to return</param>
public static List<XenRef<VMSS>> get_by_name_label(Session session, string _label)
{
return XenRef<VMSS>.Create(session.proxy.vmss_get_by_name_label(session.uuid, (_label != null) ? _label : "").parse());
}
/// <summary>
/// Get the uuid field of the given VMSS.
/// First published in XenServer 7.2.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmss">The opaque_ref of the given vmss</param>
public static string get_uuid(Session session, string _vmss)
{
return (string)session.proxy.vmss_get_uuid(session.uuid, (_vmss != null) ? _vmss : "").parse();
}
/// <summary>
/// Get the name/label field of the given VMSS.
/// First published in XenServer 7.2.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmss">The opaque_ref of the given vmss</param>
public static string get_name_label(Session session, string _vmss)
{
return (string)session.proxy.vmss_get_name_label(session.uuid, (_vmss != null) ? _vmss : "").parse();
}
/// <summary>
/// Get the name/description field of the given VMSS.
/// First published in XenServer 7.2.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmss">The opaque_ref of the given vmss</param>
public static string get_name_description(Session session, string _vmss)
{
return (string)session.proxy.vmss_get_name_description(session.uuid, (_vmss != null) ? _vmss : "").parse();
}
/// <summary>
/// Get the enabled field of the given VMSS.
/// First published in XenServer 7.2.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmss">The opaque_ref of the given vmss</param>
public static bool get_enabled(Session session, string _vmss)
{
return (bool)session.proxy.vmss_get_enabled(session.uuid, (_vmss != null) ? _vmss : "").parse();
}
/// <summary>
/// Get the type field of the given VMSS.
/// First published in XenServer 7.2.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmss">The opaque_ref of the given vmss</param>
public static vmss_type get_type(Session session, string _vmss)
{
return (vmss_type)Helper.EnumParseDefault(typeof(vmss_type), (string)session.proxy.vmss_get_type(session.uuid, (_vmss != null) ? _vmss : "").parse());
}
/// <summary>
/// Get the retained_snapshots field of the given VMSS.
/// First published in XenServer 7.2.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmss">The opaque_ref of the given vmss</param>
public static long get_retained_snapshots(Session session, string _vmss)
{
return long.Parse((string)session.proxy.vmss_get_retained_snapshots(session.uuid, (_vmss != null) ? _vmss : "").parse());
}
/// <summary>
/// Get the frequency field of the given VMSS.
/// First published in XenServer 7.2.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmss">The opaque_ref of the given vmss</param>
public static vmss_frequency get_frequency(Session session, string _vmss)
{
return (vmss_frequency)Helper.EnumParseDefault(typeof(vmss_frequency), (string)session.proxy.vmss_get_frequency(session.uuid, (_vmss != null) ? _vmss : "").parse());
}
/// <summary>
/// Get the schedule field of the given VMSS.
/// First published in XenServer 7.2.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmss">The opaque_ref of the given vmss</param>
public static Dictionary<string, string> get_schedule(Session session, string _vmss)
{
return Maps.convert_from_proxy_string_string(session.proxy.vmss_get_schedule(session.uuid, (_vmss != null) ? _vmss : "").parse());
}
/// <summary>
/// Get the last_run_time field of the given VMSS.
/// First published in XenServer 7.2.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmss">The opaque_ref of the given vmss</param>
public static DateTime get_last_run_time(Session session, string _vmss)
{
return session.proxy.vmss_get_last_run_time(session.uuid, (_vmss != null) ? _vmss : "").parse();
}
/// <summary>
/// Get the VMs field of the given VMSS.
/// First published in XenServer 7.2.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmss">The opaque_ref of the given vmss</param>
public static List<XenRef<VM>> get_VMs(Session session, string _vmss)
{
return XenRef<VM>.Create(session.proxy.vmss_get_vms(session.uuid, (_vmss != null) ? _vmss : "").parse());
}
/// <summary>
/// Set the name/label field of the given VMSS.
/// First published in XenServer 7.2.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmss">The opaque_ref of the given vmss</param>
/// <param name="_label">New value to set</param>
public static void set_name_label(Session session, string _vmss, string _label)
{
session.proxy.vmss_set_name_label(session.uuid, (_vmss != null) ? _vmss : "", (_label != null) ? _label : "").parse();
}
/// <summary>
/// Set the name/description field of the given VMSS.
/// First published in XenServer 7.2.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmss">The opaque_ref of the given vmss</param>
/// <param name="_description">New value to set</param>
public static void set_name_description(Session session, string _vmss, string _description)
{
session.proxy.vmss_set_name_description(session.uuid, (_vmss != null) ? _vmss : "", (_description != null) ? _description : "").parse();
}
/// <summary>
/// Set the enabled field of the given VMSS.
/// First published in XenServer 7.2.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmss">The opaque_ref of the given vmss</param>
/// <param name="_enabled">New value to set</param>
public static void set_enabled(Session session, string _vmss, bool _enabled)
{
session.proxy.vmss_set_enabled(session.uuid, (_vmss != null) ? _vmss : "", _enabled).parse();
}
/// <summary>
/// This call executes the snapshot schedule immediately
/// First published in XenServer 7.2.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmss">The opaque_ref of the given vmss</param>
public static string snapshot_now(Session session, string _vmss)
{
return (string)session.proxy.vmss_snapshot_now(session.uuid, (_vmss != null) ? _vmss : "").parse();
}
/// <summary>
///
/// First published in XenServer 7.2.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmss">The opaque_ref of the given vmss</param>
/// <param name="_value">the value to set</param>
public static void set_retained_snapshots(Session session, string _vmss, long _value)
{
session.proxy.vmss_set_retained_snapshots(session.uuid, (_vmss != null) ? _vmss : "", _value.ToString()).parse();
}
/// <summary>
/// Set the value of the frequency field
/// First published in XenServer 7.2.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmss">The opaque_ref of the given vmss</param>
/// <param name="_value">the snapshot schedule frequency</param>
public static void set_frequency(Session session, string _vmss, vmss_frequency _value)
{
session.proxy.vmss_set_frequency(session.uuid, (_vmss != null) ? _vmss : "", vmss_frequency_helper.ToString(_value)).parse();
}
/// <summary>
///
/// First published in XenServer 7.2.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmss">The opaque_ref of the given vmss</param>
/// <param name="_value">the value to set</param>
public static void set_schedule(Session session, string _vmss, Dictionary<string, string> _value)
{
session.proxy.vmss_set_schedule(session.uuid, (_vmss != null) ? _vmss : "", Maps.convert_to_proxy_string_string(_value)).parse();
}
/// <summary>
///
/// First published in XenServer 7.2.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmss">The opaque_ref of the given vmss</param>
/// <param name="_key">the key to add</param>
/// <param name="_value">the value to add</param>
public static void add_to_schedule(Session session, string _vmss, string _key, string _value)
{
session.proxy.vmss_add_to_schedule(session.uuid, (_vmss != null) ? _vmss : "", (_key != null) ? _key : "", (_value != null) ? _value : "").parse();
}
/// <summary>
///
/// First published in XenServer 7.2.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmss">The opaque_ref of the given vmss</param>
/// <param name="_key">the key to remove</param>
public static void remove_from_schedule(Session session, string _vmss, string _key)
{
session.proxy.vmss_remove_from_schedule(session.uuid, (_vmss != null) ? _vmss : "", (_key != null) ? _key : "").parse();
}
/// <summary>
///
/// First published in XenServer 7.2.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmss">The opaque_ref of the given vmss</param>
/// <param name="_value">the value to set</param>
public static void set_last_run_time(Session session, string _vmss, DateTime _value)
{
session.proxy.vmss_set_last_run_time(session.uuid, (_vmss != null) ? _vmss : "", _value).parse();
}
/// <summary>
///
/// First published in XenServer 7.2.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmss">The opaque_ref of the given vmss</param>
/// <param name="_value">the snapshot schedule type</param>
public static void set_type(Session session, string _vmss, vmss_type _value)
{
session.proxy.vmss_set_type(session.uuid, (_vmss != null) ? _vmss : "", vmss_type_helper.ToString(_value)).parse();
}
/// <summary>
/// Return a list of all the VMSSs known to the system.
/// First published in XenServer 7.2.
/// </summary>
/// <param name="session">The session</param>
public static List<XenRef<VMSS>> get_all(Session session)
{
return XenRef<VMSS>.Create(session.proxy.vmss_get_all(session.uuid).parse());
}
/// <summary>
/// Get all the VMSS Records at once, in a single XML RPC call
/// First published in XenServer 7.2.
/// </summary>
/// <param name="session">The session</param>
public static Dictionary<XenRef<VMSS>, VMSS> get_all_records(Session session)
{
return XenRef<VMSS>.Create<Proxy_VMSS>(session.proxy.vmss_get_all_records(session.uuid).parse());
}
/// <summary>
/// Unique identifier/object reference
/// </summary>
public virtual string uuid
{
get { return _uuid; }
set
{
if (!Helper.AreEqual(value, _uuid))
{
_uuid = value;
Changed = true;
NotifyPropertyChanged("uuid");
}
}
}
private string _uuid;
/// <summary>
/// a human-readable name
/// </summary>
public virtual string name_label
{
get { return _name_label; }
set
{
if (!Helper.AreEqual(value, _name_label))
{
_name_label = value;
Changed = true;
NotifyPropertyChanged("name_label");
}
}
}
private string _name_label;
/// <summary>
/// a notes field containing human-readable description
/// </summary>
public virtual string name_description
{
get { return _name_description; }
set
{
if (!Helper.AreEqual(value, _name_description))
{
_name_description = value;
Changed = true;
NotifyPropertyChanged("name_description");
}
}
}
private string _name_description;
/// <summary>
/// enable or disable this snapshot schedule
/// </summary>
public virtual bool enabled
{
get { return _enabled; }
set
{
if (!Helper.AreEqual(value, _enabled))
{
_enabled = value;
Changed = true;
NotifyPropertyChanged("enabled");
}
}
}
private bool _enabled;
/// <summary>
/// type of the snapshot schedule
/// </summary>
public virtual vmss_type type
{
get { return _type; }
set
{
if (!Helper.AreEqual(value, _type))
{
_type = value;
Changed = true;
NotifyPropertyChanged("type");
}
}
}
private vmss_type _type;
/// <summary>
/// maximum number of snapshots that should be stored at any time
/// </summary>
public virtual long retained_snapshots
{
get { return _retained_snapshots; }
set
{
if (!Helper.AreEqual(value, _retained_snapshots))
{
_retained_snapshots = value;
Changed = true;
NotifyPropertyChanged("retained_snapshots");
}
}
}
private long _retained_snapshots;
/// <summary>
/// frequency of taking snapshot from snapshot schedule
/// </summary>
public virtual vmss_frequency frequency
{
get { return _frequency; }
set
{
if (!Helper.AreEqual(value, _frequency))
{
_frequency = value;
Changed = true;
NotifyPropertyChanged("frequency");
}
}
}
private vmss_frequency _frequency;
/// <summary>
/// schedule of the snapshot containing 'hour', 'min', 'days'. Date/time-related information is in Local Timezone
/// </summary>
public virtual Dictionary<string, string> schedule
{
get { return _schedule; }
set
{
if (!Helper.AreEqual(value, _schedule))
{
_schedule = value;
Changed = true;
NotifyPropertyChanged("schedule");
}
}
}
private Dictionary<string, string> _schedule;
/// <summary>
/// time of the last snapshot
/// </summary>
public virtual DateTime last_run_time
{
get { return _last_run_time; }
set
{
if (!Helper.AreEqual(value, _last_run_time))
{
_last_run_time = value;
Changed = true;
NotifyPropertyChanged("last_run_time");
}
}
}
private DateTime _last_run_time;
/// <summary>
/// all VMs attached to this snapshot schedule
/// </summary>
public virtual List<XenRef<VM>> VMs
{
get { return _VMs; }
set
{
if (!Helper.AreEqual(value, _VMs))
{
_VMs = value;
Changed = true;
NotifyPropertyChanged("VMs");
}
}
}
private List<XenRef<VM>> _VMs;
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: test/proto/benchmarks/stats.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Grpc.Testing {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public static partial class Stats {
#region Descriptor
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static Stats() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CiF0ZXN0L3Byb3RvL2JlbmNobWFya3Mvc3RhdHMucHJvdG8SDGdycGMudGVz",
"dGluZyJLCgtTZXJ2ZXJTdGF0cxIUCgx0aW1lX2VsYXBzZWQYASABKAESEQoJ",
"dGltZV91c2VyGAIgASgBEhMKC3RpbWVfc3lzdGVtGAMgASgBIjsKD0hpc3Rv",
"Z3JhbVBhcmFtcxISCgpyZXNvbHV0aW9uGAEgASgBEhQKDG1heF9wb3NzaWJs",
"ZRgCIAEoASJ3Cg1IaXN0b2dyYW1EYXRhEg4KBmJ1Y2tldBgBIAMoDRIQCght",
"aW5fc2VlbhgCIAEoARIQCghtYXhfc2VlbhgDIAEoARILCgNzdW0YBCABKAES",
"FgoOc3VtX29mX3NxdWFyZXMYBSABKAESDQoFY291bnQYBiABKAEiewoLQ2xp",
"ZW50U3RhdHMSLgoJbGF0ZW5jaWVzGAEgASgLMhsuZ3JwYy50ZXN0aW5nLkhp",
"c3RvZ3JhbURhdGESFAoMdGltZV9lbGFwc2VkGAIgASgBEhEKCXRpbWVfdXNl",
"chgDIAEoARITCgt0aW1lX3N5c3RlbRgEIAEoAWIGcHJvdG8z"));
descriptor = pbr::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedCodeInfo(null, new pbr::GeneratedCodeInfo[] {
new pbr::GeneratedCodeInfo(typeof(global::Grpc.Testing.ServerStats), new[]{ "TimeElapsed", "TimeUser", "TimeSystem" }, null, null, null),
new pbr::GeneratedCodeInfo(typeof(global::Grpc.Testing.HistogramParams), new[]{ "Resolution", "MaxPossible" }, null, null, null),
new pbr::GeneratedCodeInfo(typeof(global::Grpc.Testing.HistogramData), new[]{ "Bucket", "MinSeen", "MaxSeen", "Sum", "SumOfSquares", "Count" }, null, null, null),
new pbr::GeneratedCodeInfo(typeof(global::Grpc.Testing.ClientStats), new[]{ "Latencies", "TimeElapsed", "TimeUser", "TimeSystem" }, null, null, null)
}));
}
#endregion
}
#region Messages
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class ServerStats : pb::IMessage<ServerStats> {
private static readonly pb::MessageParser<ServerStats> _parser = new pb::MessageParser<ServerStats>(() => new ServerStats());
public static pb::MessageParser<ServerStats> Parser { get { return _parser; } }
public static pbr::MessageDescriptor Descriptor {
get { return global::Grpc.Testing.Stats.Descriptor.MessageTypes[0]; }
}
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
public ServerStats() {
OnConstruction();
}
partial void OnConstruction();
public ServerStats(ServerStats other) : this() {
timeElapsed_ = other.timeElapsed_;
timeUser_ = other.timeUser_;
timeSystem_ = other.timeSystem_;
}
public ServerStats Clone() {
return new ServerStats(this);
}
public const int TimeElapsedFieldNumber = 1;
private double timeElapsed_;
public double TimeElapsed {
get { return timeElapsed_; }
set {
timeElapsed_ = value;
}
}
public const int TimeUserFieldNumber = 2;
private double timeUser_;
public double TimeUser {
get { return timeUser_; }
set {
timeUser_ = value;
}
}
public const int TimeSystemFieldNumber = 3;
private double timeSystem_;
public double TimeSystem {
get { return timeSystem_; }
set {
timeSystem_ = value;
}
}
public override bool Equals(object other) {
return Equals(other as ServerStats);
}
public bool Equals(ServerStats other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (TimeElapsed != other.TimeElapsed) return false;
if (TimeUser != other.TimeUser) return false;
if (TimeSystem != other.TimeSystem) return false;
return true;
}
public override int GetHashCode() {
int hash = 1;
if (TimeElapsed != 0D) hash ^= TimeElapsed.GetHashCode();
if (TimeUser != 0D) hash ^= TimeUser.GetHashCode();
if (TimeSystem != 0D) hash ^= TimeSystem.GetHashCode();
return hash;
}
public override string ToString() {
return pb::JsonFormatter.Default.Format(this);
}
public void WriteTo(pb::CodedOutputStream output) {
if (TimeElapsed != 0D) {
output.WriteRawTag(9);
output.WriteDouble(TimeElapsed);
}
if (TimeUser != 0D) {
output.WriteRawTag(17);
output.WriteDouble(TimeUser);
}
if (TimeSystem != 0D) {
output.WriteRawTag(25);
output.WriteDouble(TimeSystem);
}
}
public int CalculateSize() {
int size = 0;
if (TimeElapsed != 0D) {
size += 1 + 8;
}
if (TimeUser != 0D) {
size += 1 + 8;
}
if (TimeSystem != 0D) {
size += 1 + 8;
}
return size;
}
public void MergeFrom(ServerStats other) {
if (other == null) {
return;
}
if (other.TimeElapsed != 0D) {
TimeElapsed = other.TimeElapsed;
}
if (other.TimeUser != 0D) {
TimeUser = other.TimeUser;
}
if (other.TimeSystem != 0D) {
TimeSystem = other.TimeSystem;
}
}
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 9: {
TimeElapsed = input.ReadDouble();
break;
}
case 17: {
TimeUser = input.ReadDouble();
break;
}
case 25: {
TimeSystem = input.ReadDouble();
break;
}
}
}
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class HistogramParams : pb::IMessage<HistogramParams> {
private static readonly pb::MessageParser<HistogramParams> _parser = new pb::MessageParser<HistogramParams>(() => new HistogramParams());
public static pb::MessageParser<HistogramParams> Parser { get { return _parser; } }
public static pbr::MessageDescriptor Descriptor {
get { return global::Grpc.Testing.Stats.Descriptor.MessageTypes[1]; }
}
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
public HistogramParams() {
OnConstruction();
}
partial void OnConstruction();
public HistogramParams(HistogramParams other) : this() {
resolution_ = other.resolution_;
maxPossible_ = other.maxPossible_;
}
public HistogramParams Clone() {
return new HistogramParams(this);
}
public const int ResolutionFieldNumber = 1;
private double resolution_;
public double Resolution {
get { return resolution_; }
set {
resolution_ = value;
}
}
public const int MaxPossibleFieldNumber = 2;
private double maxPossible_;
public double MaxPossible {
get { return maxPossible_; }
set {
maxPossible_ = value;
}
}
public override bool Equals(object other) {
return Equals(other as HistogramParams);
}
public bool Equals(HistogramParams other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Resolution != other.Resolution) return false;
if (MaxPossible != other.MaxPossible) return false;
return true;
}
public override int GetHashCode() {
int hash = 1;
if (Resolution != 0D) hash ^= Resolution.GetHashCode();
if (MaxPossible != 0D) hash ^= MaxPossible.GetHashCode();
return hash;
}
public override string ToString() {
return pb::JsonFormatter.Default.Format(this);
}
public void WriteTo(pb::CodedOutputStream output) {
if (Resolution != 0D) {
output.WriteRawTag(9);
output.WriteDouble(Resolution);
}
if (MaxPossible != 0D) {
output.WriteRawTag(17);
output.WriteDouble(MaxPossible);
}
}
public int CalculateSize() {
int size = 0;
if (Resolution != 0D) {
size += 1 + 8;
}
if (MaxPossible != 0D) {
size += 1 + 8;
}
return size;
}
public void MergeFrom(HistogramParams other) {
if (other == null) {
return;
}
if (other.Resolution != 0D) {
Resolution = other.Resolution;
}
if (other.MaxPossible != 0D) {
MaxPossible = other.MaxPossible;
}
}
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 9: {
Resolution = input.ReadDouble();
break;
}
case 17: {
MaxPossible = input.ReadDouble();
break;
}
}
}
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class HistogramData : pb::IMessage<HistogramData> {
private static readonly pb::MessageParser<HistogramData> _parser = new pb::MessageParser<HistogramData>(() => new HistogramData());
public static pb::MessageParser<HistogramData> Parser { get { return _parser; } }
public static pbr::MessageDescriptor Descriptor {
get { return global::Grpc.Testing.Stats.Descriptor.MessageTypes[2]; }
}
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
public HistogramData() {
OnConstruction();
}
partial void OnConstruction();
public HistogramData(HistogramData other) : this() {
bucket_ = other.bucket_.Clone();
minSeen_ = other.minSeen_;
maxSeen_ = other.maxSeen_;
sum_ = other.sum_;
sumOfSquares_ = other.sumOfSquares_;
count_ = other.count_;
}
public HistogramData Clone() {
return new HistogramData(this);
}
public const int BucketFieldNumber = 1;
private static readonly pb::FieldCodec<uint> _repeated_bucket_codec
= pb::FieldCodec.ForUInt32(10);
private readonly pbc::RepeatedField<uint> bucket_ = new pbc::RepeatedField<uint>();
public pbc::RepeatedField<uint> Bucket {
get { return bucket_; }
}
public const int MinSeenFieldNumber = 2;
private double minSeen_;
public double MinSeen {
get { return minSeen_; }
set {
minSeen_ = value;
}
}
public const int MaxSeenFieldNumber = 3;
private double maxSeen_;
public double MaxSeen {
get { return maxSeen_; }
set {
maxSeen_ = value;
}
}
public const int SumFieldNumber = 4;
private double sum_;
public double Sum {
get { return sum_; }
set {
sum_ = value;
}
}
public const int SumOfSquaresFieldNumber = 5;
private double sumOfSquares_;
public double SumOfSquares {
get { return sumOfSquares_; }
set {
sumOfSquares_ = value;
}
}
public const int CountFieldNumber = 6;
private double count_;
public double Count {
get { return count_; }
set {
count_ = value;
}
}
public override bool Equals(object other) {
return Equals(other as HistogramData);
}
public bool Equals(HistogramData other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if(!bucket_.Equals(other.bucket_)) return false;
if (MinSeen != other.MinSeen) return false;
if (MaxSeen != other.MaxSeen) return false;
if (Sum != other.Sum) return false;
if (SumOfSquares != other.SumOfSquares) return false;
if (Count != other.Count) return false;
return true;
}
public override int GetHashCode() {
int hash = 1;
hash ^= bucket_.GetHashCode();
if (MinSeen != 0D) hash ^= MinSeen.GetHashCode();
if (MaxSeen != 0D) hash ^= MaxSeen.GetHashCode();
if (Sum != 0D) hash ^= Sum.GetHashCode();
if (SumOfSquares != 0D) hash ^= SumOfSquares.GetHashCode();
if (Count != 0D) hash ^= Count.GetHashCode();
return hash;
}
public override string ToString() {
return pb::JsonFormatter.Default.Format(this);
}
public void WriteTo(pb::CodedOutputStream output) {
bucket_.WriteTo(output, _repeated_bucket_codec);
if (MinSeen != 0D) {
output.WriteRawTag(17);
output.WriteDouble(MinSeen);
}
if (MaxSeen != 0D) {
output.WriteRawTag(25);
output.WriteDouble(MaxSeen);
}
if (Sum != 0D) {
output.WriteRawTag(33);
output.WriteDouble(Sum);
}
if (SumOfSquares != 0D) {
output.WriteRawTag(41);
output.WriteDouble(SumOfSquares);
}
if (Count != 0D) {
output.WriteRawTag(49);
output.WriteDouble(Count);
}
}
public int CalculateSize() {
int size = 0;
size += bucket_.CalculateSize(_repeated_bucket_codec);
if (MinSeen != 0D) {
size += 1 + 8;
}
if (MaxSeen != 0D) {
size += 1 + 8;
}
if (Sum != 0D) {
size += 1 + 8;
}
if (SumOfSquares != 0D) {
size += 1 + 8;
}
if (Count != 0D) {
size += 1 + 8;
}
return size;
}
public void MergeFrom(HistogramData other) {
if (other == null) {
return;
}
bucket_.Add(other.bucket_);
if (other.MinSeen != 0D) {
MinSeen = other.MinSeen;
}
if (other.MaxSeen != 0D) {
MaxSeen = other.MaxSeen;
}
if (other.Sum != 0D) {
Sum = other.Sum;
}
if (other.SumOfSquares != 0D) {
SumOfSquares = other.SumOfSquares;
}
if (other.Count != 0D) {
Count = other.Count;
}
}
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10:
case 8: {
bucket_.AddEntriesFrom(input, _repeated_bucket_codec);
break;
}
case 17: {
MinSeen = input.ReadDouble();
break;
}
case 25: {
MaxSeen = input.ReadDouble();
break;
}
case 33: {
Sum = input.ReadDouble();
break;
}
case 41: {
SumOfSquares = input.ReadDouble();
break;
}
case 49: {
Count = input.ReadDouble();
break;
}
}
}
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class ClientStats : pb::IMessage<ClientStats> {
private static readonly pb::MessageParser<ClientStats> _parser = new pb::MessageParser<ClientStats>(() => new ClientStats());
public static pb::MessageParser<ClientStats> Parser { get { return _parser; } }
public static pbr::MessageDescriptor Descriptor {
get { return global::Grpc.Testing.Stats.Descriptor.MessageTypes[3]; }
}
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
public ClientStats() {
OnConstruction();
}
partial void OnConstruction();
public ClientStats(ClientStats other) : this() {
Latencies = other.latencies_ != null ? other.Latencies.Clone() : null;
timeElapsed_ = other.timeElapsed_;
timeUser_ = other.timeUser_;
timeSystem_ = other.timeSystem_;
}
public ClientStats Clone() {
return new ClientStats(this);
}
public const int LatenciesFieldNumber = 1;
private global::Grpc.Testing.HistogramData latencies_;
public global::Grpc.Testing.HistogramData Latencies {
get { return latencies_; }
set {
latencies_ = value;
}
}
public const int TimeElapsedFieldNumber = 2;
private double timeElapsed_;
public double TimeElapsed {
get { return timeElapsed_; }
set {
timeElapsed_ = value;
}
}
public const int TimeUserFieldNumber = 3;
private double timeUser_;
public double TimeUser {
get { return timeUser_; }
set {
timeUser_ = value;
}
}
public const int TimeSystemFieldNumber = 4;
private double timeSystem_;
public double TimeSystem {
get { return timeSystem_; }
set {
timeSystem_ = value;
}
}
public override bool Equals(object other) {
return Equals(other as ClientStats);
}
public bool Equals(ClientStats other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!object.Equals(Latencies, other.Latencies)) return false;
if (TimeElapsed != other.TimeElapsed) return false;
if (TimeUser != other.TimeUser) return false;
if (TimeSystem != other.TimeSystem) return false;
return true;
}
public override int GetHashCode() {
int hash = 1;
if (latencies_ != null) hash ^= Latencies.GetHashCode();
if (TimeElapsed != 0D) hash ^= TimeElapsed.GetHashCode();
if (TimeUser != 0D) hash ^= TimeUser.GetHashCode();
if (TimeSystem != 0D) hash ^= TimeSystem.GetHashCode();
return hash;
}
public override string ToString() {
return pb::JsonFormatter.Default.Format(this);
}
public void WriteTo(pb::CodedOutputStream output) {
if (latencies_ != null) {
output.WriteRawTag(10);
output.WriteMessage(Latencies);
}
if (TimeElapsed != 0D) {
output.WriteRawTag(17);
output.WriteDouble(TimeElapsed);
}
if (TimeUser != 0D) {
output.WriteRawTag(25);
output.WriteDouble(TimeUser);
}
if (TimeSystem != 0D) {
output.WriteRawTag(33);
output.WriteDouble(TimeSystem);
}
}
public int CalculateSize() {
int size = 0;
if (latencies_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Latencies);
}
if (TimeElapsed != 0D) {
size += 1 + 8;
}
if (TimeUser != 0D) {
size += 1 + 8;
}
if (TimeSystem != 0D) {
size += 1 + 8;
}
return size;
}
public void MergeFrom(ClientStats other) {
if (other == null) {
return;
}
if (other.latencies_ != null) {
if (latencies_ == null) {
latencies_ = new global::Grpc.Testing.HistogramData();
}
Latencies.MergeFrom(other.Latencies);
}
if (other.TimeElapsed != 0D) {
TimeElapsed = other.TimeElapsed;
}
if (other.TimeUser != 0D) {
TimeUser = other.TimeUser;
}
if (other.TimeSystem != 0D) {
TimeSystem = other.TimeSystem;
}
}
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
if (latencies_ == null) {
latencies_ = new global::Grpc.Testing.HistogramData();
}
input.ReadMessage(latencies_);
break;
}
case 17: {
TimeElapsed = input.ReadDouble();
break;
}
case 25: {
TimeUser = input.ReadDouble();
break;
}
case 33: {
TimeSystem = input.ReadDouble();
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Security.Permissions
{
using System;
using System.Security;
using System.Security.Util;
using System.IO;
using System.Runtime.Serialization;
using System.Reflection;
using System.Collections;
using System.Globalization;
using System.Diagnostics.Contracts;
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public enum UIPermissionWindow
{
// No window use allowed at all.
NoWindows = 0x0,
// Only allow safe subwindow use (for embedded components).
SafeSubWindows = 0x01,
// Safe top-level window use only (see specification for details).
SafeTopLevelWindows = 0x02,
// All windows and all event may be used.
AllWindows = 0x03,
}
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public enum UIPermissionClipboard
{
// No clipboard access is allowed.
NoClipboard = 0x0,
// Paste from the same app domain only.
OwnClipboard = 0x1,
// Any clipboard access is allowed.
AllClipboard = 0x2,
}
[System.Runtime.InteropServices.ComVisible(true)]
[Serializable]
sealed public class UIPermission
: CodeAccessPermission, IUnrestrictedPermission, IBuiltInPermission
{
//------------------------------------------------------
//
// PRIVATE STATE DATA
//
//------------------------------------------------------
private UIPermissionWindow m_windowFlag;
private UIPermissionClipboard m_clipboardFlag;
//------------------------------------------------------
//
// PUBLIC CONSTRUCTORS
//
//------------------------------------------------------
public UIPermission(PermissionState state)
{
if (state == PermissionState.Unrestricted)
{
SetUnrestricted( true );
}
else if (state == PermissionState.None)
{
SetUnrestricted( false );
Reset();
}
else
{
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidPermissionState"));
}
}
public UIPermission(UIPermissionWindow windowFlag, UIPermissionClipboard clipboardFlag )
{
VerifyWindowFlag( windowFlag );
VerifyClipboardFlag( clipboardFlag );
m_windowFlag = windowFlag;
m_clipboardFlag = clipboardFlag;
}
public UIPermission(UIPermissionWindow windowFlag )
{
VerifyWindowFlag( windowFlag );
m_windowFlag = windowFlag;
}
public UIPermission(UIPermissionClipboard clipboardFlag )
{
VerifyClipboardFlag( clipboardFlag );
m_clipboardFlag = clipboardFlag;
}
//------------------------------------------------------
//
// PUBLIC ACCESSOR METHODS
//
//------------------------------------------------------
public UIPermissionWindow Window
{
set
{
VerifyWindowFlag(value);
m_windowFlag = value;
}
get
{
return m_windowFlag;
}
}
public UIPermissionClipboard Clipboard
{
set
{
VerifyClipboardFlag(value);
m_clipboardFlag = value;
}
get
{
return m_clipboardFlag;
}
}
//------------------------------------------------------
//
// PRIVATE AND PROTECTED HELPERS FOR ACCESSORS AND CONSTRUCTORS
//
//------------------------------------------------------
private static void VerifyWindowFlag(UIPermissionWindow flag)
{
if (flag < UIPermissionWindow.NoWindows || flag > UIPermissionWindow.AllWindows)
{
throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", (int)flag));
}
Contract.EndContractBlock();
}
private static void VerifyClipboardFlag(UIPermissionClipboard flag)
{
if (flag < UIPermissionClipboard.NoClipboard || flag > UIPermissionClipboard.AllClipboard)
{
throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", (int)flag));
}
Contract.EndContractBlock();
}
private void Reset()
{
m_windowFlag = UIPermissionWindow.NoWindows;
m_clipboardFlag = UIPermissionClipboard.NoClipboard;
}
private void SetUnrestricted( bool unrestricted )
{
if (unrestricted)
{
m_windowFlag = UIPermissionWindow.AllWindows;
m_clipboardFlag = UIPermissionClipboard.AllClipboard;
}
}
#if false
//------------------------------------------------------
//
// OBJECT METHOD OVERRIDES
//
//------------------------------------------------------
public String ToString()
{
#if _DEBUG
StringBuilder sb = new StringBuilder();
sb.Append("UIPermission(");
if (IsUnrestricted())
{
sb.Append("Unrestricted");
}
else
{
sb.Append(m_stateNameTableWindow[m_windowFlag]);
sb.Append(", ");
sb.Append(m_stateNameTableClipboard[m_clipboardFlag]);
}
sb.Append(")");
return sb.ToString();
#else
return super.ToString();
#endif
}
#endif
//------------------------------------------------------
//
// CODEACCESSPERMISSION IMPLEMENTATION
//
//------------------------------------------------------
public bool IsUnrestricted()
{
return m_windowFlag == UIPermissionWindow.AllWindows && m_clipboardFlag == UIPermissionClipboard.AllClipboard;
}
//------------------------------------------------------
//
// IPERMISSION IMPLEMENTATION
//
//------------------------------------------------------
public override bool IsSubsetOf(IPermission target)
{
if (target == null)
{
// Only safe subset if this is empty
return m_windowFlag == UIPermissionWindow.NoWindows && m_clipboardFlag == UIPermissionClipboard.NoClipboard;
}
try
{
UIPermission operand = (UIPermission)target;
if (operand.IsUnrestricted())
return true;
else if (this.IsUnrestricted())
return false;
else
return this.m_windowFlag <= operand.m_windowFlag && this.m_clipboardFlag <= operand.m_clipboardFlag;
}
catch (InvalidCastException)
{
throw new
ArgumentException(
Environment.GetResourceString("Argument_WrongType", this.GetType().FullName)
);
}
}
public override IPermission Intersect(IPermission target)
{
if (target == null)
{
return null;
}
else if (!VerifyType(target))
{
throw new
ArgumentException(
Environment.GetResourceString("Argument_WrongType", this.GetType().FullName)
);
}
UIPermission operand = (UIPermission)target;
UIPermissionWindow isectWindowFlags = m_windowFlag < operand.m_windowFlag ? m_windowFlag : operand.m_windowFlag;
UIPermissionClipboard isectClipboardFlags = m_clipboardFlag < operand.m_clipboardFlag ? m_clipboardFlag : operand.m_clipboardFlag;
if (isectWindowFlags == UIPermissionWindow.NoWindows && isectClipboardFlags == UIPermissionClipboard.NoClipboard)
return null;
else
return new UIPermission(isectWindowFlags, isectClipboardFlags);
}
public override IPermission Union(IPermission target)
{
if (target == null)
{
return this.Copy();
}
else if (!VerifyType(target))
{
throw new
ArgumentException(
Environment.GetResourceString("Argument_WrongType", this.GetType().FullName)
);
}
UIPermission operand = (UIPermission)target;
UIPermissionWindow isectWindowFlags = m_windowFlag > operand.m_windowFlag ? m_windowFlag : operand.m_windowFlag;
UIPermissionClipboard isectClipboardFlags = m_clipboardFlag > operand.m_clipboardFlag ? m_clipboardFlag : operand.m_clipboardFlag;
if (isectWindowFlags == UIPermissionWindow.NoWindows && isectClipboardFlags == UIPermissionClipboard.NoClipboard)
return null;
else
return new UIPermission(isectWindowFlags, isectClipboardFlags);
}
public override IPermission Copy()
{
return new UIPermission(this.m_windowFlag, this.m_clipboardFlag);
}
#if FEATURE_CAS_POLICY
public override SecurityElement ToXml()
{
SecurityElement esd = CodeAccessPermission.CreatePermissionElement( this, "System.Security.Permissions.UIPermission" );
if (!IsUnrestricted())
{
if (m_windowFlag != UIPermissionWindow.NoWindows)
{
esd.AddAttribute( "Window", Enum.GetName( typeof( UIPermissionWindow ), m_windowFlag ) );
}
if (m_clipboardFlag != UIPermissionClipboard.NoClipboard)
{
esd.AddAttribute( "Clipboard", Enum.GetName( typeof( UIPermissionClipboard ), m_clipboardFlag ) );
}
}
else
{
esd.AddAttribute( "Unrestricted", "true" );
}
return esd;
}
public override void FromXml(SecurityElement esd)
{
CodeAccessPermission.ValidateElement( esd, this );
if (XMLUtil.IsUnrestricted( esd ))
{
SetUnrestricted( true );
return;
}
m_windowFlag = UIPermissionWindow.NoWindows;
m_clipboardFlag = UIPermissionClipboard.NoClipboard;
String window = esd.Attribute( "Window" );
if (window != null)
m_windowFlag = (UIPermissionWindow)Enum.Parse( typeof( UIPermissionWindow ), window );
String clipboard = esd.Attribute( "Clipboard" );
if (clipboard != null)
m_clipboardFlag = (UIPermissionClipboard)Enum.Parse( typeof( UIPermissionClipboard ), clipboard );
}
#endif // FEATURE_CAS_POLICY
/// <internalonly/>
int IBuiltInPermission.GetTokenIndex()
{
return UIPermission.GetTokenIndex();
}
internal static int GetTokenIndex()
{
return BuiltInPermissionIndex.UIPermissionIndex;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.IO;
using System.IO.MemoryMappedFiles;
using Xunit;
[Collection("CreateNew")]
public class CreateNew : MMFTestBase
{
private readonly static string s_uniquifier = Guid.NewGuid().ToString();
[Fact]
public static void CreateNewTestCases()
{
bool bResult = false;
CreateNew test = new CreateNew();
try
{
bResult = test.RunTest();
}
catch (Exception exc_main)
{
bResult = false;
Console.WriteLine("FAiL! Error in CreateNew! Uncaught Exception in main(), exc_main==" + exc_main.ToString());
}
Assert.True(bResult, "One or more test cases failed.");
}
public bool RunTest()
{
try
{
////////////////////////////////////////////////////////////////////////
// CreateNew(mapName, capcity)
////////////////////////////////////////////////////////////////////////
// [] mapName
// mapname > 260 chars
VerifyCreateNew("Loc111", "CreateNew" + new String('a', 1000) + s_uniquifier, 4096);
// null
VerifyCreateNew("Loc112", null, 4096);
// empty string disallowed
VerifyCreateNewException<ArgumentException>("Loc113", String.Empty, 4096);
// all whitespace
VerifyCreateNew("Loc114", "\t\t \n\u00A0", 4096);
// MMF with this mapname already exists
if (Interop.IsWindows) // named maps not supported on Unix
{
using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew("map115" + s_uniquifier, 1000))
{
VerifyCreateNewException<IOException>("Loc115", "map115" + s_uniquifier, 1000);
}
}
// MMF with this mapname existed, but was closed
VerifyCreateNew("Loc116", "map115" + s_uniquifier, 500);
// "global/" prefix
VerifyCreateNew("Loc117", "global/CN_0" + s_uniquifier, 4096);
// "local/" prefix
VerifyCreateNew("Loc118", "local/CN_1" + s_uniquifier, 4096);
// [] capacity
// >0 capacity
VerifyCreateNew("Loc211", "CN_mapname211" + s_uniquifier, 50);
// 0 capacity
VerifyCreateNewException<ArgumentOutOfRangeException>("Loc211", "CN_mapname211" + s_uniquifier, 0);
// negative
VerifyCreateNewException<ArgumentOutOfRangeException>("Loc213", "CN_mapname213" + s_uniquifier, -1);
// negative
VerifyCreateNewException<ArgumentOutOfRangeException>("Loc214", "CN_mapname214" + s_uniquifier, -4096);
// Int64.MaxValue - cannot exceed local address space
if (IntPtr.Size == 4)
VerifyCreateNewException<ArgumentOutOfRangeException>("Loc215", "CN_mapname215" + s_uniquifier, Int64.MaxValue);
else // 64-bit machine
VerifyCreateNewException<IOException>("Loc215b", "CN_mapname215" + s_uniquifier, Int64.MaxValue); // valid but too large
////////////////////////////////////////////////////////////////////////
// CreateNew(mapName, capcity, MemoryMappedFileAccess)
////////////////////////////////////////////////////////////////////////
// [] access
// Write is disallowed
VerifyCreateNewException<ArgumentException>("Loc330", "CN_mapname330" + s_uniquifier, 1000, MemoryMappedFileAccess.Write);
// valid access
MemoryMappedFileAccess[] accessList = new MemoryMappedFileAccess[] {
MemoryMappedFileAccess.Read,
MemoryMappedFileAccess.ReadWrite,
MemoryMappedFileAccess.CopyOnWrite,
MemoryMappedFileAccess.ReadExecute,
MemoryMappedFileAccess.ReadWriteExecute,
};
foreach (MemoryMappedFileAccess access in accessList)
{
VerifyCreateNew("Loc331_" + access, "CN_mapname331_" + access + s_uniquifier, 1000, access);
}
// invalid enum value
accessList = new MemoryMappedFileAccess[] {
(MemoryMappedFileAccess)(-1),
(MemoryMappedFileAccess)(6),
};
foreach (MemoryMappedFileAccess access in accessList)
{
VerifyCreateNewException<ArgumentOutOfRangeException>("Loc332_" + ((int)access), "CN_mapname332_" + ((int)access) + s_uniquifier, 1000, access);
}
////////////////////////////////////////////////////////////////////////
// CreateNew(String, long, MemoryMappedFileAccess, MemoryMappedFileOptions,
// MemoryMappedFileSecurity, HandleInheritability)
////////////////////////////////////////////////////////////////////////
// [] mapName
// mapname > 260 chars
VerifyCreateNew("Loc411", "CreateNew2" + new String('a', 1000) + s_uniquifier, 4096, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, HandleInheritability.None);
// null
VerifyCreateNew("Loc412", null, 4096, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, HandleInheritability.None);
// empty string disallowed
VerifyCreateNewException<ArgumentException>("Loc413", String.Empty, 4096, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, HandleInheritability.None);
// all whitespace
VerifyCreateNew("Loc414", "\t\t \n\u00A0", 4096, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, HandleInheritability.None);
// MMF with this mapname already exists
if (Interop.IsWindows) // named maps not supported on Unix
{
using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew("map415" + s_uniquifier, 4096))
{
VerifyCreateNewException<IOException>("Loc415", "map415" + s_uniquifier, 4096, MemoryMappedFileAccess.Read, MemoryMappedFileOptions.None, HandleInheritability.None);
}
}
// MMF with this mapname existed, but was closed
VerifyCreateNew("Loc416", "map415" + s_uniquifier, 4096, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, HandleInheritability.None);
// "global/" prefix
VerifyCreateNew("Loc417", "global/CN_2" + s_uniquifier, 4096, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, HandleInheritability.None);
// "local/" prefix
VerifyCreateNew("Loc418", "local/CN_3" + s_uniquifier, 4096, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, HandleInheritability.None);
// [] capacity
// >0 capacity
VerifyCreateNew("Loc421", "CN_mapname421" + s_uniquifier, 50, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, HandleInheritability.None);
// 0 capacity
VerifyCreateNewException<ArgumentOutOfRangeException>("Loc422", "CN_mapname422" + s_uniquifier, 0, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, HandleInheritability.None);
// negative
VerifyCreateNewException<ArgumentOutOfRangeException>("Loc423", "CN_mapname423" + s_uniquifier, -1, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, HandleInheritability.None);
// negative
VerifyCreateNewException<ArgumentOutOfRangeException>("Loc424", "CN_mapname424" + s_uniquifier, -4096, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, HandleInheritability.None);
// Int64.MaxValue - cannot exceed local address space
if (IntPtr.Size == 4)
VerifyCreateNewException<ArgumentOutOfRangeException>("Loc425", "CN_mapname425" + s_uniquifier, Int64.MaxValue, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, HandleInheritability.None);
else // 64-bit machine
VerifyCreateNewException<IOException>("Loc425b", "CN_mapname425" + s_uniquifier, Int64.MaxValue, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, HandleInheritability.None); // valid but too large
// [] access
// Write is disallowed
VerifyCreateNewException<ArgumentException>("Loc430", "CN_mapname430" + s_uniquifier, 1000, MemoryMappedFileAccess.Write, MemoryMappedFileOptions.None, HandleInheritability.None);
// valid access
accessList = new MemoryMappedFileAccess[] {
MemoryMappedFileAccess.Read,
MemoryMappedFileAccess.ReadWrite,
MemoryMappedFileAccess.CopyOnWrite,
MemoryMappedFileAccess.ReadExecute,
MemoryMappedFileAccess.ReadWriteExecute,
};
foreach (MemoryMappedFileAccess access in accessList)
{
VerifyCreateNew("Loc431_" + access, "CN_mapname431_" + access + s_uniquifier, 1000, access, MemoryMappedFileOptions.None, HandleInheritability.None);
}
// invalid enum value
accessList = new MemoryMappedFileAccess[] {
(MemoryMappedFileAccess)(-1),
(MemoryMappedFileAccess)(6),
};
foreach (MemoryMappedFileAccess access in accessList)
{
VerifyCreateNewException<ArgumentOutOfRangeException>("Loc432_" + ((int)access), "CN_mapname432_" + ((int)access) + s_uniquifier, 1000, access, MemoryMappedFileOptions.None, HandleInheritability.None);
}
// [] options
// Default
VerifyCreateNew("Loc440a", null, 4096 * 1000);
VerifyCreateNew("Loc440b", null, 4096 * 10000);
// None
VerifyCreateNew("Loc441", "CN_mapname441" + s_uniquifier, 4096 * 10000, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, HandleInheritability.None);
// DelayAllocatePages
VerifyCreateNew("Loc442", "CN_mapname442" + s_uniquifier, 4096 * 10000, MemoryMappedFileAccess.Read, MemoryMappedFileOptions.DelayAllocatePages, HandleInheritability.None);
// invalid
VerifyCreateNewException<ArgumentOutOfRangeException>("Loc444", "CN_mapname444" + s_uniquifier, 100, MemoryMappedFileAccess.ReadWrite, (MemoryMappedFileOptions)(-1), HandleInheritability.None);
/// END TEST CASES
if (iCountErrors == 0)
{
return true;
}
else
{
Console.WriteLine("Fail: iCountErrors==" + iCountErrors);
return false;
}
}
catch (Exception ex)
{
Console.WriteLine("ERR999: Unexpected exception in runTest, {0}", ex);
return false;
}
}
/// START HELPER FUNCTIONS
public void VerifyCreateNew(String strLoc, String mapName, long capacity)
{
if (mapName != null && Interop.PlatformDetection.OperatingSystem != Interop.OperatingSystem.Windows)
{
return;
}
iCountTestcases++;
try
{
using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(mapName, capacity))
{
VerifyAccess(strLoc, mmf, MemoryMappedFileAccess.ReadWrite, capacity);
VerifyHandleInheritability(strLoc, mmf.SafeMemoryMappedFileHandle, HandleInheritability.None);
}
}
catch (Exception ex)
{
iCountErrors++;
Console.WriteLine("ERROR, {0}: Unexpected exception, {1}", strLoc, ex);
}
}
public void VerifyCreateNewException<EXCTYPE>(String strLoc, String mapName, long capacity) where EXCTYPE : Exception
{
if (mapName != null && Interop.PlatformDetection.OperatingSystem != Interop.OperatingSystem.Windows)
{
return;
}
iCountTestcases++;
try
{
using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(mapName, capacity))
{
iCountErrors++;
Console.WriteLine("ERROR, {0}: No exception thrown, expected {1}", strLoc, typeof(EXCTYPE));
}
}
catch (EXCTYPE)
{
//Console.WriteLine("{0}: Expected, {1}: {2}", strLoc, ex.GetType(), ex.Message);
}
catch (Exception ex)
{
iCountErrors++;
Console.WriteLine("ERROR, {0}: Unexpected exception, {1}", strLoc, ex);
}
}
public void VerifyCreateNew(String strLoc, String mapName, long capacity, MemoryMappedFileAccess access)
{
if (mapName != null && Interop.PlatformDetection.OperatingSystem != Interop.OperatingSystem.Windows)
{
return;
}
iCountTestcases++;
try
{
using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(mapName, capacity, access))
{
VerifyAccess(strLoc, mmf, access, capacity);
VerifyHandleInheritability(strLoc, mmf.SafeMemoryMappedFileHandle, HandleInheritability.None);
}
}
catch (Exception ex)
{
iCountErrors++;
Console.WriteLine("ERROR, {0}: Unexpected exception, {1}", strLoc, ex);
}
}
public void VerifyCreateNewException<EXCTYPE>(String strLoc, String mapName, long capacity, MemoryMappedFileAccess access) where EXCTYPE : Exception
{
if (mapName != null && Interop.PlatformDetection.OperatingSystem != Interop.OperatingSystem.Windows)
{
return;
}
iCountTestcases++;
try
{
using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(mapName, capacity, access))
{
iCountErrors++;
Console.WriteLine("ERROR, {0}: No exception thrown, expected {1}", strLoc, typeof(EXCTYPE));
}
}
catch (EXCTYPE)
{
//Console.WriteLine("{0}: Expected, {1}: {2}", strLoc, ex.GetType(), ex.Message);
}
catch (Exception ex)
{
iCountErrors++;
Console.WriteLine("ERROR, {0}: Unexpected exception, {1}", strLoc, ex);
}
}
public void VerifyCreateNew(String strLoc, String mapName, long capacity, MemoryMappedFileAccess access, MemoryMappedFileOptions options, HandleInheritability inheritability)
{
if (mapName != null && Interop.PlatformDetection.OperatingSystem != Interop.OperatingSystem.Windows)
{
return;
}
iCountTestcases++;
try
{
using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(mapName, capacity, access, options, inheritability))
{
VerifyAccess(strLoc, mmf, access, capacity);
VerifyHandleInheritability(strLoc, mmf.SafeMemoryMappedFileHandle, inheritability);
}
}
catch (Exception ex)
{
iCountErrors++;
Console.WriteLine("ERROR, {0}: Unexpected exception, {1}", strLoc, ex);
}
}
public void VerifyCreateNewException<EXCTYPE>(String strLoc, String mapName, long capacity, MemoryMappedFileAccess access, MemoryMappedFileOptions options, HandleInheritability inheritability) where EXCTYPE : Exception
{
if (mapName != null && Interop.PlatformDetection.OperatingSystem != Interop.OperatingSystem.Windows)
{
return;
}
iCountTestcases++;
try
{
using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(mapName, capacity, access, options, inheritability))
{
iCountErrors++;
Console.WriteLine("ERROR, {0}: No exception thrown, expected {1}", strLoc, typeof(EXCTYPE));
}
}
catch (EXCTYPE)
{
//Console.WriteLine("{0}: Expected, {1}: {2}", strLoc, ex.GetType(), ex.Message);
}
catch (Exception ex)
{
iCountErrors++;
Console.WriteLine("ERROR, {0}: Unexpected exception, {1}", strLoc, ex);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.