context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
using System.Drawing;
using System;
using MonoTouch.Foundation;
namespace BBlock {
[BaseType (typeof (NSObject))]
public partial interface BBlock {
[Static, Export ("dispatchOnMainThread:")]
void DispatchOnMainThread (Delegate block);
[Static, Export ("dispatchAfter:onMainThread:")]
void DispatchAfter (double delay, Delegate block);
[Static, Export ("dispatchOnSynchronousQueue:")]
void DispatchOnSynchronousQueue (Delegate block);
[Static, Export ("dispatchOnSynchronousFileQueue:")]
void DispatchOnSynchronousFileQueue (Delegate block);
[Static, Export ("dispatchOnDefaultPriorityConcurrentQueue:")]
void DispatchOnDefaultPriorityConcurrentQueue (Delegate block);
[Static, Export ("dispatchOnLowPriorityConcurrentQueue:")]
void DispatchOnLowPriorityConcurrentQueue (Delegate block);
[Static, Export ("dispatchOnHighPriorityConcurrentQueue:")]
void DispatchOnHighPriorityConcurrentQueue (Delegate block);
}
[Category, BaseType (typeof (NSArray))]
public partial interface BBlock_NSArray {
[Export ("enumerateEachObjectUsingBlock:")]
void EnumerateEachObjectUsingBlock (Delegate block);
[Export ("arrayWithObjectsMappedWithBlock:"), Verify ("NSArray may be reliably typed, check the documentation", "/Users/pavellitvinenko/Documents/Projects/Telesite/Thirdparty/iOS/BBlock/Categories/Foundation/NSArray+BBlock.h", Line = 17)]
NSObject [] ArrayWithObjectsMappedWithBlock (Delegate block);
}
[Category, BaseType (typeof (NSDictionary))]
public partial interface BBlock_NSDictionary {
[Export ("enumerateEachKeyAndObjectUsingBlock:")]
void EnumerateEachKeyAndObjectUsingBlock (Delegate block);
[Export ("enumerateEachSortedKeyAndObjectUsingBlock:")]
void EnumerateEachSortedKeyAndObjectUsingBlock (Delegate block);
}
[Category, BaseType (typeof (NSObject))]
public partial interface BBlock_NSObject {
[Export ("addObserverForKeyPath:options:block:")]
string AddObserverForKeyPath (string keyPath, NSKeyValueObservingOptions options, NSObjectBBlock block);
[Export ("removeObserverForToken:")]
void RemoveObserverForToken (string identifier);
[Export ("removeObserverBlocksForKeyPath:")]
void RemoveObserverBlocksForKeyPath (string keyPath);
[Export ("changeValueWithKey:changeBlock:")]
void ChangeValueWithKey (string key, Delegate changeBlock);
}
[Category, BaseType (typeof (NSTimer))]
public partial interface BBlock_NSTimer {
[Static, Export ("timerWithTimeInterval:andBlock:")]
BBlock_NSTimer TimerWithTimeInterval (double timeInterval, Delegate block);
[Static, Export ("timerRepeats:withTimeInterval:andBlock:")]
BBlock_NSTimer TimerRepeats (bool repeats, double timeInterval, Delegate block);
[Static, Export ("scheduledTimerWithTimeInterval:andBlock:")]
BBlock_NSTimer ScheduledTimerWithTimeInterval (double timeInterval, Delegate block);
[Static, Export ("scheduledTimerRepeats:withTimeInterval:andBlock:")]
BBlock_NSTimer ScheduledTimerRepeats (bool repeats, double timeInterval, Delegate block);
}
[Category, BaseType (typeof (NSArray))]
public partial interface BBlock_NSArray {
[Export ("enumerateEachObjectUsingBlock:")]
void EnumerateEachObjectUsingBlock (Delegate block);
[Export ("arrayWithObjectsMappedWithBlock:"), Verify ("NSArray may be reliably typed, check the documentation", "/Users/pavellitvinenko/Documents/Projects/Telesite/Thirdparty/iOS/BBlock/Categories/Foundation/NSArray+BBlock.h", Line = 17)]
NSObject [] ArrayWithObjectsMappedWithBlock (Delegate block);
}
[Category, BaseType (typeof (NSDictionary))]
public partial interface BBlock_NSDictionary {
[Export ("enumerateEachKeyAndObjectUsingBlock:")]
void EnumerateEachKeyAndObjectUsingBlock (Delegate block);
[Export ("enumerateEachSortedKeyAndObjectUsingBlock:")]
void EnumerateEachSortedKeyAndObjectUsingBlock (Delegate block);
}
[Category, BaseType (typeof (NSObject))]
public partial interface BBlock_NSObject {
[Export ("addObserverForKeyPath:options:block:")]
string AddObserverForKeyPath (string keyPath, NSKeyValueObservingOptions options, NSObjectBBlock block);
[Export ("removeObserverForToken:")]
void RemoveObserverForToken (string identifier);
[Export ("removeObserverBlocksForKeyPath:")]
void RemoveObserverBlocksForKeyPath (string keyPath);
[Export ("changeValueWithKey:changeBlock:")]
void ChangeValueWithKey (string key, Delegate changeBlock);
}
[Category, BaseType (typeof (NSTimer))]
public partial interface BBlock_NSTimer {
[Static, Export ("timerWithTimeInterval:andBlock:")]
BBlock_NSTimer TimerWithTimeInterval (double timeInterval, Delegate block);
[Static, Export ("timerRepeats:withTimeInterval:andBlock:")]
BBlock_NSTimer TimerRepeats (bool repeats, double timeInterval, Delegate block);
[Static, Export ("scheduledTimerWithTimeInterval:andBlock:")]
BBlock_NSTimer ScheduledTimerWithTimeInterval (double timeInterval, Delegate block);
[Static, Export ("scheduledTimerRepeats:withTimeInterval:andBlock:")]
BBlock_NSTimer ScheduledTimerRepeats (bool repeats, double timeInterval, Delegate block);
}
[Category, BaseType (typeof (SKProductsRequest))]
public partial interface BBlock_SKProductsRequest {
[Static, Export ("requestWithProductIdentifiers:andBlock:")]
BBlock_SKProductsRequest RequestWithProductIdentifiers (NSSet productIdentifiers, SKProductsRequestBBlock block);
[Export ("initWithProductIdentifiers:andBlock:")]
IntPtr Constructor (NSSet productIdentifiers, SKProductsRequestBBlock block);
}
[Category, BaseType (typeof (SKStoreProductViewController))]
public partial interface BBlock_SKStoreProductViewController {
[Static, Export ("productViewControllerWithDidFinishBlock:")]
NSObject ProductViewControllerWithDidFinishBlock (SKStoreProductViewControllerBBlock block);
[Export ("initWithProductViewControllerWithDidFinishBlock:")]
IntPtr Constructor (SKStoreProductViewControllerBBlock block);
}
[Category, BaseType (typeof (SKProductsRequest))]
public partial interface BBlock_SKProductsRequest {
[Static, Export ("requestWithProductIdentifiers:andBlock:")]
BBlock_SKProductsRequest RequestWithProductIdentifiers (NSSet productIdentifiers, SKProductsRequestBBlock block);
[Export ("initWithProductIdentifiers:andBlock:")]
IntPtr Constructor (NSSet productIdentifiers, SKProductsRequestBBlock block);
}
[Category, BaseType (typeof (SKStoreProductViewController))]
public partial interface BBlock_SKStoreProductViewController {
[Static, Export ("productViewControllerWithDidFinishBlock:")]
NSObject ProductViewControllerWithDidFinishBlock (SKStoreProductViewControllerBBlock block);
[Export ("initWithProductViewControllerWithDidFinishBlock:")]
IntPtr Constructor (SKStoreProductViewControllerBBlock block);
}
[Category, BaseType (typeof (UIActionSheet))]
public partial interface BBlock_UIActionSheet {
[Export ("completionBlock"), Verify ("ObjC method massaged into setter property", "/Users/pavellitvinenko/Documents/Projects/Telesite/Thirdparty/iOS/BBlock/Categories/UIKit/UIActionSheet+BBlock.h", Line = 15)]
UIActionSheetBBlock CompletionBlock { set; }
[Export ("initWithTitle:cancelButtonTitle:destructiveButtonTitle:otherButtonTitle:completionBlock:")]
IntPtr Constructor (string title, string cancelTitle, string destructiveTitle, string otherTitle, UIActionSheetBBlock block);
}
[Category, BaseType (typeof (UIAlertView))]
public partial interface BBlock_UIAlertView {
[Export ("completionBlock"), Verify ("ObjC method massaged into setter property", "/Users/pavellitvinenko/Documents/Projects/Telesite/Thirdparty/iOS/BBlock/Categories/UIKit/UIAlertView+BBlock.h", Line = 15)]
UIAlertViewBBlock CompletionBlock { set; }
[Export ("initWithTitle:message:cancelButtonTitle:otherButtonTitle:completionBlock:")]
IntPtr Constructor (string title, string message, string cancelTitle, string otherButtonTitle, UIAlertViewBBlock block);
}
[Category, BaseType (typeof (UIControl))]
public partial interface BBlock_UIControl {
[Export ("addActionForControlEvents:withBlock:")]
void AddActionForControlEvents (UIControlEvents events, BBlockUIControlBlock block);
}
[Category, BaseType (typeof (UIGestureRecognizer))]
public partial interface BBlock_UIGestureRecognizer {
[Export ("initWithBlock:")]
IntPtr Constructor (UIGestureRecognizerBBlock block);
[Static, Export ("gestureRecognizerWithBlock:")]
BBlock_UIGestureRecognizer GestureRecognizerWithBlock (UIGestureRecognizerBBlock block);
}
[Category, BaseType (typeof (UISwipeGestureRecognizer))]
public partial interface BBlock_UISwipeGestureRecognizer {
[Export ("initWithDirection:andBlock:")]
IntPtr Constructor (UISwipeGestureRecognizerDirection direction, UIGestureRecognizerBBlock block);
[Static, Export ("gestureRecognizerWithDirection:andBlock:")]
BBlock_UISwipeGestureRecognizer GestureRecognizerWithDirection (UISwipeGestureRecognizerDirection direction, UIGestureRecognizerBBlock block);
}
[Category, BaseType (typeof (UIImage))]
public partial interface BBlock_UIImage {
[Static, Export ("imageForSize:withDrawingBlock:")]
UIImage ImageForSize (SizeF size, Delegate drawingBlock);
[Static, Export ("imageForSize:opaque:withDrawingBlock:")]
UIImage ImageForSize (SizeF size, bool opaque, Delegate drawingBlock);
[Static, Export ("imageWithIdentifier:forSize:andDrawingBlock:")]
UIImage ImageWithIdentifier (string identifier, SizeF size, Delegate drawingBlock);
[Static, Export ("imageWithIdentifier:opaque:forSize:andDrawingBlock:")]
UIImage ImageWithIdentifier (string identifier, bool opaque, SizeF size, Delegate drawingBlock);
[Static, Export ("imageWithIdentifier:")]
UIImage ImageWithIdentifier (string identifier);
[Static, Export ("removeImageWithIdentifier:")]
void RemoveImageWithIdentifier (string identifier);
[Static, Export ("removeAllImages")]
void RemoveAllImages ();
}
[Category, BaseType (typeof (UIActionSheet))]
public partial interface BBlock_UIActionSheet {
[Export ("completionBlock"), Verify ("ObjC method massaged into setter property", "/Users/pavellitvinenko/Documents/Projects/Telesite/Thirdparty/iOS/BBlock/Categories/UIKit/UIActionSheet+BBlock.h", Line = 15)]
UIActionSheetBBlock CompletionBlock { set; }
[Export ("initWithTitle:cancelButtonTitle:destructiveButtonTitle:otherButtonTitle:completionBlock:")]
IntPtr Constructor (string title, string cancelTitle, string destructiveTitle, string otherTitle, UIActionSheetBBlock block);
}
[Category, BaseType (typeof (UIAlertView))]
public partial interface BBlock_UIAlertView {
[Export ("completionBlock"), Verify ("ObjC method massaged into setter property", "/Users/pavellitvinenko/Documents/Projects/Telesite/Thirdparty/iOS/BBlock/Categories/UIKit/UIAlertView+BBlock.h", Line = 15)]
UIAlertViewBBlock CompletionBlock { set; }
[Export ("initWithTitle:message:cancelButtonTitle:otherButtonTitle:completionBlock:")]
IntPtr Constructor (string title, string message, string cancelTitle, string otherButtonTitle, UIAlertViewBBlock block);
}
[Category, BaseType (typeof (UIControl))]
public partial interface BBlock_UIControl {
[Export ("addActionForControlEvents:withBlock:")]
void AddActionForControlEvents (UIControlEvents events, BBlockUIControlBlock block);
}
[Category, BaseType (typeof (UIGestureRecognizer))]
public partial interface BBlock_UIGestureRecognizer {
[Export ("initWithBlock:")]
IntPtr Constructor (UIGestureRecognizerBBlock block);
[Static, Export ("gestureRecognizerWithBlock:")]
BBlock_UIGestureRecognizer GestureRecognizerWithBlock (UIGestureRecognizerBBlock block);
}
[Category, BaseType (typeof (UISwipeGestureRecognizer))]
public partial interface BBlock_UISwipeGestureRecognizer {
[Export ("initWithDirection:andBlock:")]
IntPtr Constructor (UISwipeGestureRecognizerDirection direction, UIGestureRecognizerBBlock block);
[Static, Export ("gestureRecognizerWithDirection:andBlock:")]
BBlock_UISwipeGestureRecognizer GestureRecognizerWithDirection (UISwipeGestureRecognizerDirection direction, UIGestureRecognizerBBlock block);
}
[Category, BaseType (typeof (UIImage))]
public partial interface BBlock_UIImage {
[Static, Export ("imageForSize:withDrawingBlock:")]
UIImage ImageForSize (SizeF size, Delegate drawingBlock);
[Static, Export ("imageForSize:opaque:withDrawingBlock:")]
UIImage ImageForSize (SizeF size, bool opaque, Delegate drawingBlock);
[Static, Export ("imageWithIdentifier:forSize:andDrawingBlock:")]
UIImage ImageWithIdentifier (string identifier, SizeF size, Delegate drawingBlock);
[Static, Export ("imageWithIdentifier:opaque:forSize:andDrawingBlock:")]
UIImage ImageWithIdentifier (string identifier, bool opaque, SizeF size, Delegate drawingBlock);
[Static, Export ("imageWithIdentifier:")]
UIImage ImageWithIdentifier (string identifier);
[Static, Export ("removeImageWithIdentifier:")]
void RemoveImageWithIdentifier (string identifier);
[Static, Export ("removeAllImages")]
void RemoveAllImages ();
}
[Category, BaseType (typeof (UITextField))]
public partial interface BBlock_UITextField {
[Export ("textFieldShouldReturnWithBlock:")]
void TextFieldShouldReturnWithBlock (UITextFieldShouldReturnBBlock block);
}
[Category, BaseType (typeof (UITextField))]
public partial interface BBlock_UITextField {
[Export ("textFieldShouldReturnWithBlock:")]
void TextFieldShouldReturnWithBlock (UITextFieldShouldReturnBBlock block);
}
}
| |
/*
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.ElasticBeanstalk.Model
{
/// <summary>
/// Container for the parameters to the DescribeConfigurationOptions operation.
/// <para> Describes the configuration options that are used in a particular configuration template or environment, or that a specified solution
/// stack defines. The description includes the values the options, their default values, and an indication of the required action on a running
/// environment if an option value is changed. </para>
/// </summary>
/// <seealso cref="Amazon.ElasticBeanstalk.AmazonElasticBeanstalk.DescribeConfigurationOptions"/>
public class DescribeConfigurationOptionsRequest : AmazonWebServiceRequest
{
private string applicationName;
private string templateName;
private string environmentName;
private string solutionStackName;
private List<OptionSpecification> options = new List<OptionSpecification>();
/// <summary>
/// The name of the application associated with the configuration template or environment. Only needed if you want to describe the configuration
/// options associated with either the configuration template or environment.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Length</term>
/// <description>1 - 100</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string ApplicationName
{
get { return this.applicationName; }
set { this.applicationName = value; }
}
/// <summary>
/// Sets the ApplicationName property
/// </summary>
/// <param name="applicationName">The value to set for the ApplicationName property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DescribeConfigurationOptionsRequest WithApplicationName(string applicationName)
{
this.applicationName = applicationName;
return this;
}
// Check to see if ApplicationName property is set
internal bool IsSetApplicationName()
{
return this.applicationName != null;
}
/// <summary>
/// The name of the configuration template whose configuration options you want to describe.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Length</term>
/// <description>1 - 100</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string TemplateName
{
get { return this.templateName; }
set { this.templateName = value; }
}
/// <summary>
/// Sets the TemplateName property
/// </summary>
/// <param name="templateName">The value to set for the TemplateName property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DescribeConfigurationOptionsRequest WithTemplateName(string templateName)
{
this.templateName = templateName;
return this;
}
// Check to see if TemplateName property is set
internal bool IsSetTemplateName()
{
return this.templateName != null;
}
/// <summary>
/// The name of the environment whose configuration options you want to describe.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Length</term>
/// <description>4 - 23</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string EnvironmentName
{
get { return this.environmentName; }
set { this.environmentName = value; }
}
/// <summary>
/// Sets the EnvironmentName property
/// </summary>
/// <param name="environmentName">The value to set for the EnvironmentName property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DescribeConfigurationOptionsRequest WithEnvironmentName(string environmentName)
{
this.environmentName = environmentName;
return this;
}
// Check to see if EnvironmentName property is set
internal bool IsSetEnvironmentName()
{
return this.environmentName != null;
}
/// <summary>
/// The name of the solution stack whose configuration options you want to describe.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Length</term>
/// <description>0 - 100</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string SolutionStackName
{
get { return this.solutionStackName; }
set { this.solutionStackName = value; }
}
/// <summary>
/// Sets the SolutionStackName property
/// </summary>
/// <param name="solutionStackName">The value to set for the SolutionStackName property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DescribeConfigurationOptionsRequest WithSolutionStackName(string solutionStackName)
{
this.solutionStackName = solutionStackName;
return this;
}
// Check to see if SolutionStackName property is set
internal bool IsSetSolutionStackName()
{
return this.solutionStackName != null;
}
/// <summary>
/// If specified, restricts the descriptions to only the specified options.
///
/// </summary>
public List<OptionSpecification> Options
{
get { return this.options; }
set { this.options = value; }
}
/// <summary>
/// Adds elements to the Options collection
/// </summary>
/// <param name="options">The values to add to the Options collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DescribeConfigurationOptionsRequest WithOptions(params OptionSpecification[] options)
{
foreach (OptionSpecification element in options)
{
this.options.Add(element);
}
return this;
}
/// <summary>
/// Adds elements to the Options collection
/// </summary>
/// <param name="options">The values to add to the Options collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DescribeConfigurationOptionsRequest WithOptions(IEnumerable<OptionSpecification> options)
{
foreach (OptionSpecification element in options)
{
this.options.Add(element);
}
return this;
}
// Check to see if Options property is set
internal bool IsSetOptions()
{
return this.options.Count > 0;
}
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Linq;
using NUnit.Framework;
using osu.Framework.Extensions.EnumExtensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Cursor;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Graphics.UserInterface;
using osu.Framework.Utils;
using osu.Framework.Testing;
using osuTK;
using osuTK.Graphics;
using osuTK.Input;
namespace osu.Framework.Tests.Visual.UserInterface
{
public class TestSceneContextMenu : ManualInputManagerTestScene
{
protected override Container<Drawable> Content => contextMenuContainer ?? base.Content;
private readonly TestContextMenuContainer contextMenuContainer;
public TestSceneContextMenu()
{
base.Content.Add(contextMenuContainer = new TestContextMenuContainer { RelativeSizeAxes = Axes.Both });
}
[SetUp]
public void Setup() => Schedule(Clear);
/// <summary>
/// Tests an edge case where the submenu is visible and continues updating for a short period of time after right clicking another item.
/// In such a case, the submenu should not update its position unless it's open.
/// </summary>
[Test]
public void TestNestedMenuTransferredWithFadeOut()
{
TestContextMenuContainerWithFade fadingMenuContainer = null;
BoxWithNestedContextMenuItems box1 = null;
BoxWithNestedContextMenuItems box2 = null;
AddStep("setup", () =>
{
Child = fadingMenuContainer = new TestContextMenuContainerWithFade
{
RelativeSizeAxes = Axes.Both,
Child = new FillFlowContainer
{
AutoSizeAxes = Axes.Both,
Direction = FillDirection.Horizontal,
Spacing = new Vector2(10),
Children = new[]
{
box1 = new BoxWithNestedContextMenuItems { Size = new Vector2(100) },
box2 = new BoxWithNestedContextMenuItems { Size = new Vector2(100) }
}
}
};
});
clickBoxStep(() => box1);
AddStep("hover over menu item", () => InputManager.MoveMouseTo(fadingMenuContainer.ChildrenOfType<Menu.DrawableMenuItem>().First()));
clickBoxStep(() => box2);
AddStep("hover over menu item", () => InputManager.MoveMouseTo(fadingMenuContainer.ChildrenOfType<Menu.DrawableMenuItem>().First()));
AddAssert("submenu opened and visible", () =>
{
var targetItem = fadingMenuContainer.ChildrenOfType<Menu.DrawableMenuItem>().First();
var subMenu = fadingMenuContainer.ChildrenOfType<Menu>().Last();
return subMenu.State == MenuState.Open && subMenu.IsPresent && !subMenu.IsMaskedAway && subMenu.ScreenSpaceDrawQuad.TopLeft.X > targetItem.ScreenSpaceDrawQuad.TopLeft.X;
});
}
[Test]
public void TestMenuOpenedOnClick()
{
Drawable box = null;
addBoxStep(b => box = b, 1);
clickBoxStep(() => box);
assertMenuState(true);
}
[Test]
public void TestMenuClosedOnClickOutside()
{
Drawable box = null;
addBoxStep(b => box = b, 1);
clickBoxStep(() => box);
clickOutsideStep();
assertMenuState(false);
}
[Test]
public void TestMenuTransferredToNewTarget()
{
Drawable box1 = null;
Drawable box2 = null;
addBoxStep(b =>
{
box1 = b.With(d =>
{
d.X = -100;
d.Colour = Color4.Green;
});
}, 1);
addBoxStep(b =>
{
box2 = b.With(d =>
{
d.X = 100;
d.Colour = Color4.Red;
});
}, 1);
clickBoxStep(() => box1);
clickBoxStep(() => box2);
assertMenuState(true);
assertMenuInCentre(() => box2);
}
[Test]
public void TestMenuHiddenWhenTargetHidden()
{
Drawable box = null;
addBoxStep(b => box = b, 1);
clickBoxStep(() => box);
AddStep("hide box", () => box.Hide());
assertMenuState(false);
}
[Test]
public void TestMenuTracksMovement()
{
Drawable box = null;
addBoxStep(b => box = b, 1);
clickBoxStep(() => box);
AddStep("move box", () => box.X += 100);
assertMenuInCentre(() => box);
}
[TestCase(Anchor.TopLeft)]
[TestCase(Anchor.TopCentre)]
[TestCase(Anchor.TopRight)]
[TestCase(Anchor.CentreLeft)]
[TestCase(Anchor.CentreRight)]
[TestCase(Anchor.BottomLeft)]
[TestCase(Anchor.BottomCentre)]
[TestCase(Anchor.BottomRight)]
public void TestMenuOnScreenWhenTargetPartlyOffScreen(Anchor anchor)
{
Drawable box = null;
addBoxStep(b => box = b, 5);
clickBoxStep(() => box);
AddStep($"move box to {anchor.ToString()}", () =>
{
box.Anchor = anchor;
box.X -= 5;
box.Y -= 5;
});
assertMenuOnScreen(true);
}
[TestCase(Anchor.TopLeft)]
[TestCase(Anchor.TopCentre)]
[TestCase(Anchor.TopRight)]
[TestCase(Anchor.CentreLeft)]
[TestCase(Anchor.CentreRight)]
[TestCase(Anchor.BottomLeft)]
[TestCase(Anchor.BottomCentre)]
[TestCase(Anchor.BottomRight)]
public void TestMenuNotOnScreenWhenTargetSignificantlyOffScreen(Anchor anchor)
{
Drawable box = null;
addBoxStep(b => box = b, 5);
clickBoxStep(() => box);
AddStep($"move box to {anchor.ToString()}", () =>
{
box.Anchor = anchor;
if (anchor.HasFlagFast(Anchor.x0))
box.X -= contextMenuContainer.CurrentMenu.DrawWidth + 10;
else if (anchor.HasFlagFast(Anchor.x2))
box.X += 10;
if (anchor.HasFlagFast(Anchor.y0))
box.Y -= contextMenuContainer.CurrentMenu.DrawHeight + 10;
else if (anchor.HasFlagFast(Anchor.y2))
box.Y += 10;
});
assertMenuOnScreen(false);
}
[Test]
public void TestReturnNullInNestedDrawableOpensParentMenu()
{
Drawable box2 = null;
addBoxStep(_ => { }, 2);
addBoxStep(b => box2 = b, null);
clickBoxStep(() => box2);
assertMenuState(true);
assertMenuItems(2);
}
[Test]
public void TestReturnEmptyInNestedDrawableBlocksMenuOpening()
{
Drawable box2 = null;
addBoxStep(_ => { }, 2);
addBoxStep(b => box2 = b);
clickBoxStep(() => box2);
assertMenuState(false);
}
[Test]
public void TestHideWhileScrolledAndShow()
{
Drawable box = null;
addBoxStep(b => box = b, 1);
clickBoxStep(() => box);
assertMenuState(true);
AddStep("drag menu offscreen", () =>
{
InputManager.MoveMouseTo(contextMenuContainer.CurrentMenu);
InputManager.PressButton(MouseButton.Left);
InputManager.MoveMouseTo(contextMenuContainer.CurrentMenu, new Vector2(0, 150));
});
AddStep("hide menu", () =>
{
InputManager.Key(Key.Escape);
InputManager.ReleaseButton(MouseButton.Left);
});
clickBoxStep(() => box);
AddAssert("menu has correct size", () => contextMenuContainer.CurrentMenu.DrawSize.Y > 10);
}
private void clickBoxStep(Func<Drawable> getBoxFunc)
{
AddStep("right-click box", () =>
{
InputManager.MoveMouseTo(getBoxFunc());
InputManager.Click(MouseButton.Right);
});
}
private void clickOutsideStep()
{
AddStep("click outside", () =>
{
InputManager.MoveMouseTo(InputManager.ScreenSpaceDrawQuad.TopLeft);
InputManager.Click(MouseButton.Right);
});
}
private void addBoxStep(Action<Drawable> boxFunc, int actionCount) => addBoxStep(boxFunc, Enumerable.Repeat(new Action(() => { }), actionCount).ToArray());
private void addBoxStep(Action<Drawable> boxFunc, params Action[] actions)
{
AddStep("add box", () =>
{
var box = new BoxWithContextMenu(actions)
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Size = new Vector2(200),
};
Add(box);
boxFunc?.Invoke(box);
});
}
private void assertMenuState(bool opened)
=> AddAssert($"menu {(opened ? "opened" : "closed")}", () => (contextMenuContainer.CurrentMenu?.State == MenuState.Open) == opened);
private void assertMenuInCentre(Func<Drawable> getBoxFunc)
=> AddAssert("menu in centre of box", () => Precision.AlmostEquals(contextMenuContainer.CurrentMenu.ScreenSpaceDrawQuad.TopLeft, getBoxFunc().ScreenSpaceDrawQuad.Centre));
private void assertMenuOnScreen(bool expected) => AddAssert($"menu {(expected ? "on" : "off")} screen", () =>
{
var inputQuad = InputManager.ScreenSpaceDrawQuad;
var menuQuad = contextMenuContainer.CurrentMenu.ScreenSpaceDrawQuad;
bool result = inputQuad.Contains(menuQuad.TopLeft + new Vector2(1, 1))
&& inputQuad.Contains(menuQuad.TopRight + new Vector2(-1, 1))
&& inputQuad.Contains(menuQuad.BottomLeft + new Vector2(1, -1))
&& inputQuad.Contains(menuQuad.BottomRight + new Vector2(-1, -1));
return result == expected;
});
private void assertMenuItems(int expectedCount) => AddAssert($"menu contains {expectedCount} item(s)", () => contextMenuContainer.CurrentMenu.Items.Count == expectedCount);
private class BoxWithContextMenu : Box, IHasContextMenu
{
private readonly Action[] actions;
public BoxWithContextMenu(Action[] actions)
{
this.actions = actions;
}
public MenuItem[] ContextMenuItems => actions?.Select((a, i) => new MenuItem($"Item {i}", a)).ToArray();
}
private class BoxWithNestedContextMenuItems : Box, IHasContextMenu
{
public MenuItem[] ContextMenuItems => new[]
{
new MenuItem("First")
{
Items = new[]
{
new MenuItem("Second")
}
},
};
}
private class TestContextMenuContainer : BasicContextMenuContainer
{
public Menu CurrentMenu { get; private set; }
protected override Menu CreateMenu() => CurrentMenu = base.CreateMenu();
}
private class TestContextMenuContainerWithFade : BasicContextMenuContainer
{
protected override Menu CreateMenu() => new TestMenu();
private class TestMenu : BasicMenu
{
public TestMenu()
: base(Direction.Vertical)
{
ItemsContainer.Padding = new MarginPadding { Vertical = 2 };
}
protected override void AnimateClose() => this.FadeOut(1000, Easing.OutQuint);
protected override Menu CreateSubMenu() => new TestMenu();
}
}
}
}
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Administration
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Runtime;
using System.Runtime.Diagnostics;
using System.Security.Cryptography.X509Certificates;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Diagnostics;
class ServiceInstanceProvider : ProviderBase, IWmiProvider
{
void IWmiProvider.EnumInstances(IWmiInstances instances)
{
Fx.Assert(null != instances, "");
int processId = AppDomainInfo.Current.ProcessId;
foreach (ServiceInfo info in new ServiceInfoCollection(ManagementExtension.Services))
{
IWmiInstance instance = instances.NewInstance(null);
instance.SetProperty(AdministrationStrings.DistinguishedName, info.DistinguishedName);
instance.SetProperty(AdministrationStrings.ProcessId, processId);
FillServiceInfo(info, instance);
instances.AddInstance(instance);
}
}
bool IWmiProvider.GetInstance(IWmiInstance instance)
{
Fx.Assert(null != instance, "");
bool bFound = false;
if ((int)instance.GetProperty(AdministrationStrings.ProcessId) == AppDomainInfo.Current.ProcessId)
{
foreach (ServiceInfo info in new ServiceInfoCollection(ManagementExtension.Services))
{
if (String.Equals((string)instance.GetProperty(AdministrationStrings.DistinguishedName), info.DistinguishedName, StringComparison.OrdinalIgnoreCase))
{
FillServiceInfo(info, instance);
bFound = true;
break;
}
}
}
return bFound;
}
internal static string GetReference(ServiceInfo serviceInfo)
{
Fx.Assert(null != serviceInfo, "");
return String.Format(CultureInfo.InvariantCulture, AdministrationStrings.Service +
"." +
AdministrationStrings.DistinguishedName +
"='{0}'," +
AdministrationStrings.ProcessId +
"={1}",
serviceInfo.DistinguishedName,
AppDomainInfo.Current.ProcessId);
}
internal static IWmiInstance GetAppDomainInfo(IWmiInstance instance)
{
Fx.Assert(null != instance, "");
IWmiInstance appDomainInfo = instance.NewInstance(AdministrationStrings.AppDomainInfo);
if (null != appDomainInfo)
{
AppDomainInstanceProvider.FillAppDomainInfo(appDomainInfo);
}
return appDomainInfo;
}
void FillBehaviorsInfo(ServiceInfo info, IWmiInstance instance)
{
Fx.Assert(null != instance, "");
List<IWmiInstance> behaviors = new List<IWmiInstance>(info.Behaviors.Count);
foreach (IServiceBehavior behavior in info.Behaviors)
{
IWmiInstance behaviorInstance;
FillBehaviorInfo(behavior, instance, out behaviorInstance);
if (null != behaviorInstance)
{
behaviors.Add(behaviorInstance);
}
}
instance.SetProperty(AdministrationStrings.Behaviors, behaviors.ToArray());
}
void FillChannelsInfo(ServiceInfo info, IWmiInstance instance)
{
Fx.Assert(null != instance, "");
Fx.Assert(null != info, "");
int channelsCount = 0;
List<IWmiInstance> instances = new List<IWmiInstance>();
IEnumerable<InstanceContext> contexts = info.Service.GetInstanceContexts();
foreach (InstanceContext instanceContext in contexts)
{
lock (instanceContext.ThisLock)
{
channelsCount += instanceContext.WmiChannels.Count;
foreach (IChannel channel in instanceContext.WmiChannels)
{
IWmiInstance channelInstance = instance.NewInstance(AdministrationStrings.Channel);
FillChannelInfo(channel, channelInstance);
instances.Add(channelInstance);
}
}
}
instance.SetProperty(AdministrationStrings.Channels, instances.ToArray());
}
static void FillExtensionsInfo(ServiceInfo info, IWmiInstance instance)
{
Fx.Assert(null != instance, "");
Fx.Assert(null != info, "");
ProviderBase.FillCollectionInfo(info.Service.Extensions, instance, AdministrationStrings.Extensions);
}
void FillServiceInfo(ServiceInfo info, IWmiInstance instance)
{
Fx.Assert(null != instance, "");
Fx.Assert(null != info, "");
ProviderBase.FillCollectionInfo(info.Service.BaseAddresses, instance, AdministrationStrings.BaseAddresses);
instance.SetProperty(AdministrationStrings.CounterInstanceName, PerformanceCounters.PerformanceCountersEnabled ? ServicePerformanceCounters.CreateFriendlyInstanceName(info.Service) : String.Empty);
instance.SetProperty(AdministrationStrings.ConfigurationName, info.ConfigurationName);
instance.SetProperty(AdministrationStrings.DistinguishedName, info.DistinguishedName);
instance.SetProperty(AdministrationStrings.Name, info.Name);
instance.SetProperty(AdministrationStrings.Namespace, info.Namespace);
instance.SetProperty(AdministrationStrings.Metadata, info.Metadata);
instance.SetProperty(AdministrationStrings.Opened, ManagementExtension.GetTimeOpened(info.Service));
FillBehaviorsInfo(info, instance);
FillExtensionsInfo(info, instance);
FillChannelsInfo(info, instance);
}
void FillBehaviorInfo(IServiceBehavior behavior, IWmiInstance existingInstance, out IWmiInstance instance)
{
Fx.Assert(null != existingInstance, "");
Fx.Assert(null != behavior, "");
instance = null;
if (behavior is AspNetCompatibilityRequirementsAttribute)
{
instance = existingInstance.NewInstance("AspNetCompatibilityRequirementsAttribute");
AspNetCompatibilityRequirementsAttribute specificBehavior = (AspNetCompatibilityRequirementsAttribute)behavior;
instance.SetProperty(AdministrationStrings.RequirementsMode, specificBehavior.RequirementsMode.ToString());
}
else if (behavior is ServiceCredentials)
{
instance = existingInstance.NewInstance("ServiceCredentials");
ServiceCredentials specificBehavior = (ServiceCredentials)behavior;
if (specificBehavior.ClientCertificate != null && specificBehavior.ClientCertificate.Certificate != null)
{
string result = string.Empty;
result += String.Format(CultureInfo.InvariantCulture, "Certificate: {0}\n", specificBehavior.ClientCertificate.Certificate);
instance.SetProperty(AdministrationStrings.ClientCertificate, result);
}
if (specificBehavior.IssuedTokenAuthentication != null && specificBehavior.IssuedTokenAuthentication.KnownCertificates != null)
{
string result = string.Empty;
result += String.Format(CultureInfo.InvariantCulture, "AllowUntrustedRsaIssuers: {0}\n", specificBehavior.IssuedTokenAuthentication.AllowUntrustedRsaIssuers);
result += String.Format(CultureInfo.InvariantCulture, "CertificateValidationMode: {0}\n", specificBehavior.IssuedTokenAuthentication.CertificateValidationMode);
result += String.Format(CultureInfo.InvariantCulture, "RevocationMode: {0}\n", specificBehavior.IssuedTokenAuthentication.RevocationMode);
result += String.Format(CultureInfo.InvariantCulture, "TrustedStoreLocation: {0}\n", specificBehavior.IssuedTokenAuthentication.TrustedStoreLocation);
foreach (X509Certificate2 certificate in specificBehavior.IssuedTokenAuthentication.KnownCertificates)
{
if (certificate != null)
{
result += String.Format(CultureInfo.InvariantCulture, "Known certificate: {0}\n", certificate.FriendlyName);
}
}
result += String.Format(CultureInfo.InvariantCulture, "AudienceUriMode: {0}\n", specificBehavior.IssuedTokenAuthentication.AudienceUriMode);
if (specificBehavior.IssuedTokenAuthentication.AllowedAudienceUris != null)
{
foreach (string str in specificBehavior.IssuedTokenAuthentication.AllowedAudienceUris)
{
if (str != null)
{
result += String.Format(CultureInfo.InvariantCulture, "Allowed Uri: {0}\n", str);
}
}
}
instance.SetProperty(AdministrationStrings.IssuedTokenAuthentication, result);
}
if (specificBehavior.Peer != null && specificBehavior.Peer.Certificate != null)
{
string result = string.Empty;
result += String.Format(CultureInfo.InvariantCulture, "Certificate: {0}\n", specificBehavior.Peer.Certificate.ToString(true));
instance.SetProperty(AdministrationStrings.Peer, result);
}
if (specificBehavior.SecureConversationAuthentication != null && specificBehavior.SecureConversationAuthentication.SecurityContextClaimTypes != null)
{
string result = string.Empty;
foreach (Type claimType in specificBehavior.SecureConversationAuthentication.SecurityContextClaimTypes)
{
if (claimType != null)
{
result += String.Format(CultureInfo.InvariantCulture, "ClaimType: {0}\n", claimType);
}
}
instance.SetProperty(AdministrationStrings.SecureConversationAuthentication, result);
}
if (specificBehavior.ServiceCertificate != null && specificBehavior.ServiceCertificate.Certificate != null)
{
instance.SetProperty(AdministrationStrings.ServiceCertificate, specificBehavior.ServiceCertificate.Certificate.ToString());
}
if (specificBehavior.UserNameAuthentication != null)
{
instance.SetProperty(AdministrationStrings.UserNameAuthentication, String.Format(CultureInfo.InvariantCulture, "{0}: {1}", AdministrationStrings.ValidationMode, specificBehavior.UserNameAuthentication.UserNamePasswordValidationMode.ToString()));
}
if (specificBehavior.WindowsAuthentication != null)
{
instance.SetProperty(AdministrationStrings.WindowsAuthentication, String.Format(CultureInfo.InvariantCulture, "{0}: {1}", AdministrationStrings.AllowAnonymous, specificBehavior.WindowsAuthentication.AllowAnonymousLogons.ToString()));
}
}
else if (behavior is ServiceAuthorizationBehavior)
{
instance = existingInstance.NewInstance("ServiceAuthorizationBehavior");
ServiceAuthorizationBehavior specificBehavior = (ServiceAuthorizationBehavior)behavior;
instance.SetProperty(AdministrationStrings.ImpersonateCallerForAllOperations, specificBehavior.ImpersonateCallerForAllOperations);
instance.SetProperty(AdministrationStrings.ImpersonateOnSerializingReply, specificBehavior.ImpersonateOnSerializingReply);
if (specificBehavior.RoleProvider != null)
{
instance.SetProperty(AdministrationStrings.RoleProvider, specificBehavior.RoleProvider.ToString());
}
if (specificBehavior.ServiceAuthorizationManager != null)
{
instance.SetProperty(AdministrationStrings.ServiceAuthorizationManager, specificBehavior.ServiceAuthorizationManager.ToString());
}
instance.SetProperty(AdministrationStrings.PrincipalPermissionMode, specificBehavior.PrincipalPermissionMode.ToString());
}
else if (behavior is ServiceSecurityAuditBehavior)
{
instance = existingInstance.NewInstance("ServiceSecurityAuditBehavior");
ServiceSecurityAuditBehavior specificBehavior = (ServiceSecurityAuditBehavior)behavior;
instance.SetProperty(AdministrationStrings.AuditLogLocation, specificBehavior.AuditLogLocation.ToString());
instance.SetProperty(AdministrationStrings.SuppressAuditFailure, specificBehavior.SuppressAuditFailure);
instance.SetProperty(AdministrationStrings.ServiceAuthorizationAuditLevel, specificBehavior.ServiceAuthorizationAuditLevel.ToString());
instance.SetProperty(AdministrationStrings.MessageAuthenticationAuditLevel, specificBehavior.MessageAuthenticationAuditLevel.ToString());
}
else if (behavior is ServiceBehaviorAttribute)
{
instance = existingInstance.NewInstance("ServiceBehaviorAttribute");
ServiceBehaviorAttribute serviceBehavior = (ServiceBehaviorAttribute)behavior;
instance.SetProperty(AdministrationStrings.AddressFilterMode, serviceBehavior.AddressFilterMode.ToString());
instance.SetProperty(AdministrationStrings.AutomaticSessionShutdown, serviceBehavior.AutomaticSessionShutdown);
instance.SetProperty(AdministrationStrings.ConcurrencyMode, serviceBehavior.ConcurrencyMode.ToString());
instance.SetProperty(AdministrationStrings.ConfigurationName, serviceBehavior.ConfigurationName);
instance.SetProperty(AdministrationStrings.EnsureOrderedDispatch, serviceBehavior.EnsureOrderedDispatch);
instance.SetProperty(AdministrationStrings.IgnoreExtensionDataObject, serviceBehavior.IgnoreExtensionDataObject);
instance.SetProperty(AdministrationStrings.IncludeExceptionDetailInFaults, serviceBehavior.IncludeExceptionDetailInFaults);
instance.SetProperty(AdministrationStrings.InstanceContextMode, serviceBehavior.InstanceContextMode.ToString());
instance.SetProperty(AdministrationStrings.MaxItemsInObjectGraph, serviceBehavior.MaxItemsInObjectGraph);
instance.SetProperty(AdministrationStrings.Name, serviceBehavior.Name);
instance.SetProperty(AdministrationStrings.Namespace, serviceBehavior.Namespace);
instance.SetProperty(AdministrationStrings.ReleaseServiceInstanceOnTransactionComplete, serviceBehavior.ReleaseServiceInstanceOnTransactionComplete);
instance.SetProperty(AdministrationStrings.TransactionAutoCompleteOnSessionClose, serviceBehavior.TransactionAutoCompleteOnSessionClose);
instance.SetProperty(AdministrationStrings.TransactionIsolationLevel, serviceBehavior.TransactionIsolationLevel.ToString());
if (serviceBehavior.TransactionTimeoutSet)
{
instance.SetProperty(AdministrationStrings.TransactionTimeout, serviceBehavior.TransactionTimeoutTimespan);
}
instance.SetProperty(AdministrationStrings.UseSynchronizationContext, serviceBehavior.UseSynchronizationContext);
instance.SetProperty(AdministrationStrings.ValidateMustUnderstand, serviceBehavior.ValidateMustUnderstand);
}
else if (behavior is ServiceDebugBehavior)
{
instance = existingInstance.NewInstance("ServiceDebugBehavior");
ServiceDebugBehavior specificBehavior = (ServiceDebugBehavior)behavior;
if (null != specificBehavior.HttpHelpPageUrl)
{
instance.SetProperty(AdministrationStrings.HttpHelpPageUrl, specificBehavior.HttpHelpPageUrl.ToString());
}
instance.SetProperty(AdministrationStrings.HttpHelpPageEnabled, specificBehavior.HttpHelpPageEnabled);
if (null != specificBehavior.HttpsHelpPageUrl)
{
instance.SetProperty(AdministrationStrings.HttpsHelpPageUrl, specificBehavior.HttpsHelpPageUrl.ToString());
}
instance.SetProperty(AdministrationStrings.HttpsHelpPageEnabled, specificBehavior.HttpsHelpPageEnabled);
instance.SetProperty(AdministrationStrings.IncludeExceptionDetailInFaults, specificBehavior.IncludeExceptionDetailInFaults);
}
else if (behavior is ServiceMetadataBehavior)
{
instance = existingInstance.NewInstance("ServiceMetadataBehavior");
ServiceMetadataBehavior metadataBehavior = (ServiceMetadataBehavior)behavior;
if (null != metadataBehavior.ExternalMetadataLocation)
{
instance.SetProperty(AdministrationStrings.ExternalMetadataLocation, metadataBehavior.ExternalMetadataLocation.ToString());
}
instance.SetProperty(AdministrationStrings.HttpGetEnabled, metadataBehavior.HttpGetEnabled);
if (null != metadataBehavior.HttpGetUrl)
{
instance.SetProperty(AdministrationStrings.HttpGetUrl, metadataBehavior.HttpGetUrl.ToString());
}
instance.SetProperty(AdministrationStrings.HttpsGetEnabled, metadataBehavior.HttpsGetEnabled);
if (null != metadataBehavior.HttpsGetUrl)
{
instance.SetProperty(AdministrationStrings.HttpsGetUrl, metadataBehavior.HttpsGetUrl.ToString());
}
FillMetadataExporterInfo(instance, metadataBehavior.MetadataExporter);
}
else if (behavior is ServiceThrottlingBehavior)
{
instance = existingInstance.NewInstance("ServiceThrottlingBehavior");
ServiceThrottlingBehavior throttlingBehavior = (ServiceThrottlingBehavior)behavior;
instance.SetProperty(AdministrationStrings.MaxConcurrentCalls, throttlingBehavior.MaxConcurrentCalls);
instance.SetProperty(AdministrationStrings.MaxConcurrentSessions, throttlingBehavior.MaxConcurrentSessions);
instance.SetProperty(AdministrationStrings.MaxConcurrentInstances, throttlingBehavior.MaxConcurrentInstances);
}
else if (behavior is ServiceTimeoutsBehavior)
{
instance = existingInstance.NewInstance("ServiceTimeoutsBehavior");
ServiceTimeoutsBehavior specificBehavior = (ServiceTimeoutsBehavior)behavior;
instance.SetProperty(AdministrationStrings.TransactionTimeout, specificBehavior.TransactionTimeout);
}
else if (behavior is IWmiInstanceProvider)
{
IWmiInstanceProvider instanceProvider = (IWmiInstanceProvider)behavior;
instance = existingInstance.NewInstance(instanceProvider.GetInstanceType());
instanceProvider.FillInstance(instance);
}
else
{
instance = existingInstance.NewInstance("Behavior");
}
if (null != instance)
{
instance.SetProperty(AdministrationStrings.Type, behavior.GetType().FullName);
}
}
void FillMetadataExporterInfo(IWmiInstance instance, MetadataExporter exporter)
{
DiagnosticUtility.EventLog.LogEvent(TraceEventType.Information, (ushort)System.Runtime.Diagnostics.EventLogCategory.Wmi, (uint)System.Runtime.Diagnostics.EventLogEventId.MessageLoggingOn, true, "metadata exporter called");
Fx.Assert(null != instance, "");
Fx.Assert(null != exporter, "");
IWmiInstance metadataExporterInstance = instance.NewInstance(AdministrationStrings.MetadataExporter);
metadataExporterInstance.SetProperty(AdministrationStrings.PolicyVersion, exporter.PolicyVersion.ToString());
instance.SetProperty(AdministrationStrings.MetadataExportInfo, metadataExporterInstance);
}
void FillChannelInfo(IChannel channel, IWmiInstance instance)
{
Fx.Assert(null != instance, "");
Fx.Assert(null != channel, "");
instance.SetProperty(AdministrationStrings.Type, channel.GetType().ToString());
ServiceChannel serviceChannel = ServiceChannelFactory.GetServiceChannel(channel);
if (null != serviceChannel)
{
string uri = serviceChannel.RemoteAddress == null ? String.Empty : serviceChannel.RemoteAddress.ToString();
instance.SetProperty(AdministrationStrings.RemoteAddress, uri);
string contractName = null != serviceChannel.ClientRuntime ? serviceChannel.ClientRuntime.ContractName : String.Empty;
string remoteEndpoint = EndpointInstanceProvider.EndpointReference(uri, contractName, false);
instance.SetProperty(AdministrationStrings.RemoteEndpoint, remoteEndpoint);
instance.SetProperty(AdministrationStrings.LocalAddress, serviceChannel.LocalAddress == null ? String.Empty : serviceChannel.LocalAddress.ToString());
instance.SetProperty(AdministrationStrings.SessionId, ((IContextChannel)serviceChannel).SessionId);
}
}
}
}
| |
// Copyright (c) DotSpatial Team. All rights reserved.
// Licensed under the MIT license. See License.txt file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.Composition;
using System.IO;
using System.Linq;
using System.Text;
namespace DotSpatial.Data
{
/// <summary>
/// This can be used as a component to work as a DataManager. This also provides the very important DefaultDataManager property,
/// which is where the developer controls what DataManager should be used for their project.
/// </summary>
public class DataManager : IDataManager
{
#region Private Variables
// If this doesn't exist, a new one is created when you "get" this data manager.
private static IDataManager defaultDataManager;
private IEnumerable<IDataProvider> _dataProviders;
private string _dialogReadFilter;
private string _dialogWriteFilter;
private string _imageReadFilter;
private string _imageWriteFilter;
private string _rasterReadFilter;
private string _rasterWriteFilter;
private string _vectorReadFilter;
private string _vectorWriteFilter;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="DataManager"/> class.
/// A data manager is more or less just a list of data providers to use. The very important
/// DataManager.DefaultDataManager property controls which DataManager will be used
/// to load data. By default, each DataManager sets itself as the default in its constructor.
/// </summary>
public DataManager()
{
Configure();
}
#endregion
#region Events
/// <summary>
/// Occurs after the directory providers have been loaded into the project.
/// </summary>
public event EventHandler<DataProviderEventArgs> DirectoryProvidersLoaded;
#endregion
#region Properties
/// <summary>
/// Gets or sets the implementation of IDataManager for the project to use when accessing data.
/// This is THE place where the DataManager can be replaced by a different data manager.
/// If you add this data manager to your project, this will automatically set itself as the DefaultDataManager.
/// However, since each DM will do this, you may have to control this manually
/// if you add more than one DataManager to the project in order to set the one that will be chosen.
/// </summary>
public static IDataManager DefaultDataManager
{
get
{
return defaultDataManager ?? (defaultDataManager = new DataManager());
}
set
{
defaultDataManager = value;
}
}
/// <summary>
/// Gets or sets the list of IDataProviders that should be used in the project.
/// </summary>
[Browsable(false)]
[ImportMany(AllowRecomposition = true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public virtual IEnumerable<IDataProvider> DataProviders
{
get
{
return _dataProviders;
}
set
{
_dataProviders = value;
_imageReadFilter = null;
_imageWriteFilter = null;
_rasterReadFilter = null;
_rasterWriteFilter = null;
_vectorReadFilter = null;
_vectorWriteFilter = null;
OnProvidersLoaded(value);
}
}
/// <summary>
/// Gets or sets the dialog read filter to use for opening data files.
/// </summary>
[Category("Filters")]
[Description("Gets or sets the string that should be used when using this data manager is used to open files.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public virtual string DialogReadFilter
{
get
{
// The developer can bypass the default behavior simply by caching something here.
if (_dialogReadFilter != null) return _dialogReadFilter;
var rasterExtensions = new List<string>();
var vectorExtensions = new List<string>();
var imageExtensions = new List<string>();
var extensions = PreferredProviders.Select(item => item.Key).ToList();
foreach (IDataProvider dp in DataProviders)
{
string[] formats = dp.DialogReadFilter.Split('|');
// We don't care about the description strings, just the extensions.
for (int i = 1; i < formats.Length; i += 2)
{
// Multiple extension types are separated by semicolons
string[] potentialExtensions = formats[i].Split(';');
foreach (string potentialExtension in potentialExtensions)
{
if (extensions.Contains(potentialExtension) == false)
{
extensions.Add(potentialExtension);
if (dp is IRasterProvider) rasterExtensions.Add(potentialExtension);
if (dp is IVectorProvider && potentialExtension != "*.shx"
&& potentialExtension != "*.dbf") vectorExtensions.Add(potentialExtension);
if (dp is IImageDataProvider) imageExtensions.Add(potentialExtension);
}
}
}
}
// We now have a list of all the file extensions supported
extensions.Remove("*.dbf");
extensions.Remove("*.shx");
var result = new StringBuilder("All Supported Formats|" + string.Join(";", extensions.ToArray()));
if (vectorExtensions.Count > 0) result.Append("|Vectors|" + string.Join(";", vectorExtensions.ToArray()));
if (rasterExtensions.Count > 0) result.Append("|Rasters|" + string.Join(";", rasterExtensions.ToArray()));
if (imageExtensions.Count > 0) result.Append("|Images|" + string.Join(";", imageExtensions.ToArray()));
foreach (KeyValuePair<string, IDataProvider> item in PreferredProviders)
{
// we don't have to check for uniqueness here because it is enforced by the HashTable
result.AppendFormat("|{1} - [{0}]| {0}", item.Key, item.Value.Name);
}
// Now add each of the individual lines, prepended with the provider name
foreach (IDataProvider dp in DataProviders)
{
string[] formats = dp.DialogReadFilter.Split('|');
string potentialFormat = null;
for (int i = 0; i < formats.Length; i++)
{
if (i % 2 == 0)
{
// For descriptions, prepend the name:
potentialFormat = "|" + dp.Name + " - " + formats[i];
}
else
{
// don't add this format if it was already added by a "preferred data provider"
if (PreferredProviders.ContainsKey(formats[i]) == false)
{
string res = formats[i].Replace(";*.shx", string.Empty).Replace("*.shx", string.Empty);
res = res.Replace(";*.dbf", string.Empty).Replace("*.dbf", string.Empty);
if (formats[i] != "*.shx" && formats[i] != "*.shp")
{
result.Append(potentialFormat);
result.Append("|" + res);
}
}
}
}
}
result.Append("|All Files (*.*) |*.*");
return result.ToString();
}
set
{
_dialogReadFilter = value;
}
}
/// <summary>
/// Gets or sets the dialog write filter to use for saving data files.
/// </summary>
[Category("Filters")]
[Description("Gets or sets the string that should be used when this data manager is used to save files.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public virtual string DialogWriteFilter
{
get
{
// Setting this to something overrides the default
if (_dialogWriteFilter != null)
return _dialogWriteFilter;
var rasterExtensions = new List<string>();
var vectorExtensions = new List<string>();
var imageExtensions = new List<string>();
var extensions = PreferredProviders.Select(item => item.Key).ToList();
foreach (IDataProvider dp in DataProviders)
{
string[] formats = dp.DialogWriteFilter.Split('|');
// We don't care about the description strings, just the extensions.
for (int i = 1; i < formats.Length; i += 2)
{
// Multiple extension types are separated by semicolons
string[] potentialExtensions = formats[i].Split(';');
foreach (string potentialExtension in potentialExtensions)
{
if (extensions.Contains(potentialExtension) == false)
{
extensions.Add(potentialExtension);
if (dp is IRasterProvider)
rasterExtensions.Add(potentialExtension);
if (dp is IVectorProvider)
vectorExtensions.Add(potentialExtension);
if (dp is IImageDataProvider)
imageExtensions.Add(potentialExtension);
}
}
}
}
// We now have a list of all the file extensions supported
var result = new StringBuilder("All Supported Formats|" + string.Join(";", extensions.ToArray()));
if (vectorExtensions.Count > 0)
result.Append("|Vectors|" + string.Join(";", vectorExtensions.ToArray()));
if (rasterExtensions.Count > 0)
result.Append("|Rasters|" + string.Join(";", rasterExtensions.ToArray()));
if (imageExtensions.Count > 0)
result.Append("|Images|" + string.Join(";", imageExtensions.ToArray()));
foreach (KeyValuePair<string, IDataProvider> item in PreferredProviders)
{
// we don't have to check for uniqueness here because it is enforced by the HashTable
result.AppendFormat("| [{0}] - {1}| {0}", item.Key, item.Value.Name);
}
// Now add each of the individual lines, prepended with the provider name
foreach (IDataProvider dp in DataProviders)
{
string[] formats = dp.DialogWriteFilter.Split('|');
string potentialFormat = null;
for (int i = 0; i < formats.Length; i++)
{
if (i % 2 == 0)
{
// For descriptions, prepend the name:
potentialFormat = "|" + dp.Name + " - " + formats[i];
}
else
{
if (PreferredProviders.ContainsKey(formats[i]) == false)
{
result.Append(potentialFormat);
result.Append("|" + formats[i]);
}
}
}
}
result.Append("|All Files (*.*) |*.*");
return result.ToString();
}
set
{
_dialogWriteFilter = value;
}
}
/// <summary>
/// Gets or sets the dialog read filter to use for opening data files that are specifically raster formats.
/// </summary>
[Category("Filters")]
[Description("Gets or sets the string that should be used when using this data manager is used to open rasters.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public virtual string RasterReadFilter
{
get
{
// The developer can bypass the default behavior simply by caching something here.
if (_rasterReadFilter != null)
return _rasterReadFilter;
return GetReadFilter<IRasterProvider>("Rasters");
}
set
{
_rasterReadFilter = value;
}
}
/// <summary>
/// Gets or sets the dialog write filter to use for saving data files.
/// </summary>
[Category("Filters")]
[Description("Gets or sets the string that should be used when this data manager is used to save rasters.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public virtual string RasterWriteFilter
{
get
{
// Setting this to something overrides the default
if (_rasterWriteFilter != null)
return _rasterWriteFilter;
return GetWriteFilter<IRasterProvider>("Rasters");
}
set
{
_rasterWriteFilter = value;
}
}
/// <summary>
/// Gets or sets the dialog read filter to use for opening data files.
/// </summary>
[Category("Filters")]
[Description("Gets or sets the string that should be used when using this data manager is used to open vectors.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public virtual string VectorReadFilter
{
get
{
// The developer can bypass the default behavior simply by caching something here.
if (_vectorReadFilter != null)
return _vectorReadFilter;
return GetReadFilter<IVectorProvider>("Vectors");
}
set
{
_vectorReadFilter = value;
}
}
/// <summary>
/// Gets or sets the dialog write filter to use for saving data files.
/// </summary>
[Category("Filters")]
[Description("Gets or sets the string that should be used when this data manager is used to save vectors.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public virtual string VectorWriteFilter
{
get
{
// Setting this to something overrides the default
if (_vectorWriteFilter != null)
return _vectorWriteFilter;
return GetWriteFilter<IVectorProvider>("Vectors");
}
set
{
_vectorWriteFilter = value;
}
}
/// <summary>
/// Gets or sets the dialog read filter to use for opening data files.
/// </summary>
[Category("Filters")]
[Description("Gets or sets the string that should be used when using this data manager is used to open images.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public virtual string ImageReadFilter
{
get
{
// The developer can bypass the default behavior simply by caching something here.
if (_imageReadFilter != null)
return _imageReadFilter;
return GetReadFilter<IImageDataProvider>("Images");
}
set
{
_imageReadFilter = value;
}
}
/// <summary>
/// Gets or sets the dialog write filter to use for saving data files.
/// </summary>
[Category("Filters")]
[Description("Gets or sets the string that should be used when this data manager is used to save images.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public virtual string ImageWriteFilter
{
get
{
// Setting this to something overrides the default
if (_imageWriteFilter != null)
return _imageWriteFilter;
return GetWriteFilter<IImageDataProvider>("Images");
}
set
{
_imageWriteFilter = value;
}
}
/// <summary>
/// Gets or sets a value indicating whether the this data manager should try to load layers by default.
/// This will be overridden if the inRam property is specified as a parameter.
/// </summary>
[Category("Behavior")]
[Description("Gets or sets the default condition for subsequent load operations which may be overridden by specifying inRam in the parameters.")]
public bool LoadInRam { get; set; } = true;
/// <summary>
/// Gets or sets a dictionary of IDataProviders with corresponding extensions. The standard order is to try to load
/// the data using a PreferredProvider. If that fails, then it will check the list of dataProviders, and finally,
/// if that fails, it will check the plugin Data Providers in directories.
/// </summary>
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public virtual Dictionary<string, IDataProvider> PreferredProviders { get; set; }
/// <summary>
/// Gets or sets a progress handler for any open operations that are intiated by this
/// DataManager and don't override this value with an IProgressHandler specified in the parameters.
/// </summary>
[Category("Handlers")]
[Description("Gets or sets the object that implements the IProgressHandler interface for recieving status messages.")]
public virtual IProgressHandler ProgressHandler { get; set; }
#endregion
#region Methods
/// <summary>
/// Creates a new class of vector that matches the given fileName.
/// </summary>
/// <param name="fileName">The string fileName from which to create a vector.</param>
/// <param name="featureType">Specifies the type of feature for this vector file</param>
/// <returns>An IFeatureSet that allows working with the dataset.</returns>
public IFeatureSet CreateVector(string fileName, FeatureType featureType)
{
return CreateVector(fileName, featureType, ProgressHandler);
}
/// <summary>
/// Creates a new class of vector that matches the given fileName.
/// </summary>
/// <param name="fileName">The string fileName from which to create a vector.</param>
/// <param name="featureType">Specifies the type of feature for this vector file</param>
/// <param name="progHandler">Overrides the default progress handler with the specified progress handler</param>
/// <returns>An IFeatureSet that allows working with the dataset.</returns>
/// <exception cref="ArgumentNullException">Raised when fileName is null.</exception>
/// <exception cref="IOException">Raised when suitable DataProvider not found.</exception>
public IFeatureSet CreateVector(string fileName, FeatureType featureType, IProgressHandler progHandler)
{
if (fileName == null) throw new ArgumentNullException(nameof(fileName), DataStrings.FileNameShouldNotBeNull);
// To Do: Add Customization that allows users to specify which plugins to use in priority order.
// First check for the extension in the preferred plugins list
var ext = Path.GetExtension(fileName);
IDataProvider pdp;
if (PreferredProviders.TryGetValue(ext, out pdp))
{
var vp = pdp as IVectorProvider;
var result = vp?.CreateNew(fileName, featureType, true, progHandler);
if (result != null) return result;
// if we get here, we found the provider, but it did not succeed in opening the file.
}
// Then check the general list of developer specified providers... but not the directory providers
foreach (var dp in DataProviders.OfType<IVectorProvider>())
{
if (GetSupportedExtensions(dp.DialogReadFilter).Contains(ext))
{
// attempt to open with the fileName.
var result = dp.CreateNew(fileName, featureType, true, progHandler);
if (result != null)
return result;
}
}
throw new IOException(DataStrings.FileTypeNotSupported);
}
/// <summary>
/// Checks a dialog filter and returns a list of just the extensions.
/// </summary>
/// <param name="dialogFilter">The Dialog Filter to read extensions from</param>
/// <returns>A list of extensions</returns>
public virtual List<string> GetSupportedExtensions(string dialogFilter)
{
List<string> extensions = new List<string>();
string[] formats = dialogFilter.Split('|');
char[] wild = { '*' };
// We don't care about the description strings, just the extensions.
for (int i = 1; i < formats.Length; i += 2)
{
// Multiple extension types are separated by semicolons
string[] potentialExtensions = formats[i].Split(';');
foreach (string potentialExtension in potentialExtensions)
{
string ext = potentialExtension.TrimStart(wild);
if (extensions.Contains(ext) == false) extensions.Add(ext);
}
}
return extensions;
}
/// <summary>
/// This can help determine what kind of file format a file is, without actually opening the file.
/// </summary>
/// <param name="fileName">Path of the file that the file type should be determined for.</param>
/// <returns>The file format that was detected.</returns>
public virtual DataFormat GetFileFormat(string fileName)
{
string ext = Path.GetExtension(fileName);
foreach (IDataProvider dp in DataProviders)
{
if (GetSupportedExtensions(dp.DialogReadFilter).Contains(ext))
{
IVectorProvider vp = dp as IVectorProvider;
if (vp != null)
return DataFormat.Vector;
IRasterProvider rp = dp as IRasterProvider;
if (rp != null)
return DataFormat.Raster;
IImageDataProvider ip = dp as IImageDataProvider;
if (ip != null)
return DataFormat.Image;
return DataFormat.Custom;
}
}
return DataFormat.Custom;
}
/// <summary>
/// Instead of opening the specified file, this simply determines the correct provider,
/// and requests that the provider check the feature type for vector formats.
/// </summary>
/// <param name="fileName">Path of the file that the feature type should be determined for.</param>
/// <returns>The feature type that was detected.</returns>
public virtual FeatureType GetFeatureType(string fileName)
{
string ext = Path.GetExtension(fileName);
if (GetFileFormat(fileName) != DataFormat.Vector)
return FeatureType.Unspecified;
foreach (IDataProvider dp in DataProviders)
{
if (GetSupportedExtensions(dp.DialogReadFilter).Contains(ext))
{
IVectorProvider vp = dp as IVectorProvider;
if (vp == null)
continue;
return vp.GetFeatureType(fileName);
}
}
return FeatureType.Unspecified;
}
/// <summary>
/// Opens the specified fileName, returning an IRaster. This will return null if a manager
/// either returns the wrong data format.
/// </summary>
/// <param name="fileName">The string fileName to open</param>
/// <returns>An IRaster loaded from the specified file.</returns>
public virtual IRaster OpenRaster(string fileName)
{
return OpenFileAsIRaster(fileName, true, ProgressHandler);
}
/// <summary>
/// Opens the specified fileName, returning an IRaster. This will return null if a manager
/// either returns the wrong data format.
/// </summary>
/// <param name="fileName">The string fileName to open</param>
/// <param name="inRam">boolean, true if this should be loaded into ram</param>
/// <param name="prog">a progress interface</param>
/// <returns>An IRaster loaded from the specified file</returns>
public virtual IRaster OpenRaster(string fileName, bool inRam, IProgressHandler prog)
{
return OpenFileAsIRaster(fileName, inRam, prog);
}
/// <summary>
/// Opens a specified file as an IFeatureSet
/// </summary>
/// <param name="fileName">The string fileName to open</param>
/// <param name="inRam">boolean, true if this should be loaded into ram</param>
/// <param name="prog">a progress interface</param>
/// <returns>An IFeatureSet loaded from the specified file</returns>
public virtual IFeatureSet OpenVector(string fileName, bool inRam, IProgressHandler prog)
{
return OpenFile(fileName, inRam, prog) as IFeatureSet;
}
/// <summary>
/// Opens the file as an Image and returns an IImageData object for interacting with the file.
/// </summary>
/// <param name="fileName">The string fileName</param>
/// <returns>An IImageData object</returns>
public virtual IImageData OpenImage(string fileName)
{
return OpenFile(fileName, LoadInRam, ProgressHandler) as IImageData;
}
/// <summary>
/// Opens the file as an Image and returns an IImageData object
/// </summary>
/// <param name="fileName">The string fileName to open</param>
/// <param name="progressHandler">The progressHandler to receive progress updates</param>
/// <returns>An IImageData</returns>
public virtual IImageData OpenImage(string fileName, IProgressHandler progressHandler)
{
return OpenFile(fileName, LoadInRam, progressHandler) as IImageData;
}
/// <summary>
/// Attempts to call the open fileName method for any IDataProvider plugin
/// that matches the extension on the string.
/// </summary>
/// <param name="fileName">A String fileName to attempt to open.</param>
/// <returns>The opened IDataSet.</returns>
public virtual IDataSet OpenFile(string fileName)
{
return OpenFile(fileName, LoadInRam, ProgressHandler);
}
/// <summary>
/// Attempts to call the open fileName method for any IDataProvider plugin that matches the extension on the string.
/// </summary>
/// <param name="fileName">A String fileName to attempt to open.</param>
/// <param name="inRam">A boolean value that if true will attempt to force a load of the data into memory. This value overrides the property on this DataManager.</param>
/// <returns>The opened IDataSet.</returns>
public virtual IDataSet OpenFile(string fileName, bool inRam)
{
return OpenFile(fileName, inRam, ProgressHandler);
}
/// <summary>
/// Attempts to call the open fileName method for any IDataProvider plugin that matches the extension on the string.
/// </summary>
/// <param name="fileName">A String fileName to attempt to open.</param>
/// <param name="inRam">A boolean value that if true will attempt to force a load of the data into memory. This value overrides the property on this DataManager.</param>
/// <param name="progressHandler">Specifies the progressHandler to receive progress messages. This value overrides the property on this DataManager.</param>
/// <param name="providerName">Name of the provider that should be used for opening. If it is not set or the provider can't open the file, DS takes the first provider that can open the file.</param>
/// <returns>The opened IDataSet.</returns>
public virtual IDataSet OpenFile(string fileName, bool inRam, IProgressHandler progressHandler, string providerName = "")
{
string ext = Path.GetExtension(fileName)?.ToLower();
if (ext != null)
{
IDataSet result;
if (providerName != string.Empty)
{
// if a provider name was given we try to find this provider and use it to open the file
var provider = PreferredProviders.FirstOrDefault(kvp => kvp.Value.Name == providerName);
if (provider.Value != null)
{
if (GetSupportedExtensions(provider.Value.DialogReadFilter).Contains(ext))
{
result = provider.Value.Open(fileName);
if (result != null)
return result;
}
}
var dp = DataProviders.FirstOrDefault(kvp => kvp.Name == providerName);
if (dp != null)
{
if (GetSupportedExtensions(dp.DialogReadFilter).Contains(ext))
{
result = dp.Open(fileName);
if (result != null)
return result;
}
}
}
// Check for the extension in the preferred plugins list
if (PreferredProviders.ContainsKey(ext))
{
result = PreferredProviders[ext].Open(fileName);
if (result != null) return result;
// if we get here, we found the provider, but it did not succeed in opening the file.
}
// Check the general list of developer specified providers... but not the directory providers
foreach (IDataProvider dp in DataProviders)
{
if (!GetSupportedExtensions(dp.DialogReadFilter).Contains(ext)) continue;
// attempt to open with the fileName.
dp.ProgressHandler = ProgressHandler;
result = dp.Open(fileName);
if (result != null) return result;
}
}
throw new ApplicationException(DataStrings.FileTypeNotSupported);
}
/// <summary>
/// Creates a new image using an appropriate data provider
/// </summary>
/// <param name="fileName">The string fileName to open an image for</param>
/// <param name="width">The integer width in pixels</param>
/// <param name="height">The integer height in pixels</param>
/// <param name="bandType">The band color type</param>
/// <returns>An IImageData interface allowing access to image data</returns>
public virtual IImageData CreateImage(string fileName, int width, int height, ImageBandType bandType)
{
return CreateImage(fileName, width, height, LoadInRam, ProgressHandler, bandType);
}
/// <summary>
/// Creates a new image using an appropriate data provider
/// </summary>
/// <param name="fileName">The string fileName to open an image for</param>
/// <param name="width">The integer width in pixels</param>
/// <param name="height">The integer height in pixels</param>
/// <param name="inRam">Boolean, true if the entire file should be created in memory</param>
/// <param name="bandType">The band color type</param>
/// <returns>An IImageData interface allowing access to image data</returns>
public virtual IImageData CreateImage(string fileName, int width, int height, bool inRam, ImageBandType bandType)
{
return CreateImage(fileName, width, height, inRam, ProgressHandler, bandType);
}
/// <summary>
/// Creates a new image using an appropriate data provider
/// </summary>
/// <param name="fileName">The string fileName to open an image for</param>
/// <param name="width">The integer width in pixels</param>
/// <param name="height">The integer height in pixels</param>
/// <param name="inRam">Boolean, true if the entire file should be created in memory</param>
/// <param name="progHandler">A Progress handler</param>
/// <param name="bandType">The band color type</param>
/// <returns>An IImageData interface allowing access to image data</returns>
public virtual IImageData CreateImage(string fileName, int width, int height, bool inRam, IProgressHandler progHandler, ImageBandType bandType)
{
// First check for the extension in the preferred plugins list
string ext = Path.GetExtension(fileName)?.ToLower();
if (ext != null)
{
IImageData result;
if (PreferredProviders.ContainsKey(ext))
{
IImageDataProvider rp = PreferredProviders[ext] as IImageDataProvider;
if (rp != null)
{
result = rp.Create(fileName, width, height, inRam, progHandler, bandType);
if (result != null)
return result;
}
// if we get here, we found the provider, but it did not succeed in opening the file.
}
// Then check the general list of developer specified providers... but not the directory providers
foreach (IDataProvider dp in DataProviders)
{
if (GetSupportedExtensions(dp.DialogWriteFilter).Contains(ext))
{
IImageDataProvider rp = dp as IImageDataProvider;
if (rp != null)
{
// attempt to open with the fileName.
result = rp.Create(fileName, width, height, inRam, progHandler, bandType);
if (result != null)
return result;
}
}
}
}
throw new ApplicationException(DataStrings.FileTypeNotSupported);
}
/// <summary>
/// Creates a new raster using the specified raster provider and the Data Manager's Progress Handler,
/// as well as its LoadInRam property.
/// </summary>
/// <param name="name">The fileName of the new file to create.</param>
/// <param name="driverCode">The string code identifying the driver to use to create the raster. If no code is specified
/// the manager will attempt to match the extension with a code specified in the Dialog write filter. </param>
/// <param name="xSize">The number of columns in the raster</param>
/// <param name="ySize">The number of rows in the raster</param>
/// <param name="numBands">The number of bands in the raster</param>
/// <param name="dataType">The data type for the raster</param>
/// <param name="options">Any additional, driver specific options for creation</param>
/// <returns>An IRaster representing the created raster.</returns>
public virtual IRaster CreateRaster(string name, string driverCode, int xSize, int ySize, int numBands, Type dataType, string[] options)
{
// First check for the extension in the preferred plugins list
string ext = Path.GetExtension(name)?.ToLower();
if (ext != null)
{
IRaster result;
if (PreferredProviders.ContainsKey(ext))
{
IRasterProvider rp = PreferredProviders[ext] as IRasterProvider;
if (rp != null)
{
result = rp.Create(name, driverCode, xSize, ySize, numBands, dataType, options);
if (result != null)
return result;
}
// if we get here, we found the provider, but it did not succeed in opening the file.
}
// Then check the general list of developer specified providers... but not the directory providers
foreach (IDataProvider dp in DataProviders)
{
if (GetSupportedExtensions(dp.DialogWriteFilter).Contains(ext))
{
IRasterProvider rp = dp as IRasterProvider;
if (rp != null)
{
// attempt to open with the fileName.
result = rp.Create(name, driverCode, xSize, ySize, numBands, dataType, options);
if (result != null)
return result;
}
}
}
}
throw new ApplicationException(DataStrings.FileTypeNotSupported);
}
/// <summary>
/// Opens the file making sure it can be returned as an IRaster.
/// </summary>
/// <param name="fileName">Name of the file.</param>
/// <param name="inRam">Indicates whether the file should be loaded into ram.</param>
/// <param name="progressHandler">The progress handler.</param>
/// <returns>The IRaster that was opened.</returns>
public virtual IRaster OpenFileAsIRaster(string fileName, bool inRam, IProgressHandler progressHandler)
{
// CGX
if (File.Exists(fileName))
{
// First check for the extension in the preferred plugins list
string ext = Path.GetExtension(fileName);
if (ext != null)
{
ext = ext.ToLower();
IRaster result;
if (PreferredProviders.ContainsKey(ext))
{
result = PreferredProviders[ext].Open(fileName) as IRaster;
if (result != null) return result;
// if we get here, we found the provider, but it did not succeed in opening the file.
}
// Then check the general list of developer specified providers... but not the directory providers
foreach (IDataProvider dp in DataProviders)
{
if (!GetSupportedExtensions(dp.DialogReadFilter).Contains(ext)) continue;
// attempt to open with the fileName.
dp.ProgressHandler = ProgressHandler;
result = dp.Open(fileName) as IRaster;
if (result != null) return result;
}
}
}
else return null;
throw new ApplicationException(DataStrings.FileTypeNotSupported);
}
/// <summary>
/// Triggers the DirectoryProvidersLoaded event.
/// </summary>
/// <param name="list">List of the providers that were loaded.</param>
protected virtual void OnProvidersLoaded(IEnumerable<IDataProvider> list)
{
DirectoryProvidersLoaded?.Invoke(this, new DataProviderEventArgs(list));
}
private void Configure()
{
defaultDataManager = this;
PreferredProviders = new Dictionary<string, IDataProvider>();
// Provide a number of default providers
_dataProviders = new List<IDataProvider>
{
new ShapefileDataProvider(),
new BinaryRasterProvider(),
new DotNetImageProvider()
};
}
private string GetFilter<T>(string description, Func<IDataProvider, string> dpFilter)
where T : IDataProvider
{
var extensions = new List<string>();
foreach (KeyValuePair<string, IDataProvider> item in PreferredProviders)
{
if (item.Value is T)
{
// we don't have to check for uniqueness here because it is enforced by the HashTable
extensions.Add(item.Key);
}
}
foreach (IDataProvider dp in DataProviders)
{
string[] formats = dpFilter(dp).Split('|');
// We don't care about the description strings, just the extensions.
for (int i = 1; i < formats.Length; i += 2)
{
// Multiple extension types are separated by semicolons
string[] potentialExtensions = formats[i].Split(';');
foreach (string potentialExtension in potentialExtensions)
{
if (extensions.Contains(potentialExtension) == false)
{
if (dp is T) extensions.Add(potentialExtension);
}
}
}
}
var result = new StringBuilder();
// We now have a list of all the file extensions supported
if (extensions.Count > 0) result.Append($"{description}|" + string.Join(";", extensions.ToArray()));
foreach (KeyValuePair<string, IDataProvider> item in PreferredProviders)
{
if (item.Value is T)
{
// we don't have to check for uniqueness here because it is enforced by the HashTable
result.AppendFormat("| [{0}] - {1}| {0}", item.Key, item.Value.Name);
}
}
// Now add each of the individual lines, prepended with the provider name
foreach (IDataProvider dp in DataProviders)
{
string[] formats = dpFilter(dp).Split('|');
string potentialFormat = null;
for (int i = 0; i < formats.Length; i++)
{
if (i % 2 == 0)
{
// For descriptions, prepend the name:
potentialFormat = "|" + dp.Name + " - " + formats[i];
}
else
{
// don't add this format if it was already added by a "preferred data provider"
if (PreferredProviders.ContainsKey(formats[i]) == false)
{
if (dp is T)
{
result.Append(potentialFormat);
result.Append("|" + formats[i]);
}
}
}
}
}
result.Append("|All Files (*.*) |*.*");
return result.ToString();
}
private string GetReadFilter<T>(string description)
where T : IDataProvider
{
return GetFilter<T>(description, d => d.DialogReadFilter);
}
private string GetWriteFilter<T>(string description)
where T : IDataProvider
{
return GetFilter<T>(description, d => d.DialogWriteFilter);
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using Microsoft.Reflection;
using Microsoft.Win32;
namespace System.Diagnostics.Tracing
{
public partial class EventSource
{
// ActivityID support (see also WriteEventWithRelatedActivityIdCore)
/// <summary>
/// When a thread starts work that is on behalf of 'something else' (typically another
/// thread or network request) it should mark the thread as working on that other work.
/// This API marks the current thread as working on activity 'activityID'. This API
/// should be used when the caller knows the thread's current activity (the one being
/// overwritten) has completed. Otherwise, callers should prefer the overload that
/// return the oldActivityThatWillContinue (below).
///
/// All events created with the EventSource on this thread are also tagged with the
/// activity ID of the thread.
///
/// It is common, and good practice after setting the thread to an activity to log an event
/// with a 'start' opcode to indicate that precise time/thread where the new activity
/// started.
/// </summary>
/// <param name="activityId">A Guid that represents the new activity with which to mark
/// the current thread</param>
public static void SetCurrentThreadActivityId(Guid activityId)
{
if (TplEtwProvider.Log != null)
TplEtwProvider.Log.SetActivityId(activityId);
// We ignore errors to keep with the convention that EventSources do not throw errors.
// Note we can't access m_throwOnWrites because this is a static method.
#if FEATURE_MANAGED_ETW
#if FEATURE_PERFTRACING
// Set the activity id via EventPipe.
EventPipeInternal.EventActivityIdControl(
(uint)UnsafeNativeMethods.ManifestEtw.ActivityControl.EVENT_ACTIVITY_CTRL_SET_ID,
ref activityId);
#endif // FEATURE_PERFTRACING
#if PLATFORM_WINDOWS
// Set the activity id via ETW.
UnsafeNativeMethods.ManifestEtw.EventActivityIdControl(
UnsafeNativeMethods.ManifestEtw.ActivityControl.EVENT_ACTIVITY_CTRL_SET_ID,
ref activityId);
#endif // PLATFORM_WINDOWS
#endif // FEATURE_MANAGED_ETW
}
/// <summary>
/// When a thread starts work that is on behalf of 'something else' (typically another
/// thread or network request) it should mark the thread as working on that other work.
/// This API marks the current thread as working on activity 'activityID'. It returns
/// whatever activity the thread was previously marked with. There is a convention that
/// callers can assume that callees restore this activity mark before the callee returns.
/// To encourage this, this API returns the old activity, so that it can be restored later.
///
/// All events created with the EventSource on this thread are also tagged with the
/// activity ID of the thread.
///
/// It is common, and good practice after setting the thread to an activity to log an event
/// with a 'start' opcode to indicate that precise time/thread where the new activity
/// started.
/// </summary>
/// <param name="activityId">A Guid that represents the new activity with which to mark
/// the current thread</param>
/// <param name="oldActivityThatWillContinue">The Guid that represents the current activity
/// which will continue at some point in the future, on the current thread</param>
public static void SetCurrentThreadActivityId(Guid activityId, out Guid oldActivityThatWillContinue)
{
oldActivityThatWillContinue = activityId;
#if FEATURE_MANAGED_ETW
// We ignore errors to keep with the convention that EventSources do not throw errors.
// Note we can't access m_throwOnWrites because this is a static method.
#if FEATURE_PERFTRACING && PLATFORM_WINDOWS
EventPipeInternal.EventActivityIdControl(
(uint)UnsafeNativeMethods.ManifestEtw.ActivityControl.EVENT_ACTIVITY_CTRL_SET_ID,
ref oldActivityThatWillContinue);
#elif FEATURE_PERFTRACING
EventPipeInternal.EventActivityIdControl(
(uint)UnsafeNativeMethods.ManifestEtw.ActivityControl.EVENT_ACTIVITY_CTRL_GET_SET_ID,
ref oldActivityThatWillContinue);
#endif // FEATURE_PERFTRACING && PLATFORM_WINDOWS
#if PLATFORM_WINDOWS
UnsafeNativeMethods.ManifestEtw.EventActivityIdControl(
UnsafeNativeMethods.ManifestEtw.ActivityControl.EVENT_ACTIVITY_CTRL_GET_SET_ID,
ref oldActivityThatWillContinue);
#endif // PLATFORM_WINDOWS
#endif // FEATURE_MANAGED_ETW
// We don't call the activityDying callback here because the caller has declared that
// it is not dying.
if (TplEtwProvider.Log != null)
TplEtwProvider.Log.SetActivityId(activityId);
}
/// <summary>
/// Retrieves the ETW activity ID associated with the current thread.
/// </summary>
public static Guid CurrentThreadActivityId
{
get
{
// We ignore errors to keep with the convention that EventSources do not throw
// errors. Note we can't access m_throwOnWrites because this is a static method.
Guid retVal = new Guid();
#if FEATURE_MANAGED_ETW
#if PLATFORM_WINDOWS
UnsafeNativeMethods.ManifestEtw.EventActivityIdControl(
UnsafeNativeMethods.ManifestEtw.ActivityControl.EVENT_ACTIVITY_CTRL_GET_ID,
ref retVal);
#elif FEATURE_PERFTRACING
EventPipeInternal.EventActivityIdControl(
(uint)UnsafeNativeMethods.ManifestEtw.ActivityControl.EVENT_ACTIVITY_CTRL_GET_ID,
ref retVal);
#endif // PLATFORM_WINDOWS
#endif // FEATURE_MANAGED_ETW
return retVal;
}
}
private int GetParameterCount(EventMetadata eventData)
{
return eventData.Parameters.Length;
}
private Type GetDataType(EventMetadata eventData, int parameterId)
{
return eventData.Parameters[parameterId].ParameterType;
}
private static string GetResourceString(string key, params object[] args)
{
return SR.Format(SR.GetResourceString(key), args);
}
private static readonly bool m_EventSourcePreventRecursion = false;
}
internal partial class ManifestBuilder
{
private string GetTypeNameHelper(Type type)
{
switch (type.GetTypeCode())
{
case TypeCode.Boolean:
return "win:Boolean";
case TypeCode.Byte:
return "win:UInt8";
case TypeCode.Char:
case TypeCode.UInt16:
return "win:UInt16";
case TypeCode.UInt32:
return "win:UInt32";
case TypeCode.UInt64:
return "win:UInt64";
case TypeCode.SByte:
return "win:Int8";
case TypeCode.Int16:
return "win:Int16";
case TypeCode.Int32:
return "win:Int32";
case TypeCode.Int64:
return "win:Int64";
case TypeCode.String:
return "win:UnicodeString";
case TypeCode.Single:
return "win:Float";
case TypeCode.Double:
return "win:Double";
case TypeCode.DateTime:
return "win:FILETIME";
default:
if (type == typeof(Guid))
return "win:GUID";
else if (type == typeof(IntPtr))
return "win:Pointer";
else if ((type.IsArray || type.IsPointer) && type.GetElementType() == typeof(byte))
return "win:Binary";
ManifestError(Resources.GetResourceString("EventSource_UnsupportedEventTypeInManifest", type.Name), true);
return string.Empty;
}
}
}
internal partial class EventProvider
{
internal unsafe int SetInformation(
UnsafeNativeMethods.ManifestEtw.EVENT_INFO_CLASS eventInfoClass,
IntPtr data,
uint dataSize)
{
int status = UnsafeNativeMethods.ManifestEtw.ERROR_NOT_SUPPORTED;
if (!m_setInformationMissing)
{
try
{
status = UnsafeNativeMethods.ManifestEtw.EventSetInformation(
m_regHandle,
eventInfoClass,
(void*)data,
(int)dataSize);
}
catch (TypeLoadException)
{
m_setInformationMissing = true;
}
}
return status;
}
}
internal static class Resources
{
internal static string GetResourceString(string key, params object[] args)
{
return SR.Format(SR.GetResourceString(key), args);
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
using System.Xml;
using System.Xml.Schema;
using System.IO;
using System.Reflection;
using System.Diagnostics;
using System.Runtime.Serialization;
using System.Security.Permissions;
using System.Globalization;
//using System.Workflow.Activities;
using System.Workflow.ComponentModel;
using System.Workflow.Runtime;
using System.Workflow.Runtime.Hosting;
using Hosting = System.Workflow.Runtime.Hosting;
namespace System.Workflow.Runtime.Tracking
{
/// <summary>
/// Used for xml serializing a TrackProfile.
/// </summary>
[Obsolete("The System.Workflow.* types are deprecated. Instead, please use the new types from System.Activities.*")]
public class TrackingProfileSerializer
{
public TrackingProfileSerializer()
{
_schema = XmlSchema.Read(new StringReader(_xsd), null);
_schema.Namespaces.Add("", _ns);
}
public XmlSchema Schema
{
get
{
return _schema;
}
}
#region Deserialization
List<ValidationEventArgs> _vArgs = new List<ValidationEventArgs>();
bool _vex = false;
/// <summary>
/// Deserialize TrackingProfile in xml form to a TrackingProfile object.
/// </summary>
/// <param name="reader">TextReader containing TrackingProfile in xml form</param>
/// <param name="profile">TrackingProfile</param>
/// <exception cref="">XmlSchemaException</exception>
/// <exception cref="">XmlException</exception>
/// <exception cref="">ArgumentNullException</exception>
/// <exception cref="">ArgumentException</exception>
/// <exception cref="">ArgumentOutOfRangeException</exception>
/// <exception cref="">FormatException</exception>
/// <exception cref="">OverflowException</exception>
/// <exception cref="">InvalidOperationException</exception>
/// <exception cref="">TrackingProfileDeserializationException</exception>
public TrackingProfile Deserialize(TextReader reader)
{
TrackingProfile profile = null;
_vArgs = new List<ValidationEventArgs>();
_vex = false;
if (null == reader)
throw new ArgumentNullException("reader");
//
// Specify that if no namespace is declare the default should be interpreted as ours
NameTable nt = new NameTable();
XmlNamespaceManager nsmgr = new XmlNamespaceManager(nt);
nsmgr.AddNamespace(String.Empty, _ns);
XmlParserContext ctx = new XmlParserContext(nt, nsmgr, null, XmlSpace.None);
XmlReader pReader = XmlReader.Create(reader, GetSchemaReaderSettings(), ctx);
try
{
profile = new TrackingProfile();
//
// Schema validation will catch if element is missing
if (!pReader.ReadToDescendant("TrackingProfile"))
{
//
// Will throw exception with validation errors
CheckSchemaErrors();
return null;
}
string version = pReader.GetAttribute("version");
if ((null == version) || (0 == version.Trim().Length))
throw new TrackingProfileDeserializationException(ExecutionStringManager.InvalidProfileVersion);
profile.Version = new Version(version);
if (!pReader.ReadToDescendant("TrackPoints"))
{
//
// Will throw exception with validation errors
CheckSchemaErrors();
return null;
}
CreateTrackPoints(pReader, profile);
CheckSchemaErrors();
}
catch (Exception)
{
profile = null;
throw;
}
finally
{
_vArgs = new List<ValidationEventArgs>();
_vex = false;
pReader.Close();
}
return profile;
}
private void CheckSchemaErrors()
{
//
// If the parsing hit an error->throw
// Clients can check ValidationEventArgs to get
// all errors & warnings that were caught.
if (_vex)
{
TrackingProfileDeserializationException tpde = new TrackingProfileDeserializationException(ExecutionStringManager.TrackingDeserializationSchemaError);
if (null != _vArgs)
{
foreach (ValidationEventArgs arg in _vArgs)
tpde.ValidationEventArgs.Add(arg);
}
throw tpde;
}
}
private void CreateTrackPoints(XmlReader reader, TrackingProfile profile)
{
if (null == reader)
throw new ArgumentNullException("reader");
if (null == profile)
throw new ArgumentNullException("profile");
if (0 != string.Compare(reader.Name, "TrackPoints", StringComparison.Ordinal))
throw new TrackingProfileDeserializationException(ExecutionStringManager.TrackingDeserializationInvalidPosition + "TrackPoints.");
if (reader.IsEmptyElement)
return;
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
if (0 == string.Compare(reader.Name, "ActivityTrackPoint", StringComparison.Ordinal))
CreateActivityTrackPoint(reader, profile);
else if (0 == string.Compare(reader.Name, "UserTrackPoint", StringComparison.Ordinal))
CreateUserTrackPoint(reader, profile);
else if (0 == string.Compare(reader.Name, "WorkflowTrackPoint", StringComparison.Ordinal))
CreateWorkflowTrackPoint(reader, profile);
break;
case XmlNodeType.EndElement:
if (0 == string.Compare(reader.Name, "TrackPoints", StringComparison.Ordinal))
return;
break;
}
}
//
// Only valid exit is on an EndElement that matches the element that is passed in.
throw new TrackingProfileDeserializationException(ExecutionStringManager.TrackingDeserializationCloseElementNotFound + "TrackPoints.");
}
private void CreateActivityTrackPoint(XmlReader reader, TrackingProfile profile)
{
if (null == reader)
throw new ArgumentNullException("reader");
if (null == profile)
throw new ArgumentNullException("profile");
if (0 != string.Compare(reader.Name, "ActivityTrackPoint", StringComparison.Ordinal))
throw new TrackingProfileDeserializationException(ExecutionStringManager.TrackingDeserializationInvalidPosition + "ActivityTrackPoint.");
if (reader.IsEmptyElement)
return;
ActivityTrackPoint point = new ActivityTrackPoint();
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
if (0 == string.Compare(reader.Name, "Annotations", StringComparison.Ordinal))
CreateAnnotations(reader, point.Annotations);
else if (0 == string.Compare(reader.Name, "MatchingLocations", StringComparison.Ordinal))
CreateActivityTrackingLocations(reader, point.MatchingLocations);
else if (0 == string.Compare(reader.Name, "ExcludedLocations", StringComparison.Ordinal))
CreateActivityTrackingLocations(reader, point.ExcludedLocations);
else if (0 == string.Compare(reader.Name, "Extracts", StringComparison.Ordinal))
CreateExtracts(reader, point.Extracts);
//
// Xsd validation will catch unknown elements
break;
case XmlNodeType.EndElement:
if (0 == string.Compare(reader.Name, "ActivityTrackPoint", StringComparison.Ordinal))
{
profile.ActivityTrackPoints.Add(point);
return;
}
break;
}
}
//
// Only valid exit is on an EndElement that matches the element that is passed in.
throw new TrackingProfileDeserializationException(ExecutionStringManager.TrackingDeserializationCloseElementNotFound + "ActivityTrackPoint.");
}
private void CreateActivityTrackingLocation(XmlReader reader, ActivityTrackingLocation location)
{
if (null == reader)
throw new ArgumentNullException("reader");
if (null == location)
throw new ArgumentNullException("location");
if (0 != string.Compare(reader.Name, "ActivityTrackingLocation", StringComparison.Ordinal))
throw new TrackingProfileDeserializationException(ExecutionStringManager.TrackingDeserializationInvalidPosition + "ActivityTrackingLocation.");
if (reader.IsEmptyElement)
return;
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
if (0 == string.Compare(reader.Name, "TypeName", StringComparison.Ordinal))
{
if (null != location.ActivityType)
throw new TrackingProfileDeserializationException(ExecutionStringManager.TrackingDeserializationInvalidType);
location.ActivityTypeName = reader.ReadString();
}
else if (0 == string.Compare(reader.Name, "Type", StringComparison.Ordinal))
{
if (null != location.ActivityTypeName)
throw new TrackingProfileDeserializationException(ExecutionStringManager.TrackingDeserializationInvalidType);
if (!reader.IsEmptyElement)
{
//
// Schema validation will catch empty elements, just make sure
// we don't pass GetType a null or empty string and continue.
string type = reader.ReadString();
if ((null != type) && (type.Trim().Length > 0))
location.ActivityType = Type.GetType(type, true);
}
}
else if (0 == string.Compare(reader.Name, "MatchDerivedTypes", StringComparison.Ordinal))
location.MatchDerivedTypes = reader.ReadElementContentAsBoolean();
else if (0 == string.Compare(reader.Name, "ExecutionStatusEvents", StringComparison.Ordinal))
CreateStatusEvents(reader, location.ExecutionStatusEvents);
else if (0 == string.Compare(reader.Name, "Conditions", StringComparison.Ordinal))
CreateConditions(reader, location.Conditions);
break;
case XmlNodeType.EndElement:
if (0 == string.Compare(reader.Name, "ActivityTrackingLocation", StringComparison.Ordinal))
{
//
// If we don't have a type or name create the Activity type to track all activities
if ((null == location.ActivityType) && (null == location.ActivityTypeName))
{
location.ActivityType = typeof(Activity);
location.MatchDerivedTypes = true;
}
return;
}
break;
}
}
//
// Something bad happened
throw new TrackingProfileDeserializationException(ExecutionStringManager.TrackingDeserializationCloseElementNotFound + "ActivityTrackingLocation.");
}
private void CreateUserTrackPoint(XmlReader reader, TrackingProfile profile)
{
if (null == reader)
throw new ArgumentNullException("reader");
if (null == profile)
throw new ArgumentNullException("profile");
if (0 != string.Compare(reader.Name, "UserTrackPoint", StringComparison.Ordinal))
throw new TrackingProfileDeserializationException(ExecutionStringManager.TrackingDeserializationInvalidPosition + "UserTrackPoint.");
if (reader.IsEmptyElement)
return;
UserTrackPoint point = new UserTrackPoint();
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
if (0 == string.Compare(reader.Name, "Annotations", StringComparison.Ordinal))
CreateAnnotations(reader, point.Annotations);
else if (0 == string.Compare(reader.Name, "MatchingLocations", StringComparison.Ordinal))
CreateUserTrackingLocations(reader, point.MatchingLocations);
else if (0 == string.Compare(reader.Name, "ExcludedLocations", StringComparison.Ordinal))
CreateUserTrackingLocations(reader, point.ExcludedLocations);
else if (0 == string.Compare(reader.Name, "Extracts", StringComparison.Ordinal))
CreateExtracts(reader, point.Extracts);
//
// Xsd validation will catch unknown elements
break;
case XmlNodeType.EndElement:
if (0 == string.Compare(reader.Name, "UserTrackPoint", StringComparison.Ordinal))
{
profile.UserTrackPoints.Add(point);
return;
}
break;
}
}
//
// Only valid exit is on an EndElement that matches the element that is passed in.
throw new TrackingProfileDeserializationException(ExecutionStringManager.TrackingDeserializationCloseElementNotFound + "UserTrackPoint.");
}
private void CreateUserTrackingLocation(XmlReader reader, UserTrackingLocation location)
{
if (null == reader)
throw new ArgumentNullException("reader");
if (null == location)
throw new ArgumentNullException("location");
if (0 != string.Compare(reader.Name, "UserTrackingLocation", StringComparison.Ordinal))
throw new TrackingProfileDeserializationException(ExecutionStringManager.TrackingDeserializationInvalidPosition + "UserTrackingLocation.");
if (reader.IsEmptyElement)
return;
string name = null, type = null;
bool derived = false, seenAct = false, seenArg = false;
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
if (0 == string.Compare(reader.Name, "Activity", StringComparison.Ordinal))
seenAct = true;
else if (0 == string.Compare(reader.Name, "KeyName", StringComparison.Ordinal))
location.KeyName = reader.ReadString();
else if (0 == string.Compare(reader.Name, "Argument", StringComparison.Ordinal))
seenArg = true;
else if (0 == string.Compare(reader.Name, "TypeName", StringComparison.Ordinal))
name = reader.ReadString();
else if (0 == string.Compare(reader.Name, "Type", StringComparison.Ordinal))
type = reader.ReadString();
else if (0 == string.Compare(reader.Name, "MatchDerivedTypes", StringComparison.Ordinal))
derived = reader.ReadElementContentAsBoolean();
else if (0 == string.Compare(reader.Name, "Conditions", StringComparison.Ordinal))
CreateConditions(reader, location.Conditions);
break;
case XmlNodeType.EndElement:
if (0 == string.Compare(reader.Name, "UserTrackingLocation", StringComparison.Ordinal))
{
if (!seenAct)
{
location.ActivityType = typeof(Activity);
location.MatchDerivedActivityTypes = true;
}
if (!seenArg)
{
location.ArgumentType = typeof(object);
location.MatchDerivedArgumentTypes = true;
}
if ((null == location.ActivityType) && ((null == location.ActivityTypeName) || (0 == location.ActivityTypeName.Trim().Length)) && (null == location.ArgumentType) && ((null == location.ArgumentTypeName) || (0 == location.ArgumentTypeName.Trim().Length)))
throw new TrackingProfileDeserializationException(ExecutionStringManager.MissingActivityType);
return;
}
else if (0 == string.Compare(reader.Name, "Activity", StringComparison.Ordinal))
{
if (!seenAct)
{
location.ActivityType = typeof(Activity);
location.MatchDerivedActivityTypes = true;
}
else
{
if ((null != type) && (type.Trim().Length > 0))
location.ActivityType = Type.GetType(type, true);
else
location.ActivityTypeName = name;
location.MatchDerivedActivityTypes = derived;
}
name = null;
type = null;
derived = false;
}
else if (0 == string.Compare(reader.Name, "Argument", StringComparison.Ordinal))
{
if (!seenArg)
{
location.ArgumentType = typeof(object);
location.MatchDerivedArgumentTypes = true;
}
else
{
if ((null != type) && (type.Trim().Length > 0))
location.ArgumentType = Type.GetType(type, true);
else
location.ArgumentTypeName = name;
location.MatchDerivedArgumentTypes = derived;
}
name = null;
type = null;
derived = false;
}
break;
}
}
//
// Something bad happened
throw new TrackingProfileDeserializationException(ExecutionStringManager.TrackingDeserializationCloseElementNotFound + "UserTrackingLocation.");
}
private void CreateWorkflowTrackPoint(XmlReader reader, TrackingProfile profile)
{
if (null == reader)
throw new ArgumentNullException("reader");
if (null == profile)
throw new ArgumentNullException("profile");
if (0 != string.Compare(reader.Name, "WorkflowTrackPoint", StringComparison.Ordinal))
throw new TrackingProfileDeserializationException(ExecutionStringManager.TrackingDeserializationInvalidPosition + "WorkflowTrackPoint.");
if (reader.IsEmptyElement)
return;
WorkflowTrackPoint point = new WorkflowTrackPoint();
point.MatchingLocation = new WorkflowTrackingLocation();
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
if (0 == string.Compare(reader.Name, "Annotations", StringComparison.Ordinal))
CreateAnnotations(reader, point.Annotations);
else if (0 == string.Compare(reader.Name, "TrackingWorkflowEvent", StringComparison.Ordinal))
point.MatchingLocation.Events.Add((TrackingWorkflowEvent)Enum.Parse(typeof(TrackingWorkflowEvent), reader.ReadString()));
//
// Xsd validation will catch unknown elements
break;
case XmlNodeType.EndElement:
if (0 == string.Compare(reader.Name, "WorkflowTrackPoint", StringComparison.Ordinal))
{
profile.WorkflowTrackPoints.Add(point);
return;
}
break;
}
}
//
// Only valid exit is on an EndElement that matches the element that is passed in.
throw new TrackingProfileDeserializationException(ExecutionStringManager.TrackingDeserializationCloseElementNotFound + "WorkflowTrackPoint.");
}
private void CreateStatusEvents(XmlReader reader, IList<ActivityExecutionStatus> events)
{
if (null == reader)
throw new ArgumentNullException("reader");
if (null == events)
throw new ArgumentNullException("events");
if (0 != string.Compare("ExecutionStatusEvents", reader.Name, StringComparison.Ordinal))
throw new TrackingProfileDeserializationException(ExecutionStringManager.TrackingDeserializationInvalidPosition + "ExecutionStatusEvents.");
if (reader.IsEmptyElement)
return;
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
if (0 == string.Compare(reader.Name, "ExecutionStatus", StringComparison.Ordinal))
{
string status = reader.ReadString();
if ((null != status) && (status.Trim().Length > 0))
{
string[] names = Enum.GetNames(typeof(ActivityExecutionStatus));
foreach (string s in names)
{
if (0 == string.Compare(s, status, StringComparison.Ordinal))
events.Add((ActivityExecutionStatus)Enum.Parse(typeof(ActivityExecutionStatus), status));
}
}
}
//
// Xsd validation will catch unknown elements
break;
case XmlNodeType.EndElement:
if (0 == string.Compare(reader.Name, "ExecutionStatusEvents", StringComparison.Ordinal))
return;
break;
}
}
//
// Something is funky
throw new TrackingProfileDeserializationException(ExecutionStringManager.TrackingDeserializationCloseElementNotFound + "ExecutionStatusEvents.");
}
private void CreateConditions(XmlReader reader, TrackingConditionCollection conditions)
{
if (null == reader)
throw new ArgumentNullException("reader");
if (null == conditions)
throw new ArgumentNullException("conditions");
if (0 != string.Compare("Conditions", reader.Name, StringComparison.Ordinal))
throw new TrackingProfileDeserializationException(ExecutionStringManager.TrackingDeserializationInvalidPosition + "Conditions.");
if (reader.IsEmptyElement)
return;
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
if (0 == string.Compare(reader.Name, "ActivityTrackingCondition", StringComparison.Ordinal))
{
ActivityTrackingCondition condition = new ActivityTrackingCondition();
CreateCondition(reader, condition);
conditions.Add(condition);
}
//
// Xsd validation will catch unknown elements
break;
case XmlNodeType.EndElement:
if (0 == string.Compare(reader.Name, "Conditions", StringComparison.Ordinal))
return;
break;
}
}
//
// Only valid exit is on an EndElement that matches the element that is passed in.
throw new TrackingProfileDeserializationException(ExecutionStringManager.TrackingDeserializationCloseElementNotFound + "Conditions.");
}
private void CreateCondition(XmlReader reader, TrackingCondition condition)
{
if (null == reader)
throw new ArgumentNullException("reader");
if (null == condition)
throw new ArgumentNullException("condition");
if (0 != string.Compare(condition.GetType().Name, reader.Name, StringComparison.Ordinal))
throw new TrackingProfileDeserializationException(ExecutionStringManager.TrackingDeserializationInvalidPosition + condition.GetType().Name);
if (reader.IsEmptyElement)
return;
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
if (0 == string.Compare(reader.Name, "Member", StringComparison.Ordinal))
{
condition.Member = reader.ReadString();
}
else if (0 == string.Compare(reader.Name, "Operator", StringComparison.Ordinal))
{
string op = reader.ReadString();
if ((null != op) && (op.Trim().Length > 0))
{
string[] names = Enum.GetNames(typeof(ComparisonOperator));
foreach (string s in names)
{
if (0 == string.Compare(s, op, StringComparison.Ordinal))
condition.Operator = (ComparisonOperator)Enum.Parse(typeof(ComparisonOperator), op);
}
}
}
else if (0 == string.Compare(reader.Name, "Value", StringComparison.Ordinal))
{
if (!reader.IsEmptyElement)
condition.Value = reader.ReadString();
}
//
// Xsd validation will catch unknown elements
break;
case XmlNodeType.EndElement:
if (0 == string.Compare(reader.Name, condition.GetType().Name, StringComparison.Ordinal))
return;
break;
}
}
//
// Only valid exit is on an EndElement that matches the element that is passed in.
throw new TrackingProfileDeserializationException(ExecutionStringManager.TrackingDeserializationCloseElementNotFound + condition.GetType().Name);
}
private void CreateExtracts(XmlReader reader, ExtractCollection extracts)
{
if (null == reader)
throw new ArgumentNullException("reader");
if (null == extracts)
throw new ArgumentNullException("extracts");
if (0 != string.Compare("Extracts", reader.Name, StringComparison.Ordinal))
throw new TrackingProfileDeserializationException(ExecutionStringManager.TrackingDeserializationInvalidPosition + "Extracts");
if (reader.IsEmptyElement)
return;
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
if (0 == string.Compare(reader.Name, "ActivityDataTrackingExtract", StringComparison.Ordinal))
{
ActivityDataTrackingExtract e = new ActivityDataTrackingExtract();
CreateExtract(reader, e);
extracts.Add(e);
}
else if (0 == string.Compare(reader.Name, "WorkflowDataTrackingExtract", StringComparison.Ordinal))
{
WorkflowDataTrackingExtract e = new WorkflowDataTrackingExtract();
CreateExtract(reader, e);
extracts.Add(e);
}
//
// Xsd validation will catch unknown elements
break;
case XmlNodeType.EndElement:
if (0 == string.Compare(reader.Name, "Extracts", StringComparison.Ordinal))
return;
break;
}
}
//
// Only valid exit is on an EndElement that matches the element that is passed in.
throw new TrackingProfileDeserializationException(ExecutionStringManager.TrackingDeserializationCloseElementNotFound + "Extracts.");
}
private void CreateExtract(XmlReader reader, TrackingExtract extract)
{
if (null == reader)
throw new ArgumentNullException("reader");
if (null == extract)
throw new ArgumentNullException("extract");
if (reader.IsEmptyElement)
return;
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
if (0 == string.Compare(reader.Name, "Member", StringComparison.Ordinal))
extract.Member = reader.ReadString();
else if (0 == string.Compare(reader.Name, "Annotations", StringComparison.Ordinal))
CreateAnnotations(reader, extract.Annotations);
//
// Xsd validation will catch unknown elements
break;
case XmlNodeType.EndElement:
if (0 == string.Compare(reader.Name, extract.GetType().Name, StringComparison.Ordinal))
return;
break;
}
}
//
// Only valid exit is on an EndElement that matches the element that is passed in.
throw new TrackingProfileDeserializationException(ExecutionStringManager.TrackingDeserializationCloseElementNotFound + extract.GetType().Name);
}
private void CreateAnnotations(XmlReader reader, TrackingAnnotationCollection annotations)
{
if (null == reader)
throw new ArgumentNullException("reader");
if (null == annotations)
throw new ArgumentNullException("annotations");
if (0 != string.Compare(reader.Name, "Annotations", StringComparison.Ordinal))
throw new TrackingProfileDeserializationException(ExecutionStringManager.TrackingDeserializationInvalidPosition + "Annotations.");
if (reader.IsEmptyElement)
return;
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
if (0 == string.Compare(reader.Name, "Annotation", StringComparison.Ordinal))
{
//
// Preserve null and empty as distinct values
// null == <Annotation /> empty string = <Annotation></Annotation>
if (!reader.IsEmptyElement)
annotations.Add(reader.ReadString());
else
annotations.Add(null);
}
break;
case XmlNodeType.EndElement:
if (0 == string.Compare(reader.Name, "Annotations", StringComparison.Ordinal))
return;
break;
}
}
//
// Only valid exit is on an EndElement that matches the element that is passed in.
throw new TrackingProfileDeserializationException(ExecutionStringManager.TrackingDeserializationCloseElementNotFound + "Annotations.");
}
private void CreateActivityTrackingLocations(XmlReader reader, ActivityTrackingLocationCollection activities)
{
if (null == reader)
throw new ArgumentNullException("reader");
if (null == activities)
throw new ArgumentNullException("activities");
if (reader.IsEmptyElement)
return;
string startName = reader.Name;
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
if (0 == string.Compare(reader.Name, "ActivityTrackingLocation", StringComparison.Ordinal))
{
ActivityTrackingLocation location = new ActivityTrackingLocation();
CreateActivityTrackingLocation(reader, location);
activities.Add(location);
}
break;
case XmlNodeType.EndElement:
if (0 == string.Compare(startName, reader.Name, StringComparison.Ordinal))
return;
break;
}
}
//
// Only valid exit is on an EndElement that matches the element that is passed in.
throw new TrackingProfileDeserializationException(ExecutionStringManager.TrackingDeserializationCloseElementNotFound + startName + ".");
}
private void CreateUserTrackingLocations(XmlReader reader, UserTrackingLocationCollection user)
{
if (null == reader)
throw new ArgumentNullException("reader");
if (null == user)
throw new ArgumentNullException("user");
if (reader.IsEmptyElement)
return;
string startName = reader.Name;
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
if (0 == string.Compare(reader.Name, "UserTrackingLocation", StringComparison.Ordinal))
{
UserTrackingLocation location = new UserTrackingLocation();
CreateUserTrackingLocation(reader, location);
user.Add(location);
}
break;
case XmlNodeType.EndElement:
if (0 == string.Compare(startName, reader.Name, StringComparison.Ordinal))
return;
break;
}
}
//
// Only valid exit is on an EndElement that matches the element that is passed in.
throw new TrackingProfileDeserializationException(ExecutionStringManager.TrackingDeserializationCloseElementNotFound + startName + ".");
}
private XmlReaderSettings GetSchemaReaderSettings()
{
XmlReaderSettings profileSettings = new XmlReaderSettings();
profileSettings.Schemas.Add(_schema);
profileSettings.ValidationType = ValidationType.Schema;
profileSettings.ConformanceLevel = ConformanceLevel.Document;
profileSettings.CloseInput = false;
profileSettings.IgnoreComments = true;
profileSettings.IgnoreProcessingInstructions = true;
profileSettings.DtdProcessing = DtdProcessing.Prohibit;
profileSettings.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);
return profileSettings;
}
private void ValidationCallBack(object sender, ValidationEventArgs e)
{
_vArgs.Add(e);
if (e.Severity == XmlSeverityType.Error)
_vex = true;
}
#endregion
#region Serialization
/// <summary>
/// Xml serialize a TrackingProfile.
/// </summary>
/// <param name="profile">TrackingProfile to serialize.</param>
/// <param name="writer">TextWriter to store xml text.</param>
public void Serialize(TextWriter writer, TrackingProfile profile)
{
if (null == profile)
throw new ArgumentNullException("profile");
if (null == writer)
throw new ArgumentNullException("writer");
XmlTextWriter xmlWriter = new XmlTextWriter(writer);
InitWriter(xmlWriter);
Write(profile, xmlWriter);
xmlWriter.Flush();
xmlWriter.Close();
}
private void Write(TrackingProfile profile, XmlTextWriter writer)
{
writer.WriteStartDocument(true);
writer.WriteStartElement("TrackingProfile");
// Write the namespace declaration.
writer.WriteAttributeString("xmlns", _ns);
if (null == profile.Version)
throw new ArgumentException(ExecutionStringManager.InvalidProfileVersion);
string version = null;
if (profile.Version.Revision >= 0)
version = string.Format(NumberFormatInfo.InvariantInfo, "{0}.{1}.{2}.{3}", profile.Version.Major, profile.Version.Minor, profile.Version.Build, profile.Version.Revision);
else if (profile.Version.Build >= 0)
version = string.Format(NumberFormatInfo.InvariantInfo, "{0}.{1}.{2}", profile.Version.Major, profile.Version.Minor, profile.Version.Build);
else if (profile.Version.Minor >= 0)
version = string.Format(NumberFormatInfo.InvariantInfo, "{0}.{1}", profile.Version.Major, profile.Version.Minor);
writer.WriteAttributeString("version", version);
WriteTrackPoints(profile, writer);
writer.WriteEndElement();
writer.WriteEndDocument();
}
#region TrackPoints
private void WriteTrackPoints(TrackingProfile profile, XmlTextWriter writer)
{
//
// We must have at least 1 trackpoint or the profile won't be valid
if (((null == profile.WorkflowTrackPoints) || (0 == profile.WorkflowTrackPoints.Count))
&& ((null == profile.ActivityTrackPoints) || (0 == profile.ActivityTrackPoints.Count))
&& ((null == profile.UserTrackPoints) || (0 == profile.UserTrackPoints.Count)))
throw new ArgumentException(ExecutionStringManager.TrackingSerializationNoTrackPoints);
int count = 0;
writer.WriteStartElement("TrackPoints");
foreach (WorkflowTrackPoint point in profile.WorkflowTrackPoints)
{
if (null != point)
{
WriteWorkflowTrackPoint(point, writer);
count++;
}
}
foreach (ActivityTrackPoint point in profile.ActivityTrackPoints)
{
if (null != point)
{
WriteActivityTrackPoint(point, writer);
count++;
}
}
foreach (UserTrackPoint point in profile.UserTrackPoints)
{
if (null != point)
{
WriteUserTrackPoint(point, writer);
count++;
}
}
//
// We must have at least 1 trackpoint or the profile isn't valid
if (0 == count)
throw new ArgumentException(ExecutionStringManager.TrackingSerializationNoTrackPoints);
writer.WriteEndElement();
}
private void WriteActivityTrackPoint(ActivityTrackPoint point, XmlTextWriter writer)
{
if (null == point)
throw new ArgumentNullException("point");
//
// Validate this element's required fields
if ((null == point.MatchingLocations) || (0 == point.MatchingLocations.Count))
throw new ArgumentException(ExecutionStringManager.NoMatchingLocations);
writer.WriteStartElement("ActivityTrackPoint");
writer.WriteStartElement("MatchingLocations");
//
// Write the locations that should be matched
// At least one non null location is required.
int count = 0;
foreach (ActivityTrackingLocation location in point.MatchingLocations)
{
if (null != location)
{
WriteActivityTrackingLocation(location, writer);
count++;
}
}
if (0 == count)
throw new ArgumentException(ExecutionStringManager.NoMatchingLocations);
writer.WriteEndElement();
//
// Write the locations that should not be matched (these override the locations to match)
// Excludes are not required.
if ((null != point.ExcludedLocations) && (point.ExcludedLocations.Count > 0))
{
writer.WriteStartElement("ExcludedLocations");
foreach (ActivityTrackingLocation location in point.ExcludedLocations)
{
if (null != location)
WriteActivityTrackingLocation(location, writer);
}
writer.WriteEndElement();
}
//
// Write annotations, not a required field
WriteAnnotations(point.Annotations, writer);
//
// Write extracts, not a required field
WriteExtracts(point.Extracts, writer);
writer.WriteEndElement();
}
private void WriteWorkflowTrackPoint(WorkflowTrackPoint point, XmlTextWriter writer)
{
//
// Validate this element's required fields
if (null == point.MatchingLocation)
throw new ArgumentException(ExecutionStringManager.NoMatchingLocation);
writer.WriteStartElement("WorkflowTrackPoint");
WriteWorkflowTrackingLocation(point.MatchingLocation, writer);
//
// Write annotations, not a required field
WriteAnnotations(point.Annotations, writer);
writer.WriteEndElement();
}
private void WriteUserTrackPoint(UserTrackPoint point, XmlTextWriter writer)
{
//
// Validate this element's required fields
if ((null == point.MatchingLocations) || (0 == point.MatchingLocations.Count))
throw new ArgumentException(ExecutionStringManager.NoMatchingLocations);
writer.WriteStartElement("UserTrackPoint");
writer.WriteStartElement("MatchingLocations");
//
// Write the locations that should be matched
// At least one non null location is required.
int count = 0;
foreach (UserTrackingLocation location in point.MatchingLocations)
{
if (null != location)
{
WriteUserTrackingLocation(location, writer);
count++;
}
}
if (0 == count)
throw new ArgumentException(ExecutionStringManager.NoMatchingLocations);
writer.WriteEndElement();
//
// Write the locations that should not be matched (these override the locations to match)
// Excludes are not required.
if ((null != point.ExcludedLocations) && (point.ExcludedLocations.Count > 0))
{
writer.WriteStartElement("ExcludedLocations");
foreach (UserTrackingLocation location in point.ExcludedLocations)
{
if (null != location)
WriteUserTrackingLocation(location, writer);
}
writer.WriteEndElement();
}
//
// Write annotations, not a required field
WriteAnnotations(point.Annotations, writer);
//
// Write extracts, not a required field
WriteExtracts(point.Extracts, writer);
writer.WriteEndElement();
}
#endregion
#region Location
private void WriteActivityTrackingLocation(ActivityTrackingLocation loc, XmlTextWriter writer)
{
//
// Validate this element's required fields
if ((null == loc.ActivityType) && ((null == loc.ActivityTypeName) || (0 == loc.ActivityTypeName.Trim().Length)))
throw new ArgumentException(ExecutionStringManager.MissingActivityType);
writer.WriteStartElement("ActivityTrackingLocation");
writer.WriteStartElement("Activity");
if (null != loc.ActivityType)
writer.WriteElementString("Type", loc.ActivityType.AssemblyQualifiedName);
else
writer.WriteElementString("TypeName", loc.ActivityTypeName);
writer.WriteElementString("MatchDerivedTypes", loc.MatchDerivedTypes.ToString().ToLower(CultureInfo.InvariantCulture));
writer.WriteEndElement();
WriteEvents(loc.ExecutionStatusEvents, writer);
if ((null != loc.Conditions) && (loc.Conditions.Count > 0))
WriteConditions(loc.Conditions, writer);
writer.WriteEndElement();
}
private void WriteUserTrackingLocation(UserTrackingLocation loc, XmlTextWriter writer)
{
//
// Validate this element's required fields
if ((null == loc.ActivityType) && ((null == loc.ActivityTypeName) || (0 == loc.ActivityTypeName.Trim().Length)))
throw new ArgumentException(ExecutionStringManager.MissingActivityType);
if ((null == loc.ArgumentType) && ((null == loc.ArgumentTypeName) || (0 == loc.ArgumentTypeName.Trim().Length)))
throw new ArgumentException(ExecutionStringManager.MissingArgumentType);
writer.WriteStartElement("UserTrackingLocation");
//
// Write the Acctivity node
writer.WriteStartElement("Activity");
if (null != loc.ActivityType)
writer.WriteElementString("Type", loc.ActivityType.AssemblyQualifiedName);
else
writer.WriteElementString("TypeName", loc.ActivityTypeName);
writer.WriteElementString("MatchDerivedTypes", loc.MatchDerivedActivityTypes.ToString().ToLower(CultureInfo.InvariantCulture));
writer.WriteEndElement();
//
// Write the key name node if it is non null
if (null != loc.KeyName)
writer.WriteElementString("KeyName", loc.KeyName);
//
// Write the Argument node
writer.WriteStartElement("Argument");
if (null != loc.ArgumentType)
writer.WriteElementString("Type", loc.ArgumentType.AssemblyQualifiedName);
else
writer.WriteElementString("TypeName", loc.ArgumentTypeName);
writer.WriteElementString("MatchDerivedTypes", loc.MatchDerivedArgumentTypes.ToString().ToLower(CultureInfo.InvariantCulture));
writer.WriteEndElement();
if ((null != loc.Conditions) && (loc.Conditions.Count > 0))
WriteConditions(loc.Conditions, writer);
writer.WriteEndElement();
}
private void WriteWorkflowTrackingLocation(WorkflowTrackingLocation loc, XmlTextWriter writer)
{
if ((null == loc.Events) || (0 == loc.Events.Count))
throw new ArgumentException(ExecutionStringManager.MissingWorkflowEvents);
writer.WriteStartElement("MatchingLocation");
writer.WriteStartElement("WorkflowTrackingLocation");
WriteWorkflowEvents(loc.Events, writer);
writer.WriteEndElement();
writer.WriteEndElement();
}
#endregion
#region TrackingExtract
private void WriteExtracts(ExtractCollection extracts, XmlTextWriter writer)
{
if ((null == extracts) || (0 == extracts.Count))
return;
writer.WriteStartElement("Extracts");
foreach (TrackingExtract e in extracts)
{
if (null != e)
WriteExtract(e, writer);
}
writer.WriteEndElement();
}
private void WriteExtract(TrackingExtract extract, XmlTextWriter writer)
{
Type t = extract.GetType();
if ((extract is ActivityDataTrackingExtract) || (extract is WorkflowDataTrackingExtract))
{
writer.WriteStartElement(extract.GetType().Name);
writer.WriteElementString("Member", (null == extract.Member ? string.Empty : extract.Member));
WriteAnnotations(extract.Annotations, writer);
writer.WriteEndElement();
}
else
throw new ArgumentException(ExecutionStringManager.TrackingSerializationInvalidExtract);
}
#endregion
#region Shared
private void WriteConditions(TrackingConditionCollection conditions, XmlTextWriter writer)
{
if ((null == conditions) || (0 == conditions.Count))
return;
writer.WriteStartElement("Conditions");
foreach (TrackingCondition c in conditions)
{
if (null != c)
WriteCondition(c, writer);
}
writer.WriteEndElement();
}
private void WriteCondition(TrackingCondition condition, XmlTextWriter writer)
{
if (null == condition)
return;
writer.WriteStartElement(condition.GetType().Name);
writer.WriteElementString("Operator", condition.Operator.ToString());
if ((null == condition.Member) || (0 == condition.Member.Trim().Length))
throw new ArgumentException(ExecutionStringManager.MissingMemberName);
writer.WriteElementString("Member", condition.Member);
if (null != condition.Value)
{
if (string.Empty == condition.Value)
{
writer.WriteStartElement("Value");
writer.WriteRaw(string.Empty);
writer.WriteEndElement();
}
else
writer.WriteElementString("Value", condition.Value);
}
writer.WriteEndElement();
}
private void WriteAnnotations(TrackingAnnotationCollection annotations, XmlTextWriter writer)
{
if ((null == annotations) || (0 == annotations.Count))
return;
writer.WriteStartElement("Annotations");
foreach (string s in annotations)
{
//
// Preserve null and empty as distinct values
// null == <Annotation /> empty string = <Annotation></Annotation>
writer.WriteStartElement("Annotation");
if ((null == s) || (s.Length > 0))
{
writer.WriteValue(null == s ? String.Empty : s);
writer.WriteEndElement();
}
else
writer.WriteFullEndElement();
}
writer.WriteEndElement();
}
private void WriteEvents(IList<ActivityExecutionStatus> events, XmlTextWriter writer)
{
if ((null == events) || (0 == events.Count))
throw new ArgumentException(ExecutionStringManager.MissingActivityEvents);
writer.WriteStartElement("ExecutionStatusEvents");
foreach (ActivityExecutionStatus s in events)
{
if (!IsStatus((int)s))
throw new ArgumentException(ExecutionStringManager.InvalidStatus);
writer.WriteStartElement("ExecutionStatus");
writer.WriteValue(s.ToString());
writer.WriteEndElement();
}
writer.WriteEndElement();
}
private bool IsStatus(int val)
{
foreach (ActivityExecutionStatus s in Enum.GetValues(typeof(ActivityExecutionStatus)))
{
if ((int)s == val)
return true;
}
return false;
}
private void WriteWorkflowEvents(IList<TrackingWorkflowEvent> events, XmlTextWriter writer)
{
if ((null == events) || (0 == events.Count))
return;
writer.WriteStartElement("TrackingWorkflowEvents");
foreach (TrackingWorkflowEvent s in events)
{
if (!IsWorkflowEvent((int)s))
throw new ArgumentException(ExecutionStringManager.InvalidWorkflowEvent);
writer.WriteStartElement("TrackingWorkflowEvent");
writer.WriteValue(s.ToString());
writer.WriteEndElement();
}
writer.WriteEndElement();
}
private bool IsWorkflowEvent(int val)
{
foreach (TrackingWorkflowEvent s in Enum.GetValues(typeof(TrackingWorkflowEvent)))
{
if ((int)s == val)
return true;
}
return false;
}
#endregion
private void InitWriter(XmlTextWriter writer)
{
writer.Formatting = Formatting.Indented;
writer.Indentation = 4;
}
#endregion
#region Schema
private const string _ns = "http://schemas.microsoft.com/winfx/2006/workflow/trackingprofile";
private XmlSchema _schema = null;
internal const string _xsd = @"<?xml version=""1.0"" encoding=""utf-8""?>
<xs:schema id=""WFTrackingProfile"" targetNamespace=""http://schemas.microsoft.com/winfx/2006/workflow/trackingprofile"" elementFormDefault=""qualified"" xmlns=""http://schemas.microsoft.com/winfx/2006/workflow/trackingprofile"" xmlns:xs=""http://www.w3.org/2001/XMLSchema"">
<xs:element name=""TrackingProfile"" type=""TrackingProfileType"" />
<xs:complexType name=""TrackingProfileType"">
<xs:sequence>
<xs:element name=""TrackPoints"" type=""TrackPointListType"" minOccurs=""1"" maxOccurs=""1"" />
</xs:sequence>
<xs:attribute name=""version"" type=""VersionType"" />
</xs:complexType>
<xs:complexType name=""TrackPointListType"">
<xs:sequence>
<xs:choice minOccurs=""1"" maxOccurs=""unbounded"">
<xs:element name=""ActivityTrackPoint"" type=""ActivityTrackPointType"" />
<xs:element name=""UserTrackPoint"" type=""UserTrackPointType"" />
<xs:element name=""WorkflowTrackPoint"" type=""WorkflowTrackPointType"" />
</xs:choice>
</xs:sequence>
</xs:complexType>
<xs:complexType name=""ActivityTrackPointType"">
<xs:sequence>
<xs:element name=""MatchingLocations"" minOccurs=""1"" maxOccurs=""1"" type=""IncludeActivityTrackingLocationListType"" />
<xs:element name=""ExcludedLocations"" minOccurs=""0"" maxOccurs=""1"" type=""ExcludeActivityTrackingLocationListType"" />
<xs:element name=""Annotations"" type=""AnnotationListType"" minOccurs=""0"" maxOccurs=""1"" />
<xs:element name=""Extracts"" type=""ExtractListType"" minOccurs=""0"" maxOccurs=""1"" />
</xs:sequence>
</xs:complexType>
<xs:complexType name=""IncludeActivityTrackingLocationListType"">
<xs:sequence>
<xs:element name=""ActivityTrackingLocation"" type=""ActivityTrackingLocationType"" minOccurs=""1"" maxOccurs=""unbounded"" />
</xs:sequence>
</xs:complexType>
<xs:complexType name=""ExcludeActivityTrackingLocationListType"">
<xs:sequence>
<xs:element name=""ActivityTrackingLocation"" type=""ActivityTrackingLocationType"" minOccurs=""0"" maxOccurs=""unbounded"" />
</xs:sequence>
</xs:complexType>
<xs:complexType name=""ActivityTrackingLocationType"">
<xs:sequence>
<xs:element name=""Activity"" type=""Type"" minOccurs=""1"" maxOccurs=""1"" />
<xs:element name=""ExecutionStatusEvents"" type=""ExecutionStatusEventListType"" minOccurs=""1"" maxOccurs=""1"" />
<xs:element name=""Conditions"" type=""ConditionListType"" minOccurs=""0"" maxOccurs=""1"" />
</xs:sequence>
</xs:complexType>
<xs:complexType name=""UserTrackPointType"">
<xs:sequence>
<xs:element name=""MatchingLocations"" type=""IncludeUserTrackingLocationListType"" minOccurs=""1"" maxOccurs=""1"" />
<xs:element name=""ExcludedLocations"" type=""ExcludeUserTrackingLocationListType"" minOccurs=""0"" maxOccurs=""1"" />
<xs:element name=""Annotations"" type=""AnnotationListType"" minOccurs=""0"" maxOccurs=""1"" />
<xs:element name=""Extracts"" type=""ExtractListType"" minOccurs=""0"" maxOccurs=""1"" />
</xs:sequence>
</xs:complexType>
<xs:complexType name=""IncludeUserTrackingLocationListType"">
<xs:sequence>
<xs:element name=""UserTrackingLocation"" type=""UserTrackingLocationType"" minOccurs=""1"" maxOccurs=""unbounded"" />
</xs:sequence>
</xs:complexType>
<xs:complexType name=""ExcludeUserTrackingLocationListType"">
<xs:sequence>
<xs:element name=""UserTrackingLocation"" type=""UserTrackingLocationType"" minOccurs=""0"" maxOccurs=""unbounded"" />
</xs:sequence>
</xs:complexType>
<xs:complexType name=""UserTrackingLocationType"">
<xs:sequence>
<xs:element name=""Activity"" type=""Type"" minOccurs=""1"" maxOccurs=""1"" />
<xs:element name=""KeyName"" type=""NonNullString"" minOccurs=""0"" maxOccurs=""1"" />
<xs:element name=""Argument"" type=""Type"" minOccurs=""1"" maxOccurs=""1"" />
<xs:element name=""Conditions"" type=""ConditionListType"" minOccurs=""0"" maxOccurs=""1"" />
</xs:sequence>
</xs:complexType>
<xs:complexType name=""WorkflowTrackPointType"">
<xs:sequence>
<xs:element name=""MatchingLocation"" type=""WorkflowTrackingLocationMatchType"" minOccurs=""1"" maxOccurs=""1"" />
<xs:element name=""Annotations"" type=""AnnotationListType"" minOccurs=""0"" maxOccurs=""1"" />
</xs:sequence>
</xs:complexType>
<xs:complexType name=""WorkflowTrackingLocationMatchType"">
<xs:sequence>
<xs:element name=""WorkflowTrackingLocation"" type=""WorkflowTrackingLocationType"" minOccurs=""1"" maxOccurs=""1"" />
</xs:sequence>
</xs:complexType>
<xs:complexType name=""WorkflowTrackingLocationType"">
<xs:sequence>
<xs:element name=""TrackingWorkflowEvents"" type=""TrackingWorkflowEventListType"" minOccurs=""1"" maxOccurs=""1"" />
</xs:sequence>
</xs:complexType>
<xs:complexType name=""Type"">
<xs:sequence>
<xs:choice>
<xs:element name=""TypeName"" type=""NonNullString"" />
<xs:element name=""Type"" type=""NonNullString"" />
</xs:choice>
<xs:element name=""MatchDerivedTypes"" type=""xs:boolean"" minOccurs=""1"" maxOccurs=""1"" default=""false"" />
</xs:sequence>
</xs:complexType>
<xs:complexType name=""AnnotationListType"">
<xs:sequence>
<xs:element name=""Annotation"" type=""xs:string"" minOccurs=""0"" maxOccurs=""unbounded"" />
</xs:sequence>
</xs:complexType>
<xs:complexType name=""ConditionListType"">
<xs:sequence>
<xs:element name=""ActivityTrackingCondition"" type=""ActivityTrackingConditionType"" minOccurs=""0"" maxOccurs=""unbounded"" />
</xs:sequence>
</xs:complexType>
<xs:complexType name=""ActivityTrackingConditionType"">
<xs:sequence minOccurs=""1"" maxOccurs=""1"">
<xs:element name=""Operator"" type=""OperatorType"" minOccurs=""1"" maxOccurs=""1"" />
<xs:element name=""Member"" type=""NonNullString"" minOccurs=""1"" maxOccurs=""1"" />
<xs:element name=""Value"" type=""xs:string"" minOccurs=""0"" maxOccurs=""1"" nillable=""true"" />
</xs:sequence>
</xs:complexType>
<xs:simpleType name=""OperatorType"">
<xs:restriction base=""xs:string"">
<xs:enumeration value=""Equals"" />
<xs:enumeration value=""NotEquals"" />
</xs:restriction>
</xs:simpleType>
<xs:complexType name=""ExecutionStatusEventListType"">
<xs:sequence>
<xs:element name=""ExecutionStatus"" type=""ExecutionStatusType"" minOccurs=""1"" maxOccurs=""6"" />
</xs:sequence>
</xs:complexType>
<xs:simpleType name=""ExecutionStatusType"">
<xs:restriction base=""xs:string"">
<xs:enumeration value=""Initialized"" />
<xs:enumeration value=""Executing"" />
<xs:enumeration value=""Compensating"" />
<xs:enumeration value=""Canceling"" />
<xs:enumeration value=""Closed"" />
<xs:enumeration value=""Faulting"" />
</xs:restriction>
</xs:simpleType>
<xs:complexType name=""TrackingWorkflowEventListType"">
<xs:sequence>
<xs:element name=""TrackingWorkflowEvent"" type=""TrackingWorkflowEventType"" minOccurs=""1"" maxOccurs=""13"" />
</xs:sequence>
</xs:complexType>
<xs:simpleType name=""TrackingWorkflowEventType"">
<xs:restriction base=""xs:string"">
<xs:enumeration value=""Created"" />
<xs:enumeration value=""Completed"" />
<xs:enumeration value=""Idle"" />
<xs:enumeration value=""Suspended"" />
<xs:enumeration value=""Resumed"" />
<xs:enumeration value=""Persisted"" />
<xs:enumeration value=""Unloaded"" />
<xs:enumeration value=""Loaded"" />
<xs:enumeration value=""Exception"" />
<xs:enumeration value=""Terminated"" />
<xs:enumeration value=""Aborted"" />
<xs:enumeration value=""Changed"" />
<xs:enumeration value=""Started"" />
</xs:restriction>
</xs:simpleType>
<xs:complexType name=""ExtractListType"">
<xs:choice minOccurs=""0"" maxOccurs=""unbounded"">
<xs:element name=""ActivityDataTrackingExtract"" type=""ActivityDataTrackingExtractType"" />
<xs:element name=""WorkflowDataTrackingExtract"" type=""WorkflowDataTrackingExtractType"" />
</xs:choice>
</xs:complexType>
<xs:complexType name=""ActivityDataTrackingExtractType"">
<xs:sequence minOccurs=""1"" maxOccurs=""1"">
<xs:element name=""Member"" type=""xs:string"" minOccurs=""1"" maxOccurs=""1"" />
<xs:element name=""Annotations"" type=""AnnotationListType"" minOccurs=""0"" maxOccurs=""unbounded"" />
</xs:sequence>
</xs:complexType>
<xs:complexType name=""WorkflowDataTrackingExtractType"">
<xs:sequence minOccurs=""1"" maxOccurs=""1"">
<xs:element name=""Member"" type=""xs:string"" minOccurs=""1"" maxOccurs=""1"" />
<xs:element name=""Annotations"" type=""AnnotationListType"" minOccurs=""0"" maxOccurs=""unbounded"" />
</xs:sequence>
</xs:complexType>
<xs:simpleType name=""VersionType"">
<xs:restriction base=""xs:string"">
<xs:pattern value=""(^(0*([0-9]\d{0,8}|[1-2][0-1][0-4][0-7][0-4][0-8][0-3][0-6][0-4][0-7]))\.(0*([0-9]\d{0,8}|[1-2][0-1][0-4][0-7][0-4][0-8][0-3][0-6][0-4][0-7]))\.(0*([0-9]\d{0,8}|[1-2][0-1][0-4][0-7][0-4][0-8][0-3][0-6][0-4][0-7]))\.(0*([0-9]\d{0,8}|[1-2][0-1][0-4][0-7][0-4][0-8][0-3][0-6][0-4][0-7]))$)|(^(0*([0-9]\d{0,8}|[1-2][0-1][0-4][0-7][0-4][0-8][0-3][0-6][0-4][0-7]))\.(0*([0-9]\d{0,8}|[1-2][0-1][0-4][0-7][0-4][0-8][0-3][0-6][0-4][0-7]))\.(0*([0-9]\d{0,8}|[1-2][0-1][0-4][0-7][0-4][0-8][0-3][0-6][0-4][0-7]))$)|(^(0*([0-9]\d{0,8}|[1-2][0-1][0-4][0-7][0-4][0-8][0-3][0-6][0-4][0-7]))\.(0*([0-9]\d{0,8}|[1-2][0-1][0-4][0-7][0-4][0-8][0-3][0-6][0-4][0-7]))$)"" />
</xs:restriction>
</xs:simpleType>
<xs:simpleType name=""NonNullString"">
<xs:restriction base=""xs:string"">
<xs:minLength value=""1"" />
</xs:restriction>
</xs:simpleType>
</xs:schema>";
#endregion Schema
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Xunit;
using System;
using System.IO;
using System.Text;
namespace BinaryWriterTests
{
public class BinaryWriter_WriteByteCharTests
{
/// <summary>
/// Cases Tested:
/// 1) Tests that BinaryWriter properly writes chars into a stream.
/// 2) Tests that if someone writes surrogate characters, an argument exception is thrown
/// 3) Casting an int to char and writing it, works.
/// </summary>
[Fact]
public static void BinaryWriter_WriteCharTest()
{
MemoryStream mstr = new MemoryStream();
BinaryWriter dw2 = new BinaryWriter(mstr);
BinaryReader dr2 = new BinaryReader(mstr);
Char[] chArr = new Char[0];
int ii = 0;
// [] Write a series of characters to a MemoryStream and read them back
chArr = new Char[] { 'A', 'c', '\0', '\u2701', '$', '.', '1', 'l', '\u00FF', '\n', '\t', '\v' };
for (ii = 0; ii < chArr.Length; ii++)
dw2.Write(chArr[ii]);
dw2.Flush();
mstr.Position = 0;
for (ii = 0; ii < chArr.Length; ii++)
{
char c = dr2.ReadChar();
Assert.Equal(chArr[ii], c);
}
Assert.Throws<EndOfStreamException>(() => dr2.ReadChar());
dw2.Dispose();
dr2.Dispose();
mstr.Dispose();
//If someone writes out characters using BinaryWriter's Write(char[]) method, they must use something like BinaryReader's ReadChars(int) method to read it back in.
//They cannot use BinaryReader's ReadChar(). Similarly, data written using Write(char) can't be read back using ReadChars(int).
//A high-surrogate is a Unicode code point in the range U+D800 through U+DBFF and a low-surrogate is a Unicode code point in the range U+DC00 through U+DFFF
Char ch;
MemoryStream mem = new MemoryStream();
BinaryWriter writer = new BinaryWriter(mem, Encoding.Unicode);
//between 1 <= x < 255
int[] randomNumbers = new int[] { 1, 254, 210, 200, 105, 135, 98, 54 };
for (int i = 0; i < randomNumbers.Length; i++)
{
ch = (Char)randomNumbers[i];
writer.Write(ch);
}
mem.Position = 0;
writer.Dispose();
mem.Dispose();
}
[Fact]
public static void BinaryWriter_WriteCharTest_Negative()
{
//If someone writes out characters using BinaryWriter's Write(char[]) method, they must use something like BinaryReader's ReadChars(int) method to read it back in.
//They cannot use BinaryReader's ReadChar(). Similarly, data written using Write(char) can't be read back using ReadChars(int).
//A high-surrogate is a Unicode code point in the range U+D800 through U+DBFF and a low-surrogate is a Unicode code point in the range U+DC00 through U+DFFF
Char ch;
MemoryStream mem = new MemoryStream();
BinaryWriter writer = new BinaryWriter(mem, Encoding.Unicode);
// between 55296 <= x < 56319
int[] randomNumbers = new int[] { 55296, 56318, 55305, 56019, 55888, 55900, 56251 };
for (int i = 0; i < randomNumbers.Length; i++)
{
ch = (Char)randomNumbers[i];
Assert.Throws<ArgumentException>(() => writer.Write(ch));
}
// between 56320 <= x < 57343
randomNumbers = new int[] { 56320, 57342, 56431, 57001, 56453, 57245, 57111 };
for (int i = 0; i < randomNumbers.Length; i++)
{
ch = (Char)randomNumbers[i];
Assert.Throws<ArgumentException>(() => writer.Write(ch));
}
writer.Dispose();
mem.Dispose();
}
/// <summary>
/// Cases Tested:
/// Writing bytes casted to chars and using a different encoding; iso-2022-jp.
/// </summary>
[Fact]
public static void BinaryWriter_WriteCharTest2()
{
// BinaryReader/BinaryWriter don't do well when mixing char or char[] data and binary data.
// This behavior remains for compat.
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
Stream stream = new MemoryStream();
// string name = iso-2022-jp, codepage = 50220 (original test used a code page number).
// taken from http://msdn.microsoft.com/en-us/library/windows/desktop/dd317756(v=vs.85).aspx
string codepageName = "iso-2022-jp";
BinaryWriter writer = new BinaryWriter(stream, Encoding.GetEncoding(codepageName));
byte[] bytes = { 0x01, 0x02, 0x03, 0x04, 0x05 };
writer.Write((char)0x30ca);
writer.Write(bytes);
writer.Flush();
writer.Write('\0');
stream.Seek(0, SeekOrigin.Begin);
BinaryReader reader = new BinaryReader(stream, Encoding.GetEncoding(codepageName));
char japanese = reader.ReadChar();
Assert.Equal(0x30ca, (int)japanese);
byte[] readBytes = reader.ReadBytes(5);
for (int i = 0; i < 5; i++)
{
//We pretty much dont expect this to work
Assert.NotEqual(readBytes[i], bytes[i]);
}
stream.Dispose();
writer.Dispose();
reader.Dispose();
}
/// <summary>
/// Testing that bytes can be written to a stream with BinaryWriter.
/// </summary>
[Fact]
public static void BinaryWriter_WriteByteTest()
{
int ii = 0;
Byte[] bytArr = new Byte[] { Byte.MinValue, Byte.MaxValue, 100, 1, 10, Byte.MaxValue / 2, Byte.MaxValue - 100 };
// [] read/Write with Memorystream
MemoryStream mstr = new MemoryStream();
BinaryWriter dw2 = new BinaryWriter(mstr);
for (ii = 0; ii < bytArr.Length; ii++)
dw2.Write(bytArr[ii]);
dw2.Flush();
mstr.Position = 0;
BinaryReader dr2 = new BinaryReader(mstr);
for (ii = 0; ii < bytArr.Length; ii++)
{
Assert.Equal(bytArr[ii], dr2.ReadByte());
}
// [] Check End Of Stream
Assert.Throws<EndOfStreamException>(() => dr2.ReadByte());
dr2.Dispose();
dw2.Dispose();
mstr.Dispose();
}
/// <summary>
/// Testing that SBytes can be written to a stream with BinaryWriter.
/// </summary>
[Fact]
public static void BinaryWriter_WriteSByteTest()
{
int ii = 0;
SByte[] sbArr = new SByte[] {
SByte.MinValue, SByte.MaxValue, -100, 100, 0, SByte.MinValue / 2, SByte.MaxValue / 2,
10, 20, 30, -10, -20, -30, SByte.MaxValue - 100 };
// [] read/Write with Memorystream
MemoryStream mstr = new MemoryStream();
BinaryWriter dw2 = new BinaryWriter(mstr);
for (ii = 0; ii < sbArr.Length; ii++)
dw2.Write(sbArr[ii]);
dw2.Flush();
mstr.Position = 0;
BinaryReader dr2 = new BinaryReader(mstr);
for (ii = 0; ii < sbArr.Length; ii++)
{
Assert.Equal(sbArr[ii], dr2.ReadSByte());
}
dr2.Dispose();
dw2.Dispose();
mstr.Dispose();
}
/// <summary>
/// Testing that an ArgumentException is thrown when Sbytes are written to a stream
/// and read past the end of that stream.
/// </summary>
[Fact]
public static void BinaryWriter_WriteSByteTest_NegativeCase()
{
int ii = 0;
SByte[] sbArr = new SByte[] {
SByte.MinValue, SByte.MaxValue, -100, 100, 0, SByte.MinValue / 2, SByte.MaxValue / 2,
10, 20, 30, -10, -20, -30, SByte.MaxValue - 100 };
MemoryStream mstr = new MemoryStream();
BinaryWriter dw2 = new BinaryWriter(mstr);
for (ii = 0; ii < sbArr.Length; ii++)
dw2.Write(sbArr[ii]);
dw2.Flush();
BinaryReader dr2 = new BinaryReader(mstr);
// [] Check End Of Stream
Assert.Throws<EndOfStreamException>(() => dr2.ReadSByte());
dr2.Dispose();
dw2.Dispose();
mstr.Dispose();
}
/// <summary>
/// Testing that a byte[] can be written to a stream with BinaryWriter.
/// </summary>
[Fact]
public static void BinaryWriter_WriteBArrayTest()
{
int ii = 0;
Byte[] bytArr = new Byte[] { Byte.MinValue, Byte.MaxValue, 1, 5, 10, 100, 200 };
// [] read/Write with Memorystream
MemoryStream mstr = new MemoryStream();
BinaryWriter dw2 = new BinaryWriter(mstr);
dw2.Write(bytArr);
dw2.Flush();
mstr.Position = 0;
BinaryReader dr2 = new BinaryReader(mstr);
for (ii = 0; ii < bytArr.Length; ii++)
{
Assert.Equal(bytArr[ii], dr2.ReadByte());
}
// [] Check End Of Stream
Assert.Throws<EndOfStreamException>(() => dr2.ReadByte());
mstr.Dispose();
dw2.Dispose();
dr2.Dispose();
}
[Fact]
public static void BinaryWriter_WriteBArrayTest_Negative()
{
int[] iArrInvalidValues = new Int32[] { -1, -2, -100, -1000, -10000, -100000, -1000000, -10000000, -100000000, -1000000000, Int32.MinValue, Int16.MinValue };
int[] iArrLargeValues = new Int32[] { Int32.MaxValue, Int32.MaxValue - 1, Int32.MaxValue / 2, Int32.MaxValue / 10, Int32.MaxValue / 100 };
Byte[] bArr = new Byte[0];
// [] ArgumentNullException for null argument
MemoryStream mstr = new MemoryStream();
BinaryWriter dw2 = new BinaryWriter(mstr);
Assert.Throws<ArgumentNullException>(() => dw2.Write((Byte[])null));
mstr.Dispose();
dw2.Dispose();
// [] ArgumentNullException for null argument
mstr = new MemoryStream();
dw2 = new BinaryWriter(mstr);
Assert.Throws<ArgumentNullException>(() => dw2.Write((Byte[])null, 0, 0));
dw2.Dispose();
mstr.Dispose();
mstr = new MemoryStream();
dw2 = new BinaryWriter(mstr);
for (int iLoop = 0; iLoop < iArrInvalidValues.Length; iLoop++)
{
// [] ArgumentOutOfRange for negative offset
Assert.Throws<ArgumentOutOfRangeException>(() => dw2.Write(bArr, iArrInvalidValues[iLoop], 0));
// [] ArgumentOutOfRangeException for negative count
Assert.Throws<ArgumentOutOfRangeException>(() => dw2.Write(bArr, 0, iArrInvalidValues[iLoop]));
}
dw2.Dispose();
mstr.Dispose();
mstr = new MemoryStream();
dw2 = new BinaryWriter(mstr);
for (int iLoop = 0; iLoop < iArrLargeValues.Length; iLoop++)
{
// [] Offset out of range
Assert.Throws<ArgumentException>(() => dw2.Write(bArr, iArrLargeValues[iLoop], 0));
// [] Invalid count value
Assert.Throws<ArgumentException>(() => dw2.Write(bArr, 0, iArrLargeValues[iLoop]));
}
dw2.Dispose();
mstr.Dispose();
}
/// <summary>
/// Cases Tested:
/// 1) Testing that bytes can be written to a stream with BinaryWriter.
/// 2) Tests exceptional scenarios.
/// </summary>
[Fact]
public static void BinaryWriter_WriteBArrayTest2()
{
BinaryWriter dw2 = null;
BinaryReader dr2 = null;
MemoryStream mstr = null;
Byte[] bArr = new Byte[0];
int ii = 0;
Byte[] bReadArr = new Byte[0];
Int32 ReturnValue;
bArr = new Byte[1000];
bArr[0] = Byte.MinValue;
bArr[1] = Byte.MaxValue;
for (ii = 2; ii < 1000; ii++)
bArr[ii] = (Byte)(ii % 255);
// []read/ Write character values 0-1000 with Memorystream
mstr = new MemoryStream();
dw2 = new BinaryWriter(mstr);
dw2.Write(bArr, 0, bArr.Length);
dw2.Flush();
mstr.Position = 0;
dr2 = new BinaryReader(mstr);
bReadArr = new Byte[bArr.Length];
ReturnValue = dr2.Read(bReadArr, 0, bArr.Length);
Assert.Equal(bArr.Length, ReturnValue);
for (ii = 0; ii < bArr.Length; ii++)
{
Assert.Equal(bArr[ii], bReadArr[ii]);
}
dw2.Dispose();
dr2.Dispose();
mstr.Dispose();
}
/// <summary>
/// Cases Tested:
/// 1) Testing that char[] can be written to a stream with BinaryWriter.
/// 2) Tests exceptional scenarios.
/// </summary>
[Fact]
public static void BinaryWriter_WriteCharArrayTest()
{
int ii = 0;
Char[] chArr = new Char[1000];
chArr[0] = Char.MinValue;
chArr[1] = Char.MaxValue;
chArr[2] = '1';
chArr[3] = 'A';
chArr[4] = '\0';
chArr[5] = '#';
chArr[6] = '\t';
for (ii = 7; ii < 1000; ii++)
chArr[ii] = (Char)ii;
// [] read/Write with Memorystream
MemoryStream mstr = new MemoryStream();
BinaryWriter dw2 = new BinaryWriter(mstr);
dw2.Write(chArr);
dw2.Flush();
mstr.Position = 0;
BinaryReader dr2 = new BinaryReader(mstr);
for (ii = 0; ii < chArr.Length; ii++)
{
Assert.Equal(chArr[ii], dr2.ReadChar());
}
// [] Check End Of Stream
Assert.Throws<EndOfStreamException>(() => dr2.ReadChar());
dw2.Dispose();
dr2.Dispose();
mstr.Dispose();
}
[Fact]
public static void BinaryWriter_WriteCharArrayTest_Negative()
{
int[] iArrInvalidValues = new Int32[] { -1, -2, -100, -1000, -10000, -100000, -1000000, -10000000, -100000000, -1000000000, Int32.MinValue, Int16.MinValue };
int[] iArrLargeValues = new Int32[] { Int32.MaxValue, Int32.MaxValue - 1, Int32.MaxValue / 2, Int32.MaxValue / 10, Int32.MaxValue / 100 };
Char[] chArr = new Char[1000];
// [] ArgumentNullException for null argument
MemoryStream mstr = new MemoryStream();
BinaryWriter dw2 = new BinaryWriter(mstr);
Assert.Throws<ArgumentNullException>(() => dw2.Write((Char[])null));
dw2.Dispose();
mstr.Dispose();
// [] ArgumentNullException for null argument
mstr = new MemoryStream();
dw2 = new BinaryWriter(mstr);
Assert.Throws<ArgumentNullException>(() => dw2.Write((Char[])null, 0, 0));
mstr.Dispose();
dw2.Dispose();
mstr = new MemoryStream();
dw2 = new BinaryWriter(mstr);
for (int iLoop = 0; iLoop < iArrInvalidValues.Length; iLoop++)
{
// [] ArgumentOutOfRange for negative offset
Assert.Throws<ArgumentOutOfRangeException>(() => dw2.Write(chArr, iArrInvalidValues[iLoop], 0));
// [] negative count.
Assert.Throws<ArgumentOutOfRangeException>(() => dw2.Write(chArr, 0, iArrInvalidValues[iLoop]));
}
mstr.Dispose();
dw2.Dispose();
mstr = new MemoryStream();
dw2 = new BinaryWriter(mstr);
for (int iLoop = 0; iLoop < iArrLargeValues.Length; iLoop++)
{
// [] Offset out of range
Assert.Throws<ArgumentOutOfRangeException>(() => dw2.Write(chArr, iArrLargeValues[iLoop], 0));
// [] Invalid count value
Assert.Throws<ArgumentOutOfRangeException>(() => dw2.Write(chArr, 0, iArrLargeValues[iLoop]));
}
mstr.Dispose();
dw2.Dispose();
}
/// <summary>
/// Cases Tested:
/// If someone writes out characters using BinaryWriter's Write(char[]) method, they must use something like BinaryReader's ReadChars(int) method to read it back in.
/// They cannot use BinaryReader's ReadChar(). Similarly, data written using Write(char) can't be read back using ReadChars(int).
/// A high-surrogate is a Unicode code point in the range U+D800 through U+DBFF and a low-surrogate is a Unicode code point in the range U+DC00 through U+DFFF
///
/// We dont throw on the second read but then throws continuously - note the loop count difference in the 2 loops
///
/// BinaryReader was reverting to its original location instead of advancing. This was changed to skip past the char in the surrogate range.
/// The affected method is InternalReadOneChar (IROC). Note that the work here is slightly complicated by the way surrogates are handled by
/// the decoding classes. When IROC calls decoder.GetChars(), if the bytes passed in are surrogates, UnicodeEncoding doesn't report it.
/// charsRead would end up being one value, and since BinaryReader doesn't have the logic telling it exactly how many bytes total to expect,
/// it calls GetChars in a second loop. In that loop, UnicodeEncoding matches up a surrogate pair. If it realizes it's too big for the encoding,
/// then it throws an ArgumentException (chars overflow). This meant that BinaryReader.IROC is advancing past two chars in the surrogate
/// range, which is why the position actually needs to be moved back (but not past the first surrogate char).
///
/// Note that UnicodeEncoding doesn't always throw when it encounters two successive chars in the surrogate range. The exception
/// encountered here happens if it finds a valid pair but then determines it's too long. If the pair isn't valid (a low then a high),
/// then it returns 0xfffd, which is why BinaryReader.ReadChar needs to do an explicit check. (It always throws when it encounters a surrogate)
/// </summary>
[Fact]
public static void BinaryWriter_WriteCharArrayTest2()
{
MemoryStream mem = new MemoryStream();
BinaryWriter writer = new BinaryWriter(mem, Encoding.Unicode);
// between 55296 <= x < 56319
// between 56320 <= x < 57343
Char[] randomChars = new Char[] {
(Char)55296, (Char)57297, (Char)55513, (Char)56624, (Char)55334, (Char)56957, (Char)55857,
(Char)56355, (Char)56095, (Char)56887, (Char) 56126, (Char) 56735, (Char)55748, (Char)56405,
(Char)55787, (Char)56707, (Char) 56300, (Char)56417, (Char)55465, (Char)56944
};
writer.Write(randomChars);
mem.Position = 0;
BinaryReader reader = new BinaryReader(mem, Encoding.Unicode);
for (int i = 0; i < 50; i++)
{
try
{
reader.ReadChar();
Assert.Equal(1, i);
}
catch (ArgumentException)
{
// ArgumentException is sometimes thrown on ReadChar() due to the
// behavior outlined in the method summary.
}
}
Char[] chars = reader.ReadChars(randomChars.Length);
for (int i = 0; i < randomChars.Length; i++)
Assert.Equal(randomChars[i], chars[i]);
reader.Dispose();
writer.Dispose();
}
/// <summary>
/// Cases Tested:
/// 1) Tests that char[] can be written to a stream with BinaryWriter.
/// 2) Tests Exceptional cases.
/// </summary>
[Fact]
public static void BinaryWriter_WriteCharArrayTest3()
{
BinaryWriter dw2 = null;
BinaryReader dr2 = null;
MemoryStream mstr = null;
Char[] chArr = new Char[0];
int ii = 0;
Char[] chReadArr = new Char[0];
Int32 ReturnValue;
chArr = new Char[1000];
chArr[0] = Char.MinValue;
chArr[1] = Char.MaxValue;
chArr[2] = '1';
chArr[3] = 'A';
chArr[4] = '\0';
chArr[5] = '#';
chArr[6] = '\t';
for (ii = 7; ii < 1000; ii++)
chArr[ii] = (Char)ii;
// []read/ Write character values 0-1000 with Memorystream
mstr = new MemoryStream();
dw2 = new BinaryWriter(mstr);
dw2.Write(chArr, 0, chArr.Length);
dw2.Flush();
mstr.Position = 0;
dr2 = new BinaryReader(mstr);
chReadArr = new Char[chArr.Length];
ReturnValue = dr2.Read(chReadArr, 0, chArr.Length);
Assert.Equal(chArr.Length, ReturnValue);
for (ii = 0; ii < chArr.Length; ii++)
{
Assert.Equal(chArr[ii], chReadArr[ii]);
}
mstr.Dispose();
dw2.Dispose();
}
}
}
| |
//
// The MIT License(MIT)
//
// Copyright(c) 2014 Demonsaw LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
namespace DemonSaw.Entity
{
using DemonSaw.Component;
using DemonSaw.Json.Object;
using DemonSaw.Security;
using DemonSaw.Utility;
using System;
using System.Collections.Generic;
using System.Diagnostics;
// Delegates
public delegate void EntityEventHandler();
public sealed class Entity : IState, IComparable<Entity>, IDisposable
{
#region Variables
private Dictionary<Type, EntityComponent> _map = new Dictionary<Type, EntityComponent>();
#endregion
#region Events
public event EntityEventHandler EntityInit;
public event EntityEventHandler EntityUpdate;
public event EntityEventHandler EntityShutdown;
public event EntityEventHandler EntityChanged;
#endregion
#region Properties
public string Id { get; set; }
public string Name { get; set; }
public int Ref { get; private set; }
public int Count { get { return _map.Count; } }
public bool Empty { get { return _map.Count <= 0; } }
public bool Active { get; private set; }
public bool Inactive { get { return !Active; } }
public bool Valid
{
get
{
lock (_map)
{
foreach (EntityComponent component in _map.Values)
{
if (!component.Valid)
return false;
}
return true;
}
}
}
public bool Invalid { get { return !Valid; } }
#endregion
#region Constructors
public Entity() { Id = SecurityUtil.CreateKeyString(); }
public Entity(string id) { Id = id; }
public Entity(string id, string name) { Id = id; Name = name; }
~Entity() { Shutdown(); }
#endregion
#region System
void IDisposable.Dispose()
{
Shutdown();
}
public override string ToString()
{
return Name;
}
public int CompareTo(Entity entity)
{
return Id.CompareTo(entity.Id);
}
public bool Equals(Entity entity)
{
if (ReferenceEquals(null, entity))
return false;
if (ReferenceEquals(this, entity))
return true;
return Equals(entity.Id, Id);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
return false;
if (ReferenceEquals(this, obj))
return true;
if (!(obj is Entity))
return false;
return Equals((Entity) obj);
}
public override int GetHashCode()
{
return (Id != null) ? Id.GetHashCode() : base.GetHashCode();
}
#endregion
#region Operators
public static implicit operator JsonEntity(Entity entity) { return new JsonEntity(entity.Id, entity.Name); }
public static Entity operator ++(Entity entity)
{
entity.Ref++;
return entity;
}
public static Entity operator --(Entity entity)
{
entity.Ref--;
Debug.Assert(entity.Ref >= 0);
if (entity.Ref == 0)
entity.Shutdown();
return entity;
}
#endregion
#region Events
private void OnEntityInit()
{
if (EntityInit != null)
EntityInit();
}
private void OnEntityUpdate()
{
if (EntityUpdate != null)
EntityUpdate();
}
private void OnEntityShutdown()
{
if (EntityShutdown != null)
EntityShutdown();
}
private void OnEntityChanged()
{
if (EntityChanged != null)
EntityChanged();
}
#endregion
#region Interface
public void Init()
{
Active = true;
lock (_map)
{
foreach (EntityComponent component in _map.Values)
{
component.Owner = this;
component.Init();
}
}
OnEntityInit();
}
public void Update()
{
lock (_map)
{
foreach (EntityComponent component in _map.Values)
component.Update();
}
OnEntityUpdate();
}
public void Shutdown()
{
lock (_map)
{
foreach (EntityComponent component in _map.Values)
component.Shutdown();
}
OnEntityShutdown();
Active = false;
}
public void Clear()
{
Shutdown();
lock (_map)
_map.Clear();
}
#endregion
#region Container
public void Add<T>() where T : EntityComponent, new()
{
Add<T>(new T());
}
public void Add<T>(T component) where T : EntityComponent
{
Debug.Assert(component != null);
Debug.Assert(component.Owner == null);
component.Owner = this;
component.Init();
Type type = typeof(T);
lock (_map)
{
if (!_map.ContainsKey(type))
{
Active = true;
_map.Add(type, component);
}
else
{
_map[type].Shutdown();
_map[type] = component;
}
}
OnEntityChanged();
}
public bool Remove<T>() where T : EntityComponent
{
Type type = typeof(T);
return Remove(type);
}
public bool Remove(Type type)
{
EntityComponent component = null;
bool removed = false;
lock (_map)
{
if (_map.TryGetValue(type, out component))
{
removed = _map.Remove(type);
if (removed)
Active = !Empty;
component.Shutdown();
OnEntityChanged();
}
}
return removed;
}
public T Get<T>() where T : EntityComponent
{
Type type = typeof(T);
EntityComponent component = null;
lock (_map)
_map.TryGetValue(type, out component);
return (T) component;
}
public bool Contains<T>() where T : EntityComponent
{
Type type = typeof(T);
lock (_map)
return _map.ContainsKey(type);
}
#endregion
#region WPF
public ClientComponent Client
{
get { return Get<ClientComponent>(); }
}
public ServerComponent Server
{
get { return Get<ServerComponent>(); }
}
public MachineComponent Machine
{
get { return Get<MachineComponent>(); }
}
public SessionComponent Session
{
get { return Get<SessionComponent>(); }
}
public GroupComponent Group
{
get { return Get<GroupComponent>(); }
}
public FileComponent File
{
get { return Get<FileComponent>(); }
}
public TransferComponent Transfer
{
get { return Get<TransferComponent>(); }
}
#endregion
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
// <auto-generated />
namespace NorthwindRepository
{
/// <summary>
/// Strongly-typed collection for the Territory class.
/// </summary>
[Serializable]
public partial class TerritoryCollection : RepositoryList<Territory, TerritoryCollection>
{
public TerritoryCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>TerritoryCollection</returns>
public TerritoryCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
Territory o = this[i];
foreach (SubSonic.Where w in this.wheres)
{
bool remove = false;
System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName);
if (pi.CanRead)
{
object val = pi.GetValue(o, null);
switch (w.Comparison)
{
case SubSonic.Comparison.Equals:
if (!val.Equals(w.ParameterValue))
{
remove = true;
}
break;
}
}
if (remove)
{
this.Remove(o);
break;
}
}
}
return this;
}
}
/// <summary>
/// This is an ActiveRecord class which wraps the Territories table.
/// </summary>
[Serializable]
public partial class Territory : RepositoryRecord<Territory>, IRecordBase
{
#region .ctors and Default Settings
public Territory()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public Territory(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
protected static void SetSQLProps() { GetTableSchema(); }
#endregion
#region Schema and Query Accessor
public static Query CreateQuery() { return new Query(Schema); }
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
SetSQLProps();
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("Territories", TableType.Table, DataService.GetInstance("NorthwindRepository"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarTerritoryID = new TableSchema.TableColumn(schema);
colvarTerritoryID.ColumnName = "TerritoryID";
colvarTerritoryID.DataType = DbType.String;
colvarTerritoryID.MaxLength = 20;
colvarTerritoryID.AutoIncrement = false;
colvarTerritoryID.IsNullable = false;
colvarTerritoryID.IsPrimaryKey = true;
colvarTerritoryID.IsForeignKey = false;
colvarTerritoryID.IsReadOnly = false;
colvarTerritoryID.DefaultSetting = @"";
colvarTerritoryID.ForeignKeyTableName = "";
schema.Columns.Add(colvarTerritoryID);
TableSchema.TableColumn colvarTerritoryDescription = new TableSchema.TableColumn(schema);
colvarTerritoryDescription.ColumnName = "TerritoryDescription";
colvarTerritoryDescription.DataType = DbType.String;
colvarTerritoryDescription.MaxLength = 50;
colvarTerritoryDescription.AutoIncrement = false;
colvarTerritoryDescription.IsNullable = false;
colvarTerritoryDescription.IsPrimaryKey = false;
colvarTerritoryDescription.IsForeignKey = false;
colvarTerritoryDescription.IsReadOnly = false;
colvarTerritoryDescription.DefaultSetting = @"";
colvarTerritoryDescription.ForeignKeyTableName = "";
schema.Columns.Add(colvarTerritoryDescription);
TableSchema.TableColumn colvarRegionID = new TableSchema.TableColumn(schema);
colvarRegionID.ColumnName = "RegionID";
colvarRegionID.DataType = DbType.Int32;
colvarRegionID.MaxLength = 0;
colvarRegionID.AutoIncrement = false;
colvarRegionID.IsNullable = false;
colvarRegionID.IsPrimaryKey = false;
colvarRegionID.IsForeignKey = true;
colvarRegionID.IsReadOnly = false;
colvarRegionID.DefaultSetting = @"";
colvarRegionID.ForeignKeyTableName = "Region";
schema.Columns.Add(colvarRegionID);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["NorthwindRepository"].AddSchema("Territories",schema);
}
}
#endregion
#region Props
[XmlAttribute("TerritoryID")]
[Bindable(true)]
public string TerritoryID
{
get { return GetColumnValue<string>(Columns.TerritoryID); }
set { SetColumnValue(Columns.TerritoryID, value); }
}
[XmlAttribute("TerritoryDescription")]
[Bindable(true)]
public string TerritoryDescription
{
get { return GetColumnValue<string>(Columns.TerritoryDescription); }
set { SetColumnValue(Columns.TerritoryDescription, value); }
}
[XmlAttribute("RegionID")]
[Bindable(true)]
public int RegionID
{
get { return GetColumnValue<int>(Columns.RegionID); }
set { SetColumnValue(Columns.RegionID, value); }
}
#endregion
//no foreign key tables defined (1)
//no ManyToMany tables defined (1)
#region Typed Columns
public static TableSchema.TableColumn TerritoryIDColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn TerritoryDescriptionColumn
{
get { return Schema.Columns[1]; }
}
public static TableSchema.TableColumn RegionIDColumn
{
get { return Schema.Columns[2]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string TerritoryID = @"TerritoryID";
public static string TerritoryDescription = @"TerritoryDescription";
public static string RegionID = @"RegionID";
}
#endregion
#region Update PK Collections
#endregion
#region Deep Save
#endregion
}
}
| |
using System;
using System.Collections;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using Cuyahoga.Core.Communication;
using Cuyahoga.Core.Domain;
using Cuyahoga.Web.Admin.UI;
using Cuyahoga.Web.UI;
using Cuyahoga.Web.Util;
namespace Cuyahoga.Web.Admin
{
/// <summary>
/// Summary description for SectionEdit.
/// </summary>
public class SectionEdit : AdminBasePage
{
private Section _activeSection = null;
private IList _availableModuleTypes;
protected TextBox txtTitle;
protected CheckBox chkShowTitle;
protected DropDownList ddlModule;
protected Label lblModule;
protected DropDownList ddlPlaceholder;
protected TextBox txtCacheDuration;
protected Button btnSave;
protected HyperLink hplLookup;
protected RequiredFieldValidator rfvTitle;
protected RequiredFieldValidator rfvCache;
protected CompareValidator cpvCache;
protected Repeater rptRoles;
protected Panel pnlCustomSettings;
protected Repeater rptCustomSettings;
protected Button btnBack;
protected Panel pnlConnections;
protected HyperLink hplNewConnection;
protected Repeater rptConnections;
protected PlaceHolder plcCustomSettings;
// added for 1.6.0
protected Button btnSaveTop;
protected Button btnBackTop;
// added for 1.6.0
private void Page_Load(object sender, EventArgs e)
{
this.Title = "Edit section";
if (this._activeSection != null && ! this.IsPostBack)
{
BindSectionControls();
BindModules();
BindPlaceholders();
BindCustomSettings();
BindConnections();
BindRoles();
}
}
/// <summary>
/// Loads aan existing Section from the database or creates a new one if the SectionId = -1
/// </summary>
private void LoadSection()
{
// NOTE: Called from OnInit!
if (Context.Request.QueryString["SectionId"] != null)
{
if (Int32.Parse(Context.Request.QueryString["SectionId"]) == -1)
{
// Create a new section instance
this._activeSection = new Section();
this._activeSection.Node = this.ActiveNode;
if (! this.IsPostBack)
{
this._activeSection.CopyRolesFromNode();
}
}
else
{
// Get section data
this._activeSection = (Section)base.CoreRepository.GetObjectById(typeof(Section),
Int32.Parse(Context.Request.QueryString["SectionId"]));
}
}
// Preload available ModuleTypes because we might need them to display the CustomSettings
// of the first ModuleType if none is selected (when adding a brand new Section).
this._availableModuleTypes = base.CoreRepository.GetAll(typeof(ModuleType), "Name");
// Create the controls for the ModuleType-specific settings.
CreateCustomSettings();
}
private void CreateCustomSettings()
{
// Find out the ModuleType. Existing Sections have ModuleType property but for new ones
// we have to determine which ModuleType is selected.
ModuleType mt = null;
if (this._activeSection.ModuleType != null)
{
mt = this._activeSection.ModuleType;
}
else if (Context.Request.Form[this.ddlModule.UniqueID] != null)
{
// The user has selected a ModuleType. Fetch that one from the database and
// create the settings.
int moduleTypeId = Int32.Parse(Context.Request.Form[this.ddlModule.UniqueID]);
mt = (ModuleType)base.CoreRepository.GetObjectById(typeof(ModuleType), moduleTypeId);
}
else
{
// Get the Settings of the first ModuleType in the list.
if (this._availableModuleTypes.Count > 0)
{
mt = (ModuleType)this._availableModuleTypes[0];
}
}
if (mt != null)
{
foreach (ModuleSetting ms in mt.ModuleSettings)
{
HtmlTableRow settingRow = new HtmlTableRow();
HtmlTableCell labelCell = new HtmlTableCell();
labelCell.InnerText = ms.FriendlyName;
HtmlTableCell controlCell = new HtmlTableCell();
controlCell.Controls.Add(SettingControlHelper.CreateSettingControl(ms.Name, ms.GetRealType(), null));
settingRow.Cells.Add(labelCell);
settingRow.Cells.Add(controlCell);
this.plcCustomSettings.Controls.Add(settingRow);
}
}
this.pnlCustomSettings.Visible = mt.ModuleSettings.Count > 0;
}
private void BindSectionControls()
{
this.txtTitle.Text = this._activeSection.Title;
this.chkShowTitle.Checked = this._activeSection.ShowTitle;
this.txtCacheDuration.Text = this._activeSection.CacheDuration.ToString();
}
private void BindModules()
{
if (this._activeSection.ModuleType != null)
{
// A module is attached, there could be data already in it, so we don't give the option to change it
this.lblModule.Text = this._activeSection.ModuleType.Name;
this.ddlModule.Visible = false;
this.lblModule.Visible = true;
}
else
{
// Note: this._availableModuleTypes are preloaded in LoadSection.
foreach (ModuleType moduleType in this._availableModuleTypes)
{
this.ddlModule.Items.Add(new ListItem(moduleType.Name, moduleType.ModuleTypeId.ToString()));
}
if (this._activeSection.ModuleType != null)
{
this.ddlModule.Items.FindByValue(this._activeSection.ModuleType.ModuleTypeId.ToString()).Selected = true;
}
this.ddlModule.Visible = true;
this.lblModule.Visible = false;
}
}
private void BindPlaceholders()
{
if (this.ActiveNode != null)
{
if (this.ActiveNode.Template != null)
{
try
{
// Read template control and get the containers (placeholders)
string templatePath = UrlHelper.GetApplicationPath() + this.ActiveNode.Template.Path;
BaseTemplate template = (BaseTemplate)this.LoadControl(templatePath);
this.ddlPlaceholder.DataSource = template.Containers;
this.ddlPlaceholder.DataValueField = "Key";
this.ddlPlaceholder.DataTextField = "Key";
this.ddlPlaceholder.DataBind();
ListItem li = this.ddlPlaceholder.Items.FindByValue(this._activeSection.PlaceholderId);
if (this._activeSection.PlaceholderId != null
&& this._activeSection.PlaceholderId != ""
&& li != null)
{
li.Selected = true;
}
// Create url for lookup
this.hplLookup.NavigateUrl = "javascript:;";
this.hplLookup.Attributes.Add("onclick"
, String.Format("window.open(\"TemplatePreview.aspx?TemplateId={0}&Control={1}\", \"Preview\", \"width=760 height=400\")"
, this.ActiveNode.Template.Id
, this.ddlPlaceholder.ClientID)
);
}
catch (Exception ex)
{
this.ShowError(ex.Message);
}
}
}
else
{
this.ddlPlaceholder.Enabled = false;
}
}
private void BindCustomSettings()
{
if (this._activeSection.Settings.Count > 0)
{
foreach (ModuleSetting ms in this._activeSection.ModuleType.ModuleSettings)
{
Control ctrl = this.TemplateControl.FindControl(ms.Name);
if (this._activeSection.Settings[ms.Name] != null)
{
string settingValue = this._activeSection.Settings[ms.Name].ToString();
if (ctrl is TextBox)
{
((TextBox)ctrl).Text = settingValue;
}
else if (ctrl is CheckBox)
{
((CheckBox)ctrl).Checked = Boolean.Parse(settingValue);
}
else if (ctrl is DropDownList)
{
DropDownList ddl = (DropDownList)ctrl;
ListItem li = ddl.Items.FindByValue(settingValue);
if (li != null)
{
li.Selected = true;
}
}
}
}
}
}
private void BindConnections()
{
// First test if connections are possible
if (this._activeSection.ModuleType != null)
{
ModuleBase moduleInstance = base.ModuleLoader.GetModuleFromSection(this._activeSection);
if (moduleInstance is IActionProvider)
{
IActionProvider actionProvider = (IActionProvider)moduleInstance;
// OK, show connections panel
this.pnlConnections.Visible = true;
this.rptConnections.DataSource = this._activeSection.Connections;
this.rptConnections.DataBind();
if (this._activeSection.Connections.Count < actionProvider.GetOutboundActions().Count)
{
this.hplNewConnection.Visible = true;
if (this.ActiveNode != null)
{
this.hplNewConnection.NavigateUrl = String.Format("~/Admin/ConnectionEdit.aspx?NodeId={0}&SectionId={1}", this.ActiveNode.Id, this._activeSection.Id);
}
else
{
this.hplNewConnection.NavigateUrl = String.Format("~/Admin/ConnectionEdit.aspx?SectionId={0}", this._activeSection.Id);
}
}
else
{
this.hplNewConnection.Visible = false;
}
}
}
}
private void BindRoles()
{
IList roles = base.CoreRepository.GetAll(typeof(Role), "PermissionLevel");
this.rptRoles.ItemDataBound += new RepeaterItemEventHandler(rptRoles_ItemDataBound);
this.rptRoles.DataSource = roles;
this.rptRoles.DataBind();
}
private void SaveSection()
{
if (this._activeSection.Id > 0)
{
base.CoreRepository.UpdateObject(this._activeSection);
}
else
{
base.CoreRepository.SaveObject(this._activeSection);
if (this.ActiveNode != null)
{
Context.Response.Redirect(String.Format("NodeEdit.aspx?NodeId={0}", this.ActiveNode.Id));
}
else
{
Context.Response.Redirect("Sections.aspx");
}
}
}
private void SetCustomSettings()
{
foreach(ModuleSetting ms in this._activeSection.ModuleType.ModuleSettings)
{
Control ctrl = this.TemplateControl.FindControl(ms.Name);
object val = null;
if (ctrl is TextBox)
{
string text = ((TextBox)ctrl).Text;
if (ms.IsRequired && text == String.Empty)
{
throw new Exception(String.Format("The value for {0} is required.", ms.FriendlyName));
}
val = text;
}
else if (ctrl is CheckBox)
{
val = ((CheckBox)ctrl).Checked;
}
else if (ctrl is DropDownList)
{
val = ((DropDownList)ctrl).SelectedValue;
}
try
{
// Check if the datatype is correct -> brute force casting :)
Type type = ms.GetRealType();
if (type.IsEnum && val is string)
{
val = Enum.Parse(type, val.ToString());
}
else
{
if (val.ToString().Length > 0)
{
object testObj = Convert.ChangeType(val, type);
}
}
}
catch (InvalidCastException ex)
{
throw new Exception(String.Format("Invalid value entered for {0}: {1}", ms.FriendlyName, val.ToString()), ex);
}
this._activeSection.Settings[ms.Name] = val.ToString();
}
}
private void ValidateSettings()
{
if (this._activeSection != null)
{
ModuleBase moduleInstance = base.ModuleLoader.GetModuleFromSection(this._activeSection);
moduleInstance.ValidateSectionSettings();
}
}
private void SetRoles()
{
this._activeSection.SectionPermissions.Clear();
foreach (RepeaterItem ri in rptRoles.Items)
{
// HACK: RoleId is stored in the ViewState because the repeater doesn't have a DataKeys property.
CheckBox chkView = (CheckBox)ri.FindControl("chkViewAllowed");
CheckBox chkEdit = (CheckBox)ri.FindControl("chkEditAllowed");
if (chkView.Checked || chkEdit.Checked)
{
SectionPermission sp = new SectionPermission();
sp.Section = this._activeSection;
sp.Role = (Role)base.CoreRepository.GetObjectById(typeof(Role), (int)ViewState[ri.ClientID]);
sp.ViewAllowed = chkView.Checked;
sp.EditAllowed = chkEdit.Checked;
this._activeSection.SectionPermissions.Add(sp);
}
}
}
#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeComponent();
base.OnInit(e);
// Load the section here because we need to create dynamic controls based on the
// ModuleType of the section. This method comes after base.OnInit because there,
// the ActiveNode is set and we need that to attach that one to the section.
LoadSection();
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.rptConnections.ItemCommand += new System.Web.UI.WebControls.RepeaterCommandEventHandler(this.rptConnections_ItemCommand);
this.btnSave.Click += new System.EventHandler(this.btnSave_Click);
this.btnBack.Click += new System.EventHandler(this.btnBack_Click);
this.Load += new System.EventHandler(this.Page_Load);
// added for 1.6.0
this.btnSaveTop.Click += new System.EventHandler( this.btnSave_Click );
this.btnBackTop.Click += new System.EventHandler( this.btnBack_Click );
// added for 1.6.0
}
#endregion
private void btnBack_Click(object sender, EventArgs e)
{
if (this.ActiveNode != null)
{
Context.Response.Redirect(String.Format("NodeEdit.aspx?NodeId={0}", this.ActiveNode.Id));
}
else
{
Context.Response.Redirect("Sections.aspx");
}
}
private void btnSave_Click(object sender, EventArgs e)
{
if (this.IsValid)
{
// Remember the previous PlaceholderId and Position to detect changes
string oldPlaceholderId = this._activeSection.PlaceholderId;
int oldPosition = this._activeSection.Position;
try
{
this._activeSection.Title = this.txtTitle.Text;
this._activeSection.ShowTitle = this.chkShowTitle.Checked;
this._activeSection.Node = this.ActiveNode;
if (this.ActiveNode != null)
{
this._activeSection.Node.Sections.Add(this._activeSection);
}
if (this.ddlModule.Visible)
{
this._activeSection.ModuleType = (ModuleType)CoreRepository.GetObjectById(
typeof(ModuleType), Int32.Parse(this.ddlModule.SelectedValue));
}
this._activeSection.PlaceholderId = this.ddlPlaceholder.SelectedValue;
this._activeSection.CacheDuration = Int32.Parse(this.txtCacheDuration.Text);
// Calculate new position if the section is new or when the PlaceholderId has changed
if (this._activeSection.Id == -1 || this._activeSection.PlaceholderId != oldPlaceholderId)
{
this._activeSection.CalculateNewPosition();
}
// Custom settings
SetCustomSettings();
// Validate settings
ValidateSettings();
// Roles
SetRoles();
// Detect a placeholderId change and change positions of adjacent sections if necessary.
if (oldPosition != -1 && oldPlaceholderId != this._activeSection.PlaceholderId)
this._activeSection.ChangeAndUpdatePositionsAfterPlaceholderChange(oldPlaceholderId, oldPosition, true);
// Save the active section
SaveSection();
// Clear cached sections.
base.CoreRepository.ClearCollectionCache("Cuyahoga.Core.Domain.Node.Sections");
ShowMessage("Section saved.");
}
catch (Exception ex)
{
this.ShowError(ex.Message);
}
}
}
private void rptRoles_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
Role role = e.Item.DataItem as Role;
if (role != null)
{
CheckBox chkView = (CheckBox)e.Item.FindControl("chkViewAllowed");
chkView.Checked = this._activeSection.ViewAllowed(role);
CheckBox chkEdit = (CheckBox)e.Item.FindControl("chkEditAllowed");
if (role.HasPermission(AccessLevel.Editor) || role.HasPermission(AccessLevel.Administrator))
{
chkEdit.Checked = this._activeSection.EditAllowed(role);
}
else
{
chkEdit.Visible = false;
}
// Add RoleId to the ViewState with the ClientID of the repeateritem as key.
this.ViewState[e.Item.ClientID] = role.Id;
}
}
private void rptConnections_ItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.CommandName == "DeleteConnection")
{
string actionName = e.CommandArgument.ToString();
try
{
this._activeSection.Connections.Remove(actionName);
base.CoreRepository.UpdateObject(this._activeSection);
}
catch (Exception ex)
{
ShowError(ex.Message);
}
BindConnections();
}
}
}
}
| |
/*
* 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.IO;
using System.Reflection;
using System.Xml;
using System.Xml.Serialization;
using System.Text;
using System.Collections.Generic;
using log4net;
using Nini.Config;
using OpenSim.Framework;
using OpenMetaverse;
using Mono.Addins;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Framework.Servers;
[assembly:AddinRoot("Robust", OpenSim.VersionInfo.VersionNumber)]
namespace OpenSim.Server.Base
{
[TypeExtensionPoint(Path="/Robust/Connector", Name="RobustConnector")]
public interface IRobustConnector
{
string ConfigName
{
get;
}
bool Enabled
{
get;
}
string PluginPath
{
get;
set;
}
uint Configure(IConfigSource config);
void Initialize(IHttpServer server);
void Unload();
}
public class PluginLoader
{
static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public AddinRegistry Registry
{
get;
private set;
}
public IConfigSource Config
{
get;
private set;
}
public PluginLoader(IConfigSource config, string registryPath)
{
Config = config;
Registry = new AddinRegistry(registryPath, ".");
//suppress_console_output_(true);
AddinManager.Initialize(registryPath);
//suppress_console_output_(false);
AddinManager.Registry.Update();
CommandManager commandmanager = new CommandManager(Registry);
AddinManager.AddExtensionNodeHandler("/Robust/Connector", OnExtensionChanged);
}
private static TextWriter prev_console_;
// Temporarily masking the errors reported on start
// This is caused by a non-managed dll in the ./bin dir
// when the registry is initialized. The dll belongs to
// libomv, which has a hard-coded path to "." for pinvoke
// to load the openjpeg dll
//
// Will look for a way to fix, but for now this keeps the
// confusion to a minimum. this was copied from our region
// plugin loader, we have been doing this in there for a long time.
//
public void suppress_console_output_(bool save)
{
if (save)
{
prev_console_ = System.Console.Out;
System.Console.SetOut(new StreamWriter(Stream.Null));
}
else
{
if (prev_console_ != null)
System.Console.SetOut(prev_console_);
}
}
private void OnExtensionChanged(object s, ExtensionNodeEventArgs args)
{
IRobustConnector connector = (IRobustConnector)args.ExtensionObject;
Addin a = Registry.GetAddin(args.ExtensionNode.Addin.Id);
if(a == null)
{
Registry.Rebuild(null);
a = Registry.GetAddin(args.ExtensionNode.Addin.Id);
}
switch(args.Change)
{
case ExtensionChange.Add:
if (a.AddinFile.Contains(Registry.DefaultAddinsFolder))
{
m_log.InfoFormat("[SERVER UTILS]: Adding {0} from registry", a.Name);
connector.PluginPath = System.IO.Path.Combine(Registry.DefaultAddinsFolder,a.Name.Replace(',', '.')); }
else
{
m_log.InfoFormat("[SERVER UTILS]: Adding {0} from ./bin", a.Name);
connector.PluginPath = a.AddinFile;
}
LoadPlugin(connector);
break;
case ExtensionChange.Remove:
m_log.InfoFormat("[SERVER UTILS]: Removing {0}", a.Name);
UnloadPlugin(connector);
break;
}
}
private void LoadPlugin(IRobustConnector connector)
{
IHttpServer server = null;
uint port = connector.Configure(Config);
if(connector.Enabled)
{
server = GetServer(connector, port);
connector.Initialize(server);
}
else
{
m_log.InfoFormat("[SERVER UTILS]: {0} Disabled.", connector.ConfigName);
}
}
private void UnloadPlugin(IRobustConnector connector)
{
m_log.InfoFormat("[SERVER UTILS]: Unloading {0}", connector.ConfigName);
connector.Unload();
}
private IHttpServer GetServer(IRobustConnector connector, uint port)
{
IHttpServer server;
if(port != 0)
server = MainServer.GetHttpServer(port);
else
server = MainServer.Instance;
return server;
}
}
public static class ServerUtils
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public static byte[] SerializeResult(XmlSerializer xs, object data)
{
using (MemoryStream ms = new MemoryStream())
using (XmlTextWriter xw = new XmlTextWriter(ms, Util.UTF8))
{
xw.Formatting = Formatting.Indented;
xs.Serialize(xw, data);
xw.Flush();
ms.Seek(0, SeekOrigin.Begin);
byte[] ret = ms.GetBuffer();
Array.Resize(ref ret, (int)ms.Length);
return ret;
}
}
/// <summary>
/// Load a plugin from a dll with the given class or interface
/// </summary>
/// <param name="dllName"></param>
/// <param name="args">The arguments which control which constructor is invoked on the plugin</param>
/// <returns></returns>
public static T LoadPlugin<T> (string dllName, Object[] args) where T:class
{
// This is good to debug configuration problems
//if (dllName == string.Empty)
// Util.PrintCallStack();
string className = String.Empty;
// The path for a dynamic plugin will contain ":" on Windows
string[] parts = dllName.Split (new char[] {':'});
if (parts [0].Length > 1)
{
dllName = parts [0];
if (parts.Length > 1)
className = parts[1];
}
else
{
// This is Windows - we must replace the ":" in the path
dllName = String.Format ("{0}:{1}", parts [0], parts [1]);
if (parts.Length > 2)
className = parts[2];
}
// Handle extra string arguments in a more generic way
if (dllName.Contains("@"))
{
string[] dllNameParts = dllName.Split(new char[] {'@'});
dllName = dllNameParts[dllNameParts.Length - 1];
List<Object> argList = new List<Object>(args);
for (int i = 0 ; i < dllNameParts.Length - 1 ; ++i)
argList.Add(dllNameParts[i]);
args = argList.ToArray();
}
return LoadPlugin<T>(dllName, className, args);
}
/// <summary>
/// Load a plugin from a dll with the given class or interface
/// </summary>
/// <param name="dllName"></param>
/// <param name="className"></param>
/// <param name="args">The arguments which control which constructor is invoked on the plugin</param>
/// <returns></returns>
public static T LoadPlugin<T>(string dllName, string className, Object[] args) where T:class
{
string interfaceName = typeof(T).ToString();
try
{
Assembly pluginAssembly = Assembly.LoadFrom(dllName);
foreach (Type pluginType in pluginAssembly.GetTypes())
{
if (pluginType.IsPublic)
{
if (className != String.Empty
&& pluginType.ToString() != pluginType.Namespace + "." + className)
continue;
Type typeInterface = pluginType.GetInterface(interfaceName);
if (typeInterface != null)
{
T plug = null;
try
{
plug = (T)Activator.CreateInstance(pluginType,
args);
}
catch (Exception e)
{
if (!(e is System.MissingMethodException))
{
m_log.Error(string.Format("[SERVER UTILS]: Error loading plugin {0} from {1}. Exception: {2}",
interfaceName,
dllName,
e.InnerException == null ? e.Message : e.InnerException.Message),
e);
}
m_log.ErrorFormat("[SERVER UTILS]: Error loading plugin {0}: {1} args.Length {2}", dllName, e.Message, args.Length);
return null;
}
return plug;
}
}
}
return null;
}
catch (ReflectionTypeLoadException rtle)
{
m_log.Error(string.Format("[SERVER UTILS]: Error loading plugin from {0}:\n{1}", dllName,
String.Join("\n", Array.ConvertAll(rtle.LoaderExceptions, e => e.ToString()))),
rtle);
return null;
}
catch (Exception e)
{
m_log.Error(string.Format("[SERVER UTILS]: Error loading plugin from {0}", dllName), e);
return null;
}
}
public static Dictionary<string, object> ParseQueryString(string query)
{
Dictionary<string, object> result = new Dictionary<string, object>();
string[] terms = query.Split(new char[] {'&'});
if (terms.Length == 0)
return result;
foreach (string t in terms)
{
string[] elems = t.Split(new char[] {'='});
if (elems.Length == 0)
continue;
string name = System.Web.HttpUtility.UrlDecode(elems[0]);
string value = String.Empty;
if (elems.Length > 1)
value = System.Web.HttpUtility.UrlDecode(elems[1]);
if (name.EndsWith("[]"))
{
string cleanName = name.Substring(0, name.Length - 2);
if (result.ContainsKey(cleanName))
{
if (!(result[cleanName] is List<string>))
continue;
List<string> l = (List<string>)result[cleanName];
l.Add(value);
}
else
{
List<string> newList = new List<string>();
newList.Add(value);
result[cleanName] = newList;
}
}
else
{
if (!result.ContainsKey(name))
result[name] = value;
}
}
return result;
}
public static string BuildQueryString(Dictionary<string, object> data)
{
string qstring = String.Empty;
string part;
foreach (KeyValuePair<string, object> kvp in data)
{
if (kvp.Value is List<string>)
{
List<string> l = (List<String>)kvp.Value;
foreach (string s in l)
{
part = System.Web.HttpUtility.UrlEncode(kvp.Key) +
"[]=" + System.Web.HttpUtility.UrlEncode(s);
if (qstring != String.Empty)
qstring += "&";
qstring += part;
}
}
else
{
if (kvp.Value.ToString() != String.Empty)
{
part = System.Web.HttpUtility.UrlEncode(kvp.Key) +
"=" + System.Web.HttpUtility.UrlEncode(kvp.Value.ToString());
}
else
{
part = System.Web.HttpUtility.UrlEncode(kvp.Key);
}
if (qstring != String.Empty)
qstring += "&";
qstring += part;
}
}
return qstring;
}
public static string BuildXmlResponse(Dictionary<string, object> data)
{
XmlDocument doc = new XmlDocument();
XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration,
"", "");
doc.AppendChild(xmlnode);
XmlElement rootElement = doc.CreateElement("", "ServerResponse",
"");
doc.AppendChild(rootElement);
BuildXmlData(rootElement, data);
return doc.InnerXml;
}
private static void BuildXmlData(XmlElement parent, Dictionary<string, object> data)
{
foreach (KeyValuePair<string, object> kvp in data)
{
if (kvp.Value == null)
continue;
XmlElement elem = parent.OwnerDocument.CreateElement("",
XmlConvert.EncodeLocalName(kvp.Key), "");
if (kvp.Value is Dictionary<string, object>)
{
XmlAttribute type = parent.OwnerDocument.CreateAttribute("",
"type", "");
type.Value = "List";
elem.Attributes.Append(type);
BuildXmlData(elem, (Dictionary<string, object>)kvp.Value);
}
else
{
elem.AppendChild(parent.OwnerDocument.CreateTextNode(
kvp.Value.ToString()));
}
parent.AppendChild(elem);
}
}
public static Dictionary<string, object> ParseXmlResponse(string data)
{
//m_log.DebugFormat("[XXX]: received xml string: {0}", data);
Dictionary<string, object> ret = new Dictionary<string, object>();
XmlDocument doc = new XmlDocument();
try
{
doc.LoadXml(data);
XmlNodeList rootL = doc.GetElementsByTagName("ServerResponse");
if (rootL.Count != 1)
return ret;
XmlNode rootNode = rootL[0];
ret = ParseElement(rootNode);
}
catch (Exception e)
{
m_log.DebugFormat("[serverUtils.ParseXmlResponse]: failed error: {0} \n --- string: {1} - ",e.Message, data);
}
return ret;
}
private static Dictionary<string, object> ParseElement(XmlNode element)
{
Dictionary<string, object> ret = new Dictionary<string, object>();
XmlNodeList partL = element.ChildNodes;
foreach (XmlNode part in partL)
{
XmlNode type = part.Attributes.GetNamedItem("type");
if (type == null || type.Value != "List")
{
ret[XmlConvert.DecodeName(part.Name)] = part.InnerText;
}
else
{
ret[XmlConvert.DecodeName(part.Name)] = ParseElement(part);
}
}
return ret;
}
public static IConfig GetConfig(string configFile, string configName)
{
IConfig config;
if (File.Exists(configFile))
{
IConfigSource configsource = new IniConfigSource(configFile);
config = configsource.Configs[configName];
}
else
config = null;
return config;
}
public static IConfigSource LoadInitialConfig(string url)
{
IConfigSource source = new XmlConfigSource();
m_log.InfoFormat("[SERVER UTILS]: {0} is a http:// URI, fetching ...", url);
// The ini file path is a http URI
// Try to read it
try
{
XmlReader r = XmlReader.Create(url);
IConfigSource cs = new XmlConfigSource(r);
source.Merge(cs);
}
catch (Exception e)
{
m_log.FatalFormat("[SERVER UTILS]: Exception reading config from URI {0}\n" + e.ToString(), url);
Environment.Exit(1);
}
return source;
}
}
}
| |
#region File Description
//-----------------------------------------------------------------------------
// Int32Range.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
#region Using Statements
using System;
using System.Text;
using Microsoft.Xna.Framework.Content;
#endregion
namespace RolePlayingGameData
{
/// <summary>
/// Defines a range of values, useful for generating values in that range.
/// </summary>
public struct Int32Range
{
/// <summary>
/// The minimum value for the range, inclusively.
/// </summary>
public int Minimum;
/// <summary>
/// The maximum value for the range, inclusively.
/// </summary>
public int Maximum;
/// <summary>
/// Calculate the average value returned by this range.
/// </summary>
public Int32 Average
{
get { return Minimum + Range / 2; }
}
/// <summary>
/// Calculate the size of this range.
/// </summary>
public Int32 Range
{
get { return (Maximum - Minimum); }
}
#region Initialization
/// <summary>
/// Construct a new Int32Range object, from the given minimum and maximums.
/// </summary>
public Int32Range(Int32 minimum, Int32 maximum)
{
// check the parameters
if (maximum > minimum)
{
throw new ArgumentException(
"The minimum must be less than or equal to the maximum.");
}
// assign the parameters
this.Minimum = minimum;
this.Maximum = maximum;
}
#endregion
#region Value Generation
/// <summary>
/// Generate a random value between the minimum and maximum, inclusively.
/// </summary>
/// <param name="random">The Random object used to generate the value.</param>
public Int32 GenerateValue(Random random)
{
// check the parameters
Random usedRandom = random;
if (usedRandom == null)
{
usedRandom = new Random();
}
return usedRandom.Next(Minimum, Maximum);
}
#endregion
#region Operator: Int32Range + Int32Range
/// <summary>
/// Add one range to another, piecewise, and return the result.
/// </summary>
public static Int32Range Add(Int32Range range1, Int32Range range2)
{
Int32Range outputRange;
outputRange.Minimum = range1.Minimum + range2.Minimum;
outputRange.Maximum = range1.Maximum + range2.Maximum;
return outputRange;
}
/// <summary>
/// Add one range to another, piecewise, and return the result.
/// </summary>
public static Int32Range operator +(Int32Range range1, Int32Range range2)
{
return Add(range1, range2);
}
#endregion
#region Operator: Int32Range + Int32
/// <summary>
/// Add an Int32 to both the minimum and maximum values of the range.
/// </summary>
public static Int32Range Add(Int32Range range, Int32 amount)
{
Int32Range outputRange = range;
outputRange.Minimum += amount;
outputRange.Maximum += amount;
return outputRange;
}
/// <summary>
/// Add an Int32 to both the minimum and maximum values of the range.
/// </summary>
public static Int32Range operator +(Int32Range range, Int32 amount)
{
return Add(range, amount);
}
#endregion
#region Operator: Int32Range - Int32Range
/// <summary>
/// Subtract one range from another, piecewise, and return the result.
/// </summary>
public static Int32Range Subtract(Int32Range range1, Int32Range range2)
{
Int32Range outputRange;
outputRange.Minimum = range1.Minimum - range2.Minimum;
outputRange.Maximum = range1.Maximum - range2.Maximum;
return outputRange;
}
/// <summary>
/// Subtract one range from another, piecewise, and return the result.
/// </summary>
public static Int32Range operator -(Int32Range range1, Int32Range range2)
{
return Subtract(range1, range2);
}
#endregion
#region Operator: Int32Range - Int32
/// <summary>
/// Subtract an Int32 from both the minimum and maximum values of the range.
/// </summary>
public static Int32Range Subtract(Int32Range range, Int32 amount)
{
Int32Range outputRange = range;
outputRange.Minimum -= amount;
outputRange.Maximum -= amount;
return outputRange;
}
/// <summary>
/// Subtract an Int32 from both the minimum and maximum values of the range.
/// </summary>
public static Int32Range operator -(Int32Range range, Int32 amount)
{
return Subtract(range, amount);
}
#endregion
// Compound assignment (+=, etc.) operators use the overloaded binary operators,
// so there is no need in this case to override them explicitly
#region String Output
/// <summary>
/// Builds a string that describes this object.
/// </summary>
public override string ToString()
{
StringBuilder sb = new StringBuilder("(");
sb.Append(Minimum);
sb.Append(',');
sb.Append(Maximum);
sb.Append(')');
return sb.ToString();
}
#endregion
#region Content Type Reader
/// <summary>
/// Read an Int32Range object from the content pipeline.
/// </summary>
public class Int32RangeReader : ContentTypeReader<Int32Range>
{
protected override Int32Range Read(ContentReader input,
Int32Range existingInstance)
{
Int32Range output = existingInstance;
output.Minimum = input.ReadInt32();
output.Maximum = input.ReadInt32();
return output;
}
}
#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.
//
// 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.Collections.Generic;
using System.Linq;
using Hyak.Common;
using Microsoft.Azure.Management.SiteRecovery.Models;
namespace Microsoft.Azure.Management.SiteRecovery.Models
{
/// <summary>
/// The definition of a Fabric properties.
/// </summary>
public partial class ReplicationProtectedItemProperties
{
private string _activeLocation;
/// <summary>
/// Optional. Gets or sets the Current active location of the PE.
/// </summary>
public string ActiveLocation
{
get { return this._activeLocation; }
set { this._activeLocation = value; }
}
private IList<string> _allowedOperations;
/// <summary>
/// Optional. Gets or sets the allowed operations on the Replication
/// protected item.
/// </summary>
public IList<string> AllowedOperations
{
get { return this._allowedOperations; }
set { this._allowedOperations = value; }
}
private CurrentScenarioDetails _currentScenario;
/// <summary>
/// Optional. Gets or sets the current scenario.
/// </summary>
public CurrentScenarioDetails CurrentScenario
{
get { return this._currentScenario; }
set { this._currentScenario = value; }
}
private string _friendlyName;
/// <summary>
/// Optional. Gets or sets the name.
/// </summary>
public string FriendlyName
{
get { return this._friendlyName; }
set { this._friendlyName = value; }
}
private System.DateTime? _lastSuccessfulFailoverTime;
/// <summary>
/// Optional. Gets or sets the Last successful failover time.
/// </summary>
public System.DateTime? LastSuccessfulFailoverTime
{
get { return this._lastSuccessfulFailoverTime; }
set { this._lastSuccessfulFailoverTime = value; }
}
private System.DateTime? _lastSuccessfulTestFailoverTime;
/// <summary>
/// Optional. Gets or sets the Last successful test failover time.
/// </summary>
public System.DateTime? LastSuccessfulTestFailoverTime
{
get { return this._lastSuccessfulTestFailoverTime; }
set { this._lastSuccessfulTestFailoverTime = value; }
}
private string _policyFriendlyName;
/// <summary>
/// Optional. Gets or sets the name of Policy governing this PE.
/// </summary>
public string PolicyFriendlyName
{
get { return this._policyFriendlyName; }
set { this._policyFriendlyName = value; }
}
private string _policyID;
/// <summary>
/// Optional. Gets or sets the ID of Policy governing this PE.
/// </summary>
public string PolicyID
{
get { return this._policyID; }
set { this._policyID = value; }
}
private string _primaryFabricFriendlyName;
/// <summary>
/// Optional. Gets or sets the friendly name of the primary fabric.
/// </summary>
public string PrimaryFabricFriendlyName
{
get { return this._primaryFabricFriendlyName; }
set { this._primaryFabricFriendlyName = value; }
}
private string _primaryProtectionContainerFriendlyName;
/// <summary>
/// Optional. Gets or sets the name of primary protection container
/// friendly name.
/// </summary>
public string PrimaryProtectionContainerFriendlyName
{
get { return this._primaryProtectionContainerFriendlyName; }
set { this._primaryProtectionContainerFriendlyName = value; }
}
private string _protectableItemId;
/// <summary>
/// Optional. Gets or sets the protected item Id.
/// </summary>
public string ProtectableItemId
{
get { return this._protectableItemId; }
set { this._protectableItemId = value; }
}
private string _protectedItemType;
/// <summary>
/// Optional. Gets or sets the type of protected item type.
/// </summary>
public string ProtectedItemType
{
get { return this._protectedItemType; }
set { this._protectedItemType = value; }
}
private string _protectionState;
/// <summary>
/// Optional. Gets or sets the protection status.
/// </summary>
public string ProtectionState
{
get { return this._protectionState; }
set { this._protectionState = value; }
}
private ReplicationProviderSpecificSettings _providerSpecificDetails;
/// <summary>
/// Optional. Gets or sets the Replication provider custom settings.
/// </summary>
public ReplicationProviderSpecificSettings ProviderSpecificDetails
{
get { return this._providerSpecificDetails; }
set { this._providerSpecificDetails = value; }
}
private string _recoveryFabricFriendlyName;
/// <summary>
/// Optional. Gets or sets the friendly name of recovery fabric.
/// </summary>
public string RecoveryFabricFriendlyName
{
get { return this._recoveryFabricFriendlyName; }
set { this._recoveryFabricFriendlyName = value; }
}
private string _recoveryProtectionContainerFriendlyName;
/// <summary>
/// Optional. Gets or sets the name of recovery container friendly name.
/// </summary>
public string RecoveryProtectionContainerFriendlyName
{
get { return this._recoveryProtectionContainerFriendlyName; }
set { this._recoveryProtectionContainerFriendlyName = value; }
}
private string _recoveryServicesProviderId;
/// <summary>
/// Optional. Gets or sets the recovery provider name.
/// </summary>
public string RecoveryServicesProviderId
{
get { return this._recoveryServicesProviderId; }
set { this._recoveryServicesProviderId = value; }
}
private string _replicationHealth;
/// <summary>
/// Optional. Gets or sets the consolidated protection health
/// </summary>
public string ReplicationHealth
{
get { return this._replicationHealth; }
set { this._replicationHealth = value; }
}
private IList<HealthError> _replicationHealthErrors;
/// <summary>
/// Optional. Gets or sets list of replication health errors.
/// </summary>
public IList<HealthError> ReplicationHealthErrors
{
get { return this._replicationHealthErrors; }
set { this._replicationHealthErrors = value; }
}
private string _testFailoverStateDescription;
/// <summary>
/// Optional. Gets or sets the Test failover state description.
/// </summary>
public string TestFailoverStateDescription
{
get { return this._testFailoverStateDescription; }
set { this._testFailoverStateDescription = value; }
}
/// <summary>
/// Initializes a new instance of the
/// ReplicationProtectedItemProperties class.
/// </summary>
public ReplicationProtectedItemProperties()
{
this.AllowedOperations = new LazyList<string>();
this.ReplicationHealthErrors = new LazyList<HealthError>();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Plivo.Client;
namespace Plivo.Resource.RentedNumber
{
/// <summary>
/// Rented number interface.
/// </summary>
public class RentedNumberInterface : ResourceInterface
{
/// <summary>
/// Initializes a new instance of the <see cref="T:plivo.Resource.RentedNumber.RentedNumberInterface"/> class.
/// </summary>
/// <param name="client">Client.</param>
public RentedNumberInterface(HttpClient client) : base(client)
{
Uri = "Account/" + Client.GetAuthId() + "/Number/";
}
#region Get
/// <summary>
/// Get RentedNumber with the specified number.
/// </summary>
/// <returns>The get.</returns>
/// <param name="number">Number.</param>
public RentedNumber Get(string number)
{
return ExecuteWithExceptionUnwrap(() =>
{
var rentedNumber = Task.Run(async () => await GetResource<RentedNumber>(number).ConfigureAwait(false)).Result;
rentedNumber.Interface = this;
return rentedNumber;
});
}
/// <summary>
/// Asynchronously get RentedNumber with the specified number.
/// </summary>
/// <returns>The get.</returns>
/// <param name="number">Number.</param>
public async Task<RentedNumber> GetAsync(string number)
{
var rentedNumber = await GetResource<RentedNumber>(number);
rentedNumber.Interface = this;
return rentedNumber;
}
#endregion
#region List
/// <summary>
/// List RentedNumber with the specified type, numberStartswith, subaccount, alias, services, limit and offset.
/// </summary>
/// <returns>The list.</returns>
/// <param name="type">Type.</param>
/// <param name="numberStartswith">Number startswith.</param>
/// <param name="subaccount">Subaccount.</param>
/// <param name="alias">Alias.</param>
/// <param name="services">Services.</param>
/// <param name="limit">Limit.</param>
/// <param name="offset">Offset.</param>
public ListResponse<RentedNumber> List(
string type = null, string numberStartswith = null,
string subaccount = null, string alias = null,
string services = null, uint? limit = null, uint? offset = null)
{
var mandatoryParams = new List<string> {""};
var data = CreateData(
mandatoryParams,
new
{
type,
numberStartswith,
subaccount,
alias,
services,
limit,
offset
});
return ExecuteWithExceptionUnwrap(() =>
{
var resources = Task.Run(async () => await ListResources<ListResponse<RentedNumber>>(data).ConfigureAwait(false)).Result;
resources.Objects.ForEach(
(obj) => obj.Interface = this
);
return resources;
});
}
/// <summary>
/// List RentedNumber with the specified type, numberStartswith, subaccount, alias, services, limit and offset.
/// </summary>
/// <returns>The list.</returns>
/// <param name="type">Type.</param>
/// <param name="numberStartswith">Number startswith.</param>
/// <param name="subaccount">Subaccount.</param>
/// <param name="alias">Alias.</param>
/// <param name="services">Services.</param>
/// <param name="limit">Limit.</param>
/// <param name="offset">Offset.</param>
public async Task<ListResponse<RentedNumber>> ListAsync(
string type = null, string numberStartswith = null,
string subaccount = null, string alias = null,
string services = null, uint? limit = null, uint? offset = null)
{
var mandatoryParams = new List<string> { "" };
var data = CreateData(
mandatoryParams,
new
{
type,
numberStartswith,
subaccount,
alias,
services,
limit,
offset
});
var resources = await ListResources<ListResponse<RentedNumber>>(data);
resources.Objects.ForEach(
(obj) => obj.Interface = this
);
return resources;
}
#endregion
#region AddNumber
/// <summary>
/// Adds the number.
/// </summary>
/// <returns>The number.</returns>
/// <param name="numbers">Numbers.</param>
/// <param name="carrier">Carrier.</param>
/// <param name="region">Region.</param>
/// <param name="numberType">Number type.</param>
/// <param name="appId">App identifier.</param>
/// <param name="subaccount">Subaccount.</param>
public UpdateResponse<RentedNumber> AddNumber(
List<string> numbers, string carrier, string region,
string numberType = null, string appId = null,
string subaccount = null)
{
string _numbers = string.Join(",", numbers);
var mandatoryParams = new List<string> {""};
var data = CreateData(
mandatoryParams,
new
{
_numbers,
carrier,
region,
numberType,
appId,
subaccount
});
return ExecuteWithExceptionUnwrap(() =>
{
var result = Task.Run(async () => await Client.Update<UpdateResponse<RentedNumber>>(Uri, data).ConfigureAwait(false)).Result;
result.Object.StatusCode = result.StatusCode;
return result.Object;
});
}
/// <summary>
/// Asynchronously adds the number.
/// </summary>
/// <returns>The number.</returns>
/// <param name="numbers">Numbers.</param>
/// <param name="carrier">Carrier.</param>
/// <param name="region">Region.</param>
/// <param name="numberType">Number type.</param>
/// <param name="appId">App identifier.</param>
/// <param name="subaccount">Subaccount.</param>
public async Task<UpdateResponse<RentedNumber>> AddNumberAsync(
List<string> numbers, string carrier, string region,
string numberType = null, string appId = null,
string subaccount = null)
{
string _numbers = string.Join(",", numbers);
var mandatoryParams = new List<string> { "" };
var data = CreateData(
mandatoryParams,
new
{
_numbers,
carrier,
region,
numberType,
appId,
subaccount
});
var result = await Client.Update<UpdateResponse<RentedNumber>>(Uri, data);
result.Object.StatusCode = result.StatusCode;
return result.Object;
}
#endregion
#region Update
/// <summary>
/// Update RentedNumber with the specified number, appId, subaccount and alias.
/// </summary>
/// <returns>The update.</returns>
/// <param name="number">Number.</param>
/// <param name="appId">App identifier.</param>
/// <param name="subaccount">Subaccount.</param>
/// <param name="alias">Alias.</param>
/// <param name="verificationInfo">Verification Information.</param>
public UpdateResponse<RentedNumber> Update(
string number, string appId = null, string subaccount = null,
string alias = null, Dictionary<string, string> verificationInfo = null)
{
var mandatoryParams = new List<string> {""};
var data = CreateData(
mandatoryParams,
new
{
appId,
subaccount,
alias,
verificationInfo
});
if (appId == "null") data["app_id"] = null;
return ExecuteWithExceptionUnwrap(() =>
{
var result = Task.Run(async () => await Client.Update<UpdateResponse<RentedNumber>>(
Uri + number + "/",
data
).ConfigureAwait(false)).Result;
result.Object.StatusCode = result.StatusCode;
return result.Object;
});
}
/// <summary>
/// Asynchronously update RentedNumber with the specified number, appId, subaccount and alias.
/// </summary>
/// <returns>The update.</returns>
/// <param name="number">Number.</param>
/// <param name="appId">App identifier.</param>
/// <param name="subaccount">Subaccount.</param>
/// <param name="alias">Alias.</param>
/// <param name="verificationInfo">Verification Information.</param>
public async Task<UpdateResponse<RentedNumber>> UpdateAsync(
string number, string appId = null, string subaccount = null,
string alias = null, Dictionary<string, string> verificationInfo = null)
{
var mandatoryParams = new List<string> { "" };
var data = CreateData(
mandatoryParams,
new
{
appId,
subaccount,
alias,
verificationInfo
});
if (appId == "null") data["app_id"] = null;
var result = await Client.Update<UpdateResponse<RentedNumber>>(
Uri + number + "/",
data
);
result.Object.StatusCode = result.StatusCode;
return result.Object;
}
#endregion
#region Delete
/// <summary>
/// Unrent RentedNumber with the specified number.
/// </summary>
/// <returns>The delete.</returns>
/// <param name="number">Number.</param>
public DeleteResponse<RentedNumber> Delete(string number)
{
return ExecuteWithExceptionUnwrap(() =>
{
return Task.Run(async () => await DeleteResource<DeleteResponse<RentedNumber>>(number).ConfigureAwait(false)).Result;
});
}
/// <summary>
/// Asynchronously unrent RentedNumber with the specified number.
/// </summary>
/// <returns>The delete.</returns>
/// <param name="number">Number.</param>
public async Task<DeleteResponse<RentedNumber>> DeleteAsync(string number)
{
return await DeleteResource<DeleteResponse<RentedNumber>>(number);
}
#endregion
}
}
| |
using System;
using System.Buffers;
using System.Collections.Generic;
using System.IO.Pipelines;
using System.Net;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Connections;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Orleans.Configuration;
using Orleans.Messaging;
using Microsoft.Extensions.ObjectPool;
using Orleans.Serialization.Invocation;
namespace Orleans.Runtime.Messaging
{
internal abstract class Connection
{
private static readonly Func<ConnectionContext, Task> OnConnectedDelegate = context => OnConnectedAsync(context);
private static readonly Action<object> OnConnectionClosedDelegate = state => ((Connection)state).OnTransportConnectionClosed();
private static readonly UnboundedChannelOptions OutgoingMessageChannelOptions = new UnboundedChannelOptions
{
SingleReader = true,
SingleWriter = false,
AllowSynchronousContinuations = false
};
private static readonly ObjectPool<MessageHandler> MessageHandlerPool = ObjectPool.Create(new MessageHandlerPoolPolicy());
private readonly ConnectionCommon shared;
private readonly ConnectionDelegate middleware;
private readonly Channel<Message> outgoingMessages;
private readonly ChannelWriter<Message> outgoingMessageWriter;
private readonly List<Message> inflight = new List<Message>(4);
private readonly TaskCompletionSource<int> _transportConnectionClosed = new (TaskCreationOptions.RunContinuationsAsynchronously);
private readonly TaskCompletionSource<int> _initializationTcs = new(TaskCreationOptions.RunContinuationsAsynchronously);
private IDuplexPipe _transport;
private Task _processIncomingTask;
private Task _processOutgoingTask;
private Task _closeTask;
protected Connection(
ConnectionContext connection,
ConnectionDelegate middleware,
ConnectionCommon shared)
{
this.Context = connection ?? throw new ArgumentNullException(nameof(connection));
this.middleware = middleware ?? throw new ArgumentNullException(nameof(middleware));
this.shared = shared;
this.outgoingMessages = Channel.CreateUnbounded<Message>(OutgoingMessageChannelOptions);
this.outgoingMessageWriter = this.outgoingMessages.Writer;
// Set the connection on the connection context so that it can be retrieved by the middleware.
this.Context.Features.Set<Connection>(this);
this.RemoteEndPoint = NormalizeEndpoint(this.Context.RemoteEndPoint);
this.LocalEndPoint = NormalizeEndpoint(this.Context.LocalEndPoint);
}
public string ConnectionId => this.Context?.ConnectionId;
public virtual EndPoint RemoteEndPoint { get; }
public virtual EndPoint LocalEndPoint { get; }
protected CounterStatistic MessageReceivedCounter { get; set; }
protected CounterStatistic MessageSentCounter { get; set; }
protected ConnectionContext Context { get; }
protected NetworkingTrace Log => this.shared.NetworkingTrace;
protected MessagingTrace MessagingTrace => this.shared.MessagingTrace;
protected abstract ConnectionDirection ConnectionDirection { get; }
protected MessageFactory MessageFactory => this.shared.MessageFactory;
protected abstract IMessageCenter MessageCenter { get; }
public bool IsValid => _closeTask is null;
public Task Initialized => _initializationTcs.Task;
public static void ConfigureBuilder(ConnectionBuilder builder) => builder.Run(OnConnectedDelegate);
/// <summary>
/// Start processing this connection.
/// </summary>
/// <returns>A <see cref="Task"/> which completes when the connection terminates and has completed processing.</returns>
public async Task Run()
{
Exception error = default;
try
{
// Eventually calls through to OnConnectedAsync (unless the connection delegate has been misconfigured)
await this.middleware(this.Context);
}
catch (Exception exception)
{
error = exception;
}
finally
{
await this.CloseAsync(error);
}
}
private static Task OnConnectedAsync(ConnectionContext context)
{
var connection = context.Features.Get<Connection>();
context.ConnectionClosed.Register(OnConnectionClosedDelegate, connection);
NetworkingStatisticsGroup.OnOpenedSocket(connection.ConnectionDirection);
return connection.RunInternal();
}
protected virtual async Task RunInternal()
{
_transport = this.Context.Transport;
_processIncomingTask = this.ProcessIncoming();
_processOutgoingTask = this.ProcessOutgoing();
_initializationTcs.TrySetResult(0);
await Task.WhenAll(_processIncomingTask, _processOutgoingTask);
}
/// <summary>
/// Called immediately prior to transporting a message.
/// </summary>
/// <param name="msg"></param>
/// <returns>Whether or not to continue transporting the message.</returns>
protected abstract bool PrepareMessageForSend(Message msg);
protected abstract void RetryMessage(Message msg, Exception ex = null);
public Task CloseAsync(Exception exception)
{
StartClosing(exception);
return _closeTask;
}
private void OnTransportConnectionClosed()
{
StartClosing(new ConnectionAbortedException("Underlying connection closed"));
_transportConnectionClosed.SetResult(0);
}
private void StartClosing(Exception exception)
{
if (_closeTask is not null)
{
return;
}
var task = new Task<Task>(CloseAsync);
if (Interlocked.CompareExchange(ref _closeTask, task.Unwrap(), null) is not null)
{
return;
}
_initializationTcs.TrySetException(exception ?? new ConnectionAbortedException("Connection initialization failed"));
if (this.Log.IsEnabled(LogLevel.Information))
{
this.Log.LogInformation(
exception,
"Closing connection {Connection}",
this);
}
task.Start(TaskScheduler.Default);
}
/// <summary>
/// Close the connection. This method should only be called by <see cref="StartClosing(Exception)"/>.
/// </summary>
private async Task CloseAsync()
{
NetworkingStatisticsGroup.OnClosedSocket(this.ConnectionDirection);
// Signal the outgoing message processor to exit gracefully.
this.outgoingMessageWriter.TryComplete();
var transportFeature = Context.Features.Get<IUnderlyingTransportFeature>();
var transport = transportFeature?.Transport ?? _transport;
transport.Input.CancelPendingRead();
transport.Output.CancelPendingFlush();
// Try to gracefully stop the reader/writer loops, if they are running.
if (_processIncomingTask is { IsCompleted: false } incoming)
{
try
{
await incoming;
}
catch (Exception processIncomingException)
{
// Swallow any exceptions here.
this.Log.LogWarning(processIncomingException, "Exception processing incoming messages on connection {Connection}", this);
}
}
if (_processOutgoingTask is { IsCompleted: false } outgoing)
{
try
{
await outgoing;
}
catch (Exception processOutgoingException)
{
// Swallow any exceptions here.
this.Log.LogWarning(processOutgoingException, "Exception processing outgoing messages on connection {Connection}", this);
}
}
// Only wait for the transport to close if the connection actually started being processed.
if (_processIncomingTask is not null && _processOutgoingTask is not null)
{
// Abort the connection and wait for the transport to signal that it's closed before disposing it.
try
{
this.Context.Abort();
}
catch (Exception exception)
{
this.Log.LogWarning(exception, "Exception aborting connection {Connection}", this);
}
await _transportConnectionClosed.Task;
}
try
{
await this.Context.DisposeAsync();
}
catch (Exception abortException)
{
// Swallow any exceptions here.
this.Log.LogWarning(abortException, "Exception terminating connection {Connection}", this);
}
// Reject in-flight messages.
foreach (var message in this.inflight)
{
this.OnSendMessageFailure(message, "Connection terminated");
}
this.inflight.Clear();
// Reroute enqueued messages.
var i = 0;
while (this.outgoingMessages.Reader.TryRead(out var message))
{
if (i == 0 && Log.IsEnabled(LogLevel.Information))
{
this.Log.LogInformation(
"Rerouting messages for remote endpoint {EndPoint}",
this.RemoteEndPoint?.ToString() ?? "(never connected)");
}
++i;
this.RetryMessage(message);
}
if (i > 0 && this.Log.IsEnabled(LogLevel.Information))
{
this.Log.LogInformation(
"Rerouted {Count} messages for remote endpoint {EndPoint}",
i,
this.RemoteEndPoint?.ToString() ?? "(never connected)");
}
}
public virtual void Send(Message message)
{
if (!this.outgoingMessageWriter.TryWrite(message))
{
this.RerouteMessage(message);
}
}
public override string ToString() => $"[Local: {this.LocalEndPoint}, Remote: {this.RemoteEndPoint}, ConnectionId: {this.Context.ConnectionId}]";
protected abstract void OnReceivedMessage(Message message);
protected abstract void OnSendMessageFailure(Message message, string error);
private async Task ProcessIncoming()
{
await Task.Yield();
Exception error = default;
var serializer = this.shared.ServiceProvider.GetRequiredService<IMessageSerializer>();
try
{
var input = this._transport.Input;
var requiredBytes = 0;
Message message = default;
while (true)
{
var readResult = await input.ReadAsync();
var buffer = readResult.Buffer;
if (buffer.Length >= requiredBytes)
{
do
{
try
{
int headerLength, bodyLength;
(requiredBytes, headerLength, bodyLength) = serializer.TryRead(ref buffer, out message);
if (requiredBytes == 0)
{
MessagingStatisticsGroup.OnMessageReceive(this.MessageReceivedCounter, message, bodyLength + headerLength, headerLength, this.ConnectionDirection);
var handler = MessageHandlerPool.Get();
handler.Set(message, this);
ThreadPool.UnsafeQueueUserWorkItem(handler, preferLocal: true);
message = null;
}
}
catch (Exception exception) when (this.HandleReceiveMessageFailure(message, exception))
{
}
} while (requiredBytes == 0);
}
if (readResult.IsCanceled || readResult.IsCompleted)
{
break;
}
input.AdvanceTo(buffer.Start, buffer.End);
}
}
catch (Exception exception)
{
if (IsValid)
{
this.Log.LogWarning(
exception,
"Exception while processing messages from remote endpoint {EndPoint}",
this.RemoteEndPoint);
}
error = exception;
}
finally
{
_transport.Input.Complete();
(serializer as IDisposable)?.Dispose();
this.StartClosing(error);
}
}
private async Task ProcessOutgoing()
{
await Task.Yield();
Exception error = default;
var serializer = this.shared.ServiceProvider.GetRequiredService<IMessageSerializer>();
try
{
var output = this._transport.Output;
var reader = this.outgoingMessages.Reader;
while (true)
{
var more = await reader.WaitToReadAsync();
if (!more)
{
break;
}
Message message = default;
try
{
while (inflight.Count < inflight.Capacity && reader.TryRead(out message) && this.PrepareMessageForSend(message))
{
inflight.Add(message);
var (headerLength, bodyLength) = serializer.Write(ref output, message);
MessagingStatisticsGroup.OnMessageSend(this.MessageSentCounter, message, headerLength + bodyLength, headerLength, this.ConnectionDirection);
}
}
catch (Exception exception) when (message != default)
{
this.OnMessageSerializationFailure(message, exception);
}
var flushResult = await output.FlushAsync();
if (flushResult.IsCompleted || flushResult.IsCanceled)
{
break;
}
inflight.Clear();
}
}
catch (Exception exception)
{
if (IsValid)
{
this.Log.LogWarning(
exception,
"Exception while processing messages to remote endpoint {EndPoint}",
this.RemoteEndPoint);
}
error = exception;
}
finally
{
_transport.Output.Complete();
(serializer as IDisposable)?.Dispose();
this.StartClosing(error);
}
}
private void RerouteMessage(Message message)
{
if (this.Log.IsEnabled(LogLevel.Information))
{
this.Log.LogInformation(
"Rerouting message {Message} from remote endpoint {EndPoint}",
message,
this.RemoteEndPoint?.ToString() ?? "(never connected)");
}
ThreadPool.UnsafeQueueUserWorkItem(state =>
{
var (t, msg) = ((Connection, Message))state;
t.RetryMessage(msg);
}, (this, message));
}
private static EndPoint NormalizeEndpoint(EndPoint endpoint)
{
if (!(endpoint is IPEndPoint ep)) return endpoint;
// Normalize endpoints
if (ep.Address.IsIPv4MappedToIPv6)
{
return new IPEndPoint(ep.Address.MapToIPv4(), ep.Port);
}
return ep;
}
/// <summary>
/// Handles a message receive failure.
/// </summary>
/// <returns><see langword="true"/> if the exception should not be caught and <see langword="false"/> if it should be caught.</returns>
private bool HandleReceiveMessageFailure(Message message, Exception exception)
{
this.Log.LogWarning(
exception,
"Exception reading message {Message} from remote endpoint {Remote} to local endpoint {Local}",
message,
this.RemoteEndPoint,
this.LocalEndPoint);
// If deserialization completely failed, rethrow the exception so that it can be handled at another level.
if (message is null)
{
// Returning false here informs the caller that the exception should not be caught.
return false;
}
// The message body was not successfully decoded, but the headers were.
MessagingStatisticsGroup.OnRejectedMessage(message);
if (message.HasDirection)
{
if (message.Direction == Message.Directions.Request)
{
// Send a fast fail to the caller.
var response = this.MessageFactory.CreateResponseMessage(message);
response.Result = Message.ResponseTypes.Error;
response.BodyObject = Response.FromException(exception);
// Send the error response and continue processing the next message.
this.Send(response);
}
else if (message.Direction == Message.Directions.Response)
{
// If the message was a response, propagate the exception to the intended recipient.
message.Result = Message.ResponseTypes.Error;
message.BodyObject = Response.FromException(exception);
this.MessageCenter.DispatchLocalMessage(message);
}
}
// The exception has been handled by propagating it onwards.
return true;
}
private void OnMessageSerializationFailure(Message message, Exception exception)
{
// we only get here if we failed to serialize the msg (or any other catastrophic failure).
// Request msg fails to serialize on the sender, so we just enqueue a rejection msg.
// Response msg fails to serialize on the responding silo, so we try to send an error response back.
this.Log.LogWarning(
(int)ErrorCode.Messaging_SerializationError,
exception,
"Unexpected error serializing message {Message}",
message);
MessagingStatisticsGroup.OnFailedSentMessage(message);
if (message.Direction == Message.Directions.Request)
{
var response = this.MessageFactory.CreateResponseMessage(message);
response.Result = Message.ResponseTypes.Error;
response.BodyObject = Response.FromException(exception);
this.MessageCenter.DispatchLocalMessage(response);
}
else if (message.Direction == Message.Directions.Response && message.RetryCount < MessagingOptions.DEFAULT_MAX_MESSAGE_SEND_RETRIES)
{
// If we failed sending an original response, turn the response body into an error and reply with it.
// unless we have already tried sending the response multiple times.
message.Result = Message.ResponseTypes.Error;
message.BodyObject = Response.FromException(exception);
++message.RetryCount;
this.Send(message);
}
else
{
this.Log.LogWarning(
(int)ErrorCode.Messaging_OutgoingMS_DroppingMessage,
exception,
"Dropping message which failed during serialization: {Message}",
message);
MessagingStatisticsGroup.OnDroppedSentMessage(message);
}
}
private sealed class MessageHandlerPoolPolicy : PooledObjectPolicy<MessageHandler>
{
public override MessageHandler Create() => new MessageHandler();
public override bool Return(MessageHandler obj)
{
obj.Reset();
return true;
}
}
private sealed class MessageHandler : IThreadPoolWorkItem
{
private Message message;
private Connection connection;
public void Set(Message m, Connection c)
{
this.message = m;
this.connection = c;
}
public void Execute()
{
this.connection.OnReceivedMessage(this.message);
MessageHandlerPool.Return(this);
}
public void Reset()
{
this.message = null;
this.connection = null;
}
}
}
}
| |
using System;
namespace Org.BouncyCastle.Crypto.Digests
{
/**
* implementation of MD4 as RFC 1320 by R. Rivest, MIT Laboratory for
* Computer Science and RSA Data Security, Inc.
* <p>
* <b>NOTE</b>: This algorithm is only included for backwards compatibility
* with legacy applications, it's not secure, don't use it for anything new!</p>
*/
public class MD4Digest
: GeneralDigest
{
private const int DigestLength = 16;
private int H1, H2, H3, H4; // IV's
private int[] X = new int[16];
private int xOff;
/**
* Standard constructor
*/
public MD4Digest()
{
Reset();
}
/**
* Copy constructor. This will copy the state of the provided
* message digest.
*/
public MD4Digest(MD4Digest t) : base(t)
{
H1 = t.H1;
H2 = t.H2;
H3 = t.H3;
H4 = t.H4;
Array.Copy(t.X, 0, X, 0, t.X.Length);
xOff = t.xOff;
}
public override string AlgorithmName
{
get { return "MD4"; }
}
public override int GetDigestSize()
{
return DigestLength;
}
internal override void ProcessWord(
byte[] input,
int inOff)
{
X[xOff++] = (input[inOff] & 0xff) | ((input[inOff + 1] & 0xff) << 8)
| ((input[inOff + 2] & 0xff) << 16) | ((input[inOff + 3] & 0xff) << 24);
if (xOff == 16)
{
ProcessBlock();
}
}
internal override void ProcessLength(
long bitLength)
{
if (xOff > 14)
{
ProcessBlock();
}
X[14] = (int)(bitLength & 0xffffffff);
X[15] = (int)((ulong) bitLength >> 32);
}
private void UnpackWord(
int word,
byte[] outBytes,
int outOff)
{
outBytes[outOff] = (byte)word;
outBytes[outOff + 1] = (byte)((uint) word >> 8);
outBytes[outOff + 2] = (byte)((uint) word >> 16);
outBytes[outOff + 3] = (byte)((uint) word >> 24);
}
public override int DoFinal(
byte[] output,
int outOff)
{
Finish();
UnpackWord(H1, output, outOff);
UnpackWord(H2, output, outOff + 4);
UnpackWord(H3, output, outOff + 8);
UnpackWord(H4, output, outOff + 12);
Reset();
return DigestLength;
}
/**
* reset the chaining variables to the IV values.
*/
public override void Reset()
{
base.Reset();
H1 = unchecked((int) 0x67452301);
H2 = unchecked((int) 0xefcdab89);
H3 = unchecked((int) 0x98badcfe);
H4 = unchecked((int) 0x10325476);
xOff = 0;
for (int i = 0; i != X.Length; i++)
{
X[i] = 0;
}
}
//
// round 1 left rotates
//
private const int S11 = 3;
private const int S12 = 7;
private const int S13 = 11;
private const int S14 = 19;
//
// round 2 left rotates
//
private const int S21 = 3;
private const int S22 = 5;
private const int S23 = 9;
private const int S24 = 13;
//
// round 3 left rotates
//
private const int S31 = 3;
private const int S32 = 9;
private const int S33 = 11;
private const int S34 = 15;
/*
* rotate int x left n bits.
*/
private int RotateLeft(
int x,
int n)
{
return (x << n) | (int) ((uint) x >> (32 - n));
}
/*
* F, G, H and I are the basic MD4 functions.
*/
private int F(
int u,
int v,
int w)
{
return (u & v) | (~u & w);
}
private int G(
int u,
int v,
int w)
{
return (u & v) | (u & w) | (v & w);
}
private int H(
int u,
int v,
int w)
{
return u ^ v ^ w;
}
internal override void ProcessBlock()
{
int a = H1;
int b = H2;
int c = H3;
int d = H4;
//
// Round 1 - F cycle, 16 times.
//
a = RotateLeft((a + F(b, c, d) + X[ 0]), S11);
d = RotateLeft((d + F(a, b, c) + X[ 1]), S12);
c = RotateLeft((c + F(d, a, b) + X[ 2]), S13);
b = RotateLeft((b + F(c, d, a) + X[ 3]), S14);
a = RotateLeft((a + F(b, c, d) + X[ 4]), S11);
d = RotateLeft((d + F(a, b, c) + X[ 5]), S12);
c = RotateLeft((c + F(d, a, b) + X[ 6]), S13);
b = RotateLeft((b + F(c, d, a) + X[ 7]), S14);
a = RotateLeft((a + F(b, c, d) + X[ 8]), S11);
d = RotateLeft((d + F(a, b, c) + X[ 9]), S12);
c = RotateLeft((c + F(d, a, b) + X[10]), S13);
b = RotateLeft((b + F(c, d, a) + X[11]), S14);
a = RotateLeft((a + F(b, c, d) + X[12]), S11);
d = RotateLeft((d + F(a, b, c) + X[13]), S12);
c = RotateLeft((c + F(d, a, b) + X[14]), S13);
b = RotateLeft((b + F(c, d, a) + X[15]), S14);
//
// Round 2 - G cycle, 16 times.
//
a = RotateLeft((a + G(b, c, d) + X[ 0] + 0x5a827999), S21);
d = RotateLeft((d + G(a, b, c) + X[ 4] + 0x5a827999), S22);
c = RotateLeft((c + G(d, a, b) + X[ 8] + 0x5a827999), S23);
b = RotateLeft((b + G(c, d, a) + X[12] + 0x5a827999), S24);
a = RotateLeft((a + G(b, c, d) + X[ 1] + 0x5a827999), S21);
d = RotateLeft((d + G(a, b, c) + X[ 5] + 0x5a827999), S22);
c = RotateLeft((c + G(d, a, b) + X[ 9] + 0x5a827999), S23);
b = RotateLeft((b + G(c, d, a) + X[13] + 0x5a827999), S24);
a = RotateLeft((a + G(b, c, d) + X[ 2] + 0x5a827999), S21);
d = RotateLeft((d + G(a, b, c) + X[ 6] + 0x5a827999), S22);
c = RotateLeft((c + G(d, a, b) + X[10] + 0x5a827999), S23);
b = RotateLeft((b + G(c, d, a) + X[14] + 0x5a827999), S24);
a = RotateLeft((a + G(b, c, d) + X[ 3] + 0x5a827999), S21);
d = RotateLeft((d + G(a, b, c) + X[ 7] + 0x5a827999), S22);
c = RotateLeft((c + G(d, a, b) + X[11] + 0x5a827999), S23);
b = RotateLeft((b + G(c, d, a) + X[15] + 0x5a827999), S24);
//
// Round 3 - H cycle, 16 times.
//
a = RotateLeft((a + H(b, c, d) + X[ 0] + 0x6ed9eba1), S31);
d = RotateLeft((d + H(a, b, c) + X[ 8] + 0x6ed9eba1), S32);
c = RotateLeft((c + H(d, a, b) + X[ 4] + 0x6ed9eba1), S33);
b = RotateLeft((b + H(c, d, a) + X[12] + 0x6ed9eba1), S34);
a = RotateLeft((a + H(b, c, d) + X[ 2] + 0x6ed9eba1), S31);
d = RotateLeft((d + H(a, b, c) + X[10] + 0x6ed9eba1), S32);
c = RotateLeft((c + H(d, a, b) + X[ 6] + 0x6ed9eba1), S33);
b = RotateLeft((b + H(c, d, a) + X[14] + 0x6ed9eba1), S34);
a = RotateLeft((a + H(b, c, d) + X[ 1] + 0x6ed9eba1), S31);
d = RotateLeft((d + H(a, b, c) + X[ 9] + 0x6ed9eba1), S32);
c = RotateLeft((c + H(d, a, b) + X[ 5] + 0x6ed9eba1), S33);
b = RotateLeft((b + H(c, d, a) + X[13] + 0x6ed9eba1), S34);
a = RotateLeft((a + H(b, c, d) + X[ 3] + 0x6ed9eba1), S31);
d = RotateLeft((d + H(a, b, c) + X[11] + 0x6ed9eba1), S32);
c = RotateLeft((c + H(d, a, b) + X[ 7] + 0x6ed9eba1), S33);
b = RotateLeft((b + H(c, d, a) + X[15] + 0x6ed9eba1), S34);
H1 += a;
H2 += b;
H3 += c;
H4 += d;
//
// reset the offset and clean out the word buffer.
//
xOff = 0;
for (int i = 0; i != X.Length; i++)
{
X[i] = 0;
}
}
}
}
| |
/* ****************************************************************************
*
* 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
* vspython@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.
*
* ***************************************************************************/
using System;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using IServiceProvider = System.IServiceProvider;
using ShellConstants = Microsoft.VisualStudio.Shell.Interop.Constants;
namespace Microsoft.VisualStudioTools.Project {
/// <summary>
/// This abstract class handles opening, saving of items in the hierarchy.
/// </summary>
internal abstract class DocumentManager {
#region fields
private readonly HierarchyNode node = null;
#endregion
#region properties
protected HierarchyNode Node {
get {
return this.node;
}
}
#endregion
#region ctors
protected DocumentManager(HierarchyNode node) {
Utilities.ArgumentNotNull("node", node);
this.node = node;
}
#endregion
#region virtual methods
/// <summary>
/// Open a document using the standard editor. This method has no implementation since a document is abstract in this context
/// </summary>
/// <param name="logicalView">In MultiView case determines view to be activated by IVsMultiViewDocumentView. For a list of logical view GUIDS, see constants starting with LOGVIEWID_ defined in NativeMethods class</param>
/// <param name="docDataExisting">IntPtr to the IUnknown interface of the existing document data object</param>
/// <param name="windowFrame">A reference to the window frame that is mapped to the document</param>
/// <param name="windowFrameAction">Determine the UI action on the document window</param>
/// <returns>NotImplementedException</returns>
/// <remarks>See FileDocumentManager class for an implementation of this method</remarks>
public virtual int Open(ref Guid logicalView, IntPtr docDataExisting, out IVsWindowFrame windowFrame, WindowFrameShowAction windowFrameAction) {
throw new NotImplementedException();
}
/// <summary>
/// Open a document using a specific editor. This method has no implementation.
/// </summary>
/// <param name="editorFlags">Specifies actions to take when opening a specific editor. Possible editor flags are defined in the enumeration Microsoft.VisualStudio.Shell.Interop.__VSOSPEFLAGS</param>
/// <param name="editorType">Unique identifier of the editor type</param>
/// <param name="physicalView">Name of the physical view. If null, the environment calls MapLogicalView on the editor factory to determine the physical view that corresponds to the logical view. In this case, null does not specify the primary view, but rather indicates that you do not know which view corresponds to the logical view</param>
/// <param name="logicalView">In MultiView case determines view to be activated by IVsMultiViewDocumentView. For a list of logical view GUIDS, see constants starting with LOGVIEWID_ defined in NativeMethods class</param>
/// <param name="docDataExisting">IntPtr to the IUnknown interface of the existing document data object</param>
/// <param name="frame">A reference to the window frame that is mapped to the document</param>
/// <param name="windowFrameAction">Determine the UI action on the document window</param>
/// <returns>NotImplementedException</returns>
/// <remarks>See FileDocumentManager for an implementation of this method</remarks>
public virtual int OpenWithSpecific(uint editorFlags, ref Guid editorType, string physicalView, ref Guid logicalView, IntPtr docDataExisting, out IVsWindowFrame frame, WindowFrameShowAction windowFrameAction) {
throw new NotImplementedException();
}
/// <summary>
/// Open a document using a specific editor. This method has no implementation.
/// </summary>
/// <param name="editorFlags">Specifies actions to take when opening a specific editor. Possible editor flags are defined in the enumeration Microsoft.VisualStudio.Shell.Interop.__VSOSPEFLAGS</param>
/// <param name="editorType">Unique identifier of the editor type</param>
/// <param name="physicalView">Name of the physical view. If null, the environment calls MapLogicalView on the editor factory to determine the physical view that corresponds to the logical view. In this case, null does not specify the primary view, but rather indicates that you do not know which view corresponds to the logical view</param>
/// <param name="logicalView">In MultiView case determines view to be activated by IVsMultiViewDocumentView. For a list of logical view GUIDS, see constants starting with LOGVIEWID_ defined in NativeMethods class</param>
/// <param name="docDataExisting">IntPtr to the IUnknown interface of the existing document data object</param>
/// <param name="frame">A reference to the window frame that is mapped to the document</param>
/// <param name="windowFrameAction">Determine the UI action on the document window</param>
/// <returns>NotImplementedException</returns>
/// <remarks>See FileDocumentManager for an implementation of this method</remarks>
public virtual int ReOpenWithSpecific(uint editorFlags, ref Guid editorType, string physicalView, ref Guid logicalView, IntPtr docDataExisting, out IVsWindowFrame frame, WindowFrameShowAction windowFrameAction) {
return OpenWithSpecific(editorFlags, ref editorType, physicalView, ref logicalView, docDataExisting, out frame, windowFrameAction);
}
/// <summary>
/// Close an open document window
/// </summary>
/// <param name="closeFlag">Decides how to close the document</param>
/// <returns>S_OK if successful, otherwise an error is returned</returns>
public virtual int Close(__FRAMECLOSE closeFlag) {
if (this.node == null || this.node.ProjectMgr == null || this.node.ProjectMgr.IsClosed || this.node.ProjectMgr.IsClosing) {
return VSConstants.E_FAIL;
}
if (IsOpenedByUs) {
IVsUIShellOpenDocument shell = this.Node.ProjectMgr.Site.GetService(typeof(IVsUIShellOpenDocument)) as IVsUIShellOpenDocument;
Guid logicalView = Guid.Empty;
uint grfIDO = 0;
IVsUIHierarchy pHierOpen;
uint[] itemIdOpen = new uint[1];
IVsWindowFrame windowFrame;
int fOpen;
ErrorHandler.ThrowOnFailure(shell.IsDocumentOpen(this.Node.ProjectMgr, this.Node.ID, this.Node.Url, ref logicalView, grfIDO, out pHierOpen, itemIdOpen, out windowFrame, out fOpen));
if (windowFrame != null) {
return windowFrame.CloseFrame((uint)closeFlag);
}
}
return VSConstants.S_OK;
}
/// <summary>
/// Silently saves an open document
/// </summary>
/// <param name="saveIfDirty">Save the open document only if it is dirty</param>
/// <remarks>The call to SaveDocData may return Microsoft.VisualStudio.Shell.Interop.PFF_RESULTS.STG_S_DATALOSS to indicate some characters could not be represented in the current codepage</remarks>
public virtual void Save(bool saveIfDirty) {
if (saveIfDirty && IsDirty) {
IVsPersistDocData persistDocData = DocData;
if (persistDocData != null) {
string name;
int cancelled;
ErrorHandler.ThrowOnFailure(persistDocData.SaveDocData(VSSAVEFLAGS.VSSAVE_SilentSave, out name, out cancelled));
}
}
}
#endregion
/// <summary>
/// Queries the RDT to see if the document is currently edited and not saved.
/// </summary>
public bool IsDirty {
get {
#if DEV12_OR_LATER
var docTable = (IVsRunningDocumentTable4)node.ProjectMgr.GetService(typeof(SVsRunningDocumentTable));
if (!docTable.IsMonikerValid(node.GetMkDocument())) {
return false;
}
return docTable.IsDocumentDirty(docTable.GetDocumentCookie(node.GetMkDocument()));
#else
bool isOpen, isDirty, isOpenedByUs;
uint docCookie;
IVsPersistDocData persistDocData;
GetDocInfo(out isOpen, out isDirty, out isOpenedByUs, out docCookie, out persistDocData);
return isDirty;
#endif
}
}
/// <summary>
/// Queries the RDT to see if the document was opened by our project.
/// </summary>
public bool IsOpenedByUs {
get {
#if DEV12_OR_LATER
var docTable = (IVsRunningDocumentTable4)node.ProjectMgr.GetService(typeof(SVsRunningDocumentTable));
if (!docTable.IsMonikerValid(node.GetMkDocument())) {
return false;
}
IVsHierarchy hierarchy;
uint itemId;
docTable.GetDocumentHierarchyItem(
docTable.GetDocumentCookie(node.GetMkDocument()),
out hierarchy,
out itemId
);
return Utilities.IsSameComObject(node.ProjectMgr, hierarchy);
#else
bool isOpen, isDirty, isOpenedByUs;
uint docCookie;
IVsPersistDocData persistDocData;
GetDocInfo(out isOpen, out isDirty, out isOpenedByUs, out docCookie, out persistDocData);
return isOpenedByUs;
#endif
}
}
/// <summary>
/// Returns the doc cookie in the RDT for the associated file.
/// </summary>
public uint DocCookie {
get {
#if DEV12_OR_LATER
var docTable = (IVsRunningDocumentTable4)node.ProjectMgr.GetService(typeof(SVsRunningDocumentTable));
if (!docTable.IsMonikerValid(node.GetMkDocument())) {
return (uint)ShellConstants.VSDOCCOOKIE_NIL;
}
return docTable.GetDocumentCookie(node.GetMkDocument());
#else
bool isOpen, isDirty, isOpenedByUs;
uint docCookie;
IVsPersistDocData persistDocData;
GetDocInfo(out isOpen, out isDirty, out isOpenedByUs, out docCookie, out persistDocData);
return docCookie;
#endif
}
}
/// <summary>
/// Returns the IVsPersistDocData associated with the document, or null if there isn't one.
/// </summary>
public IVsPersistDocData DocData {
get {
#if DEV12_OR_LATER
var docTable = (IVsRunningDocumentTable4)node.ProjectMgr.GetService(typeof(SVsRunningDocumentTable));
if (!docTable.IsMonikerValid(node.GetMkDocument())) {
return null;
}
return docTable.GetDocumentData(docTable.GetDocumentCookie(node.GetMkDocument())) as IVsPersistDocData;
#else
bool isOpen, isDirty, isOpenedByUs;
uint docCookie;
IVsPersistDocData persistDocData;
GetDocInfo(out isOpen, out isDirty, out isOpenedByUs, out docCookie, out persistDocData);
return persistDocData;
#endif
}
}
#region helper methods
#if !DEV12_OR_LATER
/// <summary>
/// Get document properties from RDT
/// </summary>
private void GetDocInfo(
out bool isOpen, // true if the doc is opened
out bool isDirty, // true if the doc is dirty
out bool isOpenedByUs, // true if opened by our project
out uint docCookie, // VSDOCCOOKIE if open
out IVsPersistDocData persistDocData)
{
isOpen = isDirty = isOpenedByUs = false;
docCookie = (uint)ShellConstants.VSDOCCOOKIE_NIL;
persistDocData = null;
if (this.node == null || this.node.ProjectMgr == null || this.node.ProjectMgr.IsClosed)
{
return;
}
IVsHierarchy hierarchy;
uint vsitemid = VSConstants.VSITEMID_NIL;
VsShellUtilities.GetRDTDocumentInfo(this.node.ProjectMgr.Site, this.node.Url, out hierarchy, out vsitemid, out persistDocData, out docCookie);
if (hierarchy == null || docCookie == (uint)ShellConstants.VSDOCCOOKIE_NIL)
{
return;
}
isOpen = true;
// check if the doc is opened by another project
if (Utilities.IsSameComObject(this.node.ProjectMgr, hierarchy))
{
isOpenedByUs = true;
}
if (persistDocData != null)
{
int isDocDataDirty;
ErrorHandler.ThrowOnFailure(persistDocData.IsDocDataDirty(out isDocDataDirty));
isDirty = (isDocDataDirty != 0);
}
}
#endif
protected string GetOwnerCaption() {
Debug.Assert(this.node != null, "No node has been initialized for the document manager");
object pvar;
ErrorHandler.ThrowOnFailure(node.ProjectMgr.GetProperty(node.ID, (int)__VSHPROPID.VSHPROPID_Caption, out pvar));
return (pvar as string);
}
protected static void CloseWindowFrame(ref IVsWindowFrame windowFrame) {
if (windowFrame != null) {
try {
ErrorHandler.ThrowOnFailure(windowFrame.CloseFrame(0));
} finally {
windowFrame = null;
}
}
}
protected string GetFullPathForDocument() {
string fullPath = String.Empty;
// Get the URL representing the item
fullPath = this.node.GetMkDocument();
Debug.Assert(!String.IsNullOrEmpty(fullPath), "Could not retrive the fullpath for the node" + this.Node.ID.ToString(CultureInfo.CurrentCulture));
return fullPath;
}
#endregion
#region static methods
/// <summary>
/// Updates the caption for all windows associated to the document.
/// </summary>
/// <param name="site">The service provider.</param>
/// <param name="caption">The new caption.</param>
/// <param name="docData">The IUnknown interface to a document data object associated with a registered document.</param>
public static void UpdateCaption(IServiceProvider site, string caption, IntPtr docData) {
Utilities.ArgumentNotNull("site", site);
if (String.IsNullOrEmpty(caption)) {
throw new ArgumentException(SR.GetString(SR.ParameterCannotBeNullOrEmpty), "caption");
}
IVsUIShell uiShell = site.GetService(typeof(SVsUIShell)) as IVsUIShell;
// We need to tell the windows to update their captions.
IEnumWindowFrames windowFramesEnum;
ErrorHandler.ThrowOnFailure(uiShell.GetDocumentWindowEnum(out windowFramesEnum));
IVsWindowFrame[] windowFrames = new IVsWindowFrame[1];
uint fetched;
while (windowFramesEnum.Next(1, windowFrames, out fetched) == VSConstants.S_OK && fetched == 1) {
IVsWindowFrame windowFrame = windowFrames[0];
object data;
ErrorHandler.ThrowOnFailure(windowFrame.GetProperty((int)__VSFPROPID.VSFPROPID_DocData, out data));
IntPtr ptr = Marshal.GetIUnknownForObject(data);
try {
if (ptr == docData) {
ErrorHandler.ThrowOnFailure(windowFrame.SetProperty((int)__VSFPROPID.VSFPROPID_OwnerCaption, caption));
}
} finally {
if (ptr != IntPtr.Zero) {
Marshal.Release(ptr);
}
}
}
}
/// <summary>
/// Rename document in the running document table from oldName to newName.
/// </summary>
/// <param name="provider">The service provider.</param>
/// <param name="oldName">Full path to the old name of the document.</param>
/// <param name="newName">Full path to the new name of the document.</param>
/// <param name="newItemId">The new item id of the document</param>
public static void RenameDocument(IServiceProvider site, string oldName, string newName, uint newItemId) {
Utilities.ArgumentNotNull("site", site);
if (String.IsNullOrEmpty(oldName)) {
throw new ArgumentException(SR.GetString(SR.ParameterCannotBeNullOrEmpty), "oldName");
}
if (String.IsNullOrEmpty(newName)) {
throw new ArgumentException(SR.GetString(SR.ParameterCannotBeNullOrEmpty), "newName");
}
if (newItemId == VSConstants.VSITEMID_NIL) {
throw new ArgumentNullException("newItemId");
}
IVsRunningDocumentTable pRDT = site.GetService(typeof(SVsRunningDocumentTable)) as IVsRunningDocumentTable;
if (pRDT == null)
return;
IVsHierarchy pIVsHierarchy;
uint itemId;
IntPtr docData;
uint uiVsDocCookie;
ErrorHandler.ThrowOnFailure(pRDT.FindAndLockDocument((uint)_VSRDTFLAGS.RDT_NoLock, oldName, out pIVsHierarchy, out itemId, out docData, out uiVsDocCookie));
if (docData != IntPtr.Zero && pIVsHierarchy != null) {
try {
IntPtr pUnk = Marshal.GetIUnknownForObject(pIVsHierarchy);
Guid iid = typeof(IVsHierarchy).GUID;
IntPtr pHier;
Marshal.QueryInterface(pUnk, ref iid, out pHier);
try {
ErrorHandler.ThrowOnFailure(pRDT.RenameDocument(oldName, newName, pHier, newItemId));
} finally {
if (pHier != IntPtr.Zero)
Marshal.Release(pHier);
if (pUnk != IntPtr.Zero)
Marshal.Release(pUnk);
}
} finally {
Marshal.Release(docData);
}
}
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Xml;
using Microsoft.Build.BackEnd;
using Microsoft.Build.BackEnd.Logging;
using Microsoft.Build.Collections;
using Microsoft.Build.Construction;
using Microsoft.Build.Evaluation;
using Microsoft.Build.Execution;
using Microsoft.Build.Framework;
using Microsoft.Build.Shared;
using InvalidProjectFileException = Microsoft.Build.Exceptions.InvalidProjectFileException;
using TaskItem = Microsoft.Build.Execution.ProjectItemInstance.TaskItem;
using Xunit;
namespace Microsoft.Build.UnitTests.BackEnd
{
/// <summary>
/// The test class for the TaskExecutionHost
/// </summary>
public class TaskExecutionHost_Tests : ITestTaskHost, IBuildEngine2, IDisposable
{
/// <summary>
/// The set of parameters which have been initialized on the task.
/// </summary>
private Dictionary<string, object> _parametersSetOnTask;
/// <summary>
/// The set of outputs which were read from the task.
/// </summary>
private Dictionary<string, object> _outputsReadFromTask;
/// <summary>
/// The task execution host
/// </summary>
private ITaskExecutionHost _host;
/// <summary>
/// The mock logging service
/// </summary>
private ILoggingService _loggingService;
/// <summary>
/// The mock logger
/// </summary>
private MockLogger _logger;
/// <summary>
/// Array containing one item, used for ITaskItem tests.
/// </summary>
private ITaskItem[] _oneItem;
/// <summary>
/// Array containing two items, used for ITaskItem tests.
/// </summary>
private ITaskItem[] _twoItems;
/// <summary>
/// The bucket which receives outputs.
/// </summary>
private ItemBucket _bucket;
/// <summary>
/// Unused.
/// </summary>
public bool IsRunningMultipleNodes
{
get { return false; }
}
/// <summary>
/// Unused.
/// </summary>
public bool ContinueOnError
{
get { throw new NotImplementedException(); }
}
/// <summary>
/// Unused.
/// </summary>
public int LineNumberOfTaskNode
{
get { throw new NotImplementedException(); }
}
/// <summary>
/// Unused.
/// </summary>
public int ColumnNumberOfTaskNode
{
get { throw new NotImplementedException(); }
}
/// <summary>
/// Unused.
/// </summary>
public string ProjectFileOfTaskNode
{
get { throw new NotImplementedException(); }
}
/// <summary>
/// Prepares the environment for the test.
/// </summary>
public TaskExecutionHost_Tests()
{
InitializeHost(false);
}
/// <summary>
/// Cleans up after the test
/// </summary>
public void Dispose()
{
if (_host != null)
{
((IDisposable)_host).Dispose();
}
_host = null;
}
/// <summary>
/// Validate that setting parameters with only the required parameters works.
/// </summary>
[Fact]
public void ValidateNoParameters()
{
var parameters = new Dictionary<string, (string, ElementLocation)>(StringComparer.OrdinalIgnoreCase);
parameters["ExecuteReturnParam"] = ("true", ElementLocation.Create("foo.proj"));
Assert.True(_host.SetTaskParameters(parameters));
Assert.Single(_parametersSetOnTask);
Assert.True(_parametersSetOnTask.ContainsKey("ExecuteReturnParam"));
}
/// <summary>
/// Validate that setting no parameters when a required parameter exists fails and throws an exception.
/// </summary>
[Fact]
public void ValidateNoParameters_MissingRequired()
{
Assert.Throws<InvalidProjectFileException>(() =>
{
var parameters = new Dictionary<string, (string, ElementLocation)>(StringComparer.OrdinalIgnoreCase);
_host.SetTaskParameters(parameters);
}
);
}
/// <summary>
/// Validate that setting a non-existent parameter fails, but does not throw an exception.
/// </summary>
[Fact]
public void ValidateNonExistantParameter()
{
var parameters = new Dictionary<string, (string, ElementLocation)>(StringComparer.OrdinalIgnoreCase);
parameters["NonExistantParam"] = ("foo", ElementLocation.Create("foo.proj"));
Assert.False(_host.SetTaskParameters(parameters));
}
#region Bool Params
/// <summary>
/// Validate that setting a bool param works and sets the right value.
/// </summary>
[Fact]
public void TestSetBoolParam()
{
ValidateTaskParameter("BoolParam", "true", true);
}
/// <summary>
/// Validate that setting a bool param works and sets the right value.
/// </summary>
[Fact]
public void TestSetBoolParamFalse()
{
ValidateTaskParameter("BoolParam", "false", false);
}
/// <summary>
/// Validate that setting a bool param with an empty value does not cause the parameter to get set.
/// </summary>
[Fact]
public void TestSetBoolParamEmptyAttribute()
{
ValidateTaskParameterNotSet("BoolParam", "");
}
/// <summary>
/// Validate that setting a bool param with a property which evaluates to nothing does not cause the parameter to get set.
/// </summary>
[Fact]
public void TestSetBoolParamEmptyProperty()
{
ValidateTaskParameterNotSet("BoolParam", "$(NonExistantProperty)");
}
/// <summary>
/// Validate that setting a bool param with an item which evaluates to nothing does not cause the parameter to get set.
/// </summary>
[Fact]
public void TestSetBoolParamEmptyItem()
{
ValidateTaskParameterNotSet("BoolParam", "@(NonExistantItem)");
}
#endregion
#region Bool Array Params
/// <summary>
/// Validate that setting a bool array with a single true sets the array to one 'true' value.
/// </summary>
[Fact]
public void TestSetBoolArrayParamOneItem()
{
ValidateTaskParameterArray("BoolArrayParam", "true", new bool[] { true });
}
/// <summary>
/// Validate that setting a bool array with a list of two values sets them appropriately.
/// </summary>
[Fact]
public void TestSetBoolArrayParamTwoItems()
{
ValidateTaskParameterArray("BoolArrayParam", "false;true", new bool[] { false, true });
}
/// <summary>
/// Validate that setting the parameter with an empty value does not cause it to be set.
/// </summary>
[Fact]
public void TestSetBoolArrayParamEmptyAttribute()
{
ValidateTaskParameterNotSet("BoolArrayParam", "");
}
/// <summary>
/// Validate that setting the parameter with a property which evaluates to an empty value does not cause it to be set.
/// </summary>
[Fact]
public void TestSetBoolArrayParamEmptyProperty()
{
ValidateTaskParameterNotSet("BoolArrayParam", "$(NonExistantProperty)");
}
/// <summary>
/// Validate that setting the parameter with an item which evaluates to an empty value does not cause it to be set.
/// </summary>
[Fact]
public void TestSetBoolArrayParamEmptyItem()
{
ValidateTaskParameterNotSet("BoolArrayParam", "@(NonExistantItem)");
}
#endregion
#region Int Params
/// <summary>
/// Validate that setting an int param with a value of 0 causes it to get the correct value.
/// </summary>
[Fact]
public void TestSetIntParamZero()
{
ValidateTaskParameter("IntParam", "0", 0);
}
/// <summary>
/// Validate that setting an int param with a value of 1 causes it to get the correct value.
/// </summary>
[Fact]
public void TestSetIntParamOne()
{
ValidateTaskParameter("IntParam", "1", 1);
}
/// <summary>
/// Validate that setting the parameter with an empty value does not cause it to be set.
/// </summary>
[Fact]
public void TestSetIntParamEmptyAttribute()
{
ValidateTaskParameterNotSet("IntParam", "");
}
/// <summary>
/// Validate that setting the parameter with a property which evaluates to an empty value does not cause it to be set.
/// </summary>
[Fact]
public void TestSetIntParamEmptyProperty()
{
ValidateTaskParameterNotSet("IntParam", "$(NonExistantProperty)");
}
/// <summary>
/// Validate that setting the parameter with an item which evaluates to an empty value does not cause it to be set.
/// </summary>
[Fact]
public void TestSetIntParamEmptyItem()
{
ValidateTaskParameterNotSet("IntParam", "@(NonExistantItem)");
}
#endregion
#region Int Array Params
/// <summary>
/// Validate that setting an int array with a single value causes it to get a single value.
/// </summary>
[Fact]
public void TestSetIntArrayParamOneItem()
{
ValidateTaskParameterArray("IntArrayParam", "0", new int[] { 0 });
}
/// <summary>
/// Validate that setting an int array with a list of values causes it to get the correct values.
/// </summary>
[Fact]
public void TestSetIntArrayParamTwoItems()
{
SetTaskParameter("IntArrayParam", "1;0");
Assert.True(_parametersSetOnTask.ContainsKey("IntArrayParam"));
Assert.Equal(1, ((int[])_parametersSetOnTask["IntArrayParam"])[0]);
Assert.Equal(0, ((int[])_parametersSetOnTask["IntArrayParam"])[1]);
}
/// <summary>
/// Validate that setting the parameter with an empty value does not cause it to be set.
/// </summary>
[Fact]
public void TestSetIntArrayParamEmptyAttribute()
{
ValidateTaskParameterNotSet("IntArrayParam", "");
}
/// <summary>
/// Validate that setting the parameter with a property which evaluates to an empty value does not cause it to be set.
/// </summary>
[Fact]
public void TestSetIntArrayParamEmptyProperty()
{
ValidateTaskParameterNotSet("IntArrayParam", "$(NonExistantProperty)");
}
/// <summary>
/// Validate that setting the parameter with an item which evaluates to an empty value does not cause it to be set.
/// </summary>
[Fact]
public void TestSetIntArrayParamEmptyItem()
{
ValidateTaskParameterNotSet("IntArrayParam", "@(NonExistantItem)");
}
#endregion
#region String Params
/// <summary>
/// Test that setting a string param sets the correct value.
/// </summary>
[Fact]
public void TestSetStringParam()
{
ValidateTaskParameter("StringParam", "0", "0");
}
/// <summary>
/// Test that setting a string param sets the correct value.
/// </summary>
[Fact]
public void TestSetStringParamOne()
{
ValidateTaskParameter("StringParam", "1", "1");
}
/// <summary>
/// Validate that setting the parameter with an empty value does not cause it to be set.
/// </summary>
[Fact]
public void TestSetStringParamEmptyAttribute()
{
ValidateTaskParameterNotSet("StringParam", "");
}
/// <summary>
/// Validate that setting the parameter with a property which evaluates to an empty value does not cause it to be set.
/// </summary>
[Fact]
public void TestSetStringParamEmptyProperty()
{
ValidateTaskParameterNotSet("StringParam", "$(NonExistantProperty)");
}
/// <summary>
/// Validate that setting the parameter with an item which evaluates to an empty value does not cause it to be set.
/// </summary>
[Fact]
public void TestSetStringParamEmptyItem()
{
ValidateTaskParameterNotSet("StringParam", "@(NonExistantItem)");
}
#endregion
#region String Array Params
/// <summary>
/// Validate that setting a string array with a single value sets the correct value.
/// </summary>
[Fact]
public void TestSetStringArrayParam()
{
ValidateTaskParameterArray("StringArrayParam", "0", new string[] { "0" });
}
/// <summary>
/// Validate that setting a string array with a list of two values sets the correct values.
/// </summary>
[Fact]
public void TestSetStringArrayParamOne()
{
ValidateTaskParameterArray("StringArrayParam", "1;0", new string[] { "1", "0" });
}
/// <summary>
/// Validate that setting the parameter with an empty value does not cause it to be set.
/// </summary>
[Fact]
public void TestSetStringArrayParamEmptyAttribute()
{
ValidateTaskParameterNotSet("StringArrayParam", "");
}
/// <summary>
/// Validate that setting the parameter with a property which evaluates to an empty value does not cause it to be set.
/// </summary>
[Fact]
public void TestSetStringArrayParamEmptyProperty()
{
ValidateTaskParameterNotSet("StringArrayParam", "$(NonExistantProperty)");
}
/// <summary>
/// Validate that setting the parameter with an item which evaluates to an empty value does not cause it to be set.
/// </summary>
[Fact]
public void TestSetStringArrayParamEmptyItem()
{
ValidateTaskParameterNotSet("StringArrayParam", "@(NonExistantItem)");
}
#endregion
#region ITaskItem Params
/// <summary>
/// Validate that setting an item with an item list evaluating to one item sets the value appropriately, including metadata.
/// </summary>
[Fact]
public void TestSetItemParamSingle()
{
ValidateTaskParameterItem("ItemParam", "@(ItemListContainingOneItem)", _oneItem[0]);
}
/// <summary>
/// Validate that setting an item with an item list evaluating to two items sets the value appropriately, including metadata.
/// </summary>
[Fact]
public void TestSetItemParamDouble()
{
Assert.Throws<InvalidProjectFileException>(() =>
{
ValidateTaskParameterItems("ItemParam", "@(ItemListContainingTwoItems)", _twoItems);
}
);
}
/// <summary>
/// Validate that setting an item with a string results in an item with the evaluated include set to the string.
/// </summary>
[Fact]
public void TestSetItemParamString()
{
ValidateTaskParameterItem("ItemParam", "MyItemName");
}
/// <summary>
/// Validate that setting the parameter with an empty value does not cause it to be set.
/// </summary>
[Fact]
public void TestSetItemParamEmptyAttribute()
{
ValidateTaskParameterNotSet("ItemParam", "");
}
/// <summary>
/// Validate that setting the parameter with a property which evaluates to an empty value does not cause it to be set.
/// </summary>
[Fact]
public void TestSetItemParamEmptyProperty()
{
ValidateTaskParameterNotSet("ItemParam", "$(NonExistantProperty)");
}
/// <summary>
/// Validate that setting the parameter with an item which evaluates to an empty value does not cause it to be set.
/// </summary>
[Fact]
public void TestSetItemParamEmptyItem()
{
ValidateTaskParameterNotSet("ItemParam", "@(NonExistantItem)");
}
#endregion
#region ITaskItem Array Params
/// <summary>
/// Validate that setting an item array using an item list containing one item sets a single item.
/// </summary>
[Fact]
public void TestSetItemArrayParamSingle()
{
ValidateTaskParameterItems("ItemArrayParam", "@(ItemListContainingOneItem)", _oneItem);
}
/// <summary>
/// Validate that setting an item array using an item list containing two items sets both items.
/// </summary>
[Fact]
public void TestSetItemArrayParamDouble()
{
ValidateTaskParameterItems("ItemArrayParam", "@(ItemListContainingTwoItems)", _twoItems);
}
/// <summary>
/// Validate that setting an item array with
/// </summary>
[Fact]
public void TestSetItemArrayParamString()
{
ValidateTaskParameterItems("ItemArrayParam", "MyItemName");
}
/// <summary>
/// Validate that setting an item array with a list with multiple values creates multiple items.
/// </summary>
[Fact]
public void TestSetItemArrayParamTwoStrings()
{
ValidateTaskParameterItems("ItemArrayParam", "MyItemName;MyOtherItemName", new string[] { "MyItemName", "MyOtherItemName" });
}
/// <summary>
/// Validate that setting the parameter with an empty value does not cause it to be set.
/// </summary>
[Fact]
public void TestSetItemArrayParamEmptyAttribute()
{
ValidateTaskParameterNotSet("ItemArrayParam", "");
}
/// <summary>
/// Validate that setting the parameter with a parameter which evaluates to an empty value does not cause it to be set.
/// </summary>
[Fact]
public void TestSetItemArrayParamEmptyProperty()
{
ValidateTaskParameterNotSet("ItemArrayParam", "$(NonExistantProperty)");
}
/// <summary>
/// Validate that setting the parameter with an item which evaluates to an empty value does not cause it to be set.
/// </summary>
[Fact]
public void TestSetItemArrayParamEmptyItem()
{
ValidateTaskParameterNotSet("ItemArrayParam", "@(NonExistantItem)");
}
#endregion
#region Execute Tests
/// <summary>
/// Tests that successful execution returns true.
/// </summary>
[Fact]
public void TestExecuteTrue()
{
var parameters = new Dictionary<string, (string, ElementLocation)>(StringComparer.OrdinalIgnoreCase);
parameters["ExecuteReturnParam"] = ("true", ElementLocation.Create("foo.proj"));
Assert.True(_host.SetTaskParameters(parameters));
bool executeValue = _host.Execute();
Assert.True(executeValue);
}
/// <summary>
/// Tests that unsuccessful execution returns false.
/// </summary>
[Fact]
public void TestExecuteFalse()
{
var parameters = new Dictionary<string, (string, ElementLocation)>(StringComparer.OrdinalIgnoreCase);
parameters["ExecuteReturnParam"] = ("false", ElementLocation.Create("foo.proj"));
Assert.True(_host.SetTaskParameters(parameters));
bool executeValue = _host.Execute();
Assert.False(executeValue);
}
/// <summary>
/// Tests that when Execute throws, the exception bubbles up.
/// </summary>
[Fact]
public void TestExecuteThrow()
{
Assert.Throws<IndexOutOfRangeException>(() =>
{
var parameters = new Dictionary<string, (string, ElementLocation)>(StringComparer.OrdinalIgnoreCase);
parameters["ExecuteReturnParam"] = ("false", ElementLocation.Create("foo.proj"));
Dispose();
InitializeHost(true);
Assert.True(_host.SetTaskParameters(parameters));
_host.Execute();
}
);
}
#endregion
#region Bool Outputs
/// <summary>
/// Validate that boolean output to an item produces the correct evaluated include.
/// </summary>
[Fact]
public void TestOutputBoolToItem()
{
SetTaskParameter("BoolParam", "true");
ValidateOutputItem("BoolOutput", "True");
}
/// <summary>
/// Validate that boolean output to a property produces the correct evaluated value.
/// </summary>
[Fact]
public void TestOutputBoolToProperty()
{
SetTaskParameter("BoolParam", "true");
ValidateOutputProperty("BoolOutput", "True");
}
/// <summary>
/// Validate that boolean array output to an item array produces the correct evaluated includes.
/// </summary>
[Fact]
public void TestOutputBoolArrayToItems()
{
SetTaskParameter("BoolArrayParam", "false;true");
ValidateOutputItems("BoolArrayOutput", new string[] { "False", "True" });
}
/// <summary>
/// Validate that boolean array output to an item produces the correct semi-colon-delimited evaluated value.
/// </summary>
[Fact]
public void TestOutputBoolArrayToProperty()
{
SetTaskParameter("BoolArrayParam", "false;true");
ValidateOutputProperty("BoolArrayOutput", "False;True");
}
#endregion
#region Int Outputs
/// <summary>
/// Validate that an int output to an item produces the correct evaluated include
/// </summary>
[Fact]
public void TestOutputIntToItem()
{
SetTaskParameter("IntParam", "42");
ValidateOutputItem("IntOutput", "42");
}
/// <summary>
/// Validate that an int output to an property produces the correct evaluated value.
/// </summary>
[Fact]
public void TestOutputIntToProperty()
{
SetTaskParameter("IntParam", "42");
ValidateOutputProperty("IntOutput", "42");
}
/// <summary>
/// Validate that an int array output to an item produces the correct evaluated includes.
/// </summary>
[Fact]
public void TestOutputIntArrayToItems()
{
SetTaskParameter("IntArrayParam", "42;99");
ValidateOutputItems("IntArrayOutput", new string[] { "42", "99" });
}
/// <summary>
/// Validate that an int array output to a property produces the correct semi-colon-delimited evaluated value.
/// </summary>
[Fact]
public void TestOutputIntArrayToProperty()
{
SetTaskParameter("IntArrayParam", "42;99");
ValidateOutputProperty("IntArrayOutput", "42;99");
}
#endregion
#region String Outputs
/// <summary>
/// Validate that a string output to an item produces the correct evaluated include.
/// </summary>
[Fact]
public void TestOutputStringToItem()
{
SetTaskParameter("StringParam", "FOO");
ValidateOutputItem("StringOutput", "FOO");
}
/// <summary>
/// Validate that a string output to a property produces the correct evaluated value.
/// </summary>
[Fact]
public void TestOutputStringToProperty()
{
SetTaskParameter("StringParam", "FOO");
ValidateOutputProperty("StringOutput", "FOO");
}
/// <summary>
/// Validate that an empty string output overwrites the property value
/// </summary>
[Fact]
public void TestOutputEmptyStringToProperty()
{
_bucket.Lookup.SetProperty(ProjectPropertyInstance.Create("output", "initialvalue"));
ValidateOutputProperty("EmptyStringOutput", String.Empty);
}
/// <summary>
/// Validate that an empty string array output overwrites the property value
/// </summary>
[Fact]
public void TestOutputEmptyStringArrayToProperty()
{
_bucket.Lookup.SetProperty(ProjectPropertyInstance.Create("output", "initialvalue"));
ValidateOutputProperty("EmptyStringArrayOutput", String.Empty);
}
/// <summary>
/// A string output returning null should not cause any property set.
/// </summary>
[Fact]
public void TestOutputNullStringToProperty()
{
_bucket.Lookup.SetProperty(ProjectPropertyInstance.Create("output", "initialvalue"));
ValidateOutputProperty("NullStringOutput", "initialvalue");
}
/// <summary>
/// A string output returning null should not cause any property set.
/// </summary>
[Fact]
public void TestOutputNullITaskItemToProperty()
{
_bucket.Lookup.SetProperty(ProjectPropertyInstance.Create("output", "initialvalue"));
ValidateOutputProperty("NullITaskItemOutput", "initialvalue");
}
/// <summary>
/// A string output returning null should not cause any property set.
/// </summary>
[Fact]
public void TestOutputNullStringArrayToProperty()
{
_bucket.Lookup.SetProperty(ProjectPropertyInstance.Create("output", "initialvalue"));
ValidateOutputProperty("NullStringArrayOutput", "initialvalue");
}
/// <summary>
/// A string output returning null should not cause any property set.
/// </summary>
[Fact]
public void TestOutputNullITaskItemArrayToProperty()
{
_bucket.Lookup.SetProperty(ProjectPropertyInstance.Create("output", "initialvalue"));
ValidateOutputProperty("NullITaskItemArrayOutput", "initialvalue");
}
/// <summary>
/// Validate that a string array output to an item produces the correct evaluated includes.
/// </summary>
[Fact]
public void TestOutputStringArrayToItems()
{
SetTaskParameter("StringArrayParam", "FOO;bar");
ValidateOutputItems("StringArrayOutput", new string[] { "FOO", "bar" });
}
/// <summary>
/// Validate that a string array output to a property produces the correct semi-colon-delimited evaluated value.
/// </summary>
[Fact]
public void TestOutputStringArrayToProperty()
{
SetTaskParameter("StringArrayParam", "FOO;bar");
ValidateOutputProperty("StringArrayOutput", "FOO;bar");
}
#endregion
#region Item Outputs
/// <summary>
/// Validate that an item output to an item replicates the item, with metadata
/// </summary>
[Fact]
public void TestOutputItemToItem()
{
SetTaskParameter("ItemParam", "@(ItemListContainingOneItem)");
ValidateOutputItems("ItemOutput", _oneItem);
}
/// <summary>
/// Validate than an item output to a property produces the correct evaluated value.
/// </summary>
[Fact]
public void TestOutputItemToProperty()
{
SetTaskParameter("ItemParam", "@(ItemListContainingOneItem)");
ValidateOutputProperty("ItemOutput", _oneItem[0].ItemSpec);
}
/// <summary>
/// Validate that an item array output to an item replicates the items, with metadata.
/// </summary>
[Fact]
public void TestOutputItemArrayToItems()
{
SetTaskParameter("ItemArrayParam", "@(ItemListContainingTwoItems)");
ValidateOutputItems("ItemArrayOutput", _twoItems);
}
/// <summary>
/// Validate that an item array output to a property produces the correct semi-colon-delimited evaluated value.
/// </summary>
[Fact]
public void TestOutputItemArrayToProperty()
{
SetTaskParameter("ItemArrayParam", "@(ItemListContainingTwoItems)");
ValidateOutputProperty("ItemArrayOutput", String.Concat(_twoItems[0].ItemSpec, ";", _twoItems[1].ItemSpec));
}
#endregion
#region Other Output Tests
/// <summary>
/// Attempts to gather outputs into an item list from an string task parameter that
/// returns an empty string. This should be a no-op.
/// </summary>
[Fact]
public void TestEmptyStringInStringArrayParameterIntoItemList()
{
SetTaskParameter("StringArrayParam", "");
ValidateOutputItems("StringArrayOutput", new ITaskItem[] { });
}
/// <summary>
/// Attempts to gather outputs into an item list from an string task parameter that
/// returns an empty string. This should be a no-op.
/// </summary>
[Fact]
public void TestEmptyStringParameterIntoItemList()
{
SetTaskParameter("StringParam", "");
ValidateOutputItems("StringOutput", new ITaskItem[] { });
}
/// <summary>
/// Attempts to gather outputs from a null task parameter of type "ITaskItem[]". This should succeed.
/// </summary>
[Fact]
public void TestNullITaskItemArrayParameter()
{
ValidateOutputItems("ItemArrayNullOutput", new ITaskItem[] { });
}
/// <summary>
/// Attempts to gather outputs from a task parameter of type "ArrayList". This should fail.
/// </summary>
[Fact]
public void TestArrayListParameter()
{
Assert.Throws<InvalidProjectFileException>(() =>
{
ValidateOutputItems("ArrayListOutput", new ITaskItem[] { });
}
);
}
/// <summary>
/// Attempts to gather outputs from a non-existent output. This should fail.
/// </summary>
[Fact]
public void TestNonexistantOutput()
{
Assert.Throws<InvalidProjectFileException>(() =>
{
Assert.False(_host.GatherTaskOutputs("NonExistantOutput", ElementLocation.Create(".", 1, 1), true, "output"));
}
);
}
/// <summary>
/// object[] should not be a supported output type.
/// </summary>
[Fact]
public void TestOutputObjectArrayToProperty()
{
Assert.Throws<InvalidProjectFileException>(() =>
{
ValidateOutputProperty("ObjectArrayOutput", "");
}
);
}
#endregion
#region Other Tests
/// <summary>
/// Test that cleanup for task clears out the task instance.
/// </summary>
[Fact]
public void TestCleanupForTask()
{
_host.CleanupForBatch();
Assert.NotNull((_host as TaskExecutionHost)._UNITTESTONLY_TaskFactoryWrapper);
_host.CleanupForTask();
Assert.Null((_host as TaskExecutionHost)._UNITTESTONLY_TaskFactoryWrapper);
}
/// <summary>
/// Test that a using task which specifies an invalid assembly produces an exception.
/// </summary>
[Fact]
public void TestTaskResolutionFailureWithUsingTask()
{
Assert.Throws<InvalidProjectFileException>(() =>
{
_loggingService = new MockLoggingService();
Dispose();
_host = new TaskExecutionHost();
TargetLoggingContext tlc = new TargetLoggingContext(_loggingService, new BuildEventContext(1, 1, BuildEventContext.InvalidProjectContextId, 1));
ProjectInstance project = CreateTestProject();
_host.InitializeForTask
(
this,
tlc,
project,
"TaskWithMissingAssembly",
ElementLocation.Create("none", 1, 1),
this,
false,
#if FEATURE_APPDOMAIN
null,
#endif
false,
CancellationToken.None
);
_host.FindTask(null);
_host.InitializeForBatch(new TaskLoggingContext(_loggingService, tlc.BuildEventContext), _bucket, null);
}
);
}
/// <summary>
/// Test that specifying a task with no using task logs an error, but does not throw.
/// </summary>
[Fact]
public void TestTaskResolutionFailureWithNoUsingTask()
{
Dispose();
_host = new TaskExecutionHost();
TargetLoggingContext tlc = new TargetLoggingContext(_loggingService, new BuildEventContext(1, 1, BuildEventContext.InvalidProjectContextId, 1));
ProjectInstance project = CreateTestProject();
_host.InitializeForTask
(
this,
tlc,
project,
"TaskWithNoUsingTask",
ElementLocation.Create("none", 1, 1),
this,
false,
#if FEATURE_APPDOMAIN
null,
#endif
false,
CancellationToken.None
);
_host.FindTask(null);
_host.InitializeForBatch(new TaskLoggingContext(_loggingService, tlc.BuildEventContext), _bucket, null);
_logger.AssertLogContains("MSB4036");
}
#endregion
#region ITestTaskHost Members
#pragma warning disable xUnit1013
/// <summary>
/// Records that a parameter was set on the task.
/// </summary>
public void ParameterSet(string parameterName, object valueSet)
{
_parametersSetOnTask[parameterName] = valueSet;
}
/// <summary>
/// Records that an output was read from the task.
/// </summary>
public void OutputRead(string parameterName, object actualValue)
{
_outputsReadFromTask[parameterName] = actualValue;
}
#endregion
#region IBuildEngine2 Members
/// <summary>
/// Unused.
/// </summary>
public bool BuildProjectFile(string projectFileName, string[] targetNames, IDictionary globalProperties, IDictionary targetOutputs, string toolsVersion)
{
throw new NotImplementedException();
}
/// <summary>
/// Unused.
/// </summary>
public bool BuildProjectFilesInParallel(string[] projectFileNames, string[] targetNames, IDictionary[] globalProperties, IDictionary[] targetOutputsPerProject, string[] toolsVersion, bool useResultsCache, bool unloadProjectsOnCompletion)
{
throw new NotImplementedException();
}
#endregion
#region IBuildEngine Members
/// <summary>
/// Unused.
/// </summary>
public void LogErrorEvent(BuildErrorEventArgs e)
{
throw new NotImplementedException();
}
/// <summary>
/// Unused.
/// </summary>
public void LogWarningEvent(BuildWarningEventArgs e)
{
throw new NotImplementedException();
}
/// <summary>
/// Unused.
/// </summary>
public void LogMessageEvent(BuildMessageEventArgs e)
{
throw new NotImplementedException();
}
/// <summary>
/// Unused.
/// </summary>
public void LogCustomEvent(CustomBuildEventArgs e)
{
throw new NotImplementedException();
}
/// <summary>
/// Unused.
/// </summary>
public bool BuildProjectFile(string projectFileName, string[] targetNames, IDictionary globalProperties, IDictionary targetOutputs)
{
throw new NotImplementedException();
}
#pragma warning restore xUnit1013
#endregion
#region Validation Routines
/// <summary>
/// Is the class a task factory
/// </summary>
private static bool IsTaskFactoryClass(Type type, object unused)
{
return type.GetTypeInfo().IsClass &&
!type.GetTypeInfo().IsAbstract &&
#if FEATURE_TYPE_GETINTERFACE
(type.GetInterface("Microsoft.Build.Framework.ITaskFactory") != null);
#else
type.GetInterfaces().Any(interfaceType => interfaceType.FullName == "Microsoft.Build.Framework.ITaskFactory");
#endif
}
/// <summary>
/// Initialize the host object
/// </summary>
/// <param name="throwOnExecute">Should the task throw when executed</param>
private void InitializeHost(bool throwOnExecute)
{
_loggingService = LoggingService.CreateLoggingService(LoggerMode.Synchronous, 1);
_logger = new MockLogger();
_loggingService.RegisterLogger(_logger);
_host = new TaskExecutionHost();
TargetLoggingContext tlc = new TargetLoggingContext(_loggingService, new BuildEventContext(1, 1, BuildEventContext.InvalidProjectContextId, 1));
// Set up a temporary project and add some items to it.
ProjectInstance project = CreateTestProject();
TypeLoader typeLoader = new TypeLoader(IsTaskFactoryClass);
#if !FEATURE_ASSEMBLYLOADCONTEXT
AssemblyLoadInfo loadInfo = AssemblyLoadInfo.Create(Assembly.GetAssembly(typeof(TaskBuilderTestTask.TaskBuilderTestTaskFactory)).FullName, null);
#else
AssemblyLoadInfo loadInfo = AssemblyLoadInfo.Create(typeof(TaskBuilderTestTask.TaskBuilderTestTaskFactory).GetTypeInfo().FullName, null);
#endif
LoadedType loadedType = new LoadedType(typeof(TaskBuilderTestTask.TaskBuilderTestTaskFactory), loadInfo);
TaskBuilderTestTask.TaskBuilderTestTaskFactory taskFactory = new TaskBuilderTestTask.TaskBuilderTestTaskFactory();
taskFactory.ThrowOnExecute = throwOnExecute;
string taskName = "TaskBuilderTestTask";
(_host as TaskExecutionHost)._UNITTESTONLY_TaskFactoryWrapper = new TaskFactoryWrapper(taskFactory, loadedType, taskName, null);
_host.InitializeForTask
(
this,
tlc,
project,
taskName,
ElementLocation.Create("none", 1, 1),
this,
false,
#if FEATURE_APPDOMAIN
null,
#endif
false,
CancellationToken.None
);
ProjectTaskInstance taskInstance = project.Targets["foo"].Tasks.First();
TaskLoggingContext talc = tlc.LogTaskBatchStarted(".", taskInstance);
ItemDictionary<ProjectItemInstance> itemsByName = new ItemDictionary<ProjectItemInstance>();
ProjectItemInstance item = new ProjectItemInstance(project, "ItemListContainingOneItem", "a.cs", ".");
item.SetMetadata("Culture", "fr-fr");
itemsByName.Add(item);
_oneItem = new ITaskItem[] { new TaskItem(item) };
item = new ProjectItemInstance(project, "ItemListContainingTwoItems", "b.cs", ".");
ProjectItemInstance item2 = new ProjectItemInstance(project, "ItemListContainingTwoItems", "c.cs", ".");
item.SetMetadata("HintPath", "c:\\foo");
item2.SetMetadata("HintPath", "c:\\bar");
itemsByName.Add(item);
itemsByName.Add(item2);
_twoItems = new ITaskItem[] { new TaskItem(item), new TaskItem(item2) };
_bucket = new ItemBucket(new string[0], new Dictionary<string, string>(), new Lookup(itemsByName, new PropertyDictionary<ProjectPropertyInstance>()), 0);
_host.FindTask(null);
_host.InitializeForBatch(talc, _bucket, null);
_parametersSetOnTask = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
_outputsReadFromTask = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
}
/// <summary>
/// Helper method for tests
/// </summary>
private void ValidateOutputItem(string outputName, string value)
{
Assert.True(_host.GatherTaskOutputs(outputName, ElementLocation.Create(".", 1, 1), true, "output"));
Assert.True(_outputsReadFromTask.ContainsKey(outputName));
Assert.Single(_bucket.Lookup.GetItems("output"));
Assert.Equal(value, _bucket.Lookup.GetItems("output").First().EvaluatedInclude);
}
/// <summary>
/// Helper method for tests
/// </summary>
private void ValidateOutputItem(string outputName, ITaskItem value)
{
Assert.True(_host.GatherTaskOutputs(outputName, ElementLocation.Create(".", 1, 1), true, "output"));
Assert.True(_outputsReadFromTask.ContainsKey(outputName));
Assert.Single(_bucket.Lookup.GetItems("output"));
Assert.Equal(0, TaskItemComparer.Instance.Compare(value, new TaskItem(_bucket.Lookup.GetItems("output").First())));
}
/// <summary>
/// Helper method for tests
/// </summary>
private void ValidateOutputItems(string outputName, string[] values)
{
Assert.True(_host.GatherTaskOutputs(outputName, ElementLocation.Create(".", 1, 1), true, "output"));
Assert.True(_outputsReadFromTask.ContainsKey(outputName));
Assert.Equal(values.Length, _bucket.Lookup.GetItems("output").Count);
for (int i = 0; i < values.Length; i++)
{
Assert.Equal(values[i], _bucket.Lookup.GetItems("output").ElementAt(i).EvaluatedInclude);
}
}
/// <summary>
/// Helper method for tests
/// </summary>
private void ValidateOutputItems(string outputName, ITaskItem[] values)
{
Assert.True(_host.GatherTaskOutputs(outputName, ElementLocation.Create(".", 1, 1), true, "output"));
Assert.True(_outputsReadFromTask.ContainsKey(outputName));
Assert.Equal(values.Length, _bucket.Lookup.GetItems("output").Count);
for (int i = 0; i < values.Length; i++)
{
Assert.Equal(0, TaskItemComparer.Instance.Compare(values[i], new TaskItem(_bucket.Lookup.GetItems("output").ElementAt(i))));
}
}
/// <summary>
/// Helper method for tests
/// </summary>
private void ValidateOutputProperty(string outputName, string value)
{
Assert.True(_host.GatherTaskOutputs(outputName, ElementLocation.Create(".", 1, 1), false, "output"));
Assert.True(_outputsReadFromTask.ContainsKey(outputName));
Assert.NotNull(_bucket.Lookup.GetProperty("output"));
Assert.Equal(value, _bucket.Lookup.GetProperty("output").EvaluatedValue);
}
/// <summary>
/// Helper method for tests
/// </summary>
private void ValidateTaskParameter(string parameterName, string value, object expectedValue)
{
SetTaskParameter(parameterName, value);
Assert.True(_parametersSetOnTask.ContainsKey(parameterName));
Assert.Equal(expectedValue, _parametersSetOnTask[parameterName]);
}
/// <summary>
/// Helper method for tests
/// </summary>
private void ValidateTaskParameterItem(string parameterName, string value)
{
SetTaskParameter(parameterName, value);
Assert.True(_parametersSetOnTask.ContainsKey(parameterName));
ITaskItem actualItem = _parametersSetOnTask[parameterName] as ITaskItem;
Assert.Equal(value, actualItem.ItemSpec);
Assert.Equal(BuiltInMetadata.MetadataCount, actualItem.MetadataCount);
}
/// <summary>
/// Helper method for tests
/// </summary>
private void ValidateTaskParameterItem(string parameterName, string value, ITaskItem expectedItem)
{
SetTaskParameter(parameterName, value);
Assert.True(_parametersSetOnTask.ContainsKey(parameterName));
ITaskItem actualItem = _parametersSetOnTask[parameterName] as ITaskItem;
Assert.Equal(0, TaskItemComparer.Instance.Compare(expectedItem, actualItem));
}
/// <summary>
/// Helper method for tests
/// </summary>
private void ValidateTaskParameterItems(string parameterName, string value)
{
SetTaskParameter(parameterName, value);
Assert.True(_parametersSetOnTask.ContainsKey(parameterName));
ITaskItem[] actualItems = _parametersSetOnTask[parameterName] as ITaskItem[];
Assert.Single(actualItems);
Assert.Equal(value, actualItems[0].ItemSpec);
}
/// <summary>
/// Helper method for tests
/// </summary>
private void ValidateTaskParameterItems(string parameterName, string value, ITaskItem[] expectedItems)
{
SetTaskParameter(parameterName, value);
Assert.True(_parametersSetOnTask.ContainsKey(parameterName));
ITaskItem[] actualItems = _parametersSetOnTask[parameterName] as ITaskItem[];
Assert.Equal(expectedItems.Length, actualItems.Length);
for (int i = 0; i < expectedItems.Length; i++)
{
Assert.Equal(0, TaskItemComparer.Instance.Compare(expectedItems[i], actualItems[i]));
}
}
/// <summary>
/// Helper method for tests
/// </summary>
private void ValidateTaskParameterItems(string parameterName, string value, string[] expectedItems)
{
SetTaskParameter(parameterName, value);
Assert.True(_parametersSetOnTask.ContainsKey(parameterName));
ITaskItem[] actualItems = _parametersSetOnTask[parameterName] as ITaskItem[];
Assert.Equal(expectedItems.Length, actualItems.Length);
for (int i = 0; i < expectedItems.Length; i++)
{
Assert.Equal(expectedItems[i], actualItems[i].ItemSpec);
}
}
/// <summary>
/// Helper method for tests
/// </summary>
private void ValidateTaskParameterArray(string parameterName, string value, object expectedValue)
{
SetTaskParameter(parameterName, value);
Assert.True(_parametersSetOnTask.ContainsKey(parameterName));
Array expectedArray = expectedValue as Array;
Array actualArray = _parametersSetOnTask[parameterName] as Array;
Assert.Equal(expectedArray.Length, actualArray.Length);
for (int i = 0; i < expectedArray.Length; i++)
{
Assert.Equal(expectedArray.GetValue(i), actualArray.GetValue(i));
}
}
/// <summary>
/// Helper method for tests
/// </summary>
private void ValidateTaskParameterNotSet(string parameterName, string value)
{
SetTaskParameter(parameterName, value);
Assert.False(_parametersSetOnTask.ContainsKey(parameterName));
}
#endregion
/// <summary>
/// Helper method for tests
/// </summary>
private void SetTaskParameter(string parameterName, string value)
{
var parameters = GetStandardParametersDictionary(true);
parameters[parameterName] = (value, ElementLocation.Create("foo.proj"));
bool success = _host.SetTaskParameters(parameters);
Assert.True(success);
}
/// <summary>
/// Helper method for tests
/// </summary>
private Dictionary<string, (string, ElementLocation)> GetStandardParametersDictionary(bool returnParam)
{
var parameters = new Dictionary<string, (string, ElementLocation)>(StringComparer.OrdinalIgnoreCase);
parameters["ExecuteReturnParam"] = (returnParam ? "true" : "false", ElementLocation.Create("foo.proj"));
return parameters;
}
/// <summary>
/// Creates a test project.
/// </summary>
/// <returns>The project.</returns>
private ProjectInstance CreateTestProject()
{
string projectFileContents = ObjectModelHelpers.CleanupFileContents(@"
<Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'>
<UsingTask TaskName='TaskWithMissingAssembly' AssemblyName='madeup' />
<ItemGroup>
<Compile Include='b.cs' />
<Compile Include='c.cs' />
</ItemGroup>
<ItemGroup>
<Reference Include='System' />
</ItemGroup>
<Target Name='Empty' />
<Target Name='Skip' Inputs='testProject.proj' Outputs='testProject.proj' />
<Target Name='Error' >
<ErrorTask1 ContinueOnError='True'/>
<ErrorTask2 ContinueOnError='False'/>
<ErrorTask3 />
<OnError ExecuteTargets='Foo'/>
<OnError ExecuteTargets='Bar'/>
</Target>
<Target Name='Foo' Inputs='foo.cpp' Outputs='foo.o'>
<FooTask1/>
</Target>
<Target Name='Bar'>
<BarTask1/>
</Target>
<Target Name='Baz' DependsOnTargets='Bar'>
<BazTask1/>
<BazTask2/>
</Target>
<Target Name='Baz2' DependsOnTargets='Bar;Foo'>
<Baz2Task1/>
<Baz2Task2/>
<Baz2Task3/>
</Target>
<Target Name='DepSkip' DependsOnTargets='Skip'>
<DepSkipTask1/>
<DepSkipTask2/>
<DepSkipTask3/>
</Target>
<Target Name='DepError' DependsOnTargets='Foo;Skip;Error'>
<DepSkipTask1/>
<DepSkipTask2/>
<DepSkipTask3/>
</Target>
</Project>
");
Project project = new Project(XmlReader.Create(new StringReader(projectFileContents)));
return project.CreateProjectInstance();
}
}
}
| |
//
// StreamRatingTagger.cs
//
// Author:
// Nicholas Parker <nickbp@gmail.com>
//
// Copyright (C) 2008-2009 Nicholas Parker
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections;
using Banshee.Collection;
namespace Banshee.Streaming
{
internal static class ID3v2RatingTagger
{
// What we call ourselves in POPM tags.
private static string POPM_our_creator_name = "Banshee";
// Ordered list of ID3v2 POPM authors to attempt when importing.
// Banshee must be listed first, to ensure that we give priority to our own ratings.
// If new entries are added to this list, also make sure that
// PopmToBanshee and BansheeToPopm are still accurate.
private static string[] POPM_known_creator_list = {
POPM_our_creator_name,// This item must be first
"quodlibet@lists.sacredchao.net",// Quod Libet (their default)
"Windows Media Player 9 Series",// WMP/Vista
"no@email",// MediaMonkey
"mcored@gmail.com" // iTSfv
};
// Converts ID3v2 POPM rating to Banshee rating
private static int PopmToBanshee (byte popm_rating)
{
// The following schemes are used by the other POPM-compatible players:
// WMP/Vista: "Windows Media Player 9 Series" ratings:
// 1 = 1, 2 = 64, 3=128, 4=196 (not 192), 5=255
// MediaMonkey: "no@email" ratings:
// 0.5=26, 1=51, 1.5=76, 2=102, 2.5=128,
// 3=153, 3.5=178, 4=204, 4.5=230, 5=255
// Quod Libet: "quodlibet@lists.sacredchao.net" ratings
// (but that email can be changed):
// arbitrary scale from 0-255
// Compatible with all these rating scales (what we'll use):
// unrated=0, 1=1-63, 2=64-127, 3=128-191, 4=192-254, 5=255
if (popm_rating == 0x0)// unrated
return 0;
if (popm_rating < 0x40)// 1-63
return 1;
if (popm_rating < 0x80)// 64-127
return 2;
if (popm_rating < 0xC0)// 128-191
return 3;
if (popm_rating < 0xFF)// 192-254
return 4;
return 5;// 255
}
// Converts Banshee rating to ID3v2 POPM rating
private static byte BansheeToPopm (int banshee_rating)
{
switch (banshee_rating) {
case 1:
return 0x1;
case 2:
return 0x40;// 64
case 3:
return 0x80;// 128
case 4:
return 0xC0;// 192
case 5:
return 0xFF;// 255
default:
return 0x0;// unrated/unknown
}
}
private static TagLib.Id3v2.Tag GetTag (TagLib.File file)
{
try {
return file.GetTag (TagLib.TagTypes.Id3v2) as TagLib.Id3v2.Tag;
} catch (System.NullReferenceException e) {
// TagLib# can crash here on unusual files (Ex: FLAC files with ID3v2 metadata)
// Perhaps FLAC+ID3v2 is an unsupported combination for TagLib#?
Hyena.Log.WarningFormat ("Got exception when accessing ID3v2 Metadata in {0}:",
file.Name);
Hyena.Log.Warning (e.Message);
Hyena.Log.Warning (e.StackTrace);
return null;
}
}
// Overwrites all POPM frames with the new rating and playcount.
// If no *known-compatible* frames are found, a new "Banshee"-authored
// frame is also created to store this information.
public static void StoreRatingAndPlayCount (int rating, int playcount,
TagLib.File to_file)
{
TagLib.Id3v2.Tag id3v2tag = GetTag (to_file);
if (id3v2tag == null) {
return;
}
bool known_frames_found = false;
foreach (TagLib.Id3v2.PopularimeterFrame popm in
id3v2tag.GetFrames<TagLib.Id3v2.PopularimeterFrame> ()) {
if (System.Array.IndexOf (POPM_known_creator_list, popm.User) >= 0) {
// Found a known-good POPM frame, don't need to create a "Banshee" frame.
known_frames_found = true;
}
popm.Rating = BansheeToPopm (rating);
popm.PlayCount = (ulong)playcount;
Hyena.Log.DebugFormat ("Exporting ID3v2 Rating={0}({1}) and Playcount={2}({3}) to File \"{4}\" as Creator \"{5}\"",
rating, popm.Rating,
playcount, popm.PlayCount,
to_file.Name, popm.User);
}
if (!known_frames_found) {
// No known-good frames found, create a new POPM frame (with creator string "Banshee")
TagLib.Id3v2.PopularimeterFrame popm = TagLib.Id3v2.PopularimeterFrame.Get (id3v2tag,
POPM_our_creator_name,
true);
popm.Rating = BansheeToPopm (rating);
popm.PlayCount = (ulong)playcount;
Hyena.Log.DebugFormat ("Exporting ID3v2 Rating={0}({1}) and Playcount={2}({3}) to File \"{4}\" as Creator \"{5}\"",
rating, popm.Rating,
playcount, popm.PlayCount,
to_file.Name, POPM_our_creator_name);
}
}
// Scans the file for *known-compatible* POPM frames, with priority given to
// frames at the top of the known creator list.
public static void GetRatingAndPlayCount (TagLib.File from_file,
ref int rating, ref int playcount)
{
TagLib.Id3v2.Tag id3v2tag = GetTag (from_file);
if (id3v2tag == null) {
return;
}
TagLib.Id3v2.PopularimeterFrame popm = null;
for (int i = 0; i < POPM_known_creator_list.Length; i++) {
popm = TagLib.Id3v2.PopularimeterFrame.Get (id3v2tag,
POPM_known_creator_list[i],
false);
if (popm != null) {
break;
}
}
if (popm != null) {
rating = PopmToBanshee (popm.Rating);
playcount = (int)popm.PlayCount;
}
}
}
// Applicable for Vorbis, Speex, and many (most?) FLAC files
// Follows the naming standard established by the Quod Libet team
// See: http://code.google.com/p/quodlibet/wiki/Specs_VorbisComments
internal static class OggRatingTagger
{
// What we call ourselves in rating/playcount tags.
private static string ogg_our_creator_name = "BANSHEE";
// Prefix to rating field names (lowercase)
private static string rating_prefix = "RATING:";
// Prefix to playcount field names (lowercase)
private static string playcount_prefix = "PLAYCOUNT:";
// Converts Ogg rating to Banshee rating
private static int OggToBanshee (string ogg_rating_str)
{
double ogg_rating;
if (Double.TryParse (ogg_rating_str, out ogg_rating)) {
// Quod Libet Ogg ratings are stored as a value
// between 0.0 and 1.0 inclusive, where unrated = 0.5.
if (ogg_rating == 0.5)// unrated
return 0;
if (ogg_rating > 0.8)// (0.8,1.0]
return 5;
if (ogg_rating > 0.6)// (0.6,0.8]
return 4;
if (ogg_rating > 0.4)// (0.4,0.5),(0.5,0.6]
return 3;
if (ogg_rating > 0.2)// (0.2,0.4]
return 2;
else // [0.0,0.2]
return 1;
}
Hyena.Log.WarningFormat ("Failed to parse ogg rating string: {0}", ogg_rating_str);
return 0;
}
// Converts Banshee rating to Ogg rating
private static string BansheeToOgg (int banshee_rating)
{
// I went with this scaling so that if we switch to fractional stars
// in the future (such as "0.25 stars"), we'll have room for that.
switch (banshee_rating) {
case 1:
return "0.2";
case 2:
return "0.4";
case 3:
return "0.6";
case 4:
return "0.8";
case 5:
return "1.0";
default:
return "0.5";// unrated/unknown
}
}
private static TagLib.Ogg.XiphComment GetTag (TagLib.File file)
{
try {
return file.GetTag (TagLib.TagTypes.Xiph) as TagLib.Ogg.XiphComment;
} catch (System.NullReferenceException e) {
// Haven't seen crashes when getting Ogg tags, but just in case..
// (See commentary for ID3v2 version)
Hyena.Log.WarningFormat ("Got exception when accessing Ogg Metadata in {0}:",
file.Name);
Hyena.Log.Warning (e.Message);
Hyena.Log.Warning (e.StackTrace);
return null;
}
}
// Scans the file for ogg rating/playcount tags as defined by the Quod Libet standard
// If a Banshee tag is found, it is given priority.
// If a Banshee tag is not found, the last rating/playcount tags found are used
public static void GetRatingAndPlayCount (TagLib.File from_file,
ref int rating, ref int playcount)
{
TagLib.Ogg.XiphComment xiphtag = GetTag (from_file);
if (xiphtag == null) {
return;
}
bool banshee_rating_done = false, banshee_playcount_done = false;
string rating_raw = "", playcount_raw = "";
foreach (string fieldname in xiphtag) {
if (!banshee_rating_done &&
fieldname.ToUpper ().StartsWith (rating_prefix)) {
rating_raw = xiphtag.GetFirstField (fieldname);
string rating_creator = fieldname.Substring (rating_prefix.Length);
if (rating_creator.ToUpper () == ogg_our_creator_name) {
// We made this rating, consider it authoritative.
banshee_rating_done = true;
// Don't return -- we might not have seen a playcount yet.
}
} else if (!banshee_playcount_done &&
fieldname.ToUpper ().StartsWith (playcount_prefix)) {
playcount_raw = xiphtag.GetFirstField (fieldname);
string playcount_creator = fieldname.Substring (playcount_prefix.Length);
if (playcount_creator.ToUpper () == ogg_our_creator_name) {
// We made this playcount, consider it authoritative.
banshee_playcount_done = true;
// Don't return -- we might not have seen a rating yet.
}
}
}
if (rating_raw != "") {
rating = OggToBanshee (rating_raw);
}
if (playcount_raw != "") {
playcount = int.Parse (playcount_raw);
}
Hyena.Log.DebugFormat ("Importing Ogg Rating={0}({1}) and Playcount={2}({3}) from File \"{4}\"",
rating, rating_raw,
playcount, playcount_raw, from_file.Name);
}
// Scans the file for ogg rating/playcount tags as defined by the Quod Libet standard
// All applicable tags are overwritten with the new values, regardless of tag author
public static void StoreRatingAndPlayCount (int rating, int playcount,
TagLib.File to_file)
{
TagLib.Ogg.XiphComment xiphtag = GetTag (to_file);
if (xiphtag == null) {
return;
}
ArrayList rating_fieldnames = new ArrayList ();
ArrayList playcount_fieldnames = new ArrayList ();
// Collect list of rating and playcount tags to be updated:
foreach (string fieldname in xiphtag) {
if (fieldname.ToUpper ().StartsWith (rating_prefix)) {
rating_fieldnames.Add (fieldname);
} else if (fieldname.ToUpper ().StartsWith (playcount_prefix)) {
playcount_fieldnames.Add (fieldname);
}
}
// Add "BANSHEE" tags if no rating/playcount tags were found:
if (rating_fieldnames.Count == 0) {
rating_fieldnames.Add (rating_prefix+ogg_our_creator_name);
}
if (playcount_fieldnames.Count == 0) {
playcount_fieldnames.Add (playcount_prefix+ogg_our_creator_name);
}
string ogg_rating = BansheeToOgg (rating);
foreach (string ratingname in rating_fieldnames) {
xiphtag.SetField (ratingname, ogg_rating);
Hyena.Log.DebugFormat ("Exporting Ogg Rating={0}({1}) to File \"{2}\" as Creator \"{3}\"",
rating, ogg_rating,
to_file.Name,
ratingname.Substring (rating_prefix.Length));
}
string ogg_playcount = playcount.ToString ();
foreach (string playcountname in playcount_fieldnames) {
xiphtag.SetField (playcountname, ogg_playcount);
Hyena.Log.DebugFormat ("Exporting Ogg Playcount={0}({1}) to File \"{2}\" as Creator \"{3}\"",
playcount, ogg_playcount,
to_file.Name,
playcountname.Substring (playcount_prefix.Length));
}
}
}
public static class StreamRatingTagger
{
public static void GetRatingAndPlayCount (TagLib.File from_file,
ref int rating, ref int playcount)
{
if ((from_file.Tag.TagTypes & TagLib.TagTypes.Id3v2) != 0) {
ID3v2RatingTagger.GetRatingAndPlayCount (from_file,
ref rating, ref playcount);
}
if ((from_file.Tag.TagTypes & TagLib.TagTypes.Xiph) != 0) {
OggRatingTagger.GetRatingAndPlayCount (from_file,
ref rating, ref playcount);
}
}
public static void StoreRatingAndPlayCount (int rating, int playcount,
TagLib.File to_file)
{
if ((to_file.Tag.TagTypes & TagLib.TagTypes.Id3v2) != 0) {
ID3v2RatingTagger.StoreRatingAndPlayCount (rating, playcount,
to_file);
}
if ((to_file.Tag.TagTypes & TagLib.TagTypes.Xiph) != 0) {
OggRatingTagger.StoreRatingAndPlayCount (rating, playcount,
to_file);
}
}
}
}
| |
// Copyright (C) 2014 dot42
//
// Original filename: Javax.Security.Cert.cs
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma warning disable 1717
namespace Javax.Security.Cert
{
/// <summary>
/// <para>The exception that is thrown when a <c> Certificate </c> has expired. </para><para>Note: This package is provided only for compatibility reasons. It contains a simplified version of the java.security.cert package that was previously used by JSSE (Java SSL package). All applications that do not have to be compatible with older versions of JSSE (that is before Java SDK 1.5) should only use java.security.cert. </para>
/// </summary>
/// <java-name>
/// javax/security/cert/CertificateExpiredException
/// </java-name>
[Dot42.DexImport("javax/security/cert/CertificateExpiredException", AccessFlags = 33)]
public partial class CertificateExpiredException : global::Javax.Security.Cert.CertificateException
/* scope: __dot42__ */
{
/// <summary>
/// <para>Creates a new <c> CertificateExpiredException </c> with the specified message.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)]
public CertificateExpiredException(string msg) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Creates a new <c> CertificateExpiredException </c> . </para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public CertificateExpiredException() /* MethodBuilder.Create */
{
}
}
/// <summary>
/// <para>Abstract class to represent identity certificates. It represents a way to verify the binding of a Principal and its public key. Examples are X.509, PGP, and SDSI. </para><para>Note: This package is provided only for compatibility reasons. It contains a simplified version of the java.security.cert package that was previously used by JSSE (Java SSL package). All applications that do not have to be compatible with older versions of JSSE (that is before Java SDK 1.5) should only use java.security.cert. </para>
/// </summary>
/// <java-name>
/// javax/security/cert/Certificate
/// </java-name>
[Dot42.DexImport("javax/security/cert/Certificate", AccessFlags = 1057)]
public abstract partial class Certificate
/* scope: __dot42__ */
{
/// <summary>
/// <para>Creates a new <c> Certificate </c> . </para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public Certificate() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Compares the argument to this Certificate. If both have the same bytes they are assumed to be equal.</para><para><para>hashCode </para></para>
/// </summary>
/// <returns>
/// <para><code>true</code> if <c> obj </c> is the same as this <c> Certificate </c> , <code>false</code> otherwise </para>
/// </returns>
/// <java-name>
/// equals
/// </java-name>
[Dot42.DexImport("equals", "(Ljava/lang/Object;)Z", AccessFlags = 1)]
public override bool Equals(object obj) /* MethodBuilder.Create */
{
return default(bool);
}
/// <summary>
/// <para>Returns an integer hash code for the receiver. Any two objects which return <code>true</code> when passed to <code>equals</code> must answer the same value for this method.</para><para><para>equals </para></para>
/// </summary>
/// <returns>
/// <para>the receiver's hash </para>
/// </returns>
/// <java-name>
/// hashCode
/// </java-name>
[Dot42.DexImport("hashCode", "()I", AccessFlags = 1)]
public override int GetHashCode() /* MethodBuilder.Create */
{
return default(int);
}
/// <summary>
/// <para>Returns the encoded representation for this certificate.</para><para></para>
/// </summary>
/// <returns>
/// <para>the encoded representation for this certificate. </para>
/// </returns>
/// <java-name>
/// getEncoded
/// </java-name>
[Dot42.DexImport("getEncoded", "()[B", AccessFlags = 1025)]
public abstract sbyte[] JavaGetEncoded() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns the encoded representation for this certificate.</para><para></para>
/// </summary>
/// <returns>
/// <para>the encoded representation for this certificate. </para>
/// </returns>
/// <java-name>
/// getEncoded
/// </java-name>
[Dot42.DexImport("getEncoded", "()[B", AccessFlags = 1025, IgnoreFromJava = true)]
public abstract byte[] GetEncoded() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Verifies that this certificate was signed with the given public key.</para><para></para>
/// </summary>
/// <java-name>
/// verify
/// </java-name>
[Dot42.DexImport("verify", "(Ljava/security/PublicKey;)V", AccessFlags = 1025)]
public abstract void Verify(global::Java.Security.IPublicKey key) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Verifies that this certificate was signed with the given public key. Uses the signature algorithm given by the provider.</para><para></para>
/// </summary>
/// <java-name>
/// verify
/// </java-name>
[Dot42.DexImport("verify", "(Ljava/security/PublicKey;Ljava/lang/String;)V", AccessFlags = 1025)]
public abstract void Verify(global::Java.Security.IPublicKey key, string sigProvider) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns a string containing a concise, human-readable description of the receiver.</para><para></para>
/// </summary>
/// <returns>
/// <para>a printable representation for the receiver. </para>
/// </returns>
/// <java-name>
/// toString
/// </java-name>
[Dot42.DexImport("toString", "()Ljava/lang/String;", AccessFlags = 1025)]
public override string ToString() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Returns the public key corresponding to this certificate.</para><para></para>
/// </summary>
/// <returns>
/// <para>the public key corresponding to this certificate. </para>
/// </returns>
/// <java-name>
/// getPublicKey
/// </java-name>
[Dot42.DexImport("getPublicKey", "()Ljava/security/PublicKey;", AccessFlags = 1025)]
public abstract global::Java.Security.IPublicKey GetPublicKey() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns the encoded representation for this certificate.</para><para></para>
/// </summary>
/// <returns>
/// <para>the encoded representation for this certificate. </para>
/// </returns>
/// <java-name>
/// getEncoded
/// </java-name>
public byte[] Encoded
{
[Dot42.DexImport("getEncoded", "()[B", AccessFlags = 1025, IgnoreFromJava = true)]
get{ return GetEncoded(); }
}
/// <summary>
/// <para>Returns the public key corresponding to this certificate.</para><para></para>
/// </summary>
/// <returns>
/// <para>the public key corresponding to this certificate. </para>
/// </returns>
/// <java-name>
/// getPublicKey
/// </java-name>
public global::Java.Security.IPublicKey PublicKey
{
[Dot42.DexImport("getPublicKey", "()Ljava/security/PublicKey;", AccessFlags = 1025)]
get{ return GetPublicKey(); }
}
}
/// <summary>
/// <para>Abstract base class for X.509 certificates. </para><para>This represents a standard way for accessing the attributes of X.509 v1 certificates. </para><para>Note: This package is provided only for compatibility reasons. It contains a simplified version of the java.security.cert package that was previously used by JSSE (Java SSL package). All applications that do not have to be compatible with older versions of JSSE (that is before Java SDK 1.5) should only use java.security.cert. </para>
/// </summary>
/// <java-name>
/// javax/security/cert/X509Certificate
/// </java-name>
[Dot42.DexImport("javax/security/cert/X509Certificate", AccessFlags = 1057)]
public abstract partial class X509Certificate : global::Javax.Security.Cert.Certificate
/* scope: __dot42__ */
{
/// <summary>
/// <para>Creates a new <c> X509Certificate </c> . </para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public X509Certificate() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Creates a new <c> X509Certificate </c> and initializes it from the specified input stream.</para><para></para>
/// </summary>
/// <returns>
/// <para>the certificate initialized from the specified input stream </para>
/// </returns>
/// <java-name>
/// getInstance
/// </java-name>
[Dot42.DexImport("getInstance", "(Ljava/io/InputStream;)Ljavax/security/cert/X509Certificate;", AccessFlags = 25)]
public static global::Javax.Security.Cert.X509Certificate GetInstance(global::Java.Io.InputStream inStream) /* MethodBuilder.Create */
{
return default(global::Javax.Security.Cert.X509Certificate);
}
/// <summary>
/// <para>Creates a new <c> X509Certificate </c> and initializes it from the specified input stream.</para><para></para>
/// </summary>
/// <returns>
/// <para>the certificate initialized from the specified input stream </para>
/// </returns>
/// <java-name>
/// getInstance
/// </java-name>
[Dot42.DexImport("getInstance", "([B)Ljavax/security/cert/X509Certificate;", AccessFlags = 25)]
public static global::Javax.Security.Cert.X509Certificate GetInstance(sbyte[] inStream) /* MethodBuilder.Create */
{
return default(global::Javax.Security.Cert.X509Certificate);
}
/// <summary>
/// <para>Creates a new <c> X509Certificate </c> and initializes it from the specified input stream.</para><para></para>
/// </summary>
/// <returns>
/// <para>the certificate initialized from the specified input stream </para>
/// </returns>
/// <java-name>
/// getInstance
/// </java-name>
[Dot42.DexImport("getInstance", "([B)Ljavax/security/cert/X509Certificate;", AccessFlags = 25, IgnoreFromJava = true)]
public static global::Javax.Security.Cert.X509Certificate GetInstance(byte[] inStream) /* MethodBuilder.Create */
{
return default(global::Javax.Security.Cert.X509Certificate);
}
/// <summary>
/// <para>Checks whether the certificate is currently valid. </para><para>The validity defined in ASN.1:</para><para><pre>
/// validity Validity
///
/// Validity ::= SEQUENCE {
/// notBefore CertificateValidityDate,
/// notAfter CertificateValidityDate }
///
/// CertificateValidityDate ::= CHOICE {
/// utcTime UTCTime,
/// generalTime GeneralizedTime }
/// </pre></para><para></para>
/// </summary>
/// <java-name>
/// checkValidity
/// </java-name>
[Dot42.DexImport("checkValidity", "()V", AccessFlags = 1025)]
public abstract void CheckValidity() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Checks whether the certificate is valid at the specified date.</para><para><para>checkValidity() </para></para>
/// </summary>
/// <java-name>
/// checkValidity
/// </java-name>
[Dot42.DexImport("checkValidity", "(Ljava/util/Date;)V", AccessFlags = 1025)]
public abstract void CheckValidity(global::Java.Util.Date date) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns the certificates <c> version </c> (version number). </para><para>The version defined is ASN.1:</para><para><pre>
/// Version ::= INTEGER { v1(0), v2(1), v3(2) }
/// </pre></para><para></para>
/// </summary>
/// <returns>
/// <para>the version number. </para>
/// </returns>
/// <java-name>
/// getVersion
/// </java-name>
[Dot42.DexImport("getVersion", "()I", AccessFlags = 1025)]
public abstract int GetVersion() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns the <c> serialNumber </c> of the certificate. </para><para>The ASN.1 definition of <c> serialNumber </c> :</para><para><pre>
/// CertificateSerialNumber ::= INTEGER
/// </pre></para><para></para>
/// </summary>
/// <returns>
/// <para>the serial number. </para>
/// </returns>
/// <java-name>
/// getSerialNumber
/// </java-name>
[Dot42.DexImport("getSerialNumber", "()Ljava/math/BigInteger;", AccessFlags = 1025)]
public abstract global::Java.Math.BigInteger GetSerialNumber() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns the <c> issuer </c> (issuer distinguished name) as an implementation specific <c> Principal </c> object. </para><para>The ASN.1 definition of <c> issuer </c> :</para><para><pre>
/// issuer Name
///
/// Name ::= CHOICE {
/// RDNSequence }
///
/// RDNSequence ::= SEQUENCE OF RelativeDistinguishedName
///
/// RelativeDistinguishedName ::= SET OF AttributeTypeAndValue
///
/// AttributeTypeAndValue ::= SEQUENCE {
/// type AttributeType,
/// value AttributeValue }
///
/// AttributeType ::= OBJECT IDENTIFIER
///
/// AttributeValue ::= ANY DEFINED BY AttributeType
/// </pre></para><para></para>
/// </summary>
/// <returns>
/// <para>the <c> issuer </c> as an implementation specific <c> Principal </c> . </para>
/// </returns>
/// <java-name>
/// getIssuerDN
/// </java-name>
[Dot42.DexImport("getIssuerDN", "()Ljava/security/Principal;", AccessFlags = 1025)]
public abstract global::Java.Security.IPrincipal GetIssuerDN() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns the <c> subject </c> (subject distinguished name) as an implementation specific <c> Principal </c> object. </para><para>The ASN.1 definition of <c> subject </c> :</para><para><pre>
/// subject Name
///
/// Name ::= CHOICE {
/// RDNSequence }
///
/// RDNSequence ::= SEQUENCE OF RelativeDistinguishedName
///
/// RelativeDistinguishedName ::= SET OF AttributeTypeAndValue
///
/// AttributeTypeAndValue ::= SEQUENCE {
/// type AttributeType,
/// value AttributeValue }
///
/// AttributeType ::= OBJECT IDENTIFIER
///
/// AttributeValue ::= ANY DEFINED BY AttributeType
/// </pre></para><para></para>
/// </summary>
/// <returns>
/// <para>the <c> subject </c> (subject distinguished name). </para>
/// </returns>
/// <java-name>
/// getSubjectDN
/// </java-name>
[Dot42.DexImport("getSubjectDN", "()Ljava/security/Principal;", AccessFlags = 1025)]
public abstract global::Java.Security.IPrincipal GetSubjectDN() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns the <c> notBefore </c> date from the validity period of the certificate.</para><para></para>
/// </summary>
/// <returns>
/// <para>the start of the validity period. </para>
/// </returns>
/// <java-name>
/// getNotBefore
/// </java-name>
[Dot42.DexImport("getNotBefore", "()Ljava/util/Date;", AccessFlags = 1025)]
public abstract global::Java.Util.Date GetNotBefore() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns the <c> notAfter </c> date of the validity period of the certificate.</para><para></para>
/// </summary>
/// <returns>
/// <para>the end of the validity period. </para>
/// </returns>
/// <java-name>
/// getNotAfter
/// </java-name>
[Dot42.DexImport("getNotAfter", "()Ljava/util/Date;", AccessFlags = 1025)]
public abstract global::Java.Util.Date GetNotAfter() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns the name of the algorithm for the certificate signature.</para><para></para>
/// </summary>
/// <returns>
/// <para>the signature algorithm name. </para>
/// </returns>
/// <java-name>
/// getSigAlgName
/// </java-name>
[Dot42.DexImport("getSigAlgName", "()Ljava/lang/String;", AccessFlags = 1025)]
public abstract string GetSigAlgName() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns the OID of the signature algorithm from the certificate.</para><para></para>
/// </summary>
/// <returns>
/// <para>the OID of the signature algorithm. </para>
/// </returns>
/// <java-name>
/// getSigAlgOID
/// </java-name>
[Dot42.DexImport("getSigAlgOID", "()Ljava/lang/String;", AccessFlags = 1025)]
public abstract string GetSigAlgOID() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns the parameters of the signature algorithm in DER-encoded format.</para><para></para>
/// </summary>
/// <returns>
/// <para>the parameters of the signature algorithm, or null if none are used. </para>
/// </returns>
/// <java-name>
/// getSigAlgParams
/// </java-name>
[Dot42.DexImport("getSigAlgParams", "()[B", AccessFlags = 1025)]
public abstract sbyte[] JavaGetSigAlgParams() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns the parameters of the signature algorithm in DER-encoded format.</para><para></para>
/// </summary>
/// <returns>
/// <para>the parameters of the signature algorithm, or null if none are used. </para>
/// </returns>
/// <java-name>
/// getSigAlgParams
/// </java-name>
[Dot42.DexImport("getSigAlgParams", "()[B", AccessFlags = 1025, IgnoreFromJava = true)]
public abstract byte[] GetSigAlgParams() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns the certificates <c> version </c> (version number). </para><para>The version defined is ASN.1:</para><para><pre>
/// Version ::= INTEGER { v1(0), v2(1), v3(2) }
/// </pre></para><para></para>
/// </summary>
/// <returns>
/// <para>the version number. </para>
/// </returns>
/// <java-name>
/// getVersion
/// </java-name>
public int Version
{
[Dot42.DexImport("getVersion", "()I", AccessFlags = 1025)]
get{ return GetVersion(); }
}
/// <summary>
/// <para>Returns the <c> serialNumber </c> of the certificate. </para><para>The ASN.1 definition of <c> serialNumber </c> :</para><para><pre>
/// CertificateSerialNumber ::= INTEGER
/// </pre></para><para></para>
/// </summary>
/// <returns>
/// <para>the serial number. </para>
/// </returns>
/// <java-name>
/// getSerialNumber
/// </java-name>
public global::Java.Math.BigInteger SerialNumber
{
[Dot42.DexImport("getSerialNumber", "()Ljava/math/BigInteger;", AccessFlags = 1025)]
get{ return GetSerialNumber(); }
}
/// <summary>
/// <para>Returns the <c> issuer </c> (issuer distinguished name) as an implementation specific <c> Principal </c> object. </para><para>The ASN.1 definition of <c> issuer </c> :</para><para><pre>
/// issuer Name
///
/// Name ::= CHOICE {
/// RDNSequence }
///
/// RDNSequence ::= SEQUENCE OF RelativeDistinguishedName
///
/// RelativeDistinguishedName ::= SET OF AttributeTypeAndValue
///
/// AttributeTypeAndValue ::= SEQUENCE {
/// type AttributeType,
/// value AttributeValue }
///
/// AttributeType ::= OBJECT IDENTIFIER
///
/// AttributeValue ::= ANY DEFINED BY AttributeType
/// </pre></para><para></para>
/// </summary>
/// <returns>
/// <para>the <c> issuer </c> as an implementation specific <c> Principal </c> . </para>
/// </returns>
/// <java-name>
/// getIssuerDN
/// </java-name>
public global::Java.Security.IPrincipal IssuerDN
{
[Dot42.DexImport("getIssuerDN", "()Ljava/security/Principal;", AccessFlags = 1025)]
get{ return GetIssuerDN(); }
}
/// <summary>
/// <para>Returns the <c> subject </c> (subject distinguished name) as an implementation specific <c> Principal </c> object. </para><para>The ASN.1 definition of <c> subject </c> :</para><para><pre>
/// subject Name
///
/// Name ::= CHOICE {
/// RDNSequence }
///
/// RDNSequence ::= SEQUENCE OF RelativeDistinguishedName
///
/// RelativeDistinguishedName ::= SET OF AttributeTypeAndValue
///
/// AttributeTypeAndValue ::= SEQUENCE {
/// type AttributeType,
/// value AttributeValue }
///
/// AttributeType ::= OBJECT IDENTIFIER
///
/// AttributeValue ::= ANY DEFINED BY AttributeType
/// </pre></para><para></para>
/// </summary>
/// <returns>
/// <para>the <c> subject </c> (subject distinguished name). </para>
/// </returns>
/// <java-name>
/// getSubjectDN
/// </java-name>
public global::Java.Security.IPrincipal SubjectDN
{
[Dot42.DexImport("getSubjectDN", "()Ljava/security/Principal;", AccessFlags = 1025)]
get{ return GetSubjectDN(); }
}
/// <summary>
/// <para>Returns the <c> notBefore </c> date from the validity period of the certificate.</para><para></para>
/// </summary>
/// <returns>
/// <para>the start of the validity period. </para>
/// </returns>
/// <java-name>
/// getNotBefore
/// </java-name>
public global::Java.Util.Date NotBefore
{
[Dot42.DexImport("getNotBefore", "()Ljava/util/Date;", AccessFlags = 1025)]
get{ return GetNotBefore(); }
}
/// <summary>
/// <para>Returns the <c> notAfter </c> date of the validity period of the certificate.</para><para></para>
/// </summary>
/// <returns>
/// <para>the end of the validity period. </para>
/// </returns>
/// <java-name>
/// getNotAfter
/// </java-name>
public global::Java.Util.Date NotAfter
{
[Dot42.DexImport("getNotAfter", "()Ljava/util/Date;", AccessFlags = 1025)]
get{ return GetNotAfter(); }
}
/// <summary>
/// <para>Returns the name of the algorithm for the certificate signature.</para><para></para>
/// </summary>
/// <returns>
/// <para>the signature algorithm name. </para>
/// </returns>
/// <java-name>
/// getSigAlgName
/// </java-name>
public string SigAlgName
{
[Dot42.DexImport("getSigAlgName", "()Ljava/lang/String;", AccessFlags = 1025)]
get{ return GetSigAlgName(); }
}
/// <summary>
/// <para>Returns the OID of the signature algorithm from the certificate.</para><para></para>
/// </summary>
/// <returns>
/// <para>the OID of the signature algorithm. </para>
/// </returns>
/// <java-name>
/// getSigAlgOID
/// </java-name>
public string SigAlgOID
{
[Dot42.DexImport("getSigAlgOID", "()Ljava/lang/String;", AccessFlags = 1025)]
get{ return GetSigAlgOID(); }
}
/// <summary>
/// <para>Returns the parameters of the signature algorithm in DER-encoded format.</para><para></para>
/// </summary>
/// <returns>
/// <para>the parameters of the signature algorithm, or null if none are used. </para>
/// </returns>
/// <java-name>
/// getSigAlgParams
/// </java-name>
public byte[] SigAlgParams
{
[Dot42.DexImport("getSigAlgParams", "()[B", AccessFlags = 1025, IgnoreFromJava = true)]
get{ return GetSigAlgParams(); }
}
}
/// <summary>
/// <para>The exception that is thrown when a <c> Certificate </c> is not yet valid. </para><para>Note: This package is provided only for compatibility reasons. It contains a simplified version of the java.security.cert package that was previously used by JSSE (Java SSL package). All applications that do not have to be compatible with older versions of JSSE (that is before Java SDK 1.5) should only use java.security.cert. </para>
/// </summary>
/// <java-name>
/// javax/security/cert/CertificateNotYetValidException
/// </java-name>
[Dot42.DexImport("javax/security/cert/CertificateNotYetValidException", AccessFlags = 33)]
public partial class CertificateNotYetValidException : global::Javax.Security.Cert.CertificateException
/* scope: __dot42__ */
{
/// <summary>
/// <para>Creates a new <c> CertificateNotYetValidException </c> with the specified message.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)]
public CertificateNotYetValidException(string msg) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Creates a new <c> CertificateNotYetValidException </c> . </para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public CertificateNotYetValidException() /* MethodBuilder.Create */
{
}
}
/// <summary>
/// <para>The base class for all <c> Certificate </c> related exceptions. </para><para>Note: This package is provided only for compatibility reasons. It contains a simplified version of the java.security.cert package that was previously used by JSSE (Java SSL package). All applications that do not have to be compatible with older versions of JSSE (that is before Java SDK 1.5) should only use java.security.cert. </para>
/// </summary>
/// <java-name>
/// javax/security/cert/CertificateException
/// </java-name>
[Dot42.DexImport("javax/security/cert/CertificateException", AccessFlags = 33)]
public partial class CertificateException : global::System.Exception
/* scope: __dot42__ */
{
/// <summary>
/// <para>Creates a new <c> CertificateException </c> with the specified message.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)]
public CertificateException(string msg) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Creates a new <c> CertificateException </c> . </para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public CertificateException() /* MethodBuilder.Create */
{
}
}
/// <summary>
/// <para>The exception that is thrown when an error occurs while a <c> Certificate </c> is being encoded. </para><para>Note: This package is provided only for compatibility reasons. It contains a simplified version of the java.security.cert package that was previously used by JSSE (Java SSL package). All applications that do not have to be compatible with older versions of JSSE (that is before Java SDK 1.5) should only use java.security.cert. </para>
/// </summary>
/// <java-name>
/// javax/security/cert/CertificateEncodingException
/// </java-name>
[Dot42.DexImport("javax/security/cert/CertificateEncodingException", AccessFlags = 33)]
public partial class CertificateEncodingException : global::Javax.Security.Cert.CertificateException
/* scope: __dot42__ */
{
/// <summary>
/// <para>Creates a new <c> CertificateEncodingException </c> with the specified message.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)]
public CertificateEncodingException(string msg) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Creates a new <c> CertificateEncodingException </c> . </para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public CertificateEncodingException() /* MethodBuilder.Create */
{
}
}
/// <summary>
/// <para>The exception that is thrown when a <c> Certificate </c> can not be parsed. </para><para>Note: This package is provided only for compatibility reasons. It contains a simplified version of the java.security.cert package that was previously used by JSSE (Java SSL package). All applications that do not have to be compatible with older versions of JSSE (that is before Java SDK 1.5) should only use java.security.cert. </para>
/// </summary>
/// <java-name>
/// javax/security/cert/CertificateParsingException
/// </java-name>
[Dot42.DexImport("javax/security/cert/CertificateParsingException", AccessFlags = 33)]
public partial class CertificateParsingException : global::Javax.Security.Cert.CertificateException
/* scope: __dot42__ */
{
/// <summary>
/// <para>Creates a new <c> CertificateParsingException </c> with the specified message.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)]
public CertificateParsingException(string msg) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Creates a new <c> CertificateParsingException </c> . </para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public CertificateParsingException() /* MethodBuilder.Create */
{
}
}
}
| |
// 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.Sockets;
using Xunit;
namespace System.Net.Primitives.Functional.Tests
{
public sealed class IPAddressParsing_String : IPAddressParsing
{
public override IPAddress Parse(string ipString) => IPAddress.Parse(ipString);
public override bool TryParse(string ipString, out IPAddress address) => IPAddress.TryParse(ipString, out address);
[Fact]
public void Parse_Null_Throws()
{
Assert.Throws<ArgumentNullException>(() => Parse((string)null));
Assert.False(TryParse((string)null, out IPAddress ipAddress));
Assert.Null(ipAddress);
}
}
public abstract class IPAddressParsing
{
public abstract IPAddress Parse(string ipString);
public abstract bool TryParse(string ipString, out IPAddress address);
public static readonly object[][] ValidIpv4Addresses =
{
// Decimal
new object[] { "192.168.0.1", "192.168.0.1" },
new object[] { "0.0.0.0", "0.0.0.0" },
new object[] { "0", "0.0.0.0" },
new object[] { "12", "0.0.0.12" },
new object[] { "12.1.7", "12.1.0.7" },
new object[] { "12.1.7", "12.1.0.7" },
new object[] { "255.255.255.255", "255.255.255.255" },
new object[] { "20.65535", "20.0.255.255" },
new object[] { "157.3873051", "157.59.25.27" },
new object[] { "157.6427", "157.0.25.27" },
new object[] { "65535", "0.0.255.255" },
new object[] { "65536", "0.1.0.0" },
new object[] { "1434328179", "85.126.28.115" },
new object[] { "2637895963", "157.59.25.27" },
new object[] { "3397943208", "202.136.127.168" },
new object[] { "4294967294", "255.255.255.254" },
new object[] { "4294967295", "255.255.255.255" },
//Hex
new object[] { "0xFF.0xFF.0xFF.0xFF", "255.255.255.255" },
new object[] { "0x0", "0.0.0.0" },
new object[] { "0xFFFFFFFE", "255.255.255.254" },
new object[] { "0xFFFFFFFF", "255.255.255.255" },
new object[] { "0x9D3B191B", "157.59.25.27" },
new object[] { "0X9D.0x3B.0X19.0x1B", "157.59.25.27" },
new object[] { "0x89.0xab.0xcd.0xef", "137.171.205.239" },
new object[] { "0xff.0x7f.0x20.0x01", "255.127.32.1" },
// Octal
new object[] { "0313.027035210", "203.92.58.136" },
new object[] { "0313.0134.035210", "203.92.58.136" },
new object[] { "0377.0377.0377.0377", "255.255.255.255" },
new object[] { "037777777776", "255.255.255.254" },
new object[] { "037777777777", "255.255.255.255" },
new object[] { "023516614433", "157.59.25.27" },
new object[] { "00000023516614433", "157.59.25.27" },
new object[] { "000235.000073.0000031.00000033", "157.59.25.27" },
new object[] { "0235.073.031.033", "157.59.25.27" },
new object[] { "157.59.25.033", "157.59.25.27" }, // Partial octal
// Mixed base
new object[] { "157.59.25.0x1B", "157.59.25.27" },
new object[] { "157.59.0x001B", "157.59.0.27" },
new object[] { "157.0x00001B", "157.0.0.27" },
new object[] { "157.59.0x25.033", "157.59.37.27" },
};
[Theory]
[MemberData(nameof(ValidIpv4Addresses))]
public void ParseIPv4_ValidAddress_Success(string address, string expected)
{
IPAddress ip = Parse(address);
// Validate the ToString of the parsed address matches the expected value
Assert.Equal(expected, ip.ToString());
Assert.Equal(AddressFamily.InterNetwork, ip.AddressFamily);
// Validate the ToString representation can be parsed as well back into the same IP
IPAddress ip2 = Parse(ip.ToString());
Assert.Equal(ip, ip2);
}
public static readonly object[][] InvalidIpv4Addresses =
{
new object[] { " 127.0.0.1" }, // leading whitespace
new object[] { "127.0.0.1 " }, // trailing whitespace
new object[] { " 127.0.0.1 " }, // leading and trailing whitespace
new object[] { "192.168.0.0/16" }, // with subnet
new object[] { "157.3B191B" }, // Hex without 0x
new object[] { "1.1.1.0x" }, // Empty trailing hex segment
new object[] { "0000X9D.0x3B.0X19.0x1B" }, // Leading zeros on hex
new object[] { "0x.1.1.1" }, // Empty leading hex segment
new object[] { "260.156" }, // Left dotted segments can't be more than 255
new object[] { "255.260.156" }, // Left dotted segments can't be more than 255
new object[] { "255.1.1.256" }, // Right dotted segment can't be more than 255
new object[] { "0xFF.0xFFFFFF.0xFF" }, // Middle segment too large
new object[] { "0xFFFFFF.0xFF.0xFFFFFF" }, // Leading segment too large
new object[] { "4294967296" }, // Decimal overflow by 1
new object[] { "040000000000" }, // Octal overflow by 1
new object[] { "01011101001110110001100100011011" }, // Binary? Read as octal, overflows
new object[] { "10011101001110110001100100011011" }, // Binary? Read as decimal, overflows
new object[] { "0x100000000" }, // Hex overflow by 1
new object[] { "1.1\u67081.1.1" }, // Invalid char (unicode)
new object[] { "..." }, // Empty sections
new object[] { "1.1.1." }, // Empty trailing section
new object[] { "1..1.1" }, // Empty internal section
new object[] { ".1.1.1" }, // Empty leading section
new object[] { "..11.1" }, // Empty sections
new object[] { " text" }, // alpha text
new object[] { "1.. ." }, // whitespace section
new object[] { "12.1.8. " }, // trailing whitespace section
new object[] { "12.+1.1.4" }, // plus sign in section
new object[] { "12.1.-1.5" }, // minus sign in section
new object[] { "12.1.abc.5" }, // text in section
};
public static readonly object[][] InvalidIpv4AddressesStandalone = // but valid as part of IPv6 addresses
{
new object[] { "" }, // empty
new object[] { " " }, // whitespace
new object[] { " " }, // whitespace
new object[] { "0.0.0.089" }, // Octal (leading zero) but with 8 or 9
};
[Theory]
[MemberData(nameof(InvalidIpv4Addresses))]
[MemberData(nameof(InvalidIpv4AddressesStandalone))]
public void ParseIPv4_InvalidAddress_Failure(string address)
{
ParseInvalidAddress(address, hasInnerSocketException: !PlatformDetection.IsFullFramework);
}
public static readonly object[][] Ipv4AddressesWithPort =
{
new object[] { "192.168.0.0:80" }, // with port
new object[] { "192.168.0.1:80" }, // with port
};
[Theory]
[MemberData(nameof(Ipv4AddressesWithPort))]
public void ParseIPv4_InvalidAddress_ThrowsFormatExceptionWithInnerException(string address)
{
ParseInvalidAddress(address, hasInnerSocketException: true);
}
public static readonly object[][] ValidIpv6Addresses =
{
new object[] { "Fe08::1", "fe08::1" },
new object[] { "0000:0000:0000:0000:0000:0000:0000:0000", "::" },
new object[] { "FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF", "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff" },
new object[] { "0:0:0:0:0:0:0:0", "::" },
new object[] { "1:0:0:0:0:0:0:0", "1::" },
new object[] { "0:1:0:0:0:0:0:0", "0:1::" },
new object[] { "0:0:1:0:0:0:0:0", "0:0:1::" },
new object[] { "0:0:0:1:0:0:0:0", "0:0:0:1::" },
new object[] { "0:0:0:0:1:0:0:0", "::1:0:0:0" },
new object[] { "0:0:0:0:0:1:0:0", "::1:0:0" },
new object[] { "0:0:0:0:0:0:1:0", "::0.1.0.0" },
new object[] { "0:0:0:0:0:0:2:0", "::0.2.0.0" },
new object[] { "0:0:0:0:0:0:F:0", "::0.15.0.0" },
new object[] { "0:0:0:0:0:0:10:0", "::0.16.0.0" },
new object[] { "0:0:0:0:0:0:A0:0", "::0.160.0.0" },
new object[] { "0:0:0:0:0:0:F0:0", "::0.240.0.0" },
new object[] { "0:0:0:0:0:0:FF:0", "::0.255.0.0" },
new object[] { "0:0:0:0:0:0:0:1", "::1" },
new object[] { "0:0:0:0:0:0:0:2", "::2" },
new object[] { "0:0:0:0:0:0:0:F", "::F" },
new object[] { "0:0:0:0:0:0:0:10", "::10" },
new object[] { "0:0:0:0:0:0:0:1A", "::1A" },
new object[] { "0:0:0:0:0:0:0:A0", "::A0" },
new object[] { "0:0:0:0:0:0:0:F0", "::F0" },
new object[] { "0:0:0:0:0:0:0:FF", "::FF" },
new object[] { "0:0:0:0:0:0:0:1001", "::1001" },
new object[] { "0:0:0:0:0:0:0:1002", "::1002" },
new object[] { "0:0:0:0:0:0:0:100F", "::100F" },
new object[] { "0:0:0:0:0:0:0:1010", "::1010" },
new object[] { "0:0:0:0:0:0:0:10A0", "::10A0" },
new object[] { "0:0:0:0:0:0:0:10F0", "::10F0" },
new object[] { "0:0:0:0:0:0:0:10FF", "::10FF" },
new object[] { "0:0:0:0:0:0:1:1", "::0.1.0.1" },
new object[] { "0:0:0:0:0:0:2:2", "::0.2.0.2" },
new object[] { "0:0:0:0:0:0:F:F", "::0.15.0.15" },
new object[] { "0:0:0:0:0:0:10:10", "::0.16.0.16" },
new object[] { "0:0:0:0:0:0:A0:A0", "::0.160.0.160" },
new object[] { "0:0:0:0:0:0:F0:F0", "::0.240.0.240" },
new object[] { "0:0:0:0:0:0:FF:FF", "::0.255.0.255" },
new object[] { "0:0:0:0:0:FFFF:0:1", "::FFFF:0:1" },
new object[] { "0:0:0:0:0:FFFF:0:2", "::FFFF:0:2" },
new object[] { "0:0:0:0:0:FFFF:0:F", "::FFFF:0:F" },
new object[] { "0:0:0:0:0:FFFF:0:10", "::FFFF:0:10" },
new object[] { "0:0:0:0:0:FFFF:0:A0", "::FFFF:0:A0" },
new object[] { "0:0:0:0:0:FFFF:0:F0", "::FFFF:0:F0" },
new object[] { "0:0:0:0:0:FFFF:0:FF", "::FFFF:0:FF" },
new object[] { "0:0:0:0:0:FFFF:1:0", "::FFFF:0.1.0.0" },
new object[] { "0:0:0:0:0:FFFF:2:0", "::FFFF:0.2.0.0" },
new object[] { "0:0:0:0:0:FFFF:F:0", "::FFFF:0.15.0.0" },
new object[] { "0:0:0:0:0:FFFF:10:0", "::FFFF:0.16.0.0" },
new object[] { "0:0:0:0:0:FFFF:A0:0", "::FFFF:0.160.0.0" },
new object[] { "0:0:0:0:0:FFFF:F0:0", "::FFFF:0.240.0.0" },
new object[] { "0:0:0:0:0:FFFF:FF:0", "::FFFF:0.255.0.0" },
new object[] { "0:0:0:0:0:FFFF:0:1001", "::FFFF:0:1001" },
new object[] { "0:0:0:0:0:FFFF:0:1002", "::FFFF:0:1002" },
new object[] { "0:0:0:0:0:FFFF:0:100F", "::FFFF:0:100F" },
new object[] { "0:0:0:0:0:FFFF:0:1010", "::FFFF:0:1010" },
new object[] { "0:0:0:0:0:FFFF:0:10A0", "::FFFF:0:10A0" },
new object[] { "0:0:0:0:0:FFFF:0:10F0", "::FFFF:0:10F0" },
new object[] { "0:0:0:0:0:FFFF:0:10FF", "::FFFF:0:10FF" },
new object[] { "0:0:0:0:0:FFFF:1:1", "::FFFF:0.1.0.1" },
new object[] { "0:0:0:0:0:FFFF:2:2", "::FFFF:0.2.0.2" },
new object[] { "0:0:0:0:0:FFFF:F:F", "::FFFF:0.15.0.15" },
new object[] { "0:0:0:0:0:FFFF:10:10", "::FFFF:0.16.0.16" },
new object[] { "0:0:0:0:0:FFFF:A0:A0", "::FFFF:0.160.0.160" },
new object[] { "0:0:0:0:0:FFFF:F0:F0", "::FFFF:0.240.0.240" },
new object[] { "0:0:0:0:0:FFFF:FF:FF", "::FFFF:0.255.0.255" },
new object[] { "0:7:7:7:7:7:7:7", "0:7:7:7:7:7:7:7" },
new object[] { "1:0:0:0:0:0:0:1", "1::1" },
new object[] { "1:1:0:0:0:0:0:0", "1:1::" },
new object[] { "2:2:0:0:0:0:0:0", "2:2::" },
new object[] { "1:1:0:0:0:0:0:1", "1:1::1" },
new object[] { "1:0:1:0:0:0:0:1", "1:0:1::1" },
new object[] { "1:0:0:1:0:0:0:1", "1:0:0:1::1" },
new object[] { "1:0:0:0:1:0:0:1", "1::1:0:0:1" },
new object[] { "1:0:0:0:0:1:0:1", "1::1:0:1" },
new object[] { "1:0:0:0:0:0:1:1", "1::1:1" },
new object[] { "1:1:0:0:1:0:0:1", "1:1::1:0:0:1" },
new object[] { "1:0:1:0:0:1:0:1", "1:0:1::1:0:1" },
new object[] { "1:0:0:1:0:0:1:1", "1::1:0:0:1:1" },
new object[] { "1:1:0:0:0:1:0:1", "1:1::1:0:1" },
new object[] { "1:0:0:0:1:0:1:1", "1::1:0:1:1" },
new object[] { "1:1:1:1:1:1:1:0", "1:1:1:1:1:1:1:0" },
new object[] { "7:7:7:7:7:7:7:0", "7:7:7:7:7:7:7:0" },
new object[] { "E:0:0:0:0:0:0:1", "E::1" },
new object[] { "E:0:0:0:0:0:2:2", "E::2:2" },
new object[] { "E:0:6:6:6:6:6:6", "E:0:6:6:6:6:6:6" },
new object[] { "E:E:0:0:0:0:0:1", "E:E::1" },
new object[] { "E:E:0:0:0:0:2:2", "E:E::2:2" },
new object[] { "E:E:0:5:5:5:5:5", "E:E:0:5:5:5:5:5" },
new object[] { "E:E:E:0:0:0:0:1", "E:E:E::1" },
new object[] { "E:E:E:0:0:0:2:2", "E:E:E::2:2" },
new object[] { "E:E:E:0:4:4:4:4", "E:E:E:0:4:4:4:4" },
new object[] { "E:E:E:E:0:0:0:1", "E:E:E:E::1" },
new object[] { "E:E:E:E:0:0:2:2", "E:E:E:E::2:2" },
new object[] { "E:E:E:E:0:3:3:3", "E:E:E:E:0:3:3:3" },
new object[] { "E:E:E:E:E:0:0:1", "E:E:E:E:E::1" },
new object[] { "E:E:E:E:E:0:2:2", "E:E:E:E:E:0:2:2" },
new object[] { "E:E:E:E:E:E:0:1", "E:E:E:E:E:E:0:1" },
new object[] { "::2:3:4:5:6:7:8", "0:2:3:4:5:6:7:8" },
new object[] { "1:2:3:4:5:6:7::", "1:2:3:4:5:6:7:0" },
new object[] { "::FFFF:192.168.0.1", "::FFFF:192.168.0.1" },
new object[] { "::FFFF:0.168.0.1", "::FFFF:0.168.0.1" },
new object[] { "::0.0.255.255", "::FFFF" },
new object[] { "::EEEE:10.0.0.1", "::EEEE:A00:1" },
new object[] { "::10.0.0.1", "::10.0.0.1" },
new object[] { "1234:0:0:0:0:1234:0:0", "1234::1234:0:0" },
new object[] { "1:0:1:0:1:0:1:0", "1:0:1:0:1:0:1:0" },
new object[] { "1:1:1:0:0:1:1:0", "1:1:1::1:1:0" },
new object[] { "0:0:0:0:0:1234:0:0", "::1234:0:0" },
new object[] { "3ffe:38e1::0100:1:0001", "3ffe:38e1::100:1:1" },
new object[] { "0:0:1:2:00:00:000:0000", "0:0:1:2::" },
new object[] { "100:0:1:2:0:0:000:abcd", "100:0:1:2::abcd" },
new object[] { "ffff:0:0:0:0:0:00:abcd", "ffff::abcd" },
new object[] { "ffff:0:0:2:0:0:00:abcd", "ffff:0:0:2::abcd" },
new object[] { "0:0:1:2:0:00:0000:0000", "0:0:1:2::" },
new object[] { "0000:0000::1:0000:0000", "::1:0:0" },
new object[] { "0:0:111:234:5:6:789A:0", "::111:234:5:6:789a:0" },
new object[] { "11:22:33:44:55:66:77:8", "11:22:33:44:55:66:77:8" },
new object[] { "::7711:ab42:1230:0:0:0", "0:0:7711:ab42:1230::" },
new object[] { "::", "::" },
new object[] { "[Fe08::1]", "fe08::1" }, // brackets dropped
new object[] { "[Fe08::1]:0x80", "fe08::1" }, // brackets and port dropped
new object[] { "[Fe08::1]:0xFA", "fe08::1" }, // brackets and port dropped
new object[] { "2001:0db8::0001", "2001:db8::1" }, // leading 0s suppressed
new object[] { "3731:54:65fe:2::a7", "3731:54:65fe:2::a7" }, // Unicast
new object[] { "3731:54:65fe:2::a8", "3731:54:65fe:2::a8" }, // Anycast
// ScopeID
new object[] { "Fe08::1%13542", "fe08::1%13542" },
new object[] { "1::%1", "1::%1" },
new object[] { "::1%12", "::1%12" },
new object[] { "::%123", "::%123" },
new object[] { "Fe08::1%unknowninterface", "fe08::1" },
// v4 as v6
new object[] { "FE08::192.168.0.1", "fe08::c0a8:1" }, // Output is not IPv4 mapped
new object[] { "::192.168.0.1", "::192.168.0.1" },
new object[] { "::FFFF:192.168.0.1", "::ffff:192.168.0.1" }, // SIIT
new object[] { "::FFFF:0:192.168.0.1", "::ffff:0:192.168.0.1" }, // SIIT
new object[] { "::5EFE:192.168.0.1", "::5efe:192.168.0.1" }, // ISATAP
new object[] { "1::5EFE:192.168.0.1", "1::5efe:192.168.0.1" }, // ISATAP
new object[] { "::192.168.0.010", "::192.168.0.10" }, // Embedded IPv4 octal, read as decimal
};
[Theory]
[MemberData(nameof(ValidIpv6Addresses))]
public void ParseIPv6_ValidAddress_RoundtripMatchesExpected(string address, string expected)
{
IPAddress ip = Parse(address);
// Validate the ToString of the parsed address matches the expected value
Assert.Equal(expected.ToLowerInvariant(), ip.ToString());
Assert.Equal(AddressFamily.InterNetworkV6, ip.AddressFamily);
// Validate the ToString representation can be parsed as well back into the same IP
IPAddress ip2 = Parse(ip.ToString());
Assert.Equal(ip, ip2);
// Validate that anything that doesn't already start with brackets
// can be surrounded with brackets and still parse successfully.
if (!address.StartsWith("["))
{
Assert.Equal(
expected.ToLowerInvariant(),
Parse("[" + address + "]").ToString());
}
}
[Theory]
[MemberData(nameof(ValidIpv6Addresses))]
public void TryParseIPv6_ValidAddress_RoundtripMatchesExpected(string address, string expected)
{
Assert.True(TryParse(address, out IPAddress ip));
// Validate the ToString of the parsed address matches the expected value
Assert.Equal(expected.ToLowerInvariant(), ip.ToString());
Assert.Equal(AddressFamily.InterNetworkV6, ip.AddressFamily);
// Validate the ToString representation can be parsed as well back into the same IP
Assert.True(TryParse(ip.ToString(), out IPAddress ip2));
Assert.Equal(ip, ip2);
// Validate that anything that doesn't already start with brackets
// can be surrounded with brackets and still parse successfully.
if (!address.StartsWith("["))
{
Assert.Equal(
expected.ToLowerInvariant(),
Parse("[" + address + "]").ToString());
}
}
public static readonly object[][] ScopeIds =
{
new object[] { "Fe08::1%123", 123},
new object[] { "Fe08::1%12345678", 12345678},
new object[] { "fe80::e8b0:63ff:fee8:6b3b%9", 9},
new object[] { "fe80::e8b0:63ff:fee8:6b3b", 0},
new object[] { "fe80::e8b0:63ff:fee8:6b3b%abcd0", 0},
new object[] { "::%unknownInterface", 0},
new object[] { "::%0", 0},
};
[Theory]
[MemberData(nameof(ScopeIds))]
public void ParseIPv6_ExtractsScopeId(string address, int expectedScopeId)
{
IPAddress ip = Parse(address);
Assert.Equal(expectedScopeId, ip.ScopeId);
}
public static IEnumerable<object[]> InvalidIpv6Addresses()
{
yield return new object[] { "[:]" }; // malformed
yield return new object[] { ":::4df" };
yield return new object[] { "4df:::" };
yield return new object[] { "0:::4df" };
yield return new object[] { "4df:::0" };
yield return new object[] { "::4df:::" };
yield return new object[] { "0::4df:::" };
yield return new object[] { " ::1" };
yield return new object[] { ":: 1" };
yield return new object[] { ":" };
yield return new object[] { "0:0:0:0:0:0:0:0:0" };
yield return new object[] { "0:0:0:0:0:0:0" };
yield return new object[] { "0FFFF::" };
yield return new object[] { "FFFF0::" };
yield return new object[] { "[::1" }; // missing closing bracket
yield return new object[] { "Fe08::/64" }; // with subnet
yield return new object[] { "[Fe08::1]:80Z" }; // brackets and invalid port
yield return new object[] { "[Fe08::1" }; // leading bracket
yield return new object[] { "[[Fe08::1" }; // two leading brackets
yield return new object[] { "Fe08::1]" }; // trailing bracket
yield return new object[] { "Fe08::1]]" }; // two trailing brackets
yield return new object[] { "[Fe08::1]]" }; // one leading and two trailing brackets
yield return new object[] { ":1" }; // leading single colon
yield return new object[] { ":1:2" }; // leading single colon
yield return new object[] { ":1:2:3" }; // leading single colon
yield return new object[] { ":1:2:3:4" }; // leading single colon
yield return new object[] { ":1:2:3:4:5" }; // leading single colon
yield return new object[] { ":1:2:3:4:5:6" }; // leading single colon
yield return new object[] { ":1:2:3:4:5:6:7" }; // leading single colon
yield return new object[] { ":1:2:3:4:5:6:7:8" }; // leading single colon
yield return new object[] { ":1:2:3:4:5:6:7:8:9" }; // leading single colon
yield return new object[] { "::1:2:3:4:5:6:7:8" }; // compressor with too many number groups
yield return new object[] { "1::2:3:4:5:6:7:8" }; // compressor with too many number groups
yield return new object[] { "1:2::3:4:5:6:7:8" }; // compressor with too many number groups
yield return new object[] { "1:2:3::4:5:6:7:8" }; // compressor with too many number groups
yield return new object[] { "1:2:3:4::5:6:7:8" }; // compressor with too many number groups
yield return new object[] { "1:2:3:4:5::6:7:8" }; // compressor with too many number groups
yield return new object[] { "1:2:3:4:5:6::7:8" }; // compressor with too many number groups
yield return new object[] { "1:2:3:4:5:6:7::8" }; // compressor with too many number groups
yield return new object[] { "1:2:3:4:5:6:7:8::" }; // compressor with too many number groups
yield return new object[] { "::1:2:3:4:5:6:7:8:9" }; // compressor with too many number groups
yield return new object[] { "1:" }; // trailing single colon
yield return new object[] { " ::1" }; // leading whitespace
yield return new object[] { "::1 " }; // trailing whitespace
yield return new object[] { " ::1 " }; // leading and trailing whitespace
yield return new object[] { "1::1::1" }; // ambiguous failure
yield return new object[] { "1234::ABCD:1234::ABCD:1234:ABCD" }; // can only use :: once
yield return new object[] { "1:1\u67081:1:1" }; // invalid char
yield return new object[] { "FE08::260.168.0.1" }; // out of range
yield return new object[] { "::192.168.0.0x0" }; // hex failure
yield return new object[] { "G::" }; // invalid hex
yield return new object[] { "FFFFF::" }; // invalid value
yield return new object[] { ":%12" }; // colon scope
yield return new object[] { "[2001:0db8:85a3:08d3:1319:8a2e:0370:7344]:443/" }; // errneous ending slash after ignored port
yield return new object[] { "e3fff:ffff:ffff:ffff:ffff:ffff:ffff:abcd" }; // 1st number too long
yield return new object[] { "3fff:effff:ffff:ffff:ffff:ffff:ffff:abcd" }; // 2nd number too long
yield return new object[] { "3fff:ffff:effff:ffff:ffff:ffff:ffff:abcd" }; // 3rd number too long
yield return new object[] { "3fff:ffff:ffff:effff:ffff:ffff:ffff:abcd" }; // 4th number too long
yield return new object[] { "3fff:ffff:ffff:ffff:effff:ffff:ffff:abcd" }; // 5th number too long
yield return new object[] { "3fff:ffff:ffff:ffff:ffff:effff:ffff:abcd" }; // 6th number too long
yield return new object[] { "3fff:ffff:ffff:ffff:ffff:ffff:effff:abcd" }; // 7th number too long
yield return new object[] { "3fff:ffff:ffff:ffff:ffff:ffff:ffff:eabcd" }; // 8th number too long
// Various IPv6 addresses including invalid IPv4 addresses
foreach (object[] invalidIPv4AddressArray in InvalidIpv4Addresses)
{
string invalidIPv4Address = (string)invalidIPv4AddressArray[0];
yield return new object[] { "3fff:ffff:ffff:ffff:ffff:ffff:ffff:" + invalidIPv4Address };
yield return new object[] { "::" + invalidIPv4Address }; // SIIT
yield return new object[] { "::FF:" + invalidIPv4Address }; // SIIT
yield return new object[] { "::5EFE:" + invalidIPv4Address }; // ISATAP
yield return new object[] { "1::5EFE:" + invalidIPv4Address }; // ISATAP
}
}
[Theory]
[MemberData(nameof(InvalidIpv6Addresses))]
public void ParseIPv6_InvalidAddress_ThrowsFormatException(string invalidAddress)
{
ParseInvalidAddress(invalidAddress, hasInnerSocketException: true);
}
public static readonly object[][] InvalidIpv6AddressesNoInner =
{
new object[] { "" }, // empty
new object[] { " " }, // whitespace
new object[] { " " }, // whitespace
new object[] { "%12" }, // just scope
new object[] { "[192.168.0.1]" }, // raw v4
new object[] { "[1]" }, // incomplete
new object[] { "" }, // malformed
new object[] { "[" }, // malformed
new object[] { "[]" }, // malformed
};
[Theory]
[MemberData(nameof(InvalidIpv6AddressesNoInner))]
public void ParseIPv6_InvalidAddress_ThrowsFormatExceptionWithNoInnerExceptionInNetfx(string invalidAddress)
{
ParseInvalidAddress(invalidAddress, hasInnerSocketException: !PlatformDetection.IsFullFramework);
}
private void ParseInvalidAddress(string invalidAddress, bool hasInnerSocketException)
{
FormatException fe = Assert.Throws<FormatException>(() => Parse(invalidAddress));
if (hasInnerSocketException)
{
SocketException se = Assert.IsType<SocketException>(fe.InnerException);
Assert.NotEmpty(se.Message);
}
else
{
Assert.Null(fe.InnerException);
}
IPAddress result = IPAddress.Loopback;
Assert.False(TryParse(invalidAddress, out result));
Assert.Null(result);
}
}
}
| |
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace Infoplus.Model
{
/// <summary>
///
/// </summary>
[DataContract]
public partial class InventoryAdjustment : IEquatable<InventoryAdjustment>
{
/// <summary>
/// Initializes a new instance of the <see cref="InventoryAdjustment" /> class.
/// Initializes a new instance of the <see cref="InventoryAdjustment" />class.
/// </summary>
/// <param name="Id">Id.</param>
/// <param name="LobId">LobId.</param>
/// <param name="SkuId">SkuId.</param>
/// <param name="PoNoId">PoNoId.</param>
/// <param name="AdjustmentDate">AdjustmentDate.</param>
/// <param name="AdjustmentTime">AdjustmentTime.</param>
/// <param name="Location">Location.</param>
/// <param name="Qty">Qty.</param>
/// <param name="Note">Note.</param>
/// <param name="AuthorizedBy">AuthorizedBy.</param>
/// <param name="Printed">Printed.</param>
/// <param name="OrderNo">OrderNo.</param>
/// <param name="AdjustmentCode">AdjustmentCode.</param>
/// <param name="CustomFields">CustomFields.</param>
public InventoryAdjustment(int? Id = null, int? LobId = null, int? SkuId = null, int? PoNoId = null, DateTime? AdjustmentDate = null, string AdjustmentTime = null, string Location = null, int? Qty = null, string Note = null, string AuthorizedBy = null, string Printed = null, double? OrderNo = null, string AdjustmentCode = null, Dictionary<string, Object> CustomFields = null)
{
this.Id = Id;
this.LobId = LobId;
this.SkuId = SkuId;
this.PoNoId = PoNoId;
this.AdjustmentDate = AdjustmentDate;
this.AdjustmentTime = AdjustmentTime;
this.Location = Location;
this.Qty = Qty;
this.Note = Note;
this.AuthorizedBy = AuthorizedBy;
this.Printed = Printed;
this.OrderNo = OrderNo;
this.AdjustmentCode = AdjustmentCode;
this.CustomFields = CustomFields;
}
/// <summary>
/// Gets or Sets Id
/// </summary>
[DataMember(Name="id", EmitDefaultValue=false)]
public int? Id { get; set; }
/// <summary>
/// Gets or Sets LobId
/// </summary>
[DataMember(Name="lobId", EmitDefaultValue=false)]
public int? LobId { get; set; }
/// <summary>
/// Gets or Sets SkuId
/// </summary>
[DataMember(Name="skuId", EmitDefaultValue=false)]
public int? SkuId { get; set; }
/// <summary>
/// Gets or Sets PoNoId
/// </summary>
[DataMember(Name="poNoId", EmitDefaultValue=false)]
public int? PoNoId { get; set; }
/// <summary>
/// Gets or Sets AdjustmentDate
/// </summary>
[DataMember(Name="adjustmentDate", EmitDefaultValue=false)]
public DateTime? AdjustmentDate { get; set; }
/// <summary>
/// Gets or Sets AdjustmentTime
/// </summary>
[DataMember(Name="adjustmentTime", EmitDefaultValue=false)]
public string AdjustmentTime { get; set; }
/// <summary>
/// Gets or Sets Location
/// </summary>
[DataMember(Name="location", EmitDefaultValue=false)]
public string Location { get; set; }
/// <summary>
/// Gets or Sets Qty
/// </summary>
[DataMember(Name="qty", EmitDefaultValue=false)]
public int? Qty { get; set; }
/// <summary>
/// Gets or Sets Note
/// </summary>
[DataMember(Name="note", EmitDefaultValue=false)]
public string Note { get; set; }
/// <summary>
/// Gets or Sets AuthorizedBy
/// </summary>
[DataMember(Name="authorizedBy", EmitDefaultValue=false)]
public string AuthorizedBy { get; set; }
/// <summary>
/// Gets or Sets Printed
/// </summary>
[DataMember(Name="printed", EmitDefaultValue=false)]
public string Printed { get; set; }
/// <summary>
/// Gets or Sets OrderNo
/// </summary>
[DataMember(Name="orderNo", EmitDefaultValue=false)]
public double? OrderNo { get; set; }
/// <summary>
/// Gets or Sets AdjustmentCode
/// </summary>
[DataMember(Name="adjustmentCode", EmitDefaultValue=false)]
public string AdjustmentCode { get; set; }
/// <summary>
/// Gets or Sets CustomFields
/// </summary>
[DataMember(Name="customFields", EmitDefaultValue=false)]
public Dictionary<string, Object> CustomFields { 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 InventoryAdjustment {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" LobId: ").Append(LobId).Append("\n");
sb.Append(" SkuId: ").Append(SkuId).Append("\n");
sb.Append(" PoNoId: ").Append(PoNoId).Append("\n");
sb.Append(" AdjustmentDate: ").Append(AdjustmentDate).Append("\n");
sb.Append(" AdjustmentTime: ").Append(AdjustmentTime).Append("\n");
sb.Append(" Location: ").Append(Location).Append("\n");
sb.Append(" Qty: ").Append(Qty).Append("\n");
sb.Append(" Note: ").Append(Note).Append("\n");
sb.Append(" AuthorizedBy: ").Append(AuthorizedBy).Append("\n");
sb.Append(" Printed: ").Append(Printed).Append("\n");
sb.Append(" OrderNo: ").Append(OrderNo).Append("\n");
sb.Append(" AdjustmentCode: ").Append(AdjustmentCode).Append("\n");
sb.Append(" CustomFields: ").Append(CustomFields).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as InventoryAdjustment);
}
/// <summary>
/// Returns true if InventoryAdjustment instances are equal
/// </summary>
/// <param name="other">Instance of InventoryAdjustment to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(InventoryAdjustment other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.Id == other.Id ||
this.Id != null &&
this.Id.Equals(other.Id)
) &&
(
this.LobId == other.LobId ||
this.LobId != null &&
this.LobId.Equals(other.LobId)
) &&
(
this.SkuId == other.SkuId ||
this.SkuId != null &&
this.SkuId.Equals(other.SkuId)
) &&
(
this.PoNoId == other.PoNoId ||
this.PoNoId != null &&
this.PoNoId.Equals(other.PoNoId)
) &&
(
this.AdjustmentDate == other.AdjustmentDate ||
this.AdjustmentDate != null &&
this.AdjustmentDate.Equals(other.AdjustmentDate)
) &&
(
this.AdjustmentTime == other.AdjustmentTime ||
this.AdjustmentTime != null &&
this.AdjustmentTime.Equals(other.AdjustmentTime)
) &&
(
this.Location == other.Location ||
this.Location != null &&
this.Location.Equals(other.Location)
) &&
(
this.Qty == other.Qty ||
this.Qty != null &&
this.Qty.Equals(other.Qty)
) &&
(
this.Note == other.Note ||
this.Note != null &&
this.Note.Equals(other.Note)
) &&
(
this.AuthorizedBy == other.AuthorizedBy ||
this.AuthorizedBy != null &&
this.AuthorizedBy.Equals(other.AuthorizedBy)
) &&
(
this.Printed == other.Printed ||
this.Printed != null &&
this.Printed.Equals(other.Printed)
) &&
(
this.OrderNo == other.OrderNo ||
this.OrderNo != null &&
this.OrderNo.Equals(other.OrderNo)
) &&
(
this.AdjustmentCode == other.AdjustmentCode ||
this.AdjustmentCode != null &&
this.AdjustmentCode.Equals(other.AdjustmentCode)
) &&
(
this.CustomFields == other.CustomFields ||
this.CustomFields != null &&
this.CustomFields.SequenceEqual(other.CustomFields)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.Id != null)
hash = hash * 59 + this.Id.GetHashCode();
if (this.LobId != null)
hash = hash * 59 + this.LobId.GetHashCode();
if (this.SkuId != null)
hash = hash * 59 + this.SkuId.GetHashCode();
if (this.PoNoId != null)
hash = hash * 59 + this.PoNoId.GetHashCode();
if (this.AdjustmentDate != null)
hash = hash * 59 + this.AdjustmentDate.GetHashCode();
if (this.AdjustmentTime != null)
hash = hash * 59 + this.AdjustmentTime.GetHashCode();
if (this.Location != null)
hash = hash * 59 + this.Location.GetHashCode();
if (this.Qty != null)
hash = hash * 59 + this.Qty.GetHashCode();
if (this.Note != null)
hash = hash * 59 + this.Note.GetHashCode();
if (this.AuthorizedBy != null)
hash = hash * 59 + this.AuthorizedBy.GetHashCode();
if (this.Printed != null)
hash = hash * 59 + this.Printed.GetHashCode();
if (this.OrderNo != null)
hash = hash * 59 + this.OrderNo.GetHashCode();
if (this.AdjustmentCode != null)
hash = hash * 59 + this.AdjustmentCode.GetHashCode();
if (this.CustomFields != null)
hash = hash * 59 + this.CustomFields.GetHashCode();
return hash;
}
}
}
}
| |
// <copyright file="Constants.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
//
// Copyright (c) 2009-2010 Math.NET
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
namespace MathNet.Numerics
{
/// <summary>
/// A collection of frequently used mathematical constants.
/// </summary>
public static class Constants
{
#region Mathematical Constants
/// <summary>The number e</summary>
public const double E = 2.7182818284590452353602874713526624977572470937000d;
/// <summary>The number log[2](e)</summary>
public const double Log2E = 1.4426950408889634073599246810018921374266459541530d;
/// <summary>The number log[10](e)</summary>
public const double Log10E = 0.43429448190325182765112891891660508229439700580366d;
/// <summary>The number log[e](2)</summary>
public const double Ln2 = 0.69314718055994530941723212145817656807550013436026d;
/// <summary>The number log[e](10)</summary>
public const double Ln10 = 2.3025850929940456840179914546843642076011014886288d;
/// <summary>The number log[e](pi)</summary>
public const double LnPi = 1.1447298858494001741434273513530587116472948129153d;
/// <summary>The number log[e](2*pi)/2</summary>
public const double Ln2PiOver2 = 0.91893853320467274178032973640561763986139747363780d;
/// <summary>The number 1/e</summary>
public const double InvE = 0.36787944117144232159552377016146086744581113103176d;
/// <summary>The number sqrt(e)</summary>
public const double SqrtE = 1.6487212707001281468486507878141635716537761007101d;
/// <summary>The number sqrt(2)</summary>
public const double Sqrt2 = 1.4142135623730950488016887242096980785696718753769d;
/// <summary>The number sqrt(3)</summary>
public const double Sqrt3 = 1.7320508075688772935274463415058723669428052538104d;
/// <summary>The number sqrt(1/2) = 1/sqrt(2) = sqrt(2)/2</summary>
public const double Sqrt1Over2 = 0.70710678118654752440084436210484903928483593768845d;
/// <summary>The number sqrt(3)/2</summary>
public const double HalfSqrt3 = 0.86602540378443864676372317075293618347140262690520d;
/// <summary>The number pi</summary>
public const double Pi = 3.1415926535897932384626433832795028841971693993751d;
/// <summary>The number pi*2</summary>
public const double Pi2 = 6.2831853071795864769252867665590057683943387987502d;
/// <summary>The number pi/2</summary>
public const double PiOver2 = 1.5707963267948966192313216916397514420985846996876d;
/// <summary>The number pi*3/2</summary>
public const double Pi3Over2 = 4.71238898038468985769396507491925432629575409906266d;
/// <summary>The number pi/4</summary>
public const double PiOver4 = 0.78539816339744830961566084581987572104929234984378d;
/// <summary>The number sqrt(pi)</summary>
public const double SqrtPi = 1.7724538509055160272981674833411451827975494561224d;
/// <summary>The number sqrt(2pi)</summary>
public const double Sqrt2Pi = 2.5066282746310005024157652848110452530069867406099d;
/// <summary>The number sqrt(2*pi*e)</summary>
public const double Sqrt2PiE = 4.1327313541224929384693918842998526494455219169913d;
/// <summary>The number log(sqrt(2*pi))</summary>
public const double LogSqrt2Pi = 0.91893853320467274178032973640561763986139747363778;
/// <summary>The number log(sqrt(2*pi*e))</summary>
public const double LogSqrt2PiE = 1.4189385332046727417803297364056176398613974736378d;
/// <summary>The number log(2 * sqrt(e / pi))</summary>
public const double LogTwoSqrtEOverPi = 0.6207822376352452223455184457816472122518527279025978;
/// <summary>The number 1/pi</summary>
public const double InvPi = 0.31830988618379067153776752674502872406891929148091d;
/// <summary>The number 2/pi</summary>
public const double TwoInvPi = 0.63661977236758134307553505349005744813783858296182d;
/// <summary>The number 1/sqrt(pi)</summary>
public const double InvSqrtPi = 0.56418958354775628694807945156077258584405062932899d;
/// <summary>The number 1/sqrt(2pi)</summary>
public const double InvSqrt2Pi = 0.39894228040143267793994605993438186847585863116492d;
/// <summary>The number 2/sqrt(pi)</summary>
public const double TwoInvSqrtPi = 1.1283791670955125738961589031215451716881012586580d;
/// <summary>The number 2 * sqrt(e / pi)</summary>
public const double TwoSqrtEOverPi = 1.8603827342052657173362492472666631120594218414085755;
/// <summary>The number (pi)/180 - factor to convert from Degree (deg) to Radians (rad).</summary>
public const double Degree = 0.017453292519943295769236907684886127134428718885417d;
/// <summary>The number (pi)/200 - factor to convert from Grad (grad) to Radians (rad).</summary>
public const double Grad = 0.015707963267948966192313216916397514420985846996876d;
/// <summary>The number ln(10)/20 - factor to convert from Power Decibel (dB) to Neper (Np). Use this version when the Decibel represent a power gain but the compared values are not powers (e.g. amplitude, current, voltage).</summary>
public const double PowerDecibel = 0.11512925464970228420089957273421821038005507443144d;
/// <summary>The number ln(10)/10 - factor to convert from Neutral Decibel (dB) to Neper (Np). Use this version when either both or neither of the Decibel and the compared values represent powers.</summary>
public const double NeutralDecibel = 0.23025850929940456840179914546843642076011014886288d;
/// <summary>The Catalan constant</summary>
/// <remarks>Sum(k=0 -> inf){ (-1)^k/(2*k + 1)2 }</remarks>
public const double Catalan = 0.9159655941772190150546035149323841107741493742816721342664981196217630197762547694794d;
/// <summary>The Euler-Mascheroni constant</summary>
/// <remarks>lim(n -> inf){ Sum(k=1 -> n) { 1/k - log(n) } }</remarks>
public const double EulerMascheroni = 0.5772156649015328606065120900824024310421593359399235988057672348849d;
/// <summary>The number (1+sqrt(5))/2, also known as the golden ratio</summary>
public const double GoldenRatio = 1.6180339887498948482045868343656381177203091798057628621354486227052604628189024497072d;
/// <summary>The Glaisher constant</summary>
/// <remarks>e^(1/12 - Zeta(-1))</remarks>
public const double Glaisher = 1.2824271291006226368753425688697917277676889273250011920637400217404063088588264611297d;
/// <summary>The Khinchin constant</summary>
/// <remarks>prod(k=1 -> inf){1+1/(k*(k+2))^log(k,2)}</remarks>
public const double Khinchin = 2.6854520010653064453097148354817956938203822939944629530511523455572188595371520028011d;
/// <summary>
/// The size of a double in bytes.
/// </summary>
public const int SizeOfDouble = sizeof(double);
/// <summary>
/// The size of an int in bytes.
/// </summary>
public const int SizeOfInt = sizeof(int);
/// <summary>
/// The size of a float in bytes.
/// </summary>
public const int SizeOfFloat = sizeof(float);
/// <summary>
/// The size of a Complex in bytes.
/// </summary>
public const int SizeOfComplex = 2 * SizeOfDouble;
/// <summary>
/// The size of a Complex in bytes.
/// </summary>
public const int SizeOfComplex32 = 2 * SizeOfFloat;
#endregion
#region UNIVERSAL CONSTANTS
/// <summary>Speed of Light in Vacuum: c_0 = 2.99792458e8 [m s^-1] (defined, exact; 2007 CODATA)</summary>
public const double SpeedOfLight = 2.99792458e8;
/// <summary>Magnetic Permeability in Vacuum: mu_0 = 4*Pi * 10^-7 [N A^-2 = kg m A^-2 s^-2] (defined, exact; 2007 CODATA)</summary>
public const double MagneticPermeability = 1.2566370614359172953850573533118011536788677597500e-6;
/// <summary>Electric Permittivity in Vacuum: epsilon_0 = 1/(mu_0*c_0^2) [F m^-1 = A^2 s^4 kg^-1 m^-3] (defined, exact; 2007 CODATA)</summary>
public const double ElectricPermittivity = 8.8541878171937079244693661186959426889222899381429e-12;
/// <summary>Characteristic Impedance of Vacuum: Z_0 = mu_0*c_0 [Ohm = m^2 kg s^-3 A^-2] (defined, exact; 2007 CODATA)</summary>
public const double CharacteristicImpedanceVacuum = 376.73031346177065546819840042031930826862350835242;
/// <summary>Newtonian Constant of Gravitation: G = 6.67429e-11 [m^3 kg^-1 s^-2] (2007 CODATA)</summary>
public const double GravitationalConstant = 6.67429e-11;
/// <summary>Planck's constant: h = 6.62606896e-34 [J s = m^2 kg s^-1] (2007 CODATA)</summary>
public const double PlancksConstant = 6.62606896e-34;
/// <summary>Reduced Planck's constant: h_bar = h / (2*Pi) [J s = m^2 kg s^-1] (2007 CODATA)</summary>
public const double DiracsConstant = 1.054571629e-34;
/// <summary>Planck mass: m_p = (h_bar*c_0/G)^(1/2) [kg] (2007 CODATA)</summary>
public const double PlancksMass = 2.17644e-8;
/// <summary>Planck temperature: T_p = (h_bar*c_0^5/G)^(1/2)/k [K] (2007 CODATA)</summary>
public const double PlancksTemperature = 1.416786e32;
/// <summary>Planck length: l_p = h_bar/(m_p*c_0) [m] (2007 CODATA)</summary>
public const double PlancksLength = 1.616253e-35;
/// <summary>Planck time: t_p = l_p/c_0 [s] (2007 CODATA)</summary>
public const double PlancksTime = 5.39124e-44;
#endregion
#region ELECTROMAGNETIC CONSTANTS
/// <summary>Elementary Electron Charge: e = 1.602176487e-19 [C = A s] (2007 CODATA)</summary>
public const double ElementaryCharge = 1.602176487e-19;
/// <summary>Magnetic Flux Quantum: theta_0 = h/(2*e) [Wb = m^2 kg s^-2 A^-1] (2007 CODATA)</summary>
public const double MagneticFluxQuantum = 2.067833668e-15;
/// <summary>Conductance Quantum: G_0 = 2*e^2/h [S = m^-2 kg^-1 s^3 A^2] (2007 CODATA)</summary>
public const double ConductanceQuantum = 7.7480917005e-5;
/// <summary>Josephson Constant: K_J = 2*e/h [Hz V^-1] (2007 CODATA)</summary>
public const double JosephsonConstant = 483597.891e9;
/// <summary>Von Klitzing Constant: R_K = h/e^2 [Ohm = m^2 kg s^-3 A^-2] (2007 CODATA)</summary>
public const double VonKlitzingConstant = 25812.807557;
/// <summary>Bohr Magneton: mu_B = e*h_bar/2*m_e [J T^-1] (2007 CODATA)</summary>
public const double BohrMagneton = 927.400915e-26;
/// <summary>Nuclear Magneton: mu_N = e*h_bar/2*m_p [J T^-1] (2007 CODATA)</summary>
public const double NuclearMagneton = 5.05078324e-27;
#endregion
#region ATOMIC AND NUCLEAR CONSTANTS
/// <summary>Fine Structure Constant: alpha = e^2/4*Pi*e_0*h_bar*c_0 [1] (2007 CODATA)</summary>
public const double FineStructureConstant = 7.2973525376e-3;
/// <summary>Rydberg Constant: R_infty = alpha^2*m_e*c_0/2*h [m^-1] (2007 CODATA)</summary>
public const double RydbergConstant = 10973731.568528;
/// <summary>Bor Radius: a_0 = alpha/4*Pi*R_infty [m] (2007 CODATA)</summary>
public const double BohrRadius = 0.52917720859e-10;
/// <summary>Hartree Energy: E_h = 2*R_infty*h*c_0 [J] (2007 CODATA)</summary>
public const double HartreeEnergy = 4.35974394e-18;
/// <summary>Quantum of Circulation: h/2*m_e [m^2 s^-1] (2007 CODATA)</summary>
public const double QuantumOfCirculation = 3.6369475199e-4;
/// <summary>Fermi Coupling Constant: G_F/(h_bar*c_0)^3 [GeV^-2] (2007 CODATA)</summary>
public const double FermiCouplingConstant = 1.16637e-5;
/// <summary>Weak Mixin Angle: sin^2(theta_W) [1] (2007 CODATA)</summary>
public const double WeakMixingAngle = 0.22256;
/// <summary>Electron Mass: [kg] (2007 CODATA)</summary>
public const double ElectronMass = 9.10938215e-31;
/// <summary>Electron Mass Energy Equivalent: [J] (2007 CODATA)</summary>
public const double ElectronMassEnergyEquivalent = 8.18710438e-14;
/// <summary>Electron Molar Mass: [kg mol^-1] (2007 CODATA)</summary>
public const double ElectronMolarMass = 5.4857990943e-7;
/// <summary>Electron Compton Wavelength: [m] (2007 CODATA)</summary>
public const double ComptonWavelength = 2.4263102175e-12;
/// <summary>Classical Electron Radius: [m] (2007 CODATA)</summary>
public const double ClassicalElectronRadius = 2.8179402894e-15;
/// <summary>Tomson Cross Section: [m^2] (2002 CODATA)</summary>
public const double ThomsonCrossSection = 0.6652458558e-28;
/// <summary>Electron Magnetic Moment: [J T^-1] (2007 CODATA)</summary>
public const double ElectronMagneticMoment = -928.476377e-26;
/// <summary>Electon G-Factor: [1] (2007 CODATA)</summary>
public const double ElectronGFactor = -2.0023193043622;
/// <summary>Muon Mass: [kg] (2007 CODATA)</summary>
public const double MuonMass = 1.88353130e-28;
/// <summary>Muon Mass Energy Equivalent: [J] (2007 CODATA)</summary>
public const double MuonMassEnegryEquivalent = 1.692833511e-11;
/// <summary>Muon Molar Mass: [kg mol^-1] (2007 CODATA)</summary>
public const double MuonMolarMass = 0.1134289256e-3;
/// <summary>Muon Compton Wavelength: [m] (2007 CODATA)</summary>
public const double MuonComptonWavelength = 11.73444104e-15;
/// <summary>Muon Magnetic Moment: [J T^-1] (2007 CODATA)</summary>
public const double MuonMagneticMoment = -4.49044786e-26;
/// <summary>Muon G-Factor: [1] (2007 CODATA)</summary>
public const double MuonGFactor = -2.0023318414;
/// <summary>Tau Mass: [kg] (2007 CODATA)</summary>
public const double TauMass = 3.16777e-27;
/// <summary>Tau Mass Energy Equivalent: [J] (2007 CODATA)</summary>
public const double TauMassEnergyEquivalent = 2.84705e-10;
/// <summary>Tau Molar Mass: [kg mol^-1] (2007 CODATA)</summary>
public const double TauMolarMass = 1.90768e-3;
/// <summary>Tau Compton Wavelength: [m] (2007 CODATA)</summary>
public const double TauComptonWavelength = 0.69772e-15;
/// <summary>Proton Mass: [kg] (2007 CODATA)</summary>
public const double ProtonMass = 1.672621637e-27;
/// <summary>Proton Mass Energy Equivalent: [J] (2007 CODATA)</summary>
public const double ProtonMassEnergyEquivalent = 1.503277359e-10;
/// <summary>Proton Molar Mass: [kg mol^-1] (2007 CODATA)</summary>
public const double ProtonMolarMass = 1.00727646677e-3;
/// <summary>Proton Compton Wavelength: [m] (2007 CODATA)</summary>
public const double ProtonComptonWavelength = 1.3214098446e-15;
/// <summary>Proton Magnetic Moment: [J T^-1] (2007 CODATA)</summary>
public const double ProtonMagneticMoment = 1.410606662e-26;
/// <summary>Proton G-Factor: [1] (2007 CODATA)</summary>
public const double ProtonGFactor = 5.585694713;
/// <summary>Proton Shielded Magnetic Moment: [J T^-1] (2007 CODATA)</summary>
public const double ShieldedProtonMagneticMoment = 1.410570419e-26;
/// <summary>Proton Gyro-Magnetic Ratio: [s^-1 T^-1] (2007 CODATA)</summary>
public const double ProtonGyromagneticRatio = 2.675222099e8;
/// <summary>Proton Shielded Gyro-Magnetic Ratio: [s^-1 T^-1] (2007 CODATA)</summary>
public const double ShieldedProtonGyromagneticRatio = 2.675153362e8;
/// <summary>Neutron Mass: [kg] (2007 CODATA)</summary>
public const double NeutronMass = 1.674927212e-27;
/// <summary>Neutron Mass Energy Equivalent: [J] (2007 CODATA)</summary>
public const double NeutronMassEnegryEquivalent = 1.505349506e-10;
/// <summary>Neutron Molar Mass: [kg mol^-1] (2007 CODATA)</summary>
public const double NeutronMolarMass = 1.00866491597e-3;
/// <summary>Neuron Compton Wavelength: [m] (2007 CODATA)</summary>
public const double NeutronComptonWavelength = 1.3195908951e-1;
/// <summary>Neutron Magnetic Moment: [J T^-1] (2007 CODATA)</summary>
public const double NeutronMagneticMoment = -0.96623641e-26;
/// <summary>Neutron G-Factor: [1] (2007 CODATA)</summary>
public const double NeutronGFactor = -3.82608545;
/// <summary>Neutron Gyro-Magnetic Ratio: [s^-1 T^-1] (2007 CODATA)</summary>
public const double NeutronGyromagneticRatio = 1.83247185e8;
/// <summary>Deuteron Mass: [kg] (2007 CODATA)</summary>
public const double DeuteronMass = 3.34358320e-27;
/// <summary>Deuteron Mass Energy Equivalent: [J] (2007 CODATA)</summary>
public const double DeuteronMassEnegryEquivalent = 3.00506272e-10;
/// <summary>Deuteron Molar Mass: [kg mol^-1] (2007 CODATA)</summary>
public const double DeuteronMolarMass = 2.013553212725e-3;
/// <summary>Deuteron Magnetic Moment: [J T^-1] (2007 CODATA)</summary>
public const double DeuteronMagneticMoment = 0.433073465e-26;
/// <summary>Helion Mass: [kg] (2007 CODATA)</summary>
public const double HelionMass = 5.00641192e-27;
/// <summary>Helion Mass Energy Equivalent: [J] (2007 CODATA)</summary>
public const double HelionMassEnegryEquivalent = 4.49953864e-10;
/// <summary>Helion Molar Mass: [kg mol^-1] (2007 CODATA)</summary>
public const double HelionMolarMass = 3.0149322473e-3;
/// <summary>Avogadro constant: [mol^-1] (2010 CODATA)</summary>
public const double Avogadro = 6.0221412927e23;
#endregion
#region Scientific Prefixes
/// <summary>The SI prefix factor corresponding to 1 000 000 000 000 000 000 000 000</summary>
public const double Yotta = 1e24;
/// <summary>The SI prefix factor corresponding to 1 000 000 000 000 000 000 000</summary>
public const double Zetta = 1e21;
/// <summary>The SI prefix factor corresponding to 1 000 000 000 000 000 000</summary>
public const double Exa = 1e18;
/// <summary>The SI prefix factor corresponding to 1 000 000 000 000 000</summary>
public const double Peta = 1e15;
/// <summary>The SI prefix factor corresponding to 1 000 000 000 000</summary>
public const double Tera = 1e12;
/// <summary>The SI prefix factor corresponding to 1 000 000 000</summary>
public const double Giga = 1e9;
/// <summary>The SI prefix factor corresponding to 1 000 000</summary>
public const double Mega = 1e6;
/// <summary>The SI prefix factor corresponding to 1 000</summary>
public const double Kilo = 1e3;
/// <summary>The SI prefix factor corresponding to 100</summary>
public const double Hecto = 1e2;
/// <summary>The SI prefix factor corresponding to 10</summary>
public const double Deca = 1e1;
/// <summary>The SI prefix factor corresponding to 0.1</summary>
public const double Deci = 1e-1;
/// <summary>The SI prefix factor corresponding to 0.01</summary>
public const double Centi = 1e-2;
/// <summary>The SI prefix factor corresponding to 0.001</summary>
public const double Milli = 1e-3;
/// <summary>The SI prefix factor corresponding to 0.000 001</summary>
public const double Micro = 1e-6;
/// <summary>The SI prefix factor corresponding to 0.000 000 001</summary>
public const double Nano = 1e-9;
/// <summary>The SI prefix factor corresponding to 0.000 000 000 001</summary>
public const double Pico = 1e-12;
/// <summary>The SI prefix factor corresponding to 0.000 000 000 000 001</summary>
public const double Femto = 1e-15;
/// <summary>The SI prefix factor corresponding to 0.000 000 000 000 000 001</summary>
public const double Atto = 1e-18;
/// <summary>The SI prefix factor corresponding to 0.000 000 000 000 000 000 001</summary>
public const double Zepto = 1e-21;
/// <summary>The SI prefix factor corresponding to 0.000 000 000 000 000 000 000 001</summary>
public const double Yocto = 1e-24;
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Orleans.Runtime;
using Orleans.Streams.Core;
using Orleans.Providers;
namespace Orleans.Streams
{
[Serializable]
internal class PubSubGrainState
{
public HashSet<PubSubPublisherState> Producers { get; set; } = new HashSet<PubSubPublisherState>();
public HashSet<PubSubSubscriptionState> Consumers { get; set; } = new HashSet<PubSubSubscriptionState>();
}
[StorageProvider(ProviderName = "PubSubStore")]
internal class PubSubRendezvousGrain : Grain<PubSubGrainState>, IPubSubRendezvousGrain
{
private ILogger logger;
private const bool DEBUG_PUB_SUB = false;
private static readonly CounterStatistic counterProducersAdded;
private static readonly CounterStatistic counterProducersRemoved;
private static readonly CounterStatistic counterProducersTotal;
private static readonly CounterStatistic counterConsumersAdded;
private static readonly CounterStatistic counterConsumersRemoved;
private static readonly CounterStatistic counterConsumersTotal;
private readonly ISiloStatusOracle siloStatusOracle;
static PubSubRendezvousGrain()
{
counterProducersAdded = CounterStatistic.FindOrCreate(StatisticNames.STREAMS_PUBSUB_PRODUCERS_ADDED);
counterProducersRemoved = CounterStatistic.FindOrCreate(StatisticNames.STREAMS_PUBSUB_PRODUCERS_REMOVED);
counterProducersTotal = CounterStatistic.FindOrCreate(StatisticNames.STREAMS_PUBSUB_PRODUCERS_TOTAL);
counterConsumersAdded = CounterStatistic.FindOrCreate(StatisticNames.STREAMS_PUBSUB_CONSUMERS_ADDED);
counterConsumersRemoved = CounterStatistic.FindOrCreate(StatisticNames.STREAMS_PUBSUB_CONSUMERS_REMOVED);
counterConsumersTotal = CounterStatistic.FindOrCreate(StatisticNames.STREAMS_PUBSUB_CONSUMERS_TOTAL);
}
public PubSubRendezvousGrain(ISiloStatusOracle siloStatusOracle)
{
this.siloStatusOracle = siloStatusOracle;
}
public override Task OnActivateAsync()
{
logger = this.ServiceProvider.GetRequiredService<ILoggerFactory>().CreateLogger($"{GetType().FullName}.{RuntimeIdentity}.{IdentityString}");
LogPubSubCounts("OnActivateAsync");
return Task.CompletedTask;
}
public override Task OnDeactivateAsync()
{
LogPubSubCounts("OnDeactivateAsync");
return Task.CompletedTask;
}
public async Task<ISet<PubSubSubscriptionState>> RegisterProducer(StreamId streamId, IStreamProducerExtension streamProducer)
{
counterProducersAdded.Increment();
try
{
var publisherState = new PubSubPublisherState(streamId, streamProducer);
State.Producers.Add(publisherState);
LogPubSubCounts("RegisterProducer {0}", streamProducer);
await WriteStateAsync();
counterProducersTotal.Increment();
}
catch (Exception exc)
{
logger.Error(ErrorCode.Stream_RegisterProducerFailed, $"Failed to register a stream producer. Stream: {streamId}, Producer: {streamProducer}", exc);
// Corrupted state, deactivate grain.
DeactivateOnIdle();
throw;
}
return State.Consumers.Where(c => !c.IsFaulted).ToSet();
}
public async Task UnregisterProducer(StreamId streamId, IStreamProducerExtension streamProducer)
{
counterProducersRemoved.Increment();
try
{
int numRemoved = State.Producers.RemoveWhere(s => s.Equals(streamId, streamProducer));
LogPubSubCounts("UnregisterProducer {0} NumRemoved={1}", streamProducer, numRemoved);
if (numRemoved > 0)
{
Task updateStorageTask = State.Producers.Count == 0 && State.Consumers.Count == 0
? ClearStateAsync() //State contains no producers or consumers, remove it from storage
: WriteStateAsync();
await updateStorageTask;
}
counterProducersTotal.DecrementBy(numRemoved);
}
catch (Exception exc)
{
logger.Error(ErrorCode.Stream_UnegisterProducerFailed,
$"Failed to unregister a stream producer. Stream: {streamId}, Producer: {streamProducer}", exc);
// Corrupted state, deactivate grain.
DeactivateOnIdle();
throw;
}
if (State.Producers.Count == 0 && State.Consumers.Count == 0)
{
DeactivateOnIdle(); // No producers or consumers left now, so flag ourselves to expedite Deactivation
}
}
public async Task RegisterConsumer(
GuidId subscriptionId,
StreamId streamId,
IStreamConsumerExtension streamConsumer,
IStreamFilterPredicateWrapper filter)
{
counterConsumersAdded.Increment();
PubSubSubscriptionState pubSubState = State.Consumers.FirstOrDefault(s => s.Equals(subscriptionId));
if (pubSubState != null && pubSubState.IsFaulted)
throw new FaultedSubscriptionException(subscriptionId, streamId);
try
{
if (pubSubState == null)
{
pubSubState = new PubSubSubscriptionState(subscriptionId, streamId, streamConsumer);
State.Consumers.Add(pubSubState);
}
if (filter != null)
pubSubState.AddFilter(filter);
LogPubSubCounts("RegisterConsumer {0}", streamConsumer);
await WriteStateAsync();
counterConsumersTotal.Increment();
}
catch (Exception exc)
{
logger.Error(ErrorCode.Stream_RegisterConsumerFailed,
$"Failed to register a stream consumer. Stream: {streamId}, SubscriptionId {subscriptionId}, Consumer: {streamConsumer}", exc);
// Corrupted state, deactivate grain.
DeactivateOnIdle();
throw;
}
int numProducers = State.Producers.Count;
if (numProducers <= 0)
return;
if (logger.IsEnabled(LogLevel.Debug))
logger.Debug("Notifying {0} existing producer(s) about new consumer {1}. Producers={2}",
numProducers, streamConsumer, Utils.EnumerableToString(State.Producers));
// Notify producers about a new streamConsumer.
var tasks = new List<Task>();
var producers = State.Producers.ToList();
int initialProducerCount = producers.Count;
try
{
foreach (PubSubPublisherState producerState in producers)
{
tasks.Add(ExecuteProducerTask(producerState, producerState.Producer.AddSubscriber(subscriptionId, streamId, streamConsumer, filter)));
}
Exception exception = null;
try
{
await Task.WhenAll(tasks);
}
catch (Exception exc)
{
exception = exc;
}
// if the number of producers has been changed, resave state.
if (State.Producers.Count != initialProducerCount)
{
await WriteStateAsync();
counterConsumersTotal.DecrementBy(initialProducerCount - State.Producers.Count);
}
if (exception != null)
{
throw exception;
}
}
catch (Exception exc)
{
logger.Error(ErrorCode.Stream_RegisterConsumerFailed,
$"Failed to update producers while register a stream consumer. Stream: {streamId}, SubscriptionId {subscriptionId}, Consumer: {streamConsumer}", exc);
// Corrupted state, deactivate grain.
DeactivateOnIdle();
throw;
}
}
private void RemoveProducer(PubSubPublisherState producer)
{
logger.Warn(ErrorCode.Stream_ProducerIsDead,
"Producer {0} on stream {1} is no longer active - permanently removing producer.",
producer, producer.Stream);
State.Producers.Remove(producer);
}
public async Task UnregisterConsumer(GuidId subscriptionId, StreamId streamId)
{
counterConsumersRemoved.Increment();
try
{
int numRemoved = State.Consumers.RemoveWhere(c => c.Equals(subscriptionId));
LogPubSubCounts("UnregisterSubscription {0} NumRemoved={1}", subscriptionId, numRemoved);
if (await TryClearState())
{
// If state was cleared expedite Deactivation
DeactivateOnIdle();
}
else
{
if (numRemoved != 0)
{
await WriteStateAsync();
}
await NotifyProducersOfRemovedSubscription(subscriptionId, streamId);
}
counterConsumersTotal.DecrementBy(numRemoved);
}
catch (Exception exc)
{
logger.Error(ErrorCode.Stream_UnregisterConsumerFailed,
$"Failed to unregister a stream consumer. Stream: {streamId}, SubscriptionId {subscriptionId}", exc);
// Corrupted state, deactivate grain.
DeactivateOnIdle();
throw;
}
}
public Task<int> ProducerCount(StreamId streamId)
{
return Task.FromResult(State.Producers.Count);
}
public Task<int> ConsumerCount(StreamId streamId)
{
return Task.FromResult(GetConsumersForStream(streamId).Length);
}
public Task<PubSubSubscriptionState[]> DiagGetConsumers(StreamId streamId)
{
return Task.FromResult(GetConsumersForStream(streamId));
}
private PubSubSubscriptionState[] GetConsumersForStream(StreamId streamId)
{
return State.Consumers.Where(c => !c.IsFaulted && c.Stream.Equals(streamId)).ToArray();
}
private void LogPubSubCounts(string fmt, params object[] args)
{
if (logger.IsEnabled(LogLevel.Debug) || DEBUG_PUB_SUB)
{
int numProducers = 0;
int numConsumers = 0;
if (State?.Producers != null)
numProducers = State.Producers.Count;
if (State?.Consumers != null)
numConsumers = State.Consumers.Count;
string when = args != null && args.Length != 0 ? string.Format(fmt, args) : fmt;
logger.Info("{0}. Now have total of {1} producers and {2} consumers. All Consumers = {3}, All Producers = {4}",
when, numProducers, numConsumers, Utils.EnumerableToString(State?.Consumers), Utils.EnumerableToString(State?.Producers));
}
}
// Check that what we have cached locally matches what is in the persistent table.
public async Task Validate()
{
var captureProducers = State.Producers;
var captureConsumers = State.Consumers;
await ReadStateAsync();
if (captureProducers.Count != State.Producers.Count)
{
throw new OrleansException(
$"State mismatch between PubSubRendezvousGrain and its persistent state. captureProducers.Count={captureProducers.Count}, State.Producers.Count={State.Producers.Count}");
}
if (captureProducers.Any(producer => !State.Producers.Contains(producer)))
{
throw new OrleansException(
$"State mismatch between PubSubRendezvousGrain and its persistent state. captureProducers={Utils.EnumerableToString(captureProducers)}, State.Producers={Utils.EnumerableToString(State.Producers)}");
}
if (captureConsumers.Count != State.Consumers.Count)
{
LogPubSubCounts("Validate: Consumer count mismatch");
throw new OrleansException(
$"State mismatch between PubSubRendezvousGrain and its persistent state. captureConsumers.Count={captureConsumers.Count}, State.Consumers.Count={State.Consumers.Count}");
}
if (captureConsumers.Any(consumer => !State.Consumers.Contains(consumer)))
{
throw new OrleansException(
$"State mismatch between PubSubRendezvousGrain and its persistent state. captureConsumers={Utils.EnumerableToString(captureConsumers)}, State.Consumers={Utils.EnumerableToString(State.Consumers)}");
}
}
public Task<List<StreamSubscription>> GetAllSubscriptions(StreamId streamId, IStreamConsumerExtension streamConsumer)
{
var grainRef = streamConsumer as GrainReference;
if (grainRef != null)
{
List<StreamSubscription> subscriptions =
State.Consumers.Where(c => !c.IsFaulted && c.Consumer.Equals(streamConsumer))
.Select(
c =>
new StreamSubscription(c.SubscriptionId.Guid, streamId.ProviderName, streamId,
grainRef.GrainId)).ToList();
return Task.FromResult(subscriptions);
}
else
{
List<StreamSubscription> subscriptions =
State.Consumers.Where(c => !c.IsFaulted)
.Select(
c =>
new StreamSubscription(c.SubscriptionId.Guid, streamId.ProviderName, streamId,
c.consumerReference.GrainId)).ToList();
return Task.FromResult(subscriptions);
}
}
public async Task FaultSubscription(GuidId subscriptionId)
{
PubSubSubscriptionState pubSubState = State.Consumers.FirstOrDefault(s => s.Equals(subscriptionId));
if (pubSubState == null)
{
return;
}
try
{
pubSubState.Fault();
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Setting subscription {0} to a faulted state.", subscriptionId.Guid);
await WriteStateAsync();
await NotifyProducersOfRemovedSubscription(pubSubState.SubscriptionId, pubSubState.Stream);
}
catch (Exception exc)
{
logger.Error(ErrorCode.Stream_SetSubscriptionToFaultedFailed,
$"Failed to set subscription state to faulted. SubscriptionId {subscriptionId}", exc);
// Corrupted state, deactivate grain.
DeactivateOnIdle();
throw;
}
}
private async Task NotifyProducersOfRemovedSubscription(GuidId subscriptionId, StreamId streamId)
{
int numProducersBeforeNotify = State.Producers.Count;
if (numProducersBeforeNotify > 0)
{
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Notifying {0} existing producers about unregistered consumer.", numProducersBeforeNotify);
// Notify producers about unregistered consumer.
List<Task> tasks = State.Producers
.Select(producerState => ExecuteProducerTask(producerState, producerState.Producer.RemoveSubscriber(subscriptionId, streamId)))
.ToList();
await Task.WhenAll(tasks);
//if producers got removed
if (State.Producers.Count < numProducersBeforeNotify)
await this.WriteStateAsync();
}
}
/// <summary>
/// Try clear state will only clear the state if there are no producers or consumers.
/// </summary>
/// <returns></returns>
private async Task<bool> TryClearState()
{
if (State.Producers.Count == 0 && State.Consumers.Count == 0) // + we already know that numProducers == 0 from previous if-clause
{
await ClearStateAsync(); //State contains no producers or consumers, remove it from storage
return true;
}
return false;
}
private async Task ExecuteProducerTask(PubSubPublisherState producer, Task producerTask)
{
try
{
await producerTask;
}
catch (GrainExtensionNotInstalledException)
{
RemoveProducer(producer);
}
catch (ClientNotAvailableException)
{
RemoveProducer(producer);
}
catch (OrleansMessageRejectionException)
{
var grainRef = producer.Producer as GrainReference;
// if producer is a system target on and unavailable silo, remove it.
if (grainRef == null || grainRef.GrainId.IsSystemTarget && siloStatusOracle.GetApproximateSiloStatus(grainRef.SystemTargetSilo).IsUnavailable())
{
RemoveProducer(producer);
}
else // otherwise, throw
{
throw;
}
}
}
}
}
| |
// 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 Internal.Cryptography;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
namespace System.Security
{
public sealed partial class SecureString
{
internal SecureString(SecureString str)
{
Debug.Assert(str != null, "Expected non-null SecureString");
Debug.Assert(str._buffer != null, "Expected other SecureString's buffer to be non-null");
Debug.Assert(str._encrypted, "Expected to be used only on encrypted SecureStrings");
AllocateBuffer(str._buffer.Length);
SafeBSTRHandle.Copy(str._buffer, _buffer, str._buffer.Length * sizeof(char));
_decryptedLength = str._decryptedLength;
_encrypted = str._encrypted;
}
private unsafe void InitializeSecureString(char* value, int length)
{
Debug.Assert(length >= 0, $"Expected non-negative length, got {length}");
AllocateBuffer((uint)length);
_decryptedLength = length;
byte* bufferPtr = null;
try
{
_buffer.AcquirePointer(ref bufferPtr);
Buffer.MemoryCopy((byte*)value, bufferPtr, (long)_buffer.ByteLength, length * sizeof(char));
}
finally
{
if (bufferPtr != null)
{
_buffer.ReleasePointer();
}
}
ProtectMemory();
}
private void AppendCharCore(char c)
{
UnprotectMemory();
try
{
EnsureCapacity(_decryptedLength + 1);
_buffer.Write<char>((uint)_decryptedLength * sizeof(char), c);
_decryptedLength++;
}
finally
{
ProtectMemory();
}
}
private void ClearCore()
{
_decryptedLength = 0;
_buffer.ClearBuffer();
}
private void DisposeCore()
{
if (_buffer != null)
{
_buffer.Dispose();
_buffer = null;
}
}
private unsafe void InsertAtCore(int index, char c)
{
byte* bufferPtr = null;
UnprotectMemory();
try
{
EnsureCapacity(_decryptedLength + 1);
_buffer.AcquirePointer(ref bufferPtr);
char* pBuffer = (char*)bufferPtr;
for (int i = _decryptedLength; i > index; i--)
{
pBuffer[i] = pBuffer[i - 1];
}
pBuffer[index] = c;
++_decryptedLength;
}
finally
{
ProtectMemory();
if (bufferPtr != null)
{
_buffer.ReleasePointer();
}
}
}
private unsafe void RemoveAtCore(int index)
{
byte* bufferPtr = null;
UnprotectMemory();
try
{
_buffer.AcquirePointer(ref bufferPtr);
char* pBuffer = (char*)bufferPtr;
for (int i = index; i < _decryptedLength - 1; i++)
{
pBuffer[i] = pBuffer[i + 1];
}
pBuffer[--_decryptedLength] = (char)0;
}
finally
{
ProtectMemory();
if (bufferPtr != null)
{
_buffer.ReleasePointer();
}
}
}
private void SetAtCore(int index, char c)
{
UnprotectMemory();
try
{
_buffer.Write<char>((uint)index * sizeof(char), c);
}
finally
{
ProtectMemory();
}
}
internal unsafe IntPtr MarshalToStringCore(bool globalAlloc, bool unicode)
{
int length = _decryptedLength;
IntPtr ptr = IntPtr.Zero;
IntPtr result = IntPtr.Zero;
byte* bufferPtr = null;
UnprotectMemory();
try
{
_buffer.AcquirePointer(ref bufferPtr);
if (unicode)
{
int resultByteLength = (length + 1) * sizeof(char);
ptr = globalAlloc ? Marshal.AllocHGlobal(resultByteLength) : Marshal.AllocCoTaskMem(resultByteLength);
Buffer.MemoryCopy(bufferPtr, (byte*)ptr, resultByteLength, length * sizeof(char));
*(length + (char*)ptr) = '\0';
}
else
{
uint defaultChar = '?';
int resultByteLength = 1 + Interop.mincore.WideCharToMultiByte(
Interop.mincore.CP_ACP, Interop.mincore.WC_NO_BEST_FIT_CHARS, (char*)bufferPtr, length, null, 0, (IntPtr)(&defaultChar), IntPtr.Zero);
ptr = globalAlloc ? Marshal.AllocHGlobal(resultByteLength) : Marshal.AllocCoTaskMem(resultByteLength);
Interop.mincore.WideCharToMultiByte(
Interop.mincore.CP_ACP, Interop.mincore.WC_NO_BEST_FIT_CHARS, (char*)bufferPtr, length, (byte*)ptr, resultByteLength - 1, (IntPtr)(&defaultChar), IntPtr.Zero);
*(resultByteLength - 1 + (byte*)ptr) = 0;
}
result = ptr;
}
finally
{
ProtectMemory();
// If we failed for any reason, free the new buffer
if (result == IntPtr.Zero && ptr != IntPtr.Zero)
{
Interop.NtDll.ZeroMemory(ptr, (UIntPtr)(length * sizeof(char)));
MarshalFree(ptr, globalAlloc);
}
if (bufferPtr != null)
{
_buffer.ReleasePointer();
}
}
return result;
}
private void EnsureNotDisposed()
{
if (_buffer == null)
{
throw new ObjectDisposedException(GetType().Name);
}
}
// -----------------------------
// ---- PAL layer ends here ----
// -----------------------------
private const int BlockSize = (int)Interop.Crypt32.CRYPTPROTECTMEMORY_BLOCK_SIZE / sizeof(char);
private SafeBSTRHandle _buffer;
private bool _encrypted;
private void AllocateBuffer(uint size)
{
_buffer = SafeBSTRHandle.Allocate(GetAlignedSize(size));
}
private static uint GetAlignedSize(uint size) =>
size == 0 || size % BlockSize != 0 ?
BlockSize + ((size / BlockSize) * BlockSize) :
size;
private void EnsureCapacity(int capacity)
{
if (capacity > MaxLength)
{
throw new ArgumentOutOfRangeException(nameof(capacity), SR.ArgumentOutOfRange_Capacity);
}
if (((uint)capacity * sizeof(char)) <= _buffer.ByteLength)
{
return;
}
var oldBuffer = _buffer;
SafeBSTRHandle newBuffer = SafeBSTRHandle.Allocate(GetAlignedSize((uint)capacity));
SafeBSTRHandle.Copy(oldBuffer, newBuffer, (uint)_decryptedLength * sizeof(char));
_buffer = newBuffer;
oldBuffer.Dispose();
}
private void ProtectMemory()
{
Debug.Assert(!_buffer.IsInvalid, "Invalid buffer!");
if (_decryptedLength != 0 &&
!_encrypted &&
!Interop.Crypt32.CryptProtectMemory(_buffer, _buffer.Length * sizeof(char), Interop.Crypt32.CRYPTPROTECTMEMORY_SAME_PROCESS))
{
throw new CryptographicException(Marshal.GetLastWin32Error());
}
_encrypted = true;
}
private void UnprotectMemory()
{
Debug.Assert(!_buffer.IsInvalid, "Invalid buffer!");
if (_decryptedLength != 0 &&
_encrypted &&
!Interop.Crypt32.CryptUnprotectMemory(_buffer, _buffer.Length * sizeof(char), Interop.Crypt32.CRYPTPROTECTMEMORY_SAME_PROCESS))
{
throw new CryptographicException(Marshal.GetLastWin32Error());
}
_encrypted = false;
}
}
}
| |
#region license
// Copyright (c) 2009 Rodrigo B. de Oliveira (rbo@acm.org)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * 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 Rodrigo B. de Oliveira nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
//
// DO NOT EDIT THIS FILE!
//
// This file was generated automatically by astgen.boo.
//
namespace Boo.Lang.Compiler.Ast
{
using System.Collections;
using System.Runtime.Serialization;
[System.Serializable]
public partial class Constructor : Method
{
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
new public Constructor CloneNode()
{
return (Constructor)Clone();
}
/// <summary>
/// <see cref="Node.CleanClone"/>
/// </summary>
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
new public Constructor CleanClone()
{
return (Constructor)base.CleanClone();
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public NodeType NodeType
{
get { return NodeType.Constructor; }
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public void Accept(IAstVisitor visitor)
{
visitor.OnConstructor(this);
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public bool Matches(Node node)
{
if (node == null) return false;
if (NodeType != node.NodeType) return false;
var other = ( Constructor)node;
if (_modifiers != other._modifiers) return NoMatch("Constructor._modifiers");
if (_name != other._name) return NoMatch("Constructor._name");
if (!Node.AllMatch(_attributes, other._attributes)) return NoMatch("Constructor._attributes");
if (!Node.AllMatch(_parameters, other._parameters)) return NoMatch("Constructor._parameters");
if (!Node.AllMatch(_genericParameters, other._genericParameters)) return NoMatch("Constructor._genericParameters");
if (!Node.Matches(_returnType, other._returnType)) return NoMatch("Constructor._returnType");
if (!Node.AllMatch(_returnTypeAttributes, other._returnTypeAttributes)) return NoMatch("Constructor._returnTypeAttributes");
if (!Node.Matches(_body, other._body)) return NoMatch("Constructor._body");
if (!Node.AllMatch(_locals, other._locals)) return NoMatch("Constructor._locals");
if (_implementationFlags != other._implementationFlags) return NoMatch("Constructor._implementationFlags");
if (!Node.Matches(_explicitInfo, other._explicitInfo)) return NoMatch("Constructor._explicitInfo");
return true;
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public bool Replace(Node existing, Node newNode)
{
if (base.Replace(existing, newNode))
{
return true;
}
if (_attributes != null)
{
Attribute item = existing as Attribute;
if (null != item)
{
Attribute newItem = (Attribute)newNode;
if (_attributes.Replace(item, newItem))
{
return true;
}
}
}
if (_parameters != null)
{
ParameterDeclaration item = existing as ParameterDeclaration;
if (null != item)
{
ParameterDeclaration newItem = (ParameterDeclaration)newNode;
if (_parameters.Replace(item, newItem))
{
return true;
}
}
}
if (_genericParameters != null)
{
GenericParameterDeclaration item = existing as GenericParameterDeclaration;
if (null != item)
{
GenericParameterDeclaration newItem = (GenericParameterDeclaration)newNode;
if (_genericParameters.Replace(item, newItem))
{
return true;
}
}
}
if (_returnType == existing)
{
this.ReturnType = (TypeReference)newNode;
return true;
}
if (_returnTypeAttributes != null)
{
Attribute item = existing as Attribute;
if (null != item)
{
Attribute newItem = (Attribute)newNode;
if (_returnTypeAttributes.Replace(item, newItem))
{
return true;
}
}
}
if (_body == existing)
{
this.Body = (Block)newNode;
return true;
}
if (_locals != null)
{
Local item = existing as Local;
if (null != item)
{
Local newItem = (Local)newNode;
if (_locals.Replace(item, newItem))
{
return true;
}
}
}
if (_explicitInfo == existing)
{
this.ExplicitInfo = (ExplicitMemberInfo)newNode;
return true;
}
return false;
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public object Clone()
{
Constructor clone = (Constructor)FormatterServices.GetUninitializedObject(typeof(Constructor));
clone._lexicalInfo = _lexicalInfo;
clone._endSourceLocation = _endSourceLocation;
clone._documentation = _documentation;
clone._entity = _entity;
if (_annotations != null) clone._annotations = (Hashtable)_annotations.Clone();
clone._modifiers = _modifiers;
clone._name = _name;
if (null != _attributes)
{
clone._attributes = _attributes.Clone() as AttributeCollection;
clone._attributes.InitializeParent(clone);
}
if (null != _parameters)
{
clone._parameters = _parameters.Clone() as ParameterDeclarationCollection;
clone._parameters.InitializeParent(clone);
}
if (null != _genericParameters)
{
clone._genericParameters = _genericParameters.Clone() as GenericParameterDeclarationCollection;
clone._genericParameters.InitializeParent(clone);
}
if (null != _returnType)
{
clone._returnType = _returnType.Clone() as TypeReference;
clone._returnType.InitializeParent(clone);
}
if (null != _returnTypeAttributes)
{
clone._returnTypeAttributes = _returnTypeAttributes.Clone() as AttributeCollection;
clone._returnTypeAttributes.InitializeParent(clone);
}
if (null != _body)
{
clone._body = _body.Clone() as Block;
clone._body.InitializeParent(clone);
}
if (null != _locals)
{
clone._locals = _locals.Clone() as LocalCollection;
clone._locals.InitializeParent(clone);
}
clone._implementationFlags = _implementationFlags;
if (null != _explicitInfo)
{
clone._explicitInfo = _explicitInfo.Clone() as ExplicitMemberInfo;
clone._explicitInfo.InitializeParent(clone);
}
return clone;
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override internal void ClearTypeSystemBindings()
{
_annotations = null;
_entity = null;
if (null != _attributes)
{
_attributes.ClearTypeSystemBindings();
}
if (null != _parameters)
{
_parameters.ClearTypeSystemBindings();
}
if (null != _genericParameters)
{
_genericParameters.ClearTypeSystemBindings();
}
if (null != _returnType)
{
_returnType.ClearTypeSystemBindings();
}
if (null != _returnTypeAttributes)
{
_returnTypeAttributes.ClearTypeSystemBindings();
}
if (null != _body)
{
_body.ClearTypeSystemBindings();
}
if (null != _locals)
{
_locals.ClearTypeSystemBindings();
}
if (null != _explicitInfo)
{
_explicitInfo.ClearTypeSystemBindings();
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Spark.Bindings;
using Spark.Parser.Code;
using Spark.Parser.Markup;
namespace Spark.Compiler.NodeVisitors
{
public class BindingExpansionVisitor : NodeVisitor<BindingExpansionVisitor.Frame>
{
public BindingExpansionVisitor(VisitorContext context)
: base(context)
{
}
public class Frame
{
public ElementNode Element { get; set; }
public Binding Binding { get; set; }
public int RedundantDepth { get; set; }
public int NestingLevel { get; set; }
}
protected override void Visit(ElementNode element)
{
var binding = MatchElementBinding(element);
if (binding == null)
{
if (!element.IsEmptyElement &&
FrameData.Binding != null &&
FrameData.Binding.ElementName == element.Name)
{
++FrameData.RedundantDepth;
}
base.Visit(element);
return;
}
if (!string.IsNullOrEmpty(element.PreceedingWhitespace))
Nodes.Add(new TextNode(element.PreceedingWhitespace));
BeginBinding(element, binding);
if (element.IsEmptyElement)
EndBinding();
}
protected override void Visit(EndElementNode endElement)
{
if (FrameData.Binding != null && FrameData.Binding.ElementName == endElement.Name)
{
if (FrameData.RedundantDepth-- == 0)
{
EndBinding();
return;
}
}
base.Visit(endElement);
}
private void BeginBinding(ElementNode element, Binding binding)
{
if (binding.HasChildReference)
{
var stmt =
string.Format("{{var __bindingWriter{0} = new System.IO.StringWriter(); using(OutputScope(__bindingWriter{0})) {{",
FrameData.NestingLevel);
Accept(new StatementNode(stmt));
}
else
{
var phrase = binding.Phrases.First();
ProcessPhrase(binding, phrase, element);
}
PushFrame(Nodes, new Frame { Binding = binding, Element = element, NestingLevel = FrameData.NestingLevel + 1 });
}
private void EndBinding()
{
var element = FrameData.Element;
var binding = FrameData.Binding;
PopFrame();
if (binding.HasChildReference || binding.Phrases.Count() == 2)
{
if (binding.HasChildReference)
Accept(new StatementNode("}"));
ProcessPhrase(binding, binding.Phrases.Last(), element);
if (binding.HasChildReference)
Accept(new StatementNode("}"));
}
}
private void ProcessPhrase(Binding binding, BindingPhrase phrase, ElementNode element)
{
var snippets = phrase.Nodes.SelectMany(bindingNode => BuildSnippetsForNode(binding, bindingNode, element));
if (phrase.Type == BindingPhrase.PhraseType.Expression)
{
Accept(new ExpressionNode(snippets));
}
else if (phrase.Type == BindingPhrase.PhraseType.Statement)
{
Accept(new StatementNode(snippets));
}
else
{
throw new CompilerException("Unknown binding phrase type " + phrase.Type);
}
}
private static IEnumerable<BindingNode> AllNodes(Binding binding)
{
return binding.Phrases.SelectMany(p => p.Nodes);
}
private Binding MatchElementBinding(ElementNode node)
{
if (Context.Bindings == null) return null;
var bindingsForName = Context.Bindings.Where(binding => binding.ElementName == node.Name);
var withAttributesSatisfied = bindingsForName.Where(binding => RequiredReferencesSatisfied(binding, node));
return withAttributesSatisfied.FirstOrDefault();
}
private static bool RequiredReferencesSatisfied(Binding binding, ElementNode element)
{
// any xpath targetting a flat name must be present, or the binding doesn't qualify
foreach (var reference in AllNodes(binding).OfType<BindingNameReference>())
{
var nameReference = reference;
if (nameReference.Optional)
continue;
if (!element.Attributes.Any(attr => attr.Name == nameReference.Name))
return false;
}
// a binding with child::* mapping won't match self-closing elements
if (binding.HasChildReference && element.IsEmptyElement)
return false;
return true;
}
private IEnumerable<Snippet> BuildSnippetsForNode(Binding binding, BindingNode node, ElementNode element)
{
if (node is BindingLiteral)
return BuildSnippets(node as BindingLiteral);
if (node is BindingNameReference)
return BuildSnippets(node as BindingNameReference, element);
if (node is BindingPrefixReference)
return BuildSnippets(binding, node as BindingPrefixReference, element);
if (node is BindingChildReference)
return BuildSnippets(node as BindingChildReference);
throw new CompilerException("Binding node type " + node.GetType() + " not understood");
}
private static IEnumerable<Snippet> BuildSnippets(BindingLiteral literal)
{
return new[] { new Snippet { Value = literal.Text } };
}
private IEnumerable<Snippet> BuildSnippets(BindingChildReference literal)
{
return new[] { new Snippet { Value = "__bindingWriter" + FrameData.NestingLevel + ".ToString()" } };
}
private static IEnumerable<Snippet> BuildSnippets(BindingNameReference reference, ElementNode element)
{
var attrs = element.Attributes.Where(attr => attr.Name == reference.Name);
if (reference.AssumeStringValue)
{
var builder = new ExpressionBuilder();
PopulateBuilder(attrs.SelectMany(attr => attr.Nodes), builder);
return new[] { new Snippet { Value = builder.ToCode() } };
}
return attrs.SelectMany(attr => attr.AsCode());
}
private static IEnumerable<Snippet> BuildSnippets(Binding binding, BindingPrefixReference prefix, ElementNode element)
{
// this reference can use all attributes that start with it's prefix
var candidates = element.Attributes
.Where(attr => attr.Name.StartsWith(prefix.Prefix ?? ""));
// attributes that are matched by name, or by a longer prefix, no longer remain
var remaining = candidates
.Where(attr => AllNodes(binding).Any(compare => TestBetterMatch(attr.Name, prefix.Prefix, compare)) == false);
// remaining attributes have a name that doesn't include the prefix characters
var attrs = remaining
.Select(attr => new { PropertyName = attr.Name.Substring((prefix.Prefix ?? "").Length), Attribute = attr });
var results = new List<Snippet>();
if (prefix.AssumeDictionarySyntax)
results.Add(new Snippet { Value = "{" });
var first = true;
foreach (var attr in attrs)
{
if (first)
{
first = false;
}
else
{
results.Add(new Snippet { Value = "," });
}
if (prefix.AssumeDictionarySyntax)
results.Add(new Snippet { Value = "{\"" + attr.PropertyName + "\"," });
else
results.Add(new Snippet { Value = attr.PropertyName + "=" });
if (prefix.AssumeStringValue)
{
var builder = new ExpressionBuilder();
PopulateBuilder(attr.Attribute.Nodes, builder);
results.Add(new Snippet { Value = builder.ToCode() });
}
else
{
results.AddRange(attr.Attribute.AsCode());
}
if (prefix.AssumeDictionarySyntax)
results.Add(new Snippet { Value = "}" });
}
if (prefix.AssumeDictionarySyntax)
results.Add(new Snippet { Value = "}" });
return results;
}
private static bool TestBetterMatch(string attributeName, string matchingPrefix, BindingNode compareNode)
{
if (compareNode is BindingNameReference)
{
var nameReference = (BindingNameReference)compareNode;
if (attributeName == nameReference.Name)
{
// an exact name reference will prevent any wildcard consumption
return true;
}
}
if (compareNode is BindingPrefixReference)
{
var currentPrefix = matchingPrefix ?? "";
var comparePrefix = ((BindingPrefixReference)compareNode).Prefix ?? "";
if (comparePrefix.Length > currentPrefix.Length &&
attributeName.StartsWith(comparePrefix))
{
// A longer wildcard reference which matches the current name will
// prevent the shorter from using it
return true;
}
}
// otherwise this match is good to go.
return false;
}
private static void PopulateBuilder(IEnumerable<Node> nodes, ExpressionBuilder builder)
{
foreach (var node in nodes)
{
if (node is TextNode)
{
var text = (TextNode)node;
builder.AppendLiteral(text.Text);
}
else if (node is EntityNode)
{
var entity = (EntityNode)node;
builder.AppendLiteral("&" + entity.Name + ";");
}
else if (node is ExpressionNode)
{
var expr = (ExpressionNode)node;
builder.AppendExpression(expr.Code);
}
else
{
throw new CompilerException("Unknown content in attribute");
}
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Compute
{
using Azure;
using Management;
using Rest;
using Rest.Azure;
using Models;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for DisksOperations.
/// </summary>
public static partial class DisksOperationsExtensions
{
/// <summary>
/// Creates or updates a disk.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='diskName'>
/// The name of the disk within the given subscription and resource group.
/// </param>
/// <param name='disk'>
/// Disk object supplied in the body of the Put disk operation.
/// </param>
public static Disk CreateOrUpdate(this IDisksOperations operations, string resourceGroupName, string diskName, Disk disk)
{
return operations.CreateOrUpdateAsync(resourceGroupName, diskName, disk).GetAwaiter().GetResult();
}
/// <summary>
/// Creates or updates a disk.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='diskName'>
/// The name of the disk within the given subscription and resource group.
/// </param>
/// <param name='disk'>
/// Disk object supplied in the body of the Put disk operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Disk> CreateOrUpdateAsync(this IDisksOperations operations, string resourceGroupName, string diskName, Disk disk, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, diskName, disk, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Updates (patches) a disk.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='diskName'>
/// The name of the disk within the given subscription and resource group.
/// </param>
/// <param name='disk'>
/// Disk object supplied in the body of the Patch disk operation.
/// </param>
public static Disk Update(this IDisksOperations operations, string resourceGroupName, string diskName, DiskUpdate disk)
{
return operations.UpdateAsync(resourceGroupName, diskName, disk).GetAwaiter().GetResult();
}
/// <summary>
/// Updates (patches) a disk.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='diskName'>
/// The name of the disk within the given subscription and resource group.
/// </param>
/// <param name='disk'>
/// Disk object supplied in the body of the Patch disk operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Disk> UpdateAsync(this IDisksOperations operations, string resourceGroupName, string diskName, DiskUpdate disk, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.UpdateWithHttpMessagesAsync(resourceGroupName, diskName, disk, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets information about a disk.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='diskName'>
/// The name of the disk within the given subscription and resource group.
/// </param>
public static Disk Get(this IDisksOperations operations, string resourceGroupName, string diskName)
{
return operations.GetAsync(resourceGroupName, diskName).GetAwaiter().GetResult();
}
/// <summary>
/// Gets information about a disk.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='diskName'>
/// The name of the disk within the given subscription and resource group.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Disk> GetAsync(this IDisksOperations operations, string resourceGroupName, string diskName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, diskName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes a disk.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='diskName'>
/// The name of the disk within the given subscription and resource group.
/// </param>
public static OperationStatusResponse Delete(this IDisksOperations operations, string resourceGroupName, string diskName)
{
return operations.DeleteAsync(resourceGroupName, diskName).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes a disk.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='diskName'>
/// The name of the disk within the given subscription and resource group.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<OperationStatusResponse> DeleteAsync(this IDisksOperations operations, string resourceGroupName, string diskName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.DeleteWithHttpMessagesAsync(resourceGroupName, diskName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists all the disks under a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
public static IPage<Disk> ListByResourceGroup(this IDisksOperations operations, string resourceGroupName)
{
return operations.ListByResourceGroupAsync(resourceGroupName).GetAwaiter().GetResult();
}
/// <summary>
/// Lists all the disks under a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Disk>> ListByResourceGroupAsync(this IDisksOperations operations, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByResourceGroupWithHttpMessagesAsync(resourceGroupName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists all the disks under a subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static IPage<Disk> List(this IDisksOperations operations)
{
return operations.ListAsync().GetAwaiter().GetResult();
}
/// <summary>
/// Lists all the disks under a subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Disk>> ListAsync(this IDisksOperations operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Grants access to a disk.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='diskName'>
/// The name of the disk within the given subscription and resource group.
/// </param>
/// <param name='grantAccessData'>
/// Access data object supplied in the body of the get disk access operation.
/// </param>
public static AccessUri GrantAccess(this IDisksOperations operations, string resourceGroupName, string diskName, GrantAccessData grantAccessData)
{
return operations.GrantAccessAsync(resourceGroupName, diskName, grantAccessData).GetAwaiter().GetResult();
}
/// <summary>
/// Grants access to a disk.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='diskName'>
/// The name of the disk within the given subscription and resource group.
/// </param>
/// <param name='grantAccessData'>
/// Access data object supplied in the body of the get disk access operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<AccessUri> GrantAccessAsync(this IDisksOperations operations, string resourceGroupName, string diskName, GrantAccessData grantAccessData, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GrantAccessWithHttpMessagesAsync(resourceGroupName, diskName, grantAccessData, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Revokes access to a disk.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='diskName'>
/// The name of the disk within the given subscription and resource group.
/// </param>
public static OperationStatusResponse RevokeAccess(this IDisksOperations operations, string resourceGroupName, string diskName)
{
return operations.RevokeAccessAsync(resourceGroupName, diskName).GetAwaiter().GetResult();
}
/// <summary>
/// Revokes access to a disk.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='diskName'>
/// The name of the disk within the given subscription and resource group.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<OperationStatusResponse> RevokeAccessAsync(this IDisksOperations operations, string resourceGroupName, string diskName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.RevokeAccessWithHttpMessagesAsync(resourceGroupName, diskName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Creates or updates a disk.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='diskName'>
/// The name of the disk within the given subscription and resource group.
/// </param>
/// <param name='disk'>
/// Disk object supplied in the body of the Put disk operation.
/// </param>
public static Disk BeginCreateOrUpdate(this IDisksOperations operations, string resourceGroupName, string diskName, Disk disk)
{
return operations.BeginCreateOrUpdateAsync(resourceGroupName, diskName, disk).GetAwaiter().GetResult();
}
/// <summary>
/// Creates or updates a disk.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='diskName'>
/// The name of the disk within the given subscription and resource group.
/// </param>
/// <param name='disk'>
/// Disk object supplied in the body of the Put disk operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Disk> BeginCreateOrUpdateAsync(this IDisksOperations operations, string resourceGroupName, string diskName, Disk disk, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, diskName, disk, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Updates (patches) a disk.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='diskName'>
/// The name of the disk within the given subscription and resource group.
/// </param>
/// <param name='disk'>
/// Disk object supplied in the body of the Patch disk operation.
/// </param>
public static Disk BeginUpdate(this IDisksOperations operations, string resourceGroupName, string diskName, DiskUpdate disk)
{
return operations.BeginUpdateAsync(resourceGroupName, diskName, disk).GetAwaiter().GetResult();
}
/// <summary>
/// Updates (patches) a disk.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='diskName'>
/// The name of the disk within the given subscription and resource group.
/// </param>
/// <param name='disk'>
/// Disk object supplied in the body of the Patch disk operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Disk> BeginUpdateAsync(this IDisksOperations operations, string resourceGroupName, string diskName, DiskUpdate disk, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginUpdateWithHttpMessagesAsync(resourceGroupName, diskName, disk, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes a disk.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='diskName'>
/// The name of the disk within the given subscription and resource group.
/// </param>
public static OperationStatusResponse BeginDelete(this IDisksOperations operations, string resourceGroupName, string diskName)
{
return operations.BeginDeleteAsync(resourceGroupName, diskName).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes a disk.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='diskName'>
/// The name of the disk within the given subscription and resource group.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<OperationStatusResponse> BeginDeleteAsync(this IDisksOperations operations, string resourceGroupName, string diskName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, diskName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Grants access to a disk.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='diskName'>
/// The name of the disk within the given subscription and resource group.
/// </param>
/// <param name='grantAccessData'>
/// Access data object supplied in the body of the get disk access operation.
/// </param>
public static AccessUri BeginGrantAccess(this IDisksOperations operations, string resourceGroupName, string diskName, GrantAccessData grantAccessData)
{
return operations.BeginGrantAccessAsync(resourceGroupName, diskName, grantAccessData).GetAwaiter().GetResult();
}
/// <summary>
/// Grants access to a disk.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='diskName'>
/// The name of the disk within the given subscription and resource group.
/// </param>
/// <param name='grantAccessData'>
/// Access data object supplied in the body of the get disk access operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<AccessUri> BeginGrantAccessAsync(this IDisksOperations operations, string resourceGroupName, string diskName, GrantAccessData grantAccessData, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginGrantAccessWithHttpMessagesAsync(resourceGroupName, diskName, grantAccessData, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Revokes access to a disk.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='diskName'>
/// The name of the disk within the given subscription and resource group.
/// </param>
public static OperationStatusResponse BeginRevokeAccess(this IDisksOperations operations, string resourceGroupName, string diskName)
{
return operations.BeginRevokeAccessAsync(resourceGroupName, diskName).GetAwaiter().GetResult();
}
/// <summary>
/// Revokes access to a disk.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='diskName'>
/// The name of the disk within the given subscription and resource group.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<OperationStatusResponse> BeginRevokeAccessAsync(this IDisksOperations operations, string resourceGroupName, string diskName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginRevokeAccessWithHttpMessagesAsync(resourceGroupName, diskName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists all the disks under a resource group.
/// </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>
public static IPage<Disk> ListByResourceGroupNext(this IDisksOperations operations, string nextPageLink)
{
return operations.ListByResourceGroupNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Lists all the disks under a resource group.
/// </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='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Disk>> ListByResourceGroupNextAsync(this IDisksOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByResourceGroupNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists all the disks under a subscription.
/// </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>
public static IPage<Disk> ListNext(this IDisksOperations operations, string nextPageLink)
{
return operations.ListNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Lists all the disks under a subscription.
/// </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='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Disk>> ListNextAsync(this IDisksOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
#region Disclaimer/Info
///////////////////////////////////////////////////////////////////////////////////////////////////
// Subtext WebLog
//
// Subtext is an open source weblog system that is a fork of the .TEXT
// weblog system.
//
// For updated news and information please visit http://subtextproject.com/
// Subtext is hosted at Google Code at http://code.google.com/p/subtext/
// The development mailing list is at subtext@googlegroups.com
//
// This project is licensed under the BSD license. See the License.txt file for more information.
///////////////////////////////////////////////////////////////////////////////////////////////////
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace Subtext.Scripting
{
/// <summary>
/// A collection of <see cref="TemplateParameter"/> instances.
/// </summary>
public class TemplateParameterCollection : ICollection<TemplateParameter>
{
readonly List<TemplateParameter> _list = new List<TemplateParameter>();
/// <summary>
/// Gets the <see cref="TemplateParameter"/> at the specified index.
/// </summary>
/// <value></value>
public TemplateParameter this[int index]
{
get { return _list[index]; }
}
/// <summary>
/// Gets the <see cref="TemplateParameter"/> with the specified name.
/// </summary>
/// <value></value>
public TemplateParameter this[string name]
{
get
{
foreach (TemplateParameter parameter in _list)
{
if (String.Equals(parameter.Name, name, StringComparison.OrdinalIgnoreCase))
{
return parameter;
}
}
return null;
}
}
#region ICollection<TemplateParameter> Members
void ICollection<TemplateParameter>.Add(TemplateParameter item)
{
Add(item);
}
public void Clear()
{
_list.Clear();
}
/// <summary>
/// Gets a value indicating whether the collection contains the specified
/// <see cref="TemplateParameter">Script</see>.
/// </summary>
public bool Contains(TemplateParameter item)
{
if (item == null)
{
throw new ArgumentNullException("item");
}
return Contains(item.Name);
}
public void CopyTo(TemplateParameter[] array, int arrayIndex)
{
_list.CopyTo(array, arrayIndex);
}
public int Count
{
get { return _list.Count; }
}
public bool IsReadOnly
{
get { return false; }
}
/// <summary>
/// Removes the specified value.
/// </summary>
public bool Remove(TemplateParameter item)
{
return _list.Remove(item);
}
#endregion
#region IEnumerable<TemplateParameter> Members
IEnumerator<TemplateParameter> IEnumerable<TemplateParameter>.GetEnumerator()
{
return _list.GetEnumerator();
}
public IEnumerator GetEnumerator()
{
return _list.GetEnumerator();
}
#endregion
/// <summary>
/// Determines whether [contains] [the specified name].
/// </summary>
/// <param name="name">The name.</param>
/// <returns>
/// <c>true</c> if [contains] [the specified name]; otherwise, <c>false</c>.
/// </returns>
public bool Contains(string name)
{
return this[name] != null;
}
/// <summary>
/// Creates a template parameter from a match.
/// </summary>
/// <param name="match">The match.</param>
/// <returns></returns>
public TemplateParameter Add(Match match)
{
if (match == null)
{
throw new ArgumentNullException("match");
}
if (this[match.Groups["name"].Value] != null)
{
return this[match.Groups["name"].Value];
}
var parameter = new TemplateParameter(match.Groups["name"].Value, match.Groups["type"].Value,
match.Groups["default"].Value);
Add(parameter);
return parameter;
}
/// <summary>
/// Adds the specified value. If it already exists, returns
/// the existing one, otherwise just returns the one you added.
/// </summary>
/// <param name="value">Value.</param>
/// <returns></returns>
public TemplateParameter Add(TemplateParameter value)
{
if (value == null)
{
throw new ArgumentNullException("value");
}
if (Contains(value))
{
return this[value.Name];
}
_list.Add(value);
value.ValueChanged += OnValueChanged;
return value;
}
/// <summary>
/// Adds the contents of another <see cref="ScriptCollection">ScriptCollection</see>
/// to the end of the collection.
/// </summary>
/// <param name="value">A <see cref="ScriptCollection">ScriptCollection</see> containing the <see cref="TemplateParameter"/>s to add to the collection. </param>
public void AddRange(IEnumerable<TemplateParameter> value)
{
foreach (TemplateParameter parameter in value)
{
Add(parameter);
}
}
/// <summary>
/// Gets the index in the collection of the specified
/// <see cref="TemplateParameter">Script</see>, if it exists in the collection.
/// </summary>
/// <param name="value">The <see cref="TemplateParameter">Script</see>
/// to locate in the collection.</param>
/// <returns>The index in the collection of the specified object, if found; otherwise, -1.</returns>
public int IndexOf(TemplateParameter value)
{
return _list.IndexOf(value);
}
/// <summary>
/// Provides a shortcut to set a value.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="value">The value.</param>
public void SetValue(string name, string value)
{
if (this[name] != null)
{
this[name].Value = value;
}
}
private void OnValueChanged(object sender, ParameterValueChangedEventArgs args)
{
OnValueChanged(args);
}
protected void OnValueChanged(ParameterValueChangedEventArgs args)
{
EventHandler<ParameterValueChangedEventArgs> changeEvent = ValueChanged;
if (changeEvent != null)
{
changeEvent(this, args);
}
}
/// <summary>
/// Event raised when any parameter within this collection changes
/// its values.
/// </summary>
public event EventHandler<ParameterValueChangedEventArgs> ValueChanged;
}
}
| |
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Orleans.Tests.SqlUtils;
using Tester.RelationalUtilities;
namespace UnitTests.General
{
public abstract class RelationalStorageForTesting
{
private static readonly Dictionary<string, Func<string, RelationalStorageForTesting>> instanceFactory =
new Dictionary<string, Func<string, RelationalStorageForTesting>>
{
{AdoNetInvariants.InvariantNameSqlServer, cs => new SqlServerStorageForTesting(cs)},
{AdoNetInvariants.InvariantNameMySql, cs => new MySqlStorageForTesting(cs)},
{AdoNetInvariants.InvariantNamePostgreSql, cs => new PostgreSqlStorageForTesting(cs)}
};
public IRelationalStorage Storage { get; private set; }
public string CurrentConnectionString
{
get { return Storage.ConnectionString; }
}
/// <summary>
/// Default connection string for testing
/// </summary>
public abstract string DefaultConnectionString { get; }
/// <summary>
/// A delayed query that is then cancelled in a test to see if cancellation works.
/// </summary>
public abstract string CancellationTestQuery { get; }
public abstract string CreateStreamTestTable { get; }
public virtual string DeleteStreamTestTable { get { return "DELETE StreamingTest;"; } }
public virtual string StreamTestSelect { get { return "SELECT Id, StreamData FROM StreamingTest WHERE Id = @streamId;"; } }
public virtual string StreamTestInsert { get { return "INSERT INTO StreamingTest(Id, StreamData) VALUES(@id, @streamData);"; } }
/// <summary>
/// The script that creates Orleans schema in the database, usually CreateOrleansTables_xxxx.sql
/// </summary>
protected abstract string[] SetupSqlScriptFileNames { get; }
/// <summary>
/// A query template to create a database with a given name.
/// </summary>
protected abstract string CreateDatabaseTemplate { get; }
/// <summary>
/// A query template to drop a database with a given name.
/// </summary>
protected abstract string DropDatabaseTemplate { get; }
/// <summary>
/// A query template if a database with a given name exists.
/// </summary>
protected abstract string ExistsDatabaseTemplate { get; }
/// <summary>
/// Converts the given script into batches to execute sequentially
/// </summary>
/// <param name="setupScript">the script. usually CreateOrleansTables_xxxx.sql</param>
/// <param name="databaseName">the name of the database</param>
protected abstract IEnumerable<string> ConvertToExecutableBatches(string setupScript, string databaseName);
public static async Task<RelationalStorageForTesting> SetupInstance(string invariantName, string testDatabaseName, string connectionString = null)
{
if (string.IsNullOrWhiteSpace(invariantName))
{
throw new ArgumentException("The name of invariant must contain characters", "invariantName");
}
if (string.IsNullOrWhiteSpace(testDatabaseName))
{
throw new ArgumentException("database string must contain characters", "testDatabaseName");
}
Console.WriteLine("Initializing relational databases...");
RelationalStorageForTesting testStorage;
if(connectionString == null)
{
testStorage = CreateTestInstance(invariantName);
}
else
{
testStorage = CreateTestInstance(invariantName, connectionString);
}
Console.WriteLine("Dropping and recreating database '{0}' with connectionstring '{1}'", testDatabaseName, connectionString ?? testStorage.DefaultConnectionString);
if (await testStorage.ExistsDatabaseAsync(testDatabaseName))
{
await testStorage.DropDatabaseAsync(testDatabaseName);
}
await testStorage.CreateDatabaseAsync(testDatabaseName);
//The old storage instance has the previous connection string, time have a new handle with a new connection string...
testStorage = testStorage.CopyInstance(testDatabaseName);
Console.WriteLine("Creating database tables...");
var setupScript = String.Empty;
// Concatenate scripts
foreach (var fileName in testStorage.SetupSqlScriptFileNames)
{
setupScript += File.ReadAllText(fileName);
// Just in case add a CRLF between files, but they should end in a new line.
setupScript += "\r\n";
}
await testStorage.ExecuteSetupScript(setupScript, testDatabaseName);
Console.WriteLine("Initializing relational databases done.");
return testStorage;
}
private static RelationalStorageForTesting CreateTestInstance(string invariantName, string connectionString)
{
return instanceFactory[invariantName](connectionString);
}
private static RelationalStorageForTesting CreateTestInstance(string invariantName)
{
return CreateTestInstance(invariantName, CreateTestInstance(invariantName, "notempty").DefaultConnectionString);
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="invariantName"></param>
/// <param name="connectionString"></param>
protected RelationalStorageForTesting(string invariantName, string connectionString)
{
Storage = RelationalStorage.CreateInstance(invariantName, connectionString);
}
/// <summary>
/// Executes the given script in a test context.
/// </summary>
/// <param name="setupScript">the script. usually CreateOrleansTables_xxxx.sql</param>
/// <param name="dataBaseName">the target database to be populated</param>
/// <returns></returns>
private async Task ExecuteSetupScript(string setupScript, string dataBaseName)
{
var splitScripts = ConvertToExecutableBatches(setupScript, dataBaseName);
foreach (var script in splitScripts)
{
var res1 = await Storage.ExecuteAsync(script);
}
}
/// <summary>
/// Checks the existence of a database using the given <see paramref="storage"/> storage object.
/// </summary>
/// <param name="databaseName">The name of the database existence of which to check.</param>
/// <returns><em>TRUE</em> if the given database exists. <em>FALSE</em> otherwise.</returns>
private async Task<bool> ExistsDatabaseAsync(string databaseName)
{
var ret = await Storage.ReadAsync(string.Format(ExistsDatabaseTemplate, databaseName), command =>
{ }, (selector, resultSetCount, cancellationToken) => { return Task.FromResult(selector.GetBoolean(0)); }).ConfigureAwait(continueOnCapturedContext: false);
return ret.First();
}
/// <summary>
/// Creates a database with a given name.
/// </summary>
/// <param name="databaseName">The name of the database to create.</param>
/// <returns>The call will be successful if the DDL query is successful. Otherwise an exception will be thrown.</returns>
private async Task CreateDatabaseAsync(string databaseName)
{
await Storage.ExecuteAsync(string.Format(CreateDatabaseTemplate, databaseName), command => { }).ConfigureAwait(continueOnCapturedContext: false);
}
/// <summary>
/// Drops a database with a given name.
/// </summary>
/// <param name="databaseName">The name of the database to drop.</param>
/// <returns>The call will be successful if the DDL query is successful. Otherwise an exception will be thrown.</returns>
private Task DropDatabaseAsync(string databaseName)
{
return Storage.ExecuteAsync(string.Format(DropDatabaseTemplate, databaseName), command => { });
}
/// <summary>
/// Creates a new instance of the storage based on the old connection string by changing the database name.
/// </summary>
/// <param name="newDatabaseName">Connection string instance name of the database.</param>
/// <returns>A new <see cref="RelationalStorageForTesting"/> instance with having the same connection string but with a new databaseName.</returns>
private RelationalStorageForTesting CopyInstance(string newDatabaseName)
{
var csb = new DbConnectionStringBuilder();
csb.ConnectionString = Storage.ConnectionString;
csb["Database"] = newDatabaseName;
return CreateTestInstance(Storage.InvariantName, csb.ConnectionString);
}
}
}
| |
// Copyright 2017 Esri.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific
// language governing permissions and limitations under the License.
using Esri.ArcGISRuntime.Data;
using Esri.ArcGISRuntime.Geometry;
using Esri.ArcGISRuntime.Mapping;
using Esri.ArcGISRuntime.Symbology;
using Esri.ArcGISRuntime.UI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Drawing;
using Windows.UI.Popups;
using Windows.UI.Xaml;
namespace ArcGISRuntime.UWP.Samples.SketchOnMap
{
[ArcGISRuntime.Samples.Shared.Attributes.Sample(
name: "Sketch on map",
category: "GraphicsOverlay",
description: "Use the Sketch Editor to edit or sketch a new point, line, or polygon geometry on to a map.",
instructions: "Choose which geometry type to sketch from one of the available buttons. Choose from points, multipoints, polylines, polygons, freehand polylines, and freehand polygons.",
tags: new[] { "draw", "edit" })]
public sealed partial class SketchOnMap
{
// Graphics overlay to host sketch graphics
private GraphicsOverlay _sketchOverlay;
public SketchOnMap()
{
InitializeComponent();
// Call a function to set up the map and sketch editor
Initialize();
}
private void Initialize()
{
// Create a light gray canvas map
Map myMap = new Map(BasemapStyle.ArcGISLightGray);
// Create graphics overlay to display sketch geometry
_sketchOverlay = new GraphicsOverlay();
MyMapView.GraphicsOverlays.Add(_sketchOverlay);
// Assign the map to the MapView
MyMapView.Map = myMap;
// Fill the combo box with choices for the sketch modes (shapes)
SketchModeComboBox.ItemsSource = System.Enum.GetValues(typeof(SketchCreationMode));
SketchModeComboBox.SelectedIndex = 0;
// Set the sketch editor as the page's data context
DataContext = MyMapView.SketchEditor;
}
#region Graphic and symbol helpers
private Graphic CreateGraphic(Esri.ArcGISRuntime.Geometry.Geometry geometry)
{
// Create a graphic to display the specified geometry
Symbol symbol = null;
switch (geometry.GeometryType)
{
// Symbolize with a fill symbol
case GeometryType.Envelope:
case GeometryType.Polygon:
{
symbol = new SimpleFillSymbol()
{
Color = Color.Red,
Style = SimpleFillSymbolStyle.Solid
};
break;
}
// Symbolize with a line symbol
case GeometryType.Polyline:
{
symbol = new SimpleLineSymbol()
{
Color = Color.Red,
Style = SimpleLineSymbolStyle.Solid,
Width = 5d
};
break;
}
// Symbolize with a marker symbol
case GeometryType.Point:
case GeometryType.Multipoint:
{
symbol = new SimpleMarkerSymbol()
{
Color = Color.Red,
Style = SimpleMarkerSymbolStyle.Circle,
Size = 15d
};
break;
}
}
// pass back a new graphic with the appropriate symbol
return new Graphic(geometry, symbol);
}
private async Task<Graphic> GetGraphicAsync()
{
// Wait for the user to click a location on the map
MapPoint mapPoint = (MapPoint)await MyMapView.SketchEditor.StartAsync(SketchCreationMode.Point, false);
// Convert the map point to a screen point
var screenCoordinate = MyMapView.LocationToScreen(mapPoint);
// Identify graphics in the graphics overlay using the point
IReadOnlyList<IdentifyGraphicsOverlayResult> results = await MyMapView.IdentifyGraphicsOverlaysAsync(screenCoordinate, 2, false);
// If results were found, get the first graphic
Graphic graphic = null;
IdentifyGraphicsOverlayResult idResult = results.FirstOrDefault();
if (idResult != null && idResult.Graphics.Count > 0)
{
graphic = idResult.Graphics.FirstOrDefault();
}
// Return the graphic (or null if none were found)
return graphic;
}
#endregion
private async void DrawButtonClick(object sender, RoutedEventArgs e)
{
try
{
// Set the focus to the map view(close the flyout panel)
DrawToolsFlyout.Hide();
// Let the user draw on the map view using the chosen sketch mode
SketchCreationMode creationMode = (SketchCreationMode)SketchModeComboBox.SelectedItem;
Esri.ArcGISRuntime.Geometry.Geometry geometry = await MyMapView.SketchEditor.StartAsync(creationMode, true);
// Create and add a graphic from the geometry the user drew
Graphic graphic = CreateGraphic(geometry);
_sketchOverlay.Graphics.Add(graphic);
// Enable/disable the clear and edit buttons according to whether or not graphics exist in the overlay
ClearButton.IsEnabled = _sketchOverlay.Graphics.Count > 0;
EditButton.IsEnabled = _sketchOverlay.Graphics.Count > 0;
}
catch (TaskCanceledException)
{
// Ignore ... let the user cancel drawing
}
catch (Exception ex)
{
// Report exceptions
MessageDialog dialog = new MessageDialog("Error drawing graphic shape: " + ex.Message);
await dialog.ShowAsync();
}
}
private void ClearButtonClick(object sender, RoutedEventArgs e)
{
// Remove all graphics from the graphics overlay
_sketchOverlay.Graphics.Clear();
// Cancel any uncompleted sketch
if (MyMapView.SketchEditor.CancelCommand.CanExecute(null))
{
MyMapView.SketchEditor.CancelCommand.Execute(null);
}
// Disable buttons that require graphics
ClearButton.IsEnabled = false;
EditButton.IsEnabled = false;
}
private async void EditButtonClick(object sender, RoutedEventArgs e)
{
try
{
// Set the focus to the map view(close the flyout panel)
DrawToolsFlyout.Hide();
// Allow the user to select a graphic
Graphic editGraphic = await GetGraphicAsync();
if (editGraphic == null) { return; }
// Let the user make changes to the graphic's geometry, await the result (updated geometry)
Geometry newGeometry = await MyMapView.SketchEditor.StartAsync(editGraphic.Geometry);
// Display the updated geometry in the graphic
editGraphic.Geometry = newGeometry;
}
catch (TaskCanceledException)
{
// Ignore ... let the user cancel editing
}
catch (Exception ex)
{
// Report exceptions
MessageDialog dialog = new MessageDialog("Error editing shape: " + ex.Message);
await dialog.ShowAsync();
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.IO;
using System.Collections.Generic;
namespace ILCompiler.IBC
{
public class IBCDataReader
{
// These fields are only valid during a call to Read()
private BinaryReader reader;
private bool minified;
private uint majorVersion;
private Dictionary<byte, uint> seenFlags = new Dictionary<byte, uint>();
private IBC.LastTokens lastTokens;
#region Stream Functions
private long CurrentPosition
{
get
{
return reader.BaseStream.Position;
}
}
private void SeekTo(long position)
{
reader.BaseStream.Seek(position, SeekOrigin.Begin);
}
#endregion
#region Minify Utilities
uint ReadTokenWithMemory(ref uint lastToken)
{
if (!minified)
{
return reader.ReadUInt32();
}
uint current = reader.Read7BitEncodedUInt();
byte highByte = (byte)(current >> 24);
uint result;
if (highByte == 0)
{
result = current | (lastToken & 0xff000000);
}
else if (highByte == 0xff)
{
result = current & 0x00ffffff;
}
else
{
result = current;
}
lastToken = result;
return result;
}
uint ReadFlagWithLookup()
{
if (!minified)
{
return reader.ReadUInt32();
}
byte index = reader.ReadByte();
if (index == 0xff)
{
return reader.ReadUInt32();
}
else if (seenFlags.ContainsKey(index))
{
return seenFlags[index];
}
else
{
seenFlags[index] = reader.ReadUInt32();
return seenFlags[index];
}
}
// When V2 IBC data writes the size of a block of data to follow, it
// includes the size of the "header", i.e. the size field. More lyrically,
// size includes the size of size. V2 writes size as a four-byte integer,
// so this is pretty easily done. V3 data writes size as a variable-length
// 7-bit-encoded integer, which would require speculatively writing the
// size in order to determine what the size was. To make things much
// simpler, when the file is minifed, the size of the header is not
// included--size does not include the size of size.
private long ReadSizeAndGetStart(out int size)
{
long start;
if (minified)
{
size = reader.Read7BitEncodedInt();
start = CurrentPosition;
}
else
{
start = CurrentPosition;
size = reader.ReadInt32();
}
return start;
}
// These methods make it much easier to write code to read both formats.
private int ReadSmallInt()
{
return minified ? reader.Read7BitEncodedInt() : reader.ReadInt32();
}
private uint ReadSmallUInt()
{
return minified ? reader.Read7BitEncodedUInt() : reader.ReadUInt32();
}
#endregion
#region File-level Structures
void ReadHeader(out Guid mvid, out uint majorVersion, out uint minorVersion, out bool partialNGen)
{
// minified should always be false here, so ReadSizeAndGetStart would
// work. However, since the header's size is always written in the
// same way, there's no harm making that explicit here.
long startPosition = CurrentPosition;
int size = reader.ReadInt32();
uint magicNumber = reader.ReadUInt32();
if (magicNumber != IBC.Constants.HeaderMagicNumber)
{
throw new IBCException("Invalid file header");
}
majorVersion = reader.ReadUInt32();
mvid = reader.ReadGuid();
// Look for the optional header. Read only the parts of the optional
// header that are present (if any).
uint optionalHeaderSize = reader.ReadUInt32();
uint remaining = optionalHeaderSize - sizeof(int);
minorVersion = 0;
if (remaining >= sizeof(uint))
{
minorVersion = reader.ReadUInt32();
remaining -= sizeof(int);
}
minified = false;
partialNGen = false;
if (remaining >= sizeof(uint))
{
var fileFlags = (IBC.Constants.FileFlags)reader.ReadUInt32();
minified = fileFlags.HasFlag(IBC.Constants.FileFlags.Minified);
partialNGen = fileFlags.HasFlag(IBC.Constants.FileFlags.PartialNGen);
if (minified && (majorVersion < IBC.Constants.LowestMajorVersionSupportingMinify))
{
throw new IBCException("Minified flag is set but the file's version should not support it.");
}
remaining -= sizeof(uint);
}
SeekTo(startPosition + size);
// Make sure that CompatibleVersion <= ReadVersion <= CurrentVersion
// (Ngen only pays attention to major version, but ideally even a new
// minor version should be accompanied by a new version of IBCMerge.)
if ((majorVersion > IBC.Constants.CurrentMajorVersion) ||
((majorVersion == IBC.Constants.CurrentMajorVersion) && (minorVersion > IBC.Constants.CurrentMinorVersion)) ||
(majorVersion < IBC.Constants.CompatibleMajorVersion) ||
((majorVersion == IBC.Constants.CompatibleMajorVersion) && (minorVersion < IBC.Constants.CompatibleMinorVersion)))
{
throw new IBCException(String.Format("Version mismatch: {0}.{1} not between {2}.{3} and {4}.{5}",
majorVersion,
minorVersion,
IBC.Constants.CompatibleMajorVersion,
IBC.Constants.CompatibleMinorVersion,
IBC.Constants.CurrentMajorVersion,
IBC.Constants.CurrentMinorVersion));
}
}
void ReadFooter()
{
uint endToken = reader.ReadUInt32();
if (endToken != IBC.Constants.FooterMagicNumber)
{
throw new IBCException("Invalid file footer");
}
}
private struct SectionInfo
{
public long Offset;
public long Length;
}
Dictionary<SectionFormat, SectionInfo> ReadSectionTable(out long highestValidOffset)
{
uint NumberOfEntries = reader.ReadUInt32();
var result = new Dictionary<SectionFormat, SectionInfo>();
highestValidOffset = 0;
for (int i = 0; i < NumberOfEntries; ++i)
{
SectionInfo sectionInfo;
SectionFormat sectionFormat = (SectionFormat)reader.ReadInt32();
if ((majorVersion == 1) &&
(sectionFormat < SectionFormat.UserStringPoolProfilingData))
{
// The ScenarioInfo section was added in V2 and assigned index
// zero. Every other section that existed at that point was
// bumped up by one.
++sectionFormat;
}
sectionInfo.Offset = reader.ReadUInt32();
sectionInfo.Length = reader.ReadUInt32();
highestValidOffset = Math.Max(highestValidOffset, sectionInfo.Offset + sectionInfo.Length);
result.Add(sectionFormat, sectionInfo);
}
return result;
}
#endregion
#region Scenario Section
IBC.ScenarioRunData ReadScenarioRun()
{
var result = new IBC.ScenarioRunData();
result.RunTime = DateTime.FromFileTime(reader.ReadInt64());
result.Mvid = reader.ReadGuid();
int commandLineLength = reader.ReadInt32();
int systemInformationLength = reader.ReadInt32();
result.CommandLine = reader.ReadEncodedString(commandLineLength);
result.SystemInformation = reader.ReadEncodedString(systemInformationLength);
return result;
}
IBC.ScenarioData ReadScenario()
{
long startPosition = CurrentPosition;
var result = new IBC.ScenarioData();
uint size = reader.ReadUInt32();
result.Id = reader.ReadUInt32();
result.Mask = reader.ReadUInt32();
result.Priority = reader.ReadUInt32();
uint numberOfRuns = reader.ReadUInt32();
int nameLength = reader.ReadInt32();
result.Name = reader.ReadEncodedString(nameLength);
for (int i = 0; i < numberOfRuns; ++i)
{
result.Runs.Add(ReadScenarioRun());
}
SeekTo(startPosition + size);
return result;
}
List<IBC.ScenarioData> ReadScenarioSection(ref uint totalRuns)
{
var result = new List<IBC.ScenarioData>();
totalRuns = reader.ReadUInt32();
uint numberOfScenarios = reader.ReadUInt32();
for (int i = 0; i < numberOfScenarios; ++i)
{
result.Add(ReadScenario());
}
return result;
}
#endregion
#region Basic Block Section
void ReadBlocks(List<IBC.BasicBlockData> blockList, uint numberOfBlocks)
{
for (int i = 0; i < numberOfBlocks; ++i)
{
uint ilOffset = ReadSmallUInt();
uint hitCount = ReadSmallUInt();
blockList.Add(new IBC.BasicBlockData { ILOffset = ilOffset, ExecutionCount = hitCount });
}
}
IBC.MethodData ReadMethod()
{
var result = new IBC.MethodData();
int size;
long startPosition = ReadSizeAndGetStart(out size);
if (!minified)
{
reader.ReadUInt32(); // Number of "detail" items. Ignored.
}
result.Token = ReadTokenWithMemory(ref lastTokens.LastMethodToken);
result.ILSize = ReadSmallUInt();
if (minified)
{
uint firstBlockHitCount = reader.Read7BitEncodedUInt();
result.BasicBlocks.Add(new IBC.BasicBlockData { ILOffset = 0, ExecutionCount = firstBlockHitCount });
}
uint numberOfBlocks = ReadSmallUInt();
ReadBlocks(result.BasicBlocks, numberOfBlocks);
SeekTo(startPosition + size); // Usually a no-op
return result;
}
IBC.MethodData ReadV1Method()
{
var result = new IBC.MethodData();
result.ILSize = 0;
reader.ReadUInt32(); // Header size. Ignored.
result.Token = reader.ReadUInt32();
// V1 files stored the size of the block count data in bytes. For each
// block an offset and a count are stored, both as uints.
uint blockDataSize = reader.ReadUInt32();
uint numberOfBlocks = blockDataSize / (2 * sizeof(uint));
ReadBlocks(result.BasicBlocks, numberOfBlocks);
return result;
}
List<IBC.MethodData> ReadBasicBlockSection(ref uint totalRuns)
{
var result = new List<IBC.MethodData>();
uint numberOfMethods;
Func<IBC.MethodData> readFn;
// Unminified V2+ files store the total number of runs in the
// scenario section. V1 files didn't have a scenario section and
// stored that number here. Minified files can omit the scenario
// section, and therefore store the information here again.
// Note that V1 and minified V3+ files do not store numberOfMethods
// and totalRuns in the same order. Minified files also add an extra
// datum, a block count hint, which is used by Ngen.
if (majorVersion == 1)
{
numberOfMethods = reader.ReadUInt32();
totalRuns = reader.ReadUInt32();
readFn = (Func<IBC.MethodData>)ReadV1Method;
}
else
{
if (minified)
{
totalRuns = reader.ReadUInt32();
reader.ReadUInt32(); // Block count hint. Ignored here.
}
numberOfMethods = reader.ReadUInt32();
readFn = (Func<IBC.MethodData>)ReadMethod;
}
for (int i = 0; i < numberOfMethods; ++i)
{
result.Add(readFn());
}
return result;
}
#endregion
#region Token Sections
List<IBC.TokenData> ReadTokenSection(SectionFormat section)
{
var result = new List<IBC.TokenData>();
uint numberOfTokens = reader.ReadUInt32();
uint LastToken = IBC.Utilities.InitialTokenForSection(section);
for (int i = 0; i < numberOfTokens; ++i)
{
uint token = ReadTokenWithMemory(ref LastToken);
uint flags = ReadFlagWithLookup();
// Neither minified nor V1 files stored the scenario mask.
uint? scenarioMask = null;
if (!minified && (majorVersion > 1))
{
scenarioMask = reader.ReadUInt32();
}
result.Add(new IBC.TokenData { Token = token, Flags = flags, ScenarioMask = scenarioMask });
}
return result;
}
#endregion
#region Blob Stream Section
IBC.BlobEntry.PoolEntry ReadPoolPayload()
{
var result = new IBC.BlobEntry.PoolEntry();
int size = ReadSmallInt();
result.Data = reader.ReadBytes(size);
return result;
}
// The trimFirstByte parameter is for reading method signatures in V1
// files, which contain an unneeded one-byte prefix.
IBC.BlobEntry.SignatureEntry ReadSignaturePayload(bool trimFirstByte)
{
var result = new IBC.BlobEntry.SignatureEntry();
int signatureLength = ReadSmallInt();
if (trimFirstByte)
{
--signatureLength;
reader.ReadByte();
}
result.Signature = reader.ReadBytes(signatureLength);
return result;
}
IBC.BlobEntry.SignatureEntry ReadSignaturePayload()
{
return ReadSignaturePayload(false);
}
IBC.BlobEntry.ExternalNamespaceEntry ReadExternalNamespacePayload()
{
var result = new IBC.BlobEntry.ExternalNamespaceEntry();
int nameLength = ReadSmallInt();
result.Name = reader.ReadBytes(nameLength);
return result;
}
IBC.BlobEntry.ExternalTypeEntry ReadExternalTypePayload()
{
var result = new IBC.BlobEntry.ExternalTypeEntry();
result.AssemblyToken = ReadTokenWithMemory(ref lastTokens.LastAssemblyToken);
result.NestedClassToken = ReadTokenWithMemory(ref lastTokens.LastExternalTypeToken);
result.NamespaceToken = ReadTokenWithMemory(ref lastTokens.LastExternalNamespaceToken);
int nameLength = ReadSmallInt();
result.Name = reader.ReadBytes(nameLength);
return result;
}
IBC.BlobEntry.ExternalSignatureEntry ReadExternalSignaturePayload()
{
var result = new IBC.BlobEntry.ExternalSignatureEntry();
int signatureLength = ReadSmallInt();
result.Signature = reader.ReadBytes(signatureLength);
return result;
}
IBC.BlobEntry.ExternalMethodEntry ReadExternalMethodPayload()
{
var result = new IBC.BlobEntry.ExternalMethodEntry();
result.ClassToken = ReadTokenWithMemory(ref lastTokens.LastExternalTypeToken);
result.SignatureToken = ReadTokenWithMemory(ref lastTokens.LastExternalSignatureToken);
int nameLength = ReadSmallInt();
result.Name = reader.ReadBytes(nameLength);
return result;
}
private IBC.BlobEntry ReadBlobEntry()
{
int size;
long startPosition = ReadSizeAndGetStart(out size);
BlobType type = (BlobType)ReadSmallInt();
uint token = ReadTokenWithMemory(ref lastTokens.LastBlobToken);
IBC.BlobEntry blob;
// The "Read...Payload" functions create objects of the right type and
// populate the type-specific information from the stream. The
// fields common to all blob entries (read above) are set after
// the object is returned.
switch (type)
{
case BlobType.MetadataStringPool:
case BlobType.MetadataGuidPool:
case BlobType.MetadataBlobPool:
case BlobType.MetadataUserStringPool:
blob = ReadPoolPayload();
break;
case BlobType.ParamTypeSpec:
case BlobType.ParamMethodSpec:
blob = ReadSignaturePayload();
break;
case BlobType.ExternalNamespaceDef:
blob = ReadExternalNamespacePayload();
break;
case BlobType.ExternalTypeDef:
blob = ReadExternalTypePayload();
break;
case BlobType.ExternalSignatureDef:
blob = ReadExternalSignaturePayload();
break;
case BlobType.ExternalMethodDef:
blob = ReadExternalMethodPayload();
break;
case BlobType.EndOfBlobStream:
blob = new IBC.BlobEntry.EndOfStreamEntry();
break;
default:
long read = CurrentPosition - startPosition;
byte[] data = reader.ReadBytes((int)size - (int)read);
blob = new IBC.BlobEntry.UnknownEntry { Payload = data };
break;
}
blob.Token = token;
blob.Type = type;
SeekTo(startPosition + size);
return blob;
}
private IBC.BlobEntry ReadV1BlobEntry()
{
BlobType type = (BlobType)reader.ReadInt32();
reader.ReadUInt32(); // Flags. Unused here.
IBC.BlobEntry blob;
switch (type)
{
case BlobType.MetadataStringPool:
case BlobType.MetadataGuidPool:
case BlobType.MetadataBlobPool:
case BlobType.MetadataUserStringPool:
blob = ReadPoolPayload();
break;
case BlobType.ParamTypeSpec:
blob = ReadSignaturePayload();
break;
case BlobType.ParamMethodSpec:
// V1 data used a special prefix to indicate method signatures.
// It's not obvious why this was necessary given that the type
// field already contains this information; in any event, the
// prefix is removed here by passing true.
blob = ReadSignaturePayload(true);
break;
case BlobType.EndOfBlobStream:
blob = new IBC.BlobEntry.EndOfStreamEntry();
break;
default:
throw new IBCException("Unexpected blob type in V1 file.");
}
blob.Token = 0; // V1 files didn't store tokens for blob entries.
blob.Type = type;
return blob;
}
List<IBC.BlobEntry> ReadBlobStreamSection()
{
var blobs = new List<IBC.BlobEntry>();
IBC.BlobEntry blob = null;
Func<IBC.BlobEntry> readFn =
(majorVersion == 1) ? (Func<IBC.BlobEntry>)ReadV1BlobEntry :
(Func<IBC.BlobEntry>)ReadBlobEntry;
do
{
blob = readFn();
blobs.Add(blob);
}
while (blob.Type != BlobType.EndOfBlobStream);
return blobs;
}
#endregion
#region Top Level
private void IfPresent(Dictionary<SectionFormat, SectionInfo> sectionTable, SectionFormat section, Action f)
{
if (sectionTable.ContainsKey(section))
{
SectionInfo info = sectionTable[section];
SeekTo(info.Offset);
f();
}
}
private IBC.AssemblyData ReadInternal()
{
var result = new IBC.AssemblyData();
ReadHeader(out result.Mvid, out result.FormatMajorVersion, out result.FormatMinorVersion, out result.PartialNGen);
this.majorVersion = result.FormatMajorVersion;
long highestValidOffset;
var sectionTable = ReadSectionTable(out highestValidOffset);
IfPresent(sectionTable, SectionFormat.ScenarioInfo, () => result.Scenarios = ReadScenarioSection(ref result.TotalNumberOfRuns));
IfPresent(sectionTable, SectionFormat.BasicBlockInfo, () => result.Methods = ReadBasicBlockSection(ref result.TotalNumberOfRuns));
foreach (SectionFormat section in IBCData.SectionIterator(IBCData.SectionIteratorKind.TokenFlags))
{
IfPresent(sectionTable, section, () => result.Tokens[section] = ReadTokenSection(section));
}
IfPresent(sectionTable, SectionFormat.BlobStream, () => result.BlobStream = ReadBlobStreamSection());
SeekTo(highestValidOffset);
ReadFooter();
return result;
}
private void Clear()
{
this.minified = false;
this.majorVersion = 0;
seenFlags.Clear();
lastTokens = new IBC.LastTokens();
}
public IBC.AssemblyData Read(byte[] buffer, ref int pos, out bool minified)
{
Clear();
using (var m = new MemoryStream(buffer, pos, buffer.Length - pos))
{
this.reader = new BinaryReader(m);
var result = ReadInternal();
pos += (int)CurrentPosition;
this.reader = null;
minified = this.minified;
return result;
}
}
// IBCMerge stores and manipulates blob entries internally as byte arrays
// mirroring their verbose on-disk format. This allows the serializer to
// create an object-model representation from a byte array.
public IBC.BlobEntry BlobEntryFromByteArray(byte[] buffer)
{
Clear();
using (var m = new MemoryStream(buffer))
{
this.reader = new BinaryReader(m);
var result = ReadBlobEntry();
this.reader = null;
return result;
}
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Linq.Expressions;
using Xunit;
namespace System.Linq.Tests
{
public class MaxTests : EnumerableBasedTests
{
[Fact]
public void NullInt32Source()
{
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IQueryable<int>)null).Max());
}
[Fact]
public void EmptyInt32()
{
Assert.Throws<InvalidOperationException>(() => Enumerable.Empty<int>().AsQueryable().Max());
}
[Fact]
public void Int32MaxRepeated()
{
int[] source = { -6, 0, -9, 0, -10, 0 };
Assert.Equal(0, source.AsQueryable().Max());
}
[Fact]
public void NullInt64Source()
{
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IQueryable<long>)null).Max());
}
[Fact]
public void EmptyInt64()
{
Assert.Throws<InvalidOperationException>(() => Enumerable.Empty<long>().AsQueryable().Max());
}
[Fact]
public void Int64MaxRepeated()
{
long[] source = { 6, 50, 9, 50, 10, 50 };
Assert.Equal(50, source.AsQueryable().Max());
}
[Fact]
public void EmptySingle()
{
Assert.Throws<InvalidOperationException>(() => Enumerable.Empty<float>().AsQueryable().Max());
}
[Fact]
public void Single_MaxRepeated()
{
float[] source = { -5.5f, float.PositiveInfinity, 9.9f, float.PositiveInfinity };
Assert.True(float.IsPositiveInfinity(source.AsQueryable().Max()));
}
[Fact]
public void NullSingleSource()
{
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IQueryable<float>)null).Max());
}
[Fact]
public void NullDoubleSource()
{
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IQueryable<double>)null).Max());
}
[Fact]
public void EmptyDouble()
{
Assert.Throws<InvalidOperationException>(() => Enumerable.Empty<double>().AsQueryable().Max());
}
[Fact]
public void DoubleMaximumRepeated()
{
double[] source = { -5.5, double.PositiveInfinity, 9.9, double.PositiveInfinity };
Assert.True(double.IsPositiveInfinity(source.AsQueryable().Max()));
}
[Fact]
public void NullDecimalSource()
{
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IQueryable<decimal>)null).Max());
}
[Fact]
public void EmptyDecimal()
{
Assert.Throws<InvalidOperationException>(() => Enumerable.Empty<decimal>().AsQueryable().Max());
}
[Fact]
public void DecimalMaximumRepeated()
{
decimal[] source = { -5.5m, 0m, 9.9m, -5.5m, 9.9m };
Assert.Equal(9.9m, source.AsQueryable().Max());
}
[Fact]
public void NullNullableInt32Source()
{
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IQueryable<int?>)null).Max());
}
[Fact]
public void EmptyNullableInt32()
{
Assert.Null(Enumerable.Empty<int?>().AsQueryable().Max());
}
[Fact]
public void NullableInt32MaxRepeated()
{
int?[] source = { 6, null, null, 100, 9, 100, 10, 100 };
Assert.Equal(100, source.AsQueryable().Max());
}
[Fact]
public void NullNullableInt64Source()
{
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IQueryable<long?>)null).Max());
}
[Fact]
public void EmptyNullableInt64()
{
Assert.Null(Enumerable.Empty<long?>().AsQueryable().Max(x => x));
}
[Fact]
public void NullableInt64MaximumRepeated()
{
long?[] source = { -6, null, null, 0, -9, 0, -10, -30 };
Assert.Equal(0, source.AsQueryable().Max());
}
[Fact]
public void EmptyNullableSingle()
{
Assert.Null(Enumerable.Empty<float?>().AsQueryable().Max());
}
[Fact]
public void NullableSingleMaxRepeated()
{
float?[] source = { -6.4f, null, null, -0.5f, -9.4f, -0.5f, -10.9f, -0.5f };
Assert.Equal(-0.5f, source.AsQueryable().Max());
}
[Fact]
public void NullNullableDoubleSource()
{
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IQueryable<double?>)null).Max());
}
[Fact]
public void EmptyNullableDouble()
{
Assert.Null(Enumerable.Empty<double?>().AsQueryable().Max());
}
[Fact]
public void NullNullableDecimalSource()
{
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IQueryable<decimal?>)null).Max());
}
[Fact]
public void EmptyNullableDecimal()
{
Assert.Null(Enumerable.Empty<decimal?>().AsQueryable().Max());
}
[Fact]
public void NullableDecimalMaximumRepeated()
{
decimal?[] source = { 6.4m, null, null, decimal.MaxValue, 9.4m, decimal.MaxValue, 10.9m, decimal.MaxValue };
Assert.Equal(decimal.MaxValue, source.AsQueryable().Max());
}
[Fact]
public void EmptyDateTime()
{
Assert.Throws<InvalidOperationException>(() => Enumerable.Empty<DateTime>().AsQueryable().Max());
}
[Fact]
public void NullDateTimeSource()
{
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IQueryable<DateTime>)null).Max());
}
[Fact]
public void NullStringSource()
{
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IQueryable<string>)null).Max());
}
[Fact]
public void EmptyString()
{
Assert.Null(Enumerable.Empty<string>().AsQueryable().Max());
}
[Fact]
public void StringMaximumRepeated()
{
string[] source = { "ooo", "ccc", "ccc", "ooo", "ooo", "nnn" };
Assert.Equal("ooo", source.AsQueryable().Max());
}
[Fact]
public void EmptyInt32WithSelector()
{
Assert.Throws<InvalidOperationException>(() => Enumerable.Empty<int>().Max(x => x));
}
[Fact]
public void NullInt32SourceWithSelector()
{
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IQueryable<int>)null).Max(i => i));
}
[Fact]
public void Int32SourceWithNullSelector()
{
Expression<Func<int, int>> selector = null;
AssertExtensions.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<int>().AsQueryable().Max(selector));
}
[Fact]
public void MaxInt32WithSelectorAccessingProperty()
{
var source = new[]{
new { name="Tim", num=10 },
new { name="John", num=-105 },
new { name="Bob", num=30 }
};
Assert.Equal(30, source.AsQueryable().Max(e => e.num));
}
[Fact]
public void EmptyInt64WithSelector()
{
Assert.Throws<InvalidOperationException>(() => Enumerable.Empty<long>().AsQueryable().Max(x => x));
}
[Fact]
public void NullInt64SourceWithSelector()
{
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IQueryable<long>)null).Max(i => i));
}
[Fact]
public void Int64SourceWithNullSelector()
{
Expression<Func<long, long>> selector = null;
AssertExtensions.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<long>().AsQueryable().Max(selector));
}
[Fact]
public void MaxInt64WithSelectorAccessingProperty()
{
var source = new[]{
new { name="Tim", num=10L },
new { name="John", num=-105L },
new { name="Bob", num=long.MaxValue }
};
Assert.Equal(long.MaxValue, source.AsQueryable().Max(e => e.num));
}
[Fact]
public void MaxSingleWithSelectorAccessingProperty()
{
var source = new []
{
new { name = "Tim", num = 40.5f },
new { name = "John", num = -10.25f },
new { name = "Bob", num = 100.45f }
};
Assert.Equal(100.45f, source.AsQueryable().Max(e => e.num));
}
[Fact]
public void NullSingleSourceWithSelector()
{
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IQueryable<float>)null).Max(i => i));
}
[Fact]
public void SingleSourceWithNullSelector()
{
Expression<Func<float, float>> selector = null;
AssertExtensions.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<float>().AsQueryable().Max(selector));
}
[Fact]
public void EmptySingleWithSelector()
{
Assert.Throws<InvalidOperationException>(() => Enumerable.Empty<float>().AsQueryable().Max(x => x));
}
[Fact]
public void EmptyDoubleWithSelector()
{
Assert.Throws<InvalidOperationException>(() => Enumerable.Empty<double>().AsQueryable().Max(x => x));
}
[Fact]
public void NullDoubleSourceWithSelector()
{
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IQueryable<double>)null).Max(i => i));
}
[Fact]
public void DoubleSourceWithNullSelector()
{
Expression<Func<double, double>> selector = null;
AssertExtensions.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<double>().AsQueryable().Max(selector));
}
[Fact]
public void MaxDoubleWithSelectorAccessingField()
{
var source = new[]{
new { name="Tim", num=40.5 },
new { name="John", num=-10.25 },
new { name="Bob", num=100.45 }
};
Assert.Equal(100.45, source.AsQueryable().Max(e => e.num));
}
[Fact]
public void EmptyDecimalWithSelector()
{
Assert.Throws<InvalidOperationException>(() => Enumerable.Empty<decimal>().AsQueryable().Max(x => x));
}
[Fact]
public void NullDecimalSourceWithSelector()
{
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IQueryable<decimal>)null).Max(i => i));
}
[Fact]
public void DecimalSourceWithNullSelector()
{
Expression<Func<decimal, decimal>> selector = null;
AssertExtensions.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<decimal>().AsQueryable().Max(selector));
}
[Fact]
public void MaxDecimalWithSelectorAccessingProperty()
{
var source = new[]{
new { name="Tim", num=420.5m },
new { name="John", num=900.25m },
new { name="Bob", num=10.45m }
};
Assert.Equal(900.25m, source.AsQueryable().Max(e => e.num));
}
[Fact]
public void EmptyNullableInt32WithSelector()
{
Assert.Null(Enumerable.Empty<int?>().Max(x => x));
}
[Fact]
public void NullNullableInt32SourceWithSelector()
{
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IQueryable<int?>)null).Max(i => i));
}
[Fact]
public void NullableInt32SourceWithNullSelector()
{
Expression<Func<int?, int?>> selector = null;
AssertExtensions.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<int?>().AsQueryable().Max(selector));
}
[Fact]
public void MaxNullableInt32WithSelectorAccessingField()
{
var source = new[]{
new { name="Tim", num=(int?)10 },
new { name="John", num=(int?)-105 },
new { name="Bob", num=(int?)null }
};
Assert.Equal(10, source.AsQueryable().Max(e => e.num));
}
[Fact]
public void EmptyNullableInt64WithSelector()
{
Assert.Null(Enumerable.Empty<long?>().AsQueryable().Max(x => x));
}
[Fact]
public void NullNullableInt64SourceWithSelector()
{
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IQueryable<long?>)null).Max(i => i));
}
[Fact]
public void NullableInt64SourceWithNullSelector()
{
Expression<Func<long?, long?>> selector = null;
AssertExtensions.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<long?>().AsQueryable().Max(selector));
}
[Fact]
public void MaxNullableInt64WithSelectorAccessingField()
{
var source = new[]{
new {name="Tim", num=default(long?) },
new {name="John", num=(long?)-105L },
new {name="Bob", num=(long?)long.MaxValue }
};
Assert.Equal(long.MaxValue, source.AsQueryable().Max(e => e.num));
}
[Fact]
public void EmptyNullableSingleWithSelector()
{
Assert.Null(Enumerable.Empty<float?>().AsQueryable().Max(x => x));
}
[Fact]
public void NullNullableSingleSourceWithSelector()
{
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IQueryable<float?>)null).Max(i => i));
}
[Fact]
public void NullableSingleSourceWithNullSelector()
{
Expression<Func<float?, float?>> selector = null;
AssertExtensions.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<float?>().AsQueryable().Max(selector));
}
[Fact]
public void MaxNullableSingleWithSelectorAccessingProperty()
{
var source = new[]
{
new { name="Tim", num=(float?)40.5f },
new { name="John", num=(float?)null },
new { name="Bob", num=(float?)100.45f }
};
Assert.Equal(100.45f, source.AsQueryable().Max(e => e.num));
}
[Fact]
public void EmptyNullableDoubleWithSelector()
{
Assert.Null(Enumerable.Empty<double?>().AsQueryable().Max(x => x));
}
[Fact]
public void NullNullableDoubleSourceWithSelector()
{
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IQueryable<double?>)null).Max(i => i));
}
[Fact]
public void NullableDoubleSourceWithNullSelector()
{
Expression<Func<double?, double?>> selector = null;
AssertExtensions.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<double?>().AsQueryable().Max(selector));
}
[Fact]
public void MaxNullableDoubleWithSelectorAccessingProperty()
{
var source = new []{
new { name = "Tim", num = (double?)40.5},
new { name = "John", num = default(double?)},
new { name = "Bob", num = (double?)100.45}
};
Assert.Equal(100.45, source.AsQueryable().Max(e => e.num));
}
[Fact]
public void EmptyNullableDecimalWithSelector()
{
Assert.Null(Enumerable.Empty<decimal?>().AsQueryable().Max(x => x));
}
[Fact]
public void NullNullableDecimalSourceWithSelector()
{
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IQueryable<decimal?>)null).Max(i => i));
}
[Fact]
public void NullableDecimalSourceWithNullSelector()
{
Expression<Func<decimal?, decimal?>> selector = null;
AssertExtensions.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<decimal?>().AsQueryable().Max(selector));
}
[Fact]
public void MaxNullableDecimalWithSelectorAccessingProperty()
{
var source = new[] {
new { name="Tim", num=(decimal?)420.5m },
new { name="John", num=default(decimal?) },
new { name="Bob", num=(decimal?)10.45m }
};
Assert.Equal(420.5m, source.AsQueryable().Max(e => e.num));
}
[Fact]
public void EmptyNullableDateTimeWithSelector()
{
Assert.Null(Enumerable.Empty<DateTime?>().AsQueryable().Max(x => x));
}
[Fact]
public void NullNullableDateTimeSourceWithSelector()
{
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IQueryable<DateTime?>)null).Max(i => i));
}
[Fact]
public void NullableDateTimeSourceWithNullSelector()
{
Expression<Func<DateTime?, DateTime?>> selector = null;
AssertExtensions.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<DateTime?>().AsQueryable().Max(selector));
}
public void EmptyStringSourceWithSelector()
{
Assert.Null(Enumerable.Empty<string>().AsQueryable().Max(x => x));
}
[Fact]
public void NullStringSourceWithSelector()
{
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IQueryable<string>)null).Max(i => i));
}
[Fact]
public void StringSourceWithNullSelector()
{
Expression<Func<string, string>> selector = null;
AssertExtensions.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<string>().AsQueryable().Max(selector));
}
[Fact]
public void MaxStringWithSelectorAccessingProperty()
{
var source = new[]{
new { name="Tim", num=420.5m },
new { name="John", num=900.25m },
new { name="Bob", num=10.45m }
};
Assert.Equal("Tim", source.AsQueryable().Max(e => e.name));
}
[Fact]
public void EmptyBoolean()
{
Assert.Throws<InvalidOperationException>(() => Enumerable.Empty<bool>().AsQueryable().Max());
}
[Fact]
public void Max1()
{
var val = (new int[] { 0, 2, 1 }).AsQueryable().Max();
Assert.Equal(2, val);
}
[Fact]
public void Max2()
{
var val = (new int[] { 0, 2, 1 }).AsQueryable().Max(n => n);
Assert.Equal(2, val);
}
}
}
| |
// 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.Drawing;
using System.Globalization;
using System.Linq;
using Xunit;
namespace System.ComponentModel.TypeConverterTests
{
public class SizeFConverterTests : StringTypeConverterTestBase<SizeF>
{
protected override TypeConverter Converter { get; } = new SizeFConverter();
protected override bool StandardValuesSupported { get; } = false;
protected override bool StandardValuesExclusive { get; } = false;
protected override SizeF Default => new SizeF(1, 1);
protected override bool CreateInstanceSupported { get; } = true;
protected override bool IsGetPropertiesSupported { get; } = true;
protected override IEnumerable<Tuple<SizeF, Dictionary<string, object>>> CreateInstancePairs
{
get
{
yield return Tuple.Create(new SizeF(10, 20), new Dictionary<string, object>
{
["Width"] = 10f,
["Height"] = 20f,
});
yield return Tuple.Create(new SizeF(-2, 3), new Dictionary<string, object>
{
["Width"] = -2f,
["Height"] = 3f,
});
}
}
[Theory]
[InlineData(typeof(string))]
public void CanConvertFromTrue(Type type)
{
CanConvertFrom(type);
}
[Theory]
[InlineData(typeof(Rectangle))]
[InlineData(typeof(RectangleF))]
[InlineData(typeof(Point))]
[InlineData(typeof(PointF))]
[InlineData(typeof(Color))]
[InlineData(typeof(Size))]
[InlineData(typeof(SizeF))]
[InlineData(typeof(object))]
[InlineData(typeof(int))]
public void CanConvertFromFalse(Type type)
{
CannotConvertFrom(type);
}
[Theory]
[InlineData(typeof(string))]
public void CanConvertToTrue(Type type)
{
CanConvertTo(type);
}
[Theory]
[InlineData(typeof(Rectangle))]
[InlineData(typeof(RectangleF))]
[InlineData(typeof(Point))]
[InlineData(typeof(PointF))]
[InlineData(typeof(Color))]
[InlineData(typeof(Size))]
[InlineData(typeof(SizeF))]
[InlineData(typeof(object))]
[InlineData(typeof(int))]
public void CanConvertToFalse(Type type)
{
CannotConvertTo(type);
}
public static IEnumerable<object[]> SizeFData =>
new[]
{
new object[] {0, 0},
new object[] {1, 1},
new object[] {-1, 1},
new object[] {1, -1},
new object[] {-1, -1},
new object[] {float.MaxValue, float.MaxValue},
new object[] {float.MinValue, float.MaxValue},
new object[] {float.MaxValue, float.MinValue},
new object[] {float.MinValue, float.MinValue},
};
[Theory]
[MemberData(nameof(SizeFData))]
public void ConvertFrom(float width, float height)
{
TestConvertFromString(new SizeF(width, height), FormattableString.Invariant($"{width:G9}, {height:G9}"));
}
[Theory]
[InlineData("1")]
[InlineData("1, 1, 1")]
public void ConvertFrom_ArgumentException(string value)
{
ConvertFromThrowsArgumentExceptionForString(value);
}
[Fact]
public void ConvertFrom_Invalid()
{
ConvertFromThrowsFormatInnerExceptionForString("*1, 1");
}
public static IEnumerable<object[]> ConvertFrom_NotSupportedData =>
new[]
{
new object[] {new Point(1, 1)},
new object[] {new PointF(1, 1)},
new object[] {new SizeF(1, 1)},
new object[] {new SizeF(1, 1)},
new object[] {0x10},
};
[Theory]
[MemberData(nameof(ConvertFrom_NotSupportedData))]
public void ConvertFrom_NotSupported(object value)
{
ConvertFromThrowsNotSupportedFor(value);
}
[Theory]
[MemberData(nameof(SizeFData))]
[SkipOnTargetFramework(~TargetFrameworkMonikers.NetFramework)]
public void ConvertTo_NetFramework(float width, float height)
{
TestConvertToString(new SizeF(width, height), FormattableString.Invariant($"{width:G9}, {height:G9}"));
}
[Theory]
[MemberData(nameof(SizeFData))]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)]
public void ConvertTo_NotNetFramework(float width, float height)
{
TestConvertToString(new SizeF(width, height), FormattableString.Invariant($"{width}, {height}"));
}
[Theory]
[InlineData(typeof(Size))]
[InlineData(typeof(SizeF))]
[InlineData(typeof(Point))]
[InlineData(typeof(PointF))]
[InlineData(typeof(int))]
public void ConvertTo_NotSupportedException(Type type)
{
ConvertToThrowsNotSupportedForType(type);
}
[Fact]
public void ConvertTo_NullCulture()
{
string listSep = CultureInfo.CurrentCulture.TextInfo.ListSeparator;
Assert.Equal($"1{listSep} 1", Converter.ConvertTo(null, null, new SizeF(1, 1), typeof(string)));
}
[Fact]
public void CreateInstance_CaseSensitive()
{
// NET Framework throws NullReferenceException but we want it to be friendly on Core so it
// correctly throws an ArgumentException
Type expectedExceptionType =
PlatformDetection.IsFullFramework ? typeof(NullReferenceException) : typeof(ArgumentException);
Assert.Throws(expectedExceptionType, () =>
{
Converter.CreateInstance(null, new Dictionary<string, object>
{
["width"] = 1,
["Height"] = 1,
});
});
}
[Fact]
public void GetProperties()
{
var pt = new SizeF(1, 1);
var props = Converter.GetProperties(new SizeF(1, 1));
Assert.Equal(2, props.Count);
Assert.Equal(1f, props["Width"].GetValue(pt));
Assert.Equal(1f, props["Height"].GetValue(pt));
props = Converter.GetProperties(null, new SizeF(1, 1));
Assert.Equal(2, props.Count);
Assert.Equal(1f, props["Width"].GetValue(pt));
Assert.Equal(1f, props["Height"].GetValue(pt));
props = Converter.GetProperties(null, new SizeF(1, 1), null);
Assert.Equal(3, props.Count);
Assert.Equal(1f, props["Width"].GetValue(pt));
Assert.Equal(1f, props["Height"].GetValue(pt));
Assert.Equal(false, props["IsEmpty"].GetValue(pt));
props = Converter.GetProperties(null, new SizeF(1, 1), new Attribute[0]);
Assert.Equal(3, props.Count);
Assert.Equal(1f, props["Width"].GetValue(pt));
Assert.Equal(1f, props["Height"].GetValue(pt));
Assert.Equal(false, props["IsEmpty"].GetValue(pt));
// Pick an attibute that cannot be applied to properties to make sure everything gets filtered
props = Converter.GetProperties(null, new SizeF(1, 1), new Attribute[] { new System.Reflection.AssemblyCopyrightAttribute("")});
Assert.Equal(0, props.Count);
}
[Theory]
[MemberData(nameof(SizeFData))]
public void ConvertFromInvariantString(float width, float height)
{
var point = (SizeF)Converter.ConvertFromInvariantString(FormattableString.Invariant($"{width:G9}, {height:G9}"));
Assert.Equal(width, point.Width);
Assert.Equal(height, point.Height);
}
[Fact]
public void ConvertFromInvariantString_ArgumentException()
{
ConvertFromInvariantStringThrowsArgumentException("1");
}
[Fact]
public void ConvertFromInvariantString_FormatException()
{
ConvertFromInvariantStringThrowsFormatInnerException("hello");
}
[Theory]
[MemberData(nameof(SizeFData))]
public void ConvertFromString(float width, float height)
{
var point =
(SizeF)Converter.ConvertFromString(string.Format(CultureInfo.CurrentCulture, "{0:g9}{2} {1:g9}", width, height,
CultureInfo.CurrentCulture.TextInfo.ListSeparator));
Assert.Equal(width, point.Width);
Assert.Equal(height, point.Height);
}
[Fact]
public void ConvertFromString_ArgumentException()
{
ConvertFromStringThrowsArgumentException("1");
}
[Fact]
public void ConvertFromString_FormatException()
{
ConvertFromStringThrowsFormatInnerException("hello");
}
[Theory]
[MemberData(nameof(SizeFData))]
[SkipOnTargetFramework(~TargetFrameworkMonikers.NetFramework)]
public void ConvertToInvariantString_NetFramework(float width, float height)
{
var str = Converter.ConvertToInvariantString(new SizeF(width, height));
Assert.Equal(FormattableString.Invariant($"{width:G9}, {height:G9}"), str);
}
[Theory]
[MemberData(nameof(SizeFData))]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)]
public void ConvertToInvariantString_NotNetFramework(float width, float height)
{
var str = Converter.ConvertToInvariantString(new SizeF(width, height));
Assert.Equal(FormattableString.Invariant($"{width}, {height}"), str);
}
[Theory]
[MemberData(nameof(SizeFData))]
[SkipOnTargetFramework(~TargetFrameworkMonikers.NetFramework)]
public void ConvertToString_NetFramework(float width, float height)
{
var str = Converter.ConvertToString(new SizeF(width, height));
Assert.Equal(string.Format(CultureInfo.CurrentCulture, "{0:G9}{2} {1:G9}", width, height, CultureInfo.CurrentCulture.TextInfo.ListSeparator), str);
}
[Theory]
[MemberData(nameof(SizeFData))]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)]
public void ConvertToString_NotNetFramework(float width, float height)
{
var str = Converter.ConvertToString(new SizeF(width, height));
Assert.Equal(string.Format(CultureInfo.CurrentCulture, "{0}{2} {1}", width, height, CultureInfo.CurrentCulture.TextInfo.ListSeparator), str);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Runtime;
using System.Diagnostics;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using Internal.Runtime.Augments;
using Internal.Reflection.Extensibility;
#if ENABLE_REFLECTION_TRACE
using Internal.Reflection.Tracing;
#endif
namespace Internal.Reflection.Core.NonPortable
{
//
// Base type for all RuntimeType classes implemented by the runtime. The actual implementation class can live either in System.Private.CoreLib or
// System.Reflection.Runtime.
//
// Mostly, this sets many of the "flavor-specific" properties to return the desktop-compatible "error case" result.
// This minimizes the number of methods the subclasses must override.
//
[DebuggerDisplay("{_debugName}")]
public abstract class RuntimeType : ExtensibleType, IEquatable<RuntimeType>
{
protected RuntimeType()
: base()
{
}
//=====================================================================================================================
// Equals/GetHashCode() - Important!
//
// RuntimeType objects are currently unified and stored as weak references. Because of this, it's sufficient for Equals()
// to do an instance equality check, but GetHashCode() must return a hash code based on semantic identity.
//
// Ideally, we'd override Equals() and seal it but FxCop would likely complain
// if our derived types overrode GetHashCode() without overriding Equals(). Thus, all derived types that
// override GetHashCode() must override Equals() to keep FxCop happy but should implemented as:
//
// public sealed override bool Equals(Object obj)
// {
// return InternalIsEqual(obj);
// }
//
// so that the assumption of unification is encapsulated in one place.
//
// We could also have sealed both overrides here and had our GetHashCode() do a call to a virtual "InternalGetHashCode".
// But that would impose a double virtual dispatch on the perf-critical GetHashCode() method.
//=====================================================================================================================
public abstract override bool Equals(Object obj);
public abstract override int GetHashCode();
public bool Equals(RuntimeType runtimeType)
{
Debug.Assert(!(this.InternalViolatesTypeIdentityRules || runtimeType.InternalViolatesTypeIdentityRules), "A shadow type escaped into the wild!");
return Object.ReferenceEquals(this, runtimeType);
}
public sealed override String AssemblyQualifiedName
{
get
{
#if ENABLE_REFLECTION_TRACE
if (ReflectionTrace.Enabled)
ReflectionTrace.Type_AssemblyQualifiedName(this);
#endif
String fullName = FullName;
if (fullName == null) // Some Types (such as generic parameters) return null for FullName by design.
return null;
String assemblyName = InternalFullNameOfAssembly;
return fullName + ", " + assemblyName;
}
}
//
// Left unsealed as nested and generic parameter types must override this.
//
public override Type DeclaringType
{
get { return null; }
}
//
// Left unsealed as this is only correct for named types. Other type flavors must override this.
//
public override String FullName
{
get
{
#if ENABLE_REFLECTION_TRACE
if (ReflectionTrace.Enabled)
ReflectionTrace.Type_FullName(this);
#endif
Debug.Assert(!IsConstructedGenericType);
Debug.Assert(!IsGenericParameter);
Debug.Assert(!HasElementType);
String name = Name;
Type declaringType = this.DeclaringType;
if (declaringType != null)
{
String declaringTypeFullName = declaringType.FullName;
return declaringTypeFullName + "+" + name;
}
String ns = Namespace;
if (ns == null)
return name;
return ns + "." + name;
}
}
//
// Left unsealed as generic parameter types must override this.
//
public override int GenericParameterPosition
{
get
{
Debug.Assert(!IsGenericParameter);
throw new InvalidOperationException(SR.Arg_NotGenericParameter);
}
}
public sealed override Type[] GenericTypeArguments
{
get
{
RuntimeType[] genericTypeArguments = this.InternalRuntimeGenericTypeArguments;
if (genericTypeArguments.Length == 0)
return Array.Empty<Type>();
Type[] result = new Type[genericTypeArguments.Length];
for (int i = 0; i < genericTypeArguments.Length; i++)
result[i] = genericTypeArguments[i];
return result;
}
}
//
// This group of predicates is left unsealed since most type flavors return true for at least one of them.
//
public override bool IsArray { get { return false; } }
public override bool IsByRef { get { return false; } }
public override bool IsConstructedGenericType { get { return false; } }
public override bool IsGenericParameter { get { return false; } }
public override bool IsPointer { get { return false; } }
//
// Left unsealed as array types must override this.
//
public override int GetArrayRank()
{
Debug.Assert(!IsArray);
throw new ArgumentException(SR.Argument_HasToBeArrayClass);
}
public sealed override Type GetElementType()
{
return InternalRuntimeElementType;
}
//
// Left unsealed as IsGenericType types must override this.
//
public override Type GetGenericTypeDefinition()
{
Debug.Assert(!IsConstructedGenericType);
throw new InvalidOperationException(SR.InvalidOperation_NotGenericType);
}
public sealed override Type MakeArrayType()
{
#if ENABLE_REFLECTION_TRACE
if (ReflectionTrace.Enabled)
ReflectionTrace.Type_MakeArrayType(this);
#endif
// Do not implement this as a call to MakeArrayType(1) - they are not interchangable. MakeArrayType() returns a
// vector type ("SZArray") while MakeArrayType(1) returns a multidim array of rank 1. These are distinct types
// in the ECMA model and in CLR Reflection.
return ReflectionCoreNonPortable.GetArrayType(this);
}
public sealed override Type MakeArrayType(int rank)
{
#if ENABLE_REFLECTION_TRACE
if (ReflectionTrace.Enabled)
ReflectionTrace.Type_MakeArrayType(this);
#endif
if (rank <= 0)
throw new IndexOutOfRangeException();
return ReflectionCoreNonPortable.GetMultiDimArrayType(this, rank);
}
public sealed override Type MakeByRefType()
{
return ReflectionCoreNonPortable.GetByRefType(this);
}
public sealed override Type MakeGenericType(params Type[] instantiation)
{
#if ENABLE_REFLECTION_TRACE
if (ReflectionTrace.Enabled)
ReflectionTrace.Type_MakeGenericType(this, instantiation);
#endif
if (instantiation == null)
throw new ArgumentNullException("instantiation");
if (!(this.InternalIsGenericTypeDefinition))
throw new InvalidOperationException(SR.Format(SR.Arg_NotGenericTypeDefinition, this));
// We intentionally don't validate the number of arguments or their suitability to the generic type's constraints.
// In a pay-for-play world, this can cause needless MissingMetadataExceptions. There is no harm in creating
// the Type object for an inconsistent generic type - no EEType will ever match it so any attempt to "invoke" it
// will throw an exception.
RuntimeType[] genericTypeArguments = new RuntimeType[instantiation.Length];
for (int i = 0; i < instantiation.Length; i++)
{
genericTypeArguments[i] = instantiation[i] as RuntimeType;
if (genericTypeArguments[i] == null)
{
if (instantiation[i] == null)
throw new ArgumentNullException();
else
throw new PlatformNotSupportedException(SR.PlatformNotSupported_MakeGenericType); // "PlatformNotSupported" because on desktop, passing in a foreign type is allowed and creates a RefEmit.TypeBuilder
}
}
return ReflectionCoreNonPortable.GetConstructedGenericType(this, genericTypeArguments);
}
public sealed override Type MakePointerType()
{
return ReflectionCoreNonPortable.GetPointerType(this);
}
public sealed override String Name
{
get
{
#if ENABLE_REFLECTION_TRACE
if (ReflectionTrace.Enabled)
ReflectionTrace.Type_Name(this);
#endif
RuntimeType rootCauseForFailure = null;
String name = this.InternalGetNameIfAvailable(ref rootCauseForFailure);
if (name == null)
throw RuntimeAugments.Callbacks.CreateMissingMetadataException(rootCauseForFailure);
return name;
}
}
//
// Left unsealed so that invokable types can override. NOTE! If you override this, you must also override
// InternalTryGetTypeHandle().
//
public override RuntimeTypeHandle TypeHandle
{
get
{
if (this.IsByRef)
throw new PlatformNotSupportedException(SR.PlatformNotSupported_NoTypeHandleForByRef);
// If a constructed type doesn't have an type handle, it's either because the reducer tossed it (in which case,
// we would thrown a MissingMetadataException when attempting to construct the type) or because one of
// component types contains open type parameters. Since we eliminated the first case, it must be the second.
// Throwing PlatformNotSupported since the desktop does, in fact, create type handles for open types.
if (this.HasElementType || this.IsConstructedGenericType || this.IsGenericParameter)
throw new PlatformNotSupportedException(SR.PlatformNotSupported_NoTypeHandleForOpenTypes);
// If got here, this is a "plain old type" that has metadata but no type handle. We can get here if the only
// representation of the type is in the native metadata and there's no EEType at the runtime side.
// If you squint hard, this is a missing metadata situation - the metadata is missing on the runtime side - and
// the action for the user to take is the same: go mess with RD.XML.
throw RuntimeAugments.Callbacks.CreateMissingMetadataException(this);
}
}
//
// The default Type.ToString() assumes that it's safe to call Type.Name - which is not true in the world of optin metadata.
// Block this here to make sure each subclass provides a safe implementation.
//
public abstract override String ToString();
//
// Return the full name of the "defining assembly" for the purpose of computing Type.AssemblyQualifiedName;
//
// (Note: I don't like this member being public but C# rules don't permit "protected", and I can't use "protected internal"
// since this is shared across two implementation assemblies.)
//
public abstract String InternalFullNameOfAssembly { get; }
//
// (Note: I don't like this member being public but I can't use "internal" since this is shared across two implementation assemblies.)
// NOTE: If you override this, you must also override TypeHandle.
//
public virtual bool InternalTryGetTypeHandle(out RuntimeTypeHandle typeHandle)
{
typeHandle = default(RuntimeTypeHandle);
return false;
}
//
// (Note: I don't like this member being public but I can't use "internal" since this is shared across two implementation assemblies.)
//
public virtual bool InternalIsGenericTypeDefinition
{
get
{
return false;
}
}
//
// (Note: I don't like this member being public but I can't use "internal" since this is shared across two implementation assemblies.)
//
public virtual RuntimeType InternalRuntimeElementType
{
get
{
return null;
}
}
//
// (Note: I don't like this member being public but I can't use "internal" since this is shared across two implementation assemblies.)
//
public virtual RuntimeType[] InternalRuntimeGenericTypeArguments
{
get
{
Debug.Assert(!IsConstructedGenericType);
return Array.Empty<RuntimeType>();
}
}
//
// (Note: I don't like this member being public but I can't use "internal" since this is shared across two implementation assemblies.)
//
// This helper stores the companion RuntimeTypeInfo on behalf of S.R.R.
//
// - The generic method variable RUNTIMETYPEINFO is *always* RuntimeTypeInfo. It's only generic because we can't directly mention that class
// from System.Private.CoreLib. You must never instantiate this method over any other type since there's only one underlying storage slot.
//
public RUNTIMETYPEINFO InternalGetLatchedRuntimeTypeInfo<RUNTIMETYPEINFO>(Func<RuntimeType, RUNTIMETYPEINFO> factory) where RUNTIMETYPEINFO : class
{
if (_lazyRuntimeTypeInfo == null)
{
// Note that it's possible for Type to not have a TypeInfo, in which case, _lazyRuntimeTypeInfo remains null
// and this "one-time" initialization will in fact run every time. The assumption is that it's better to throw
// the null case under the bus in exchange for not introducing an extra indirection for the cases where
// a TypeInfo actually exists.
_lazyRuntimeTypeInfo = factory(this);
}
return RuntimeHelpers.UncheckedCast<RUNTIMETYPEINFO>(_lazyRuntimeTypeInfo);
}
//
// (Note: I don't like this member being public but I can't use "internal" since this is shared across two implementation assemblies.)
//
// "Shadow" runtime types are created behind the scenes to provide metadata-level functionality for
// types that have metadata but are represented by "EE" versions of the Type objects. These Type objects
// necessary violate identity and must never escape into the wild. This method calls out those types
// that checked builds can identify them.
//
public virtual bool InternalViolatesTypeIdentityRules
{
get
{
return false;
}
}
//
// (Note: I don't like this member being public but I can't use "internal" since this is shared across two implementation assemblies.)
//
// This is the central implementation for all Equals(Object) overrides by RuntimeType subclasses. Ideally,
// we'd just have sealed our own override of Equals() but this would cause FxCop violations on the subclasses for
// overriding GetHashCode() without overriding Equals().
//
public bool InternalIsEqual(Object obj)
{
Debug.Assert(!(this.InternalViolatesTypeIdentityRules || (obj is RuntimeType && ((RuntimeType)obj).InternalViolatesTypeIdentityRules)), "A shadow type escaped into the wild!");
return Object.ReferenceEquals(this, obj);
}
//
// (Note: I don't like this member being public but I can't use "internal" since this is shared across two implementation assemblies.)
//
// Pay-for-play-safe implementation of Type.Name - returns null if name is unavailable due to lack of metadata.
//
public String InternalNameIfAvailable
{
get
{
RuntimeType ignore = null;
return InternalGetNameIfAvailable(ref ignore);
}
}
//
// (Note: I don't like this member being public but I can't use "internal" since this is shared across two implementation assemblies.)
//
// Pay-for-play-safe implementation of Type.Name - if name is unavailable due to lack of metadata and sets rootCauseForFailure
// to be the type (or one of the types if multiple types were involved) that actually caused the name to be available.
//
public abstract String InternalGetNameIfAvailable(ref RuntimeType rootCauseForFailure);
//
// (Note: I don't like this member being public but I can't use "internal" since this is shared across two implementation assemblies.)
//
public virtual bool InternalIsMultiDimArray
{
get
{
return false;
}
}
//
// (Note: I don't like this member being public but I can't use "internal" since this is shared across two implementation assemblies.)
//
// Pay-for-play safe implementation of TypeInfo.ContainsGenericParameters()
//
public abstract bool InternalIsOpen { get; }
//
// Note: This can be (and is) called multiple times. We do not do this work in the constructor as calling ToString()
// in the constructor causes some serious recursion issues.
//
public void EstablishDebugName()
{
bool populateDebugNames = DeveloperExperienceState.DeveloperExperienceModeEnabled;
#if DEBUG
populateDebugNames = true;
#endif
if (!populateDebugNames)
return;
if (_debugName == null)
{
_debugName = "Constructing..."; // Protect against any inadvertent reentrancy.
String debugName;
#if ENABLE_REFLECTION_TRACE
if (ReflectionTrace.Enabled)
{
debugName = this.GetTraceString(); // If tracing on, call this.GetTraceString() which only gives you useful strings when metadata is available but doesn't pollute the ETW trace.
}
else
#endif
{
debugName = this.ToString();
}
if (debugName == null)
debugName = "";
_debugName = debugName;
}
return;
}
private volatile Object _lazyRuntimeTypeInfo; // This is actually a RuntimeTypeInfo.
private String _debugName;
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using NSubstitute.Core;
using NSubstitute.Routing;
#if (NET4 || NET45)
using System.Threading.Tasks;
#endif
namespace NSubstitute
{
public static class SubstituteExtensions
{
/// <summary>
/// Set a return value for this call.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="value"></param>
/// <param name="returnThis">Value to return</param>
/// <param name="returnThese">Optionally return these values next</param>
/// <returns></returns>
public static ConfiguredCall Returns<T>(this T value, T returnThis, params T[] returnThese)
{
return Returns(MatchArgs.AsSpecifiedInCall, returnThis, returnThese);
}
/// <summary>
/// Set a return value for this call, calculated by the provided function.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="value"></param>
/// <param name="returnThis">Function to calculate the return value</param>
/// <param name="returnThese">Optionally use these functions next</param>
/// <returns></returns>
public static ConfiguredCall Returns<T>(this T value, Func<CallInfo, T> returnThis, params Func<CallInfo, T>[] returnThese)
{
return Returns(MatchArgs.AsSpecifiedInCall, returnThis, returnThese);
}
#if (NET4 || NET45)
/// <summary>
/// Set a return value for this call. The value(s) to be returned will be wrapped in Tasks.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="value"></param>
/// <param name="returnThis">Value to return. Will be wrapped in a Task</param>
/// <param name="returnThese">Optionally use these functions next</param>
/// <returns></returns>
public static ConfiguredCall Returns<T>(this Task<T> value, T returnThis, params T[] returnThese)
{
var wrappedReturnValue = CompletedTask(returnThis);
var wrappedParameters = returnThese.Select(CompletedTask);
return Returns(MatchArgs.AsSpecifiedInCall, wrappedReturnValue, wrappedParameters.ToArray());
}
/// <summary>
/// Set a return value for this call, calculated by the provided function. The value(s) to be returned will be wrapped in Tasks.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="value"></param>
/// <param name="returnThis">Function to calculate the return value</param>
/// <param name="returnThese">Optionally use these functions next</param>
/// <returns></returns>
public static ConfiguredCall Returns<T>(this Task<T> value, Func<CallInfo, T> returnThis, params Func<CallInfo, T>[] returnThese)
{
var wrappedFunc = WrapFuncInTask(returnThis);
var wrappedFuncs = returnThese.Select(WrapFuncInTask);
return Returns(MatchArgs.AsSpecifiedInCall, wrappedFunc, wrappedFuncs.ToArray());
}
/// <summary>
/// Set a return value for this call made with any arguments. The value(s) to be returned will be wrapped in Tasks.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="value"></param>
/// <param name="returnThis">Value to return</param>
/// <param name="returnThese">Optionally return these values next</param>
/// <returns></returns>
public static ConfiguredCall ReturnsForAnyArgs<T>(this Task<T> value, T returnThis, params T[] returnThese)
{
var wrappedReturnValue = CompletedTask(returnThis);
var wrappedParameters = returnThese.Select(CompletedTask);
return Returns(MatchArgs.Any, wrappedReturnValue, wrappedParameters.ToArray());
}
/// <summary>
/// Set a return value for this call made with any arguments, calculated by the provided function. The value(s) to be returned will be wrapped in Tasks.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="value"></param>
/// <param name="returnThis">Function to calculate the return value</param>
/// <param name="returnThese">Optionally use these functions next</param>
/// <returns></returns>
public static ConfiguredCall ReturnsForAnyArgs<T>(this Task<T> value, Func<CallInfo, T> returnThis, params Func<CallInfo, T>[] returnThese)
{
var wrappedFunc = WrapFuncInTask(returnThis);
var wrappedFuncs = returnThese.Select(WrapFuncInTask);
return Returns(MatchArgs.Any, wrappedFunc, wrappedFuncs.ToArray());
}
#endif
/// <summary>
/// Set a return value for this call made with any arguments.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="value"></param>
/// <param name="returnThis">Value to return</param>
/// <param name="returnThese">Optionally return these values next</param>
/// <returns></returns>
public static ConfiguredCall ReturnsForAnyArgs<T>(this T value, T returnThis, params T[] returnThese)
{
return Returns(MatchArgs.Any, returnThis, returnThese);
}
/// <summary>
/// Set a return value for this call made with any arguments, calculated by the provided function.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="value"></param>
/// <param name="returnThis">Function to calculate the return value</param>
/// <param name="returnThese">Optionally use these functions next</param>
/// <returns></returns>
public static ConfiguredCall ReturnsForAnyArgs<T>(this T value, Func<CallInfo, T> returnThis, params Func<CallInfo, T>[] returnThese)
{
return Returns(MatchArgs.Any, returnThis, returnThese);
}
internal static ConfiguredCall Returns<T>(MatchArgs matchArgs, T returnThis, params T[] returnThese)
{
var context = SubstitutionContext.Current;
IReturn returnValue;
if (returnThese == null || returnThese.Length == 0)
{
returnValue = new ReturnValue(returnThis);
}
else
{
returnValue = new ReturnMultipleValues<T>(new[] {returnThis}.Concat(returnThese));
}
return context.LastCallShouldReturn(returnValue, matchArgs);
}
internal static ConfiguredCall Returns<T>(MatchArgs matchArgs, Func<CallInfo, T> returnThis, params Func<CallInfo, T>[] returnThese)
{
var context = SubstitutionContext.Current;
IReturn returnValue;
if (returnThese == null || returnThese.Length == 0)
{
returnValue = new ReturnValueFromFunc<T>(returnThis);
}
else
{
returnValue = new ReturnMultipleFuncsValues<T>(new[] { returnThis }.Concat(returnThese));
}
return context.LastCallShouldReturn(returnValue, matchArgs);
}
/// <summary>
/// Checks this substitute has received the following call.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="substitute"></param>
/// <returns></returns>
public static T Received<T>(this T substitute) where T : class
{
var router = GetRouterForSubstitute(substitute);
router.SetRoute(x => RouteFactory().CheckReceivedCalls(x, MatchArgs.AsSpecifiedInCall, Quantity.AtLeastOne()));
return substitute;
}
/// <summary>
/// Checks this substitute has received the following call the required number of times.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="substitute"></param>
/// <param name="requiredNumberOfCalls"></param>
/// <returns></returns>
public static T Received<T>(this T substitute, int requiredNumberOfCalls) where T : class
{
var router = GetRouterForSubstitute(substitute);
router.SetRoute(x => RouteFactory().CheckReceivedCalls(x, MatchArgs.AsSpecifiedInCall, Quantity.Exactly(requiredNumberOfCalls)));
return substitute;
}
/// <summary>
/// Checks this substitute has not received the following call.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="substitute"></param>
/// <returns></returns>
public static T DidNotReceive<T>(this T substitute) where T : class
{
var router = GetRouterForSubstitute(substitute);
router.SetRoute(x => RouteFactory().CheckReceivedCalls(x, MatchArgs.AsSpecifiedInCall, Quantity.None()));
return substitute;
}
/// <summary>
/// Checks this substitute has received the following call with any arguments.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="substitute"></param>
/// <returns></returns>
public static T ReceivedWithAnyArgs<T>(this T substitute) where T : class
{
var router = GetRouterForSubstitute(substitute);
router.SetRoute(x => RouteFactory().CheckReceivedCalls(x, MatchArgs.Any, Quantity.AtLeastOne()));
return substitute;
}
/// <summary>
/// Checks this substitute has received the following call with any arguments the required number of times.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="substitute"></param>
/// <param name="requiredNumberOfCalls"></param>
/// <returns></returns>
public static T ReceivedWithAnyArgs<T>(this T substitute, int requiredNumberOfCalls) where T : class
{
var router = GetRouterForSubstitute(substitute);
router.SetRoute(x => RouteFactory().CheckReceivedCalls(x, MatchArgs.Any, Quantity.Exactly(requiredNumberOfCalls)));
return substitute;
}
/// <summary>
/// Checks this substitute has not received the following call with any arguments.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="substitute"></param>
/// <returns></returns>
public static T DidNotReceiveWithAnyArgs<T>(this T substitute) where T : class
{
var router = GetRouterForSubstitute(substitute);
router.SetRoute(x => RouteFactory().CheckReceivedCalls(x, MatchArgs.Any, Quantity.None()));
return substitute;
}
/// <summary>
/// Forget all the calls this substitute has received.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="substitute"></param>
/// <remarks>
/// Note that this will not clear any results set up for the substitute using Returns().
/// </remarks>
public static void ClearReceivedCalls<T>(this T substitute) where T : class
{
var router = GetRouterForSubstitute(substitute);
router.ClearReceivedCalls();
}
/// <summary>
/// Perform an action when this member is called.
/// Must be followed by <see cref="WhenCalled{T}.Do(Action{CallInfo})"/> to provide the callback.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="substitute"></param>
/// <param name="substituteCall"></param>
/// <returns></returns>
public static WhenCalled<T> When<T>(this T substitute, Action<T> substituteCall) where T : class
{
var context = SubstitutionContext.Current;
return new WhenCalled<T>(context, substitute, substituteCall, MatchArgs.AsSpecifiedInCall);
}
/// <summary>
/// Perform an action when this member is called with any arguments.
/// Must be followed by <see cref="WhenCalled{T}.Do(Action{CallInfo})"/> to provide the callback.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="substitute"></param>
/// <param name="substituteCall"></param>
/// <returns></returns>
public static WhenCalled<T> WhenForAnyArgs<T>(this T substitute, Action<T> substituteCall) where T : class
{
var context = SubstitutionContext.Current;
return new WhenCalled<T>(context, substitute, substituteCall, MatchArgs.Any);
}
/// <summary>
/// Returns the calls received by this substitute.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="substitute"></param>
/// <returns></returns>
public static IEnumerable<ICall> ReceivedCalls<T>(this T substitute) where T : class
{
return GetRouterForSubstitute(substitute).ReceivedCalls();
}
#if NET4 || NET45
private static Func<CallInfo, Task<T>> WrapFuncInTask<T>(Func<CallInfo, T> returnThis)
{
return x => CompletedTask(returnThis(x));
}
private static Task<T> CompletedTask<T>(T result)
{
#if NET45
return Task.FromResult(result);
#elif NET4
var tcs = new TaskCompletionSource<T>();
tcs.SetResult(result);
return tcs.Task;
#endif
}
#endif
private static ICallRouter GetRouterForSubstitute<T>(T substitute)
{
var context = SubstitutionContext.Current;
return context.GetCallRouterFor(substitute);
}
private static IRouteFactory RouteFactory()
{
return SubstitutionContext.Current.GetRouteFactory();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection.Internal;
using System.Reflection.Metadata.Ecma335;
namespace System.Reflection.Metadata
{
public struct SequencePointCollection : IEnumerable<SequencePoint>
{
private readonly MemoryBlock _block;
private readonly DocumentHandle _document;
internal SequencePointCollection(MemoryBlock block, DocumentHandle document)
{
_block = block;
_document = document;
}
public Enumerator GetEnumerator()
{
return new Enumerator(_block, _document);
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
IEnumerator<SequencePoint> IEnumerable<SequencePoint>.GetEnumerator()
{
return GetEnumerator();
}
public struct Enumerator : IEnumerator<SequencePoint>
{
private BlobReader _reader;
private SequencePoint _current;
private int _previousNonHiddenStartLine;
private ushort _previousNonHiddenStartColumn;
internal Enumerator(MemoryBlock block, DocumentHandle document)
{
_reader = new BlobReader(block);
_current = new SequencePoint(document, -1);
_previousNonHiddenStartLine = -1;
_previousNonHiddenStartColumn = 0;
}
public bool MoveNext()
{
if (_reader.RemainingBytes == 0)
{
return false;
}
DocumentHandle document = _current.Document;
int offset, deltaLines, deltaColumns, startLine;
ushort startColumn;
if (_reader.Offset == 0)
{
// header (skip local signature rid):
_reader.ReadCompressedInteger();
if (document.IsNil)
{
document = ReadDocumentHandle();
}
// IL offset:
offset = _reader.ReadCompressedInteger();
}
else
{
// skip all document records and update the current document accordingly:
int deltaOffset;
while ((deltaOffset = _reader.ReadCompressedInteger()) == 0)
{
document = ReadDocumentHandle();
}
// IL offset:
offset = AddOffsets(_current.Offset, deltaOffset);
}
ReadDeltaLinesAndColumns(out deltaLines, out deltaColumns);
// hidden
if (deltaLines == 0 && deltaColumns == 0)
{
_current = new SequencePoint(document, offset);
return true;
}
// delta Start Line & Column:
if (_previousNonHiddenStartLine < 0)
{
Debug.Assert(_previousNonHiddenStartColumn == 0);
startLine = ReadLine();
startColumn = ReadColumn();
}
else
{
startLine = AddLines(_previousNonHiddenStartLine, _reader.ReadCompressedSignedInteger());
startColumn = AddColumns(_previousNonHiddenStartColumn, _reader.ReadCompressedSignedInteger());
}
_previousNonHiddenStartLine = startLine;
_previousNonHiddenStartColumn = startColumn;
_current = new SequencePoint(
document,
offset,
startLine,
startColumn,
AddLines(startLine, deltaLines),
AddColumns(startColumn, deltaColumns));
return true;
}
private void ReadDeltaLinesAndColumns(out int deltaLines, out int deltaColumns)
{
deltaLines = _reader.ReadCompressedInteger();
deltaColumns = (deltaLines == 0) ? _reader.ReadCompressedInteger() : _reader.ReadCompressedSignedInteger();
}
private int ReadLine()
{
return _reader.ReadCompressedInteger();
}
private ushort ReadColumn()
{
int column = _reader.ReadCompressedInteger();
if (column > ushort.MaxValue)
{
Throw.SequencePointValueOutOfRange();
}
return (ushort)column;
}
private int AddOffsets(int value, int delta)
{
int result = unchecked(value + delta);
if (result < 0 || result > int.MaxValue)
{
Throw.SequencePointValueOutOfRange();
}
return result;
}
private int AddLines(int value, int delta)
{
int result = unchecked(value + delta);
if (result < 0 || result >= SequencePoint.HiddenLine)
{
Throw.SequencePointValueOutOfRange();
}
return result;
}
private ushort AddColumns(ushort value, int delta)
{
int result = unchecked(value + delta);
if (result < 0 || result >= ushort.MaxValue)
{
Throw.SequencePointValueOutOfRange();
}
return (ushort)result;
}
private DocumentHandle ReadDocumentHandle()
{
int rowId = _reader.ReadCompressedInteger();
if (rowId == 0 || !TokenTypeIds.IsValidRowId(rowId))
{
Throw.InvalidHandle();
}
return DocumentHandle.FromRowId(rowId);
}
public SequencePoint Current
{
get { return _current; }
}
object IEnumerator.Current
{
get { return _current; }
}
public void Reset()
{
_reader.SeekOffset(0);
_current = default(SequencePoint);
}
void IDisposable.Dispose()
{
}
}
}
}
| |
using System;
using UnityEngine;
using System.Runtime.InteropServices;
/// <summary>Functions relating to liquidfun particle systems or every particle in the system</summary>
public static class LPAPIParticleSystems {
#region CreateParticleSystem
/**
* <summary>Creates a particle system and returns an IntPtr with its memory address.</summary>
* <param name="worldPointer">A pointer to Box2D World.</param>
* <param name="radius">Particle radius.</param>
* <param name="damping">Particle damping.</param>
* <param name="gravityScale">Scale of gravity.</param>
**/
#if UNITY_IPHONE && !UNITY_EDITOR
[DllImport ("__Internal")]
#else
[DllImport ("liquidfundll")]
#endif
public static extern IntPtr CreateParticleSystem(IntPtr worldPointer, float radius, float damping, float gravityScale,int number);
#endregion CreateParticleSystem
#region CreateParticleSystem2
/**
* <summary>Creates a particle system and returns an IntPtr with its memory address.</summary>
* <param name="worldPointer">A pointer to Box2D World.</param>
* <param name="radius">Particle radius.</param>
* <param name="damping">Particle damping.</param>
* <param name="gravityScale">Scale of gravity.</param>
**/
#if UNITY_IPHONE && !UNITY_EDITOR
[DllImport ("__Internal")]
#else
[DllImport ("liquidfundll")]
#endif
public static extern IntPtr CreateParticleSystem2(IntPtr worldPointer, float radius, float damping, float gravityScale,int number, float tennorm,float tenpres, float viscstr);
#endregion CreateParticleSystem2
#if UNITY_IPHONE && !UNITY_EDITOR
[DllImport ("__Internal")]
#else
[DllImport ("liquidfundll")]
#endif
public static extern void SetParticleSystemIndex(IntPtr partsysPointer, int userData);
#region GetParticleIterations
/**
* <summary>Gets the recommended value for Particle Iterations.</summary>
* <param name="gravity">Force of gravity in the world.</param>
* <param name="particleRadius">Radius of the particles in the system.</param>
* <param name="timeStep">The amount of time to simulate. This should not vary.</param>
**/
#if UNITY_IPHONE && !UNITY_EDITOR
[DllImport ("__Internal")]
#else
[DllImport ("liquidfundll")]
#endif
public static extern Int32 GetParticleIterations(float gravity, float particleRadius, float timeStep);
#endregion EndParticleIterations
#region GetParticlePositions
/**
* <summary>Returns a pointer to a float array containing the positions of all particles in a particle group. The array is of length (2*numberOfParticles)+1. The number of particles in the system is returned at index position 0. The X and Y positions are alternated starting from index 1. The array must be Marshalled to managed memory before use.</summary>
* <param name="particlePointer">A pointer to the particle system who's information will be returned.</param>
**/
#if UNITY_IPHONE && !UNITY_EDITOR
[DllImport ("__Internal")]
#else
[DllImport ("liquidfundll")]
#endif
public static extern IntPtr GetParticlePositions(IntPtr particlePointer);
#endregion GetParticlePositions
#region GetParticlePositionsAndColor
/**
* <summary>Returns a pointer to a float array containing the positions and RGBA colors of all particles in a particle group. The array is of length (6*numberOfParticles)+1. The number of particles in the system is returned at index position 0. The X, Y, R, G, B, and A values start from index 1. The array must be Marshalled to managed memory before use.</summary>
* <param name="particlePointer">A pointer to the particle system who's information will be returned.</param>
**/
#if UNITY_IPHONE && !UNITY_EDITOR
[DllImport ("__Internal")]
#else
[DllImport ("liquidfundll")]
#endif
public static extern IntPtr GetParticlePositionsAndColors(IntPtr particlePointer);
#endregion GetParticlePositionsAndColor
#region GetParticlesDetails
/**
* <summary>Returns a pointer to a float array containing selected info about all the particlers in the system
The array must be Marshalled to managed memory before use.</summary>
* <param name="particlePointer">A pointer to the particle system who's information will be returned.</param>
**/
#if UNITY_IPHONE && !UNITY_EDITOR
[DllImport ("__Internal")]
#else
[DllImport ("liquidfundll")]
#endif
public static extern IntPtr GetParticlesDetails(IntPtr particlePointer,bool position,bool color,bool age,bool weight,bool velocity,bool userdata);
#endregion GetParticlesDetails
#region GetNumberOfParticles
/**
* <summary>Gets the number of particles in a system.</summary>
* <param name="particlePointer">The particle system who's information will be returned.</param>
**/
#if UNITY_IPHONE && !UNITY_EDITOR
[DllImport ("__Internal")]
#else
[DllImport ("liquidfundll")]
#endif
public static extern int GetNumberOfParticles(IntPtr particlePointer);
#endregion GetNumberOfParticles
#region DeleteParticleSystem
/**
* <summary>Deletes a particle system. This function is locked during callbacks.</summary>
* <param name="worldPointer">Pointer to the world that the particle system will be deleted from.</param>
* <param name="particlesPointer">The particle system which will be deleted.</param>
**/
#if UNITY_IPHONE && !UNITY_EDITOR
[DllImport ("__Internal")]
#else
[DllImport ("liquidfundll")]
#endif
public static extern void DeleteParticleSystem(IntPtr worldPointer, IntPtr particlesPointer);
#endregion DeleteParticleSystem
#region SetAllParticleFlags
/**
* <summary>Set the flags for all particles in a particle system.</summary>
* <param name="particleSystemPointer">Pointer to the particle system.</param>
* <param name="particleFlags">The particle flags (b2ParticleFlag).</param>
**/
#if UNITY_IPHONE && !UNITY_EDITOR
[DllImport ("__Internal")]
#else
[DllImport ("liquidfundll")]
#endif
public static extern void SetAllParticleFlags(IntPtr particleSystemPointer, int particleFlags);
#endregion SetAllParticleFlags
#region SetParticleFlagsUpToLimit
/**
* <summary>Set the flags for a set number of particles in a particle system. Takes an upper limit as a parameter - all particles from from system[0] up to system[upperLimit] will be set.</summary>
* <param name="particleSystemPointer">Pointer to the particle system.</param>
* <param name="particleFlags">The particle flags (b2ParticleFlag).</param>
* <param name="upperBound">The index of the last particle who's flags will be set. All particles from system[0] up to system[upperBound] will be set.</param>
**/
#if UNITY_IPHONE && !UNITY_EDITOR
[DllImport ("__Internal")]
#else
[DllImport ("liquidfundll")]
#endif
public static extern void SetParticleFlagsUpToLimit(IntPtr particleSystemPointer, int particleFlags, int upperBound);
#endregion SetParticleFlagsUpToLimit
#region GetStuckCandidateCount
/**
* <summary>Get the number of stuck particle candidates from the last step.</summary>
* <param name="particleSystemPointer">Pointer to the particle system.</param>
**/
#if UNITY_IPHONE && !UNITY_EDITOR
[DllImport ("__Internal")]
#else
[DllImport ("liquidfundll")]
#endif
public static extern int GetStuckCandidateCount(IntPtr particleSystemPointer);
#endregion GetStuckCandidateCount
#region SetStuckThreshold
/**
* <summary>Set an optional threshold for the maximum number of consecutive particle iterations that a particle may contact multiple bodies before it is considered a candidate for being "stuck". Setting to zero or less disables.</summary>
* <param name="particleSystemPointer">Pointer to the particle system.</param>
* <param name="iterations">The number of consecutive particle iterations.</param>
**/
#if UNITY_IPHONE && !UNITY_EDITOR
[DllImport ("__Internal")]
#else
[DllImport ("liquidfundll")]
#endif
public static extern void SetStuckThreshold(IntPtr particleSystemPointer, int iterations);
#endregion SetStuckThreshold
#region DestroyParticlesInShape
/**
* <summary>Destroy particles inside a shape. Returns the number of particles destroyed. This function is locked during callbacks. This function immediately destroys particles in the shape, rather than on the next simulation step.</summary>
* <param name="particleSystemPointer">Pointer to the particle system.</param>
* <param name="shapePointer">Pointer to a shape which encloses particles that should be destroyed.</param>
* <param name="shapeX">X position of the shape.</param>
* <param name="shapeY">Y position of the shape.</param>
* <param name="shapeRotation">Angle of the shape in radians.</param>
* <param name="callDestructionListener">Should the world b2DestructionListener be called for each particle destroyed.</param>
**/
#if UNITY_IPHONE && !UNITY_EDITOR
[DllImport ("__Internal")]
#else
[DllImport ("liquidfundll")]
#endif
public static extern int DestroyParticlesInShape(IntPtr particleSystemPointer, IntPtr shapePointer, float shapeX, float shapeY, float shapeRotation, bool callDestructionListener);
#endregion DestroyParticlesInShape
#region GetParticlesInShape
/**
* <summary>Gets the indices of particles inside a shape. Returns an unmarshalled int array of length array[0]. This function is locked during callbacks.</summary>
* <param name="particleSystemPointer">Pointer to the particle system.</param>
* <param name="shapePointer">Pointer to a shape which encloses particles.</param>
* <param name="shapeX">X position of the shape.</param>
* <param name="shapeY">Y position of the shape.</param>
**/
#if UNITY_IPHONE && !UNITY_EDITOR
[DllImport ("__Internal")]
#else
[DllImport ("liquidfundll")]
#endif
public static extern IntPtr GetParticlesInShape(IntPtr worldPtr, IntPtr particleSystemPtr, IntPtr shapePointer, float shapeX, float shapeY, float shapeRotation);
#endregion GetParticlesInShape
#region SetDesctructionByAge
/**
* <summary>Set whether particles in a system will be destroyed after a certain amount of time.</summary>
* <param name="particleSystemPointer">Pointer to the particle system.</param>
* <param name="isSet">Set to true if particles should have lifetimes/destruction.</param>
**/
#if UNITY_IPHONE && !UNITY_EDITOR
[DllImport ("__Internal")]
#else
[DllImport("liquidfundll")]
#endif
public static extern void SetDestructionByAge(IntPtr particleSystemPointer, bool isSet);
#endregion SetDesctructionByAge
#region GetDesctructionByAge
/**
* <summary>Checks whether particle destruction by age is enabled in a particle system. Returns true if it is.</summary>
* <param name="particleSystemPointer">Pointer to the particle system.</param>
**/
#if UNITY_IPHONE && !UNITY_EDITOR
[DllImport ("__Internal")]
#else
[DllImport("liquidfundll")]
#endif
public static extern bool GetDestructionByAge(IntPtr particleSystemPointer);
#endregion GetDesctructionByAge
#region SetAllParticleLifetimes
/**
* <summary>Set the lifetime of all particles in a particle system. Note: SetDestructionByAge must be called to enable destruction.</summary>
* <param name="particleSystemPointer">Pointer to the particle system.</param>
* <param name="lifetime">Time before the particles are destroyed.</param>
**/
#if UNITY_IPHONE && !UNITY_EDITOR
[DllImport ("__Internal")]
#else
[DllImport("liquidfundll")]
#endif
public static extern void SetAllParticleLifetimes(IntPtr particleSystemPointer, float lifetime);
#endregion SetAllParticleLifetimes
#region GetMaxParticleCount
/**
* <summary>Gets the max particle count of a particle system.</summary>
* <param name="particleSystemPointer">Pointer to the particle system.</param>
**/
#if UNITY_IPHONE && !UNITY_EDITOR
[DllImport ("__Internal")]
#else
[DllImport ("liquidfundll")]
#endif
public static extern int GetMaxParticleCount(IntPtr particleSystemPointer);
#endregion GetMaxParticleCount
#region SetMaxParticleCount
/**
* <summary>Sets the max particle count of a particle system..</summary>
* <param name="particleSystemPointer">Pointer to the particle system.</param>
* <param name="maxParticleCount">The new max count.</param>
**/
#if UNITY_IPHONE && !UNITY_EDITOR
[DllImport ("__Internal")]
#else
[DllImport ("liquidfundll")]
#endif
public static extern void SetMaxParticleCount(IntPtr particleSystemPointer, int maxParticleCount);
#endregion SetMaxParticleCount
#region GetParticleSystemContacts
/**
* <summary>Get the particle system contacts. Returns an unmarshalled array of ints, which is of length ((array[0] * 4) + 1). Contains: indexA, indexB, userdata A,userdataB.</summary>
* <param name="particleSystemPointer">Pointer to the particle system.</param>
**/
#if UNITY_IPHONE && !UNITY_EDITOR
[DllImport ("__Internal")]
#else
[DllImport ("liquidfundll")]
#endif
public static extern IntPtr GetParticleSystemContacts(IntPtr particleSystemPointer);
#endregion GetParticleSystemContacts
#region GetParticleSystemBodyContacts
/**
* <summary>Get the particle system body contacts. Returns an unmarshalled array of floats, which is of length ((array[0] * 7) + 1).
* Contains: particle index, particle userdata, bodyUserData, fixtureUserData, normalX, notmalY, contact weight, for each contact.</summary>
* <param name="particleSystemPointer">Pointer to the particle system.</param>
**/
#if UNITY_IPHONE && !UNITY_EDITOR
[DllImport ("__Internal")]
#else
[DllImport ("liquidfundll")]
#endif
public static extern IntPtr GetParticleSystemBodyContacts(IntPtr particleSystemPointer);
#endregion GetParticleSystemBodyContacts
#region GetParticleGroupCount
/**
* <summary>Gets the count of a particle groups in the system.</summary>
* <param name="particleSystemPointer">Pointer to the particle system.</param>
**/
#if UNITY_IPHONE && !UNITY_EDITOR
[DllImport ("__Internal")]
#else
[DllImport("liquidfundll")]
#endif
public static extern Int32 GetParticleGroupCount(IntPtr particleSystemPointer);
#endregion GetParticleGroupCount
#region GetParticleGroupPointers
/**
* <summary>Gets the list of pointers for each group.</summary>
* <param name="particleSystemPointer">Pointer to the particle system.</param>
**/
#if UNITY_IPHONE && !UNITY_EDITOR
[DllImport ("__Internal")]
#else
[DllImport("liquidfundll")]
#endif
public static extern IntPtr GetParticleGroupPointers(IntPtr particleSystemPointer);
#endregion GetParticleGroupPointers
#region GetParticleGroupPointerForLargestGroup
/**
* <summary>Gets the pointer for the largest group.</summary>
* <param name="particleSystemPointer">Pointer to the particle system.</param>
**/
#if UNITY_IPHONE && !UNITY_EDITOR
[DllImport ("__Internal")]
#else
[DllImport("liquidfundll")]
#endif
public static extern IntPtr GetParticleGroupPointerForLargestGroup(IntPtr particleSystemPointer);
#endregion GetParticleGroupPointers
}
| |
using System;
using System.ComponentModel;
using System.Data;
using System.Xml;
using Epi;
using Epi.Data;
using Epi.Data.Services;
namespace Epi.Fields
{
/// <summary>
/// Date Time Field.
/// </summary>
public class DateTimeField : InputTextBoxField
{
#region Private Members
private XmlElement viewElement;
private XmlNode fieldNode;
private BackgroundWorker _updater;
private BackgroundWorker _inserter;
#endregion Private members
#region Constructors
/// <summary>
/// Constructor for the class
/// </summary>
/// <param name="page">The page this field belongs to</param>
public DateTimeField(Page page)
: base(page)
{
construct();
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="view">View</param>
public DateTimeField(View view)
: base(view)
{
construct();
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="page">Page</param>
/// <param name="viewElement">Xml view element</param>
public DateTimeField(Page page, XmlElement viewElement)
: base(page)
{
construct();
this.viewElement = viewElement;
this.Page = page;
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="view">View</param>
/// <param name="fieldNode">Xml field node</param>
public DateTimeField(View view, XmlNode fieldNode)
: base(view)
{
construct();
this.fieldNode = fieldNode;
this.view.Project.Metadata.GetFieldData(this, this.fieldNode);
}
private void construct()
{
genericDbColumnType = GenericDbColumnType.DateTime;
this.dbColumnType = DbType.DateTime;
}
/// <summary>
/// Load from row
/// </summary>
/// <param name="row">Row</param>
public override void LoadFromRow(DataRow row)
{
base.LoadFromRow(row);
}
public DateTimeField Clone()
{
DateTimeField clone = (DateTimeField)this.MemberwiseClone();
base.AssignMembers(clone);
return clone;
}
#endregion Constructors
#region Public Properties
public virtual string Watermark
{
get
{
System.Globalization.DateTimeFormatInfo formatInfo = System.Globalization.DateTimeFormatInfo.CurrentInfo;
return string.Format("{0} {1}", formatInfo.ShortDatePattern.ToUpperInvariant(), formatInfo.LongTimePattern.ToUpperInvariant());
}
set { ;}
}
/// <summary>
/// Returns field type
/// </summary>
public override MetaFieldType FieldType
{
get
{
return MetaFieldType.DateTime;
}
}
/// <summary>
/// The view element of the field
/// </summary>
public XmlElement ViewElement
{
get
{
return viewElement;
}
set
{
viewElement = value;
}
}
/// <summary>
/// Returns a string representation of Current Record Value
/// </summary>
public override string CurrentRecordValueString
{
get
{
if (CurrentRecordValueObject == null || CurrentRecordValueObject.Equals(DBNull.Value))
{
return string.Empty;
}
else
{
if (CurrentRecordValueObject is DateTime)
{
return ((DateTime)CurrentRecordValueObject).ToString();
}
else if (CurrentRecordValueObject is String)
{
DateTime dateTime = new DateTime();
if (DateTime.TryParse((string)CurrentRecordValueObject, out dateTime))
{
CurrentRecordValueObject = dateTime;
return dateTime.ToString();
}
}
}
return string.Empty;
}
set
{
if (!string.IsNullOrEmpty(value))
{
bool result;
DateTime dateTimeEntered;
result = DateTime.TryParse(value, out dateTimeEntered);
if (result)
{
CurrentRecordValueObject = dateTimeEntered;
}
else
{
CurrentRecordValueObject = null;
}
}
else
{
CurrentRecordValueObject = null;
}
}
}
#endregion Public Properties
#region Public Methods
/// <summary>
/// Returns the string value that is reflected my a mirror field.
/// </summary>
/// <returns>reflected value string</returns>
public virtual string GetReflectedValue()
{
return this.CurrentRecordValueObject.ToString();
}
#endregion Public methods
#region Private Methods
/// <summary>
/// Inserts the field to the database
/// </summary>
protected override void InsertField()
{
this.Id = GetMetadata().CreateField(this);
base.OnFieldAdded();
}
/// <summary>
/// Update the field to the database
/// </summary>
protected override void UpdateField()
{
GetMetadata().UpdateField(this);
}
#endregion Protected Methods
#region Event Handlers
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Text;
//
// Visual Basic .NET Parser
//
// Copyright (C) 2005, Microsoft Corporation. All rights reserved.
//
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER
// EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF
// MERCHANTIBILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
//
namespace VBConverter.CodeParser.Trees
{
/// <summary>
/// The root class of all trees.
/// </summary>
public abstract class Tree
{
#region Nested Elements
public class Types
{
public static bool IsCollection(TreeType type)
{
return
type >= TreeType.ArgumentCollection &&
type <= TreeType.DeclarationCollection;
}
public static bool IsFile(TreeType type)
{
return
type == TreeType.FileTree;
}
public static bool IsComment(TreeType type)
{
return
type == TreeType.Comment;
}
public static bool IsName(TreeType type)
{
return
type >= TreeType.SimpleName &&
type <= TreeType.QualifiedName;
}
public static bool IsType(TreeType type)
{
return
type >= TreeType.IntrinsicType &&
type <= TreeType.ArrayType;
}
public static bool IsArgument(TreeType type)
{
return
type == TreeType.Argument;
}
public static bool IsExpression(TreeType type)
{
return
type >= TreeType.SimpleNameExpression &&
type <= TreeType.GetTypeExpression;
}
public static bool IsStatement(TreeType type)
{
return
type >= TreeType.EmptyStatement &&
type <= TreeType.EndBlockStatement;
}
public static bool IsModifier(TreeType type)
{
return
type == TreeType.Modifier;
}
public static bool IsVariableDeclarator(TreeType type)
{
return
type == TreeType.VariableDeclarator;
}
public static bool IsCaseClause(TreeType type)
{
return
type >= TreeType.ComparisonCaseClause &&
type <= TreeType.RangeCaseClause;
}
public static bool IsAttribute(TreeType type)
{
return
type == TreeType.AttributeTree;
}
public static bool IsDeclaration(TreeType type)
{
return
type >= TreeType.EmptyDeclaration &&
type <= TreeType.DelegateFunctionDeclaration;
}
public static bool IsParameter(TreeType type)
{
return
type == TreeType.Parameter;
}
public static bool IsTypeParameter(TreeType type)
{
return
type == TreeType.TypeParameter;
}
public static bool IsImport(TreeType type)
{
return
type >= TreeType.NameImport &&
type <= TreeType.AliasImport;
}
public static bool IsCollection(Tree tree)
{
return tree != null && IsCollection(tree.Type);
}
public static bool IsFile(Tree tree)
{
return tree != null && IsFile(tree.Type);
}
public static bool IsComment(Tree tree)
{
return tree != null && IsComment(tree.Type);
}
public static bool IsName(Tree tree)
{
return tree != null && IsName(tree.Type);
}
public static bool IsType(Tree tree)
{
return tree != null && IsType(tree.Type);
}
public static bool IsArgument(Tree tree)
{
return tree != null && IsArgument(tree.Type);
}
public static bool IsExpression(Tree tree)
{
return tree != null && IsExpression(tree.Type);
}
public static bool IsStatement(Tree tree)
{
return tree != null && IsStatement(tree.Type);
}
public static bool IsModifier(Tree tree)
{
return tree != null && IsModifier(tree.Type);
}
public static bool IsVariableDeclarator(Tree tree)
{
return tree != null && IsVariableDeclarator(tree.Type);
}
public static bool IsCaseClause(Tree tree)
{
return tree != null && IsCaseClause(tree.Type);
}
public static bool IsAttribute(Tree tree)
{
return tree != null && IsAttribute(tree.Type);
}
public static bool IsDeclaration(Tree tree)
{
return tree != null && IsDeclaration(tree.Type);
}
public static bool IsParameter(Tree tree)
{
return tree != null && IsParameter(tree.Type);
}
public static bool IsTypeParameter(Tree tree)
{
return tree != null && IsTypeParameter(tree.Type);
}
public static bool IsImport(Tree tree)
{
return tree != null && IsImport(tree.Type);
}
}
#endregion
#region Fields
private readonly TreeType _Type;
private readonly Span _Span;
private Tree _Parent;
private ReadOnlyCollection<Tree> _Children;
#endregion
#region Properties
/// <summary>
/// The type of the tree.
/// </summary>
public TreeType Type
{
get { return _Type; }
}
/// <summary>
/// The location of the tree.
/// </summary>
/// <remarks>
/// The span ends at the first character beyond the tree
/// </remarks>
public Span Span
{
get { return _Span; }
}
/// <summary>
/// The parent of the tree. Nothing if the root tree.
/// </summary>
public Tree Parent
{
get { return _Parent; }
}
/// <summary>
/// The children of the tree.
/// </summary>
public ReadOnlyCollection<Tree> Children
{
get
{
if (_Children == null)
{
List<Tree> ChildList = new List<Tree>();
GetChildTrees(ChildList);
_Children = new ReadOnlyCollection<Tree>(ChildList);
}
return _Children;
}
}
/// <summary>
/// Whether the tree is 'bad'.
/// </summary>
public virtual bool IsBad
{
get { return false; }
}
#endregion
#region Constructor
protected Tree(TreeType type, Span span)
{
Debug.Assert(type >= TreeType.SyntaxError && type <= TreeType.FileTree);
_Type = type;
_Span = span;
}
#endregion
#region Protected Methods
protected void SetParent(Tree child)
{
if (child != null)
{
child._Parent = this;
}
}
protected void SetParents<T>(IList<T> children) where T : Tree
{
if (children != null)
{
foreach (Tree Child in children) {
SetParent(Child);
}
}
}
#endregion
#region Static Methods
protected static void AddChild(IList<Tree> childList, Tree child)
{
if (child != null)
childList.Add(child);
}
protected static void AddChildren<T>(IList<Tree> childList, ReadOnlyCollection<T> children) where T : Tree
{
if (children != null)
{
foreach (Tree Child in children)
childList.Add(Child);
}
}
protected virtual void GetChildTrees(IList<Tree> childList)
{
// By default, trees have no children
}
#endregion
}
}
| |
// Copyright (c) 2015, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Xml;
using System.Collections.Generic;
using System.Text;
using WebsitePanel.Setup.Common;
namespace WebsitePanel.Setup
{
/// <summary>
/// Variables container.
/// </summary>
public sealed class SetupVariables
{
//
public static readonly SetupVariables Empty = new SetupVariables();
public bool EnableScpaMode { get; set; }
public string PeerAdminPassword { get; set; }
public string DatabaseUser { get; set; }
public string DatabaseUserPassword { get; set; }
public bool NewDatabaseUser { get; set; }
/// <summary>
/// Installation folder
/// </summary>
public string InstallationFolder { get; set; }
public string InstallFolder
{
get { return InstallationFolder; }
set { InstallationFolder = value; }
}
/// <summary>
/// Component id
/// </summary>
public string ComponentId { get; set; }
public string ComponentDescription { get; set; }
/// <summary>
/// Component code
/// </summary>
public string ComponentCode { get; set; }
/// <summary>
/// Component name
/// </summary>
public string ComponentName { get; set; }
/// <summary>
/// Component name
/// </summary>
public string ApplicationName { get; set; }
public string ComponentFullName
{
get { return ApplicationName + " " + ComponentName; }
}
public string Instance { get; set; }
/// <summary>
/// Install currentScenario
/// </summary>
public SetupActions SetupAction { get; set; }
/// <summary>
/// Product key
/// </summary>
public string ProductKey { get; set; }
/// <summary>
/// Release Id
/// </summary>
public int ReleaseId { get; set; }
// Workaround
public string Release
{
get { return Version; }
set { Version = value; }
}
/// <summary>
/// Release name
/// </summary>
public string Version { get; set; }
/// <summary>
/// Connection string
/// </summary>
public string ConnectionString { get; set; }
/// <summary>
/// Database
/// </summary>
public string Database { get; set; }
/// <summary>
/// DatabaseServer
/// </summary>
public string DatabaseServer { get; set; }
/// <summary>
/// Database install connection string
/// </summary>
public string DbInstallConnectionString { get; set; }
public string InstallConnectionString
{
get { return DbInstallConnectionString; }
set { DbInstallConnectionString = value; }
}
/// <summary>
/// Create database
/// </summary>
public bool CreateDatabase { get; set; }
public bool NewVirtualDirectory { get; set; }
public bool NewWebApplicationPool { get; set; }
public string WebApplicationPoolName { get; set; }
public string ApplicationPool
{
get { return WebApplicationPoolName; }
set { WebApplicationPoolName = value; }
}
/// <summary>
/// Virtual directory
/// </summary>
public string VirtualDirectory { get; set; }
public bool NewWebSite { get; set; }
/// <summary>
/// Website Id
/// </summary>
public string WebSiteId { get; set; }
/// <summary>
/// Website IP
/// </summary>
public string WebSiteIP { get; set; }
/// <summary>
/// Website port
/// </summary>
public string WebSitePort { get; set; }
/// <summary>
/// Website domain
/// </summary>
public string WebSiteDomain { get; set; }
/// <summary>
/// User account
/// </summary>
public string UserAccount { get; set; }
/// <summary>
/// User password
/// </summary>
public string UserPassword { get; set; }
/// <summary>
/// User Membership
/// </summary>
public string[] UserMembership
{
get
{
if (ComponentCode.Equals(Global.Server.ComponentCode, StringComparison.OrdinalIgnoreCase))
{
return Global.Server.ServiceUserMembership;
}
else if(ComponentCode.Equals(Global.EntServer.ComponentCode, StringComparison.OrdinalIgnoreCase))
{
return Global.EntServer.ServiceUserMembership;
}
else if (ComponentCode.Equals(Global.WebPortal.ComponentCode, StringComparison.OrdinalIgnoreCase))
{
return Global.WebPortal.ServiceUserMembership;
}
else
{
return new string[] {};
}
}
}
/// <summary>
/// Welcome screen has been skipped
/// </summary>
public bool WelcomeScreenSkipped { get; set; }
public string InstallerFolder { get; set; }
public string Installer { get; set; }
public string InstallerType { get; set; }
public string InstallerPath { get; set; }
public XmlNode ComponentConfig { get; set; }
public string ServerPassword { get; set; }
public string CryptoKey { get; set; }
public bool UpdateWebSite { get; set; }
public bool UpdateServerPassword { get; set; }
public bool UpdateServerAdminPassword { get; set; }
public string ServerAdminPassword { get; set; }
public string BaseDirectory { get; set; }
public string SpecialBaseDirectory { get; set; }
public IDictionary<string, string> FileNameMap { get; set; }
public IDictionary<string, string> SessionVariables { get; set; }
public IDictionary<string, string[]> XmlData { get; set; } // XPath, Value.
public string[] SysFields; // Fields that saved in sys config.
public bool ComponentExists { get; set; }
public string UpdateVersion { get; set; }
public string EnterpriseServerURL { get; set; }
public string UserDomain { get; set; }
public string Domain
{
get { return UserDomain; }
set { UserDomain = value; }
}
public bool NewUserAccount { get; set; }
public bool NewApplicationPool { get; set; }
public ServerItem[] SQLServers { get; set; }
public string Product { get; set; }
public Version IISVersion { get; set; }
public string ServiceIP { get; set; }
public string ServicePort { get; set; }
public string ServiceName { get; set; }
public string ConfigurationFile { get; set; }
private bool m_UseUserCredentials = true;
public bool UseUserCredentials { get { return m_UseUserCredentials; } set { m_UseUserCredentials = value; } }
public string ServiceFile { get; set; }
public string LicenseKey { get; set; }
public string SetupXml { get; set; }
public string RemoteServerUrl
{
get
{
string address = "http://";
string server = String.Empty;
string ipPort = String.Empty;
//server
if (String.IsNullOrEmpty(WebSiteDomain) == false
&& WebSiteDomain.Trim().Length > 0)
{
//domain
server = WebSiteDomain.Trim();
}
else
{
//ip
if (String.IsNullOrEmpty(WebSiteIP) == false
&& WebSiteIP.Trim().Length > 0)
{
server = WebSiteIP.Trim();
}
}
//port
if (server.Length > 0 &&
WebSiteIP.Trim().Length > 0 &&
WebSitePort.Trim() != "80")
{
ipPort = ":" + WebSitePort.Trim();
}
//address string
address += server + ipPort;
//
return address;
}
}
public string RemoteServerPassword { get; set; }
public string ServerComponentId { get; set; }
public string PortalComponentId { get; set; }
public string EnterpriseServerComponentId { get; set; }
public SetupVariables Clone()
{
return (SetupVariables)this.MemberwiseClone();
}
}
}
| |
namespace DeOps.Services.Profile
{
partial class EditProfile
{
/// <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(EditProfile));
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.TemplateCombo = new System.Windows.Forms.ComboBox();
this.FieldsCombo = new System.Windows.Forms.ComboBox();
this.ValueTextBox = new System.Windows.Forms.TextBox();
this.ButtonOK = new System.Windows.Forms.Button();
this.ButtonCancel = new System.Windows.Forms.Button();
this.LinkEdit = new System.Windows.Forms.LinkLabel();
this.LinkBrowse = new System.Windows.Forms.LinkLabel();
this.LinkNew = new System.Windows.Forms.LinkLabel();
this.LinkPreview = new System.Windows.Forms.LinkLabel();
this.SuspendLayout();
//
// label1
//
this.label1.AutoSize = true;
this.label1.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label1.Location = new System.Drawing.Point(12, 18);
this.label1.Name = "label1";
this.label1.Padding = new System.Windows.Forms.Padding(0, 0, 0, 5);
this.label1.Size = new System.Drawing.Size(61, 18);
this.label1.TabIndex = 3;
this.label1.Text = "Template";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label2.Location = new System.Drawing.Point(12, 95);
this.label2.Name = "label2";
this.label2.Padding = new System.Windows.Forms.Padding(0, 0, 0, 5);
this.label2.Size = new System.Drawing.Size(39, 18);
this.label2.TabIndex = 4;
this.label2.Text = "Fields";
//
// TemplateCombo
//
this.TemplateCombo.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.TemplateCombo.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.TemplateCombo.FormattingEnabled = true;
this.TemplateCombo.Location = new System.Drawing.Point(15, 39);
this.TemplateCombo.Name = "TemplateCombo";
this.TemplateCombo.Size = new System.Drawing.Size(227, 21);
this.TemplateCombo.TabIndex = 5;
this.TemplateCombo.SelectedIndexChanged += new System.EventHandler(this.TemplateCombo_SelectedIndexChanged);
//
// FieldsCombo
//
this.FieldsCombo.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.FieldsCombo.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.FieldsCombo.FormattingEnabled = true;
this.FieldsCombo.Location = new System.Drawing.Point(57, 92);
this.FieldsCombo.Name = "FieldsCombo";
this.FieldsCombo.Size = new System.Drawing.Size(124, 21);
this.FieldsCombo.TabIndex = 6;
this.FieldsCombo.SelectedIndexChanged += new System.EventHandler(this.FieldsCombo_SelectedIndexChanged);
//
// ValueTextBox
//
this.ValueTextBox.AcceptsReturn = true;
this.ValueTextBox.AcceptsTab = true;
this.ValueTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.ValueTextBox.BackColor = System.Drawing.Color.White;
this.ValueTextBox.Location = new System.Drawing.Point(15, 116);
this.ValueTextBox.Multiline = true;
this.ValueTextBox.Name = "ValueTextBox";
this.ValueTextBox.ReadOnly = true;
this.ValueTextBox.Size = new System.Drawing.Size(227, 149);
this.ValueTextBox.TabIndex = 7;
this.ValueTextBox.TextChanged += new System.EventHandler(this.ValueTextBox_TextChanged);
//
// ButtonOK
//
this.ButtonOK.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.ButtonOK.Location = new System.Drawing.Point(86, 276);
this.ButtonOK.Name = "ButtonOK";
this.ButtonOK.Size = new System.Drawing.Size(75, 23);
this.ButtonOK.TabIndex = 9;
this.ButtonOK.Text = "OK";
this.ButtonOK.UseVisualStyleBackColor = true;
this.ButtonOK.Click += new System.EventHandler(this.ButtonOK_Click);
//
// ButtonCancel
//
this.ButtonCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.ButtonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.ButtonCancel.Location = new System.Drawing.Point(167, 276);
this.ButtonCancel.Name = "ButtonCancel";
this.ButtonCancel.Size = new System.Drawing.Size(75, 23);
this.ButtonCancel.TabIndex = 8;
this.ButtonCancel.Text = "Cancel";
this.ButtonCancel.UseVisualStyleBackColor = true;
this.ButtonCancel.Click += new System.EventHandler(this.ButtonCancel_Click);
//
// LinkEdit
//
this.LinkEdit.AutoSize = true;
this.LinkEdit.Location = new System.Drawing.Point(168, 18);
this.LinkEdit.Name = "LinkEdit";
this.LinkEdit.Size = new System.Drawing.Size(25, 13);
this.LinkEdit.TabIndex = 10;
this.LinkEdit.TabStop = true;
this.LinkEdit.Text = "Edit";
this.LinkEdit.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.LinkEdit_LinkClicked);
//
// LinkBrowse
//
this.LinkBrowse.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.LinkBrowse.AutoSize = true;
this.LinkBrowse.Enabled = false;
this.LinkBrowse.Location = new System.Drawing.Point(187, 95);
this.LinkBrowse.Name = "LinkBrowse";
this.LinkBrowse.Size = new System.Drawing.Size(51, 13);
this.LinkBrowse.TabIndex = 11;
this.LinkBrowse.TabStop = true;
this.LinkBrowse.Text = "Browse...";
this.LinkBrowse.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.LinkBrowse_LinkClicked);
//
// LinkNew
//
this.LinkNew.AutoSize = true;
this.LinkNew.Location = new System.Drawing.Point(133, 18);
this.LinkNew.Name = "LinkNew";
this.LinkNew.Size = new System.Drawing.Size(29, 13);
this.LinkNew.TabIndex = 12;
this.LinkNew.TabStop = true;
this.LinkNew.Text = "New";
this.LinkNew.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.LinkNew_LinkClicked);
//
// LinkPreview
//
this.LinkPreview.AutoSize = true;
this.LinkPreview.Location = new System.Drawing.Point(199, 18);
this.LinkPreview.Name = "LinkPreview";
this.LinkPreview.Size = new System.Drawing.Size(45, 13);
this.LinkPreview.TabIndex = 13;
this.LinkPreview.TabStop = true;
this.LinkPreview.Text = "Preview";
this.LinkPreview.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.LinkPreview_LinkClicked);
//
// EditProfile
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.CancelButton = this.ButtonCancel;
this.ClientSize = new System.Drawing.Size(254, 311);
this.Controls.Add(this.LinkPreview);
this.Controls.Add(this.LinkNew);
this.Controls.Add(this.LinkBrowse);
this.Controls.Add(this.LinkEdit);
this.Controls.Add(this.ButtonOK);
this.Controls.Add(this.ButtonCancel);
this.Controls.Add(this.ValueTextBox);
this.Controls.Add(this.FieldsCombo);
this.Controls.Add(this.TemplateCombo);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MaximizeBox = false;
this.MinimizeBox = false;
this.MinimumSize = new System.Drawing.Size(200, 219);
this.Name = "EditProfile";
this.ShowInTaskbar = false;
this.Text = "My Profile";
this.Load += new System.EventHandler(this.EditProfile_Load);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
public System.Windows.Forms.ComboBox TemplateCombo;
private System.Windows.Forms.ComboBox FieldsCombo;
private System.Windows.Forms.TextBox ValueTextBox;
private System.Windows.Forms.Button ButtonOK;
private System.Windows.Forms.Button ButtonCancel;
private System.Windows.Forms.LinkLabel LinkEdit;
private System.Windows.Forms.LinkLabel LinkBrowse;
private System.Windows.Forms.LinkLabel LinkNew;
private System.Windows.Forms.LinkLabel LinkPreview;
}
}
| |
//
// System.Web.UI.WebControls.TreeNodeCollection.cs
//
// Authors:
// Lluis Sanchez Gual (lluis@novell.com)
//
// (C) 2004 Novell, Inc (http://www.novell.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.
//
// Copyright (C) 2004 Novell, Inc (http://www.novell.com)
//
#if NET_2_0
using System;
using System.Web.UI;
using System.Collections;
namespace System.Web.UI.WebControls
{
public sealed class TreeNodeCollection: ICollection, IEnumerable, IStateManager
{
TreeNode[] originalItems;
ArrayList items = new ArrayList ();
TreeView tree;
TreeNode parent;
bool marked;
bool dirty;
public TreeNodeCollection ()
{
}
public TreeNodeCollection (TreeNode owner)
{
this.parent = owner;
this.tree = owner.Tree;
}
internal TreeNodeCollection (TreeView tree)
{
this.tree = tree;
}
internal void SetTree (TreeView tree)
{
this.tree = tree;
foreach (TreeNode node in items)
node.Tree = tree;
}
public TreeNode this [int i] {
get { return (TreeNode) items [i]; }
}
public void Add (TreeNode child)
{
child.Index = items.Add (child);
child.Tree = tree;
child.SetParent (parent);
if (marked) {
child.TrackViewState ();
child.SetDirty ();
dirty = true;
}
}
public void AddAt (int index, TreeNode child)
{
items.Insert (index, child);
child.Index = index;
child.Tree = tree;
child.SetParent (parent);
for (int n=index+1; n<items.Count; n++)
((TreeNode)items[n]).Index = n;
if (marked) {
child.TrackViewState ();
child.SetDirty ();
dirty = true;
}
}
public void Clear ()
{
if (tree != null || parent != null) {
foreach (TreeNode nod in items) {
nod.Tree = null;
nod.SetParent (null);
}
}
items.Clear ();
dirty = true;
}
public bool Contains (TreeNode child)
{
return items.Contains (child);
}
public void CopyTo (TreeNode[] nodeArray, int index)
{
items.CopyTo (nodeArray, index);
}
public IEnumerator GetEnumerator ()
{
return items.GetEnumerator ();
}
public int IndexOf (TreeNode node)
{
return items.IndexOf (node);
}
public void Remove (TreeNode node)
{
int i = IndexOf (node);
if (i == -1) return;
items.RemoveAt (i);
if (tree != null)
node.Tree = null;
dirty = true;
}
public void RemoveAt (int index)
{
TreeNode node = (TreeNode) items [index];
items.RemoveAt (index);
if (tree != null)
node.Tree = null;
dirty = true;
}
public int Count {
get { return items.Count; }
}
public bool IsSynchronized {
get { return false; }
}
public object SyncRoot {
get { return items; }
}
void System.Collections.ICollection.CopyTo (Array array, int index)
{
items.CopyTo (array, index);
}
void IStateManager.LoadViewState (object state)
{
if (state == null) return;
object[] its = (object[]) state;
dirty = (bool)its [0];
if (dirty)
items.Clear ();
for (int n=1; n<its.Length; n++) {
Pair pair = (Pair) its [n];
int oi = (int) pair.First;
TreeNode node;
if (oi != -1) node = originalItems [oi];
else node = new TreeNode ();
if (dirty) Add (node);
node.LoadViewState (pair.Second);
}
}
object IStateManager.SaveViewState ()
{
object[] state = null;
bool hasData = false;
if (dirty) {
state = new object [items.Count + 1];
state [0] = true;
for (int n=0; n<items.Count; n++) {
TreeNode node = items[n] as TreeNode;
int oi = Array.IndexOf (originalItems, node);
object ns = node.SaveViewState ();
if (ns != null) hasData = true;
state [n + 1] = new Pair (oi, ns);
}
} else {
ArrayList list = new ArrayList ();
for (int n=0; n<items.Count; n++) {
TreeNode node = items[n] as TreeNode;
object ns = node.SaveViewState ();
if (ns != null) {
hasData = true;
list.Add (new Pair (n, ns));
}
}
if (hasData) {
list.Insert (0, false);
state = list.ToArray ();
}
}
if (hasData)
return state;
else
return null;
}
void IStateManager.TrackViewState ()
{
marked = true;
originalItems = new TreeNode [items.Count];
for (int n=0; n<items.Count; n++) {
originalItems [n] = (TreeNode) items [n];
originalItems [n].TrackViewState ();
}
}
bool IStateManager.IsTrackingViewState {
get { return marked; }
}
}
}
#endif
| |
/*
* Created by SharpDevelop.
* User: Lars Brubaker
* Date: 10/13/2007
* Time: 12:08 PM
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
using Gaming.Game;
using MatterHackers.Agg;
using MatterHackers.VectorMath;
using System;
namespace RockBlaster
{
/// <summary>
/// Description of Entity.
/// </summary>
public abstract class Entity : GameObject
{
#region GameObjectStuff
public Entity()
{
}
public static new GameObject Load(String PathName)
{
return GameObject.Load(PathName);
}
#endregion GameObjectStuff
private static int s_GameHeight;
private static int s_GameWidth;
protected double m_Radius;
protected double m_Damage = 0;
protected double m_MaxDamage = 1;
[GameDataVector2D("Position")]
protected Vector2 m_Position;
protected Vector2 m_Velocity;
public double MaxDamage
{
get
{
return m_MaxDamage;
}
}
public double Damage
{
get
{
return m_Damage;
}
set
{
m_Damage = value;
}
}
public static int GameWidth
{
get
{
return s_GameWidth;
}
set
{
s_GameWidth = value;
}
}
public static int GameHeight
{
get
{
return s_GameHeight;
}
set
{
s_GameHeight = value;
}
}
public Entity(double radius)
{
m_Radius = radius;
m_Velocity = new Vector2(60, 120);
}
public Vector2 Position
{
get
{
return m_Position;
}
set
{
m_Position = value;
}
}
public Vector2 Velocity
{
get
{
return m_Velocity;
}
set
{
m_Velocity = value;
}
}
public double Radius
{
get
{
return m_Radius;
}
}
public virtual void Update(double numSecondsPassed)
{
m_Position += m_Velocity * numSecondsPassed;
if (m_Position.X > GameWidth)
{
m_Position.X -= GameWidth;
}
if (m_Position.X < 0)
{
m_Position.X += GameWidth;
}
if (m_Position.Y > GameHeight)
{
m_Position.Y -= GameHeight;
}
if (m_Position.Y < 0)
{
m_Position.Y += GameHeight;
}
}
public virtual void Draw(Graphics2D destRenderer)
{
DoDraw(destRenderer);
MirrorAsNeeded(destRenderer);
}
protected abstract void DoDraw(Graphics2D destRenderer);
private void MirrorOnY(Graphics2D destRenderer)
{
if (Position.Y < Radius)
{
Vector2 oldPosition = Position;
oldPosition.Y += GameHeight;
Position = oldPosition;
this.DoDraw(destRenderer);
}
else if (Position.Y > GameHeight - Radius)
{
Vector2 oldPosition = Position;
oldPosition.Y -= GameHeight;
Position = oldPosition;
this.DoDraw(destRenderer);
}
}
public virtual double GiveDamage()
{
return 0.0;
}
private void MirrorOnX(Graphics2D destRenderer)
{
if (Position.X < Radius)
{
Vector2 oldPosition = Position;
oldPosition.X += GameWidth;
Position = oldPosition;
DoDraw(destRenderer);
}
else if (Position.X > GameWidth - Radius)
{
Vector2 oldPosition = Position;
oldPosition.X -= GameWidth;
Position = oldPosition;
DoDraw(destRenderer);
}
}
public virtual void TakeDamage(double DamageToTake, Player playerThatDeliveredDamage)
{
Damage = Damage + DamageToTake;
}
public virtual void Destroying()
{
}
public void MirrorAsNeeded(Graphics2D destRenderer)
{
Vector2 oldPosition = Position;
MirrorOnX(destRenderer);
MirrorOnY(destRenderer);
MirrorOnX(destRenderer);
Position = oldPosition;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Diagnostics;
namespace System.IO.Compression
{
//All blocks.TryReadBlock do a check to see if signature is correct. Generic extra field is slightly different
//all of the TryReadBlocks will throw if there are not enough bytes in the stream
internal struct ZipGenericExtraField
{
private const Int32 SizeOfHeader = 4;
private UInt16 _tag;
private UInt16 _size;
private Byte[] _data;
public UInt16 Tag { get { return _tag; } }
//returns size of data, not of the entire block
public UInt16 Size { get { return _size; } }
public Byte[] Data { get { return _data; } }
public void WriteBlock(Stream stream)
{
BinaryWriter writer = new BinaryWriter(stream);
writer.Write(Tag);
writer.Write(Size);
writer.Write(Data);
}
//shouldn't ever read the byte at position endExtraField
//assumes we are positioned at the beginning of an extra field subfield
public static Boolean TryReadBlock(BinaryReader reader, Int64 endExtraField, out ZipGenericExtraField field)
{
field = new ZipGenericExtraField();
//not enough bytes to read tag + size
if (endExtraField - reader.BaseStream.Position < 4)
return false;
field._tag = reader.ReadUInt16();
field._size = reader.ReadUInt16();
//not enough bytes to read the data
if (endExtraField - reader.BaseStream.Position < field._size)
return false;
field._data = reader.ReadBytes(field._size);
return true;
}
//shouldn't ever read the byte at position endExtraField
public static List<ZipGenericExtraField> ParseExtraField(Stream extraFieldData)
{
List<ZipGenericExtraField> extraFields = new List<ZipGenericExtraField>();
using (BinaryReader reader = new BinaryReader(extraFieldData))
{
ZipGenericExtraField field;
while (TryReadBlock(reader, extraFieldData.Length, out field))
{
extraFields.Add(field);
}
}
return extraFields;
}
public static Int32 TotalSize(List<ZipGenericExtraField> fields)
{
Int32 size = 0;
foreach (ZipGenericExtraField field in fields)
size += field.Size + SizeOfHeader; //size is only size of data
return size;
}
public static void WriteAllBlocks(List<ZipGenericExtraField> fields, Stream stream)
{
foreach (ZipGenericExtraField field in fields)
field.WriteBlock(stream);
}
}
internal struct Zip64ExtraField
{
/* Size is size of the record not including the tag or size fields
* If the extra field is going in the local header, it cannot include only
* one of uncompressed/compressed size
* */
public const Int32 OffsetToFirstField = 4;
private const UInt16 TagConstant = 1;
private UInt16 _size;
private Int64? _uncompressedSize;
private Int64? _compressedSize;
private Int64? _localHeaderOffset;
private Int32? _startDiskNumber;
public UInt16 TotalSize
{
get { return (UInt16)(_size + 4); }
}
public Int64? UncompressedSize
{
get { return _uncompressedSize; }
set { _uncompressedSize = value; UpdateSize(); }
}
public Int64? CompressedSize
{
get { return _compressedSize; }
set { _compressedSize = value; UpdateSize(); }
}
public Int64? LocalHeaderOffset
{
get { return _localHeaderOffset; }
set { _localHeaderOffset = value; UpdateSize(); }
}
public Int32? StartDiskNumber
{
get { return _startDiskNumber; }
}
private void UpdateSize()
{
_size = 0;
if (_uncompressedSize != null) _size += 8;
if (_compressedSize != null) _size += 8;
if (_localHeaderOffset != null) _size += 8;
if (_startDiskNumber != null) _size += 4;
}
/* There is a small chance that something very weird could happen here. The code calling into this function
* will ask for a value from the extra field if the field was masked with FF's. It's theoretically possible
* that a field was FF's legitimately, and the writer didn't decide to write the corresponding extra field.
* Also, at the same time, other fields were masked with FF's to indicate looking in the zip64 record.
* Then, the search for the zip64 record will fail because the expected size is wrong,
* and a nulled out Zip64ExtraField will be returned. Thus, even though there was Zip64 data,
* it will not be used. It is questionable whether this situation is possible to detect
*/
/* unlike the other functions that have try-pattern semantics, these functions always return a
* Zip64ExtraField. If a Zip64 extra field actually doesn't exist, all of the fields in the
* returned struct will be null
*
* If there are more than one Zip64 extra fields, we take the first one that has the expected size
*/
public static Zip64ExtraField GetJustZip64Block(Stream extraFieldStream,
Boolean readUncompressedSize, Boolean readCompressedSize,
Boolean readLocalHeaderOffset, Boolean readStartDiskNumber)
{
Zip64ExtraField zip64Field;
using (BinaryReader reader = new BinaryReader(extraFieldStream))
{
ZipGenericExtraField currentExtraField;
while (ZipGenericExtraField.TryReadBlock(reader, extraFieldStream.Length, out currentExtraField))
{
if (TryGetZip64BlockFromGenericExtraField(currentExtraField, readUncompressedSize,
readCompressedSize, readLocalHeaderOffset, readStartDiskNumber, out zip64Field))
{
return zip64Field;
}
}
}
zip64Field = new Zip64ExtraField();
zip64Field._compressedSize = null;
zip64Field._uncompressedSize = null;
zip64Field._localHeaderOffset = null;
zip64Field._startDiskNumber = null;
return zip64Field;
}
private static Boolean TryGetZip64BlockFromGenericExtraField(ZipGenericExtraField extraField,
Boolean readUncompressedSize, Boolean readCompressedSize,
Boolean readLocalHeaderOffset, Boolean readStartDiskNumber,
out Zip64ExtraField zip64Block)
{
zip64Block = new Zip64ExtraField();
zip64Block._compressedSize = null;
zip64Block._uncompressedSize = null;
zip64Block._localHeaderOffset = null;
zip64Block._startDiskNumber = null;
if (extraField.Tag != TagConstant)
return false;
//this pattern needed because nested using blocks trigger CA2202
MemoryStream ms = null;
try
{
ms = new MemoryStream(extraField.Data);
using (BinaryReader reader = new BinaryReader(ms))
{
ms = null;
zip64Block._size = extraField.Size;
UInt16 expectedSize = 0;
if (readUncompressedSize) expectedSize += 8;
if (readCompressedSize) expectedSize += 8;
if (readLocalHeaderOffset) expectedSize += 8;
if (readStartDiskNumber) expectedSize += 4;
//if it is not the expected size, perhaps there is another extra field that matches
if (expectedSize != zip64Block._size)
return false;
if (readUncompressedSize) zip64Block._uncompressedSize = reader.ReadInt64();
if (readCompressedSize) zip64Block._compressedSize = reader.ReadInt64();
if (readLocalHeaderOffset) zip64Block._localHeaderOffset = reader.ReadInt64();
if (readStartDiskNumber) zip64Block._startDiskNumber = reader.ReadInt32();
//original values are unsigned, so implies value is too big to fit in signed integer
if (zip64Block._uncompressedSize < 0) throw new InvalidDataException(SR.FieldTooBigUncompressedSize);
if (zip64Block._compressedSize < 0) throw new InvalidDataException(SR.FieldTooBigCompressedSize);
if (zip64Block._localHeaderOffset < 0) throw new InvalidDataException(SR.FieldTooBigLocalHeaderOffset);
if (zip64Block._startDiskNumber < 0) throw new InvalidDataException(SR.FieldTooBigStartDiskNumber);
return true;
}
}
finally
{
if (ms != null)
ms.Dispose();
}
}
public static Zip64ExtraField GetAndRemoveZip64Block(List<ZipGenericExtraField> extraFields,
Boolean readUncompressedSize, Boolean readCompressedSize,
Boolean readLocalHeaderOffset, Boolean readStartDiskNumber)
{
Zip64ExtraField zip64Field = new Zip64ExtraField();
zip64Field._compressedSize = null;
zip64Field._uncompressedSize = null;
zip64Field._localHeaderOffset = null;
zip64Field._startDiskNumber = null;
List<ZipGenericExtraField> markedForDelete = new List<ZipGenericExtraField>();
Boolean zip64FieldFound = false;
foreach (ZipGenericExtraField ef in extraFields)
{
if (ef.Tag == TagConstant)
{
markedForDelete.Add(ef);
if (!zip64FieldFound)
{
if (TryGetZip64BlockFromGenericExtraField(ef, readUncompressedSize, readCompressedSize,
readLocalHeaderOffset, readStartDiskNumber, out zip64Field))
{
zip64FieldFound = true;
}
}
}
}
foreach (ZipGenericExtraField ef in markedForDelete)
extraFields.Remove(ef);
return zip64Field;
}
public static void RemoveZip64Blocks(List<ZipGenericExtraField> extraFields)
{
List<ZipGenericExtraField> markedForDelete = new List<ZipGenericExtraField>();
foreach (ZipGenericExtraField field in extraFields)
if (field.Tag == TagConstant)
markedForDelete.Add(field);
foreach (ZipGenericExtraField field in markedForDelete)
extraFields.Remove(field);
}
public void WriteBlock(Stream stream)
{
BinaryWriter writer = new BinaryWriter(stream);
writer.Write(TagConstant);
writer.Write(_size);
if (_uncompressedSize != null) writer.Write(_uncompressedSize.Value);
if (_compressedSize != null) writer.Write(_compressedSize.Value);
if (_localHeaderOffset != null) writer.Write(_localHeaderOffset.Value);
if (_startDiskNumber != null) writer.Write(_startDiskNumber.Value);
}
}
internal struct Zip64EndOfCentralDirectoryLocator
{
public const UInt32 SignatureConstant = 0x07064B50;
public const Int32 SizeOfBlockWithoutSignature = 16;
public UInt32 NumberOfDiskWithZip64EOCD;
public UInt64 OffsetOfZip64EOCD;
public UInt32 TotalNumberOfDisks;
public static Boolean TryReadBlock(BinaryReader reader, out Zip64EndOfCentralDirectoryLocator zip64EOCDLocator)
{
zip64EOCDLocator = new Zip64EndOfCentralDirectoryLocator();
if (reader.ReadUInt32() != SignatureConstant)
return false;
zip64EOCDLocator.NumberOfDiskWithZip64EOCD = reader.ReadUInt32();
zip64EOCDLocator.OffsetOfZip64EOCD = reader.ReadUInt64();
zip64EOCDLocator.TotalNumberOfDisks = reader.ReadUInt32();
return true;
}
public static void WriteBlock(Stream stream, Int64 zip64EOCDRecordStart)
{
BinaryWriter writer = new BinaryWriter(stream);
writer.Write(SignatureConstant);
writer.Write((UInt32)0); //number of disk with start of zip64 eocd
writer.Write(zip64EOCDRecordStart);
writer.Write((UInt32)1); //total number of disks
}
}
internal struct Zip64EndOfCentralDirectoryRecord
{
private const UInt32 SignatureConstant = 0x06064B50;
private const UInt64 NormalSize = 0x2C; //the size of the data excluding the size/signature fields if no extra data included
public UInt64 SizeOfThisRecord;
public UInt16 VersionMadeBy;
public UInt16 VersionNeededToExtract;
public UInt32 NumberOfThisDisk;
public UInt32 NumberOfDiskWithStartOfCD;
public UInt64 NumberOfEntriesOnThisDisk;
public UInt64 NumberOfEntriesTotal;
public UInt64 SizeOfCentralDirectory;
public UInt64 OffsetOfCentralDirectory;
public static Boolean TryReadBlock(BinaryReader reader, out Zip64EndOfCentralDirectoryRecord zip64EOCDRecord)
{
zip64EOCDRecord = new Zip64EndOfCentralDirectoryRecord();
if (reader.ReadUInt32() != SignatureConstant)
return false;
zip64EOCDRecord.SizeOfThisRecord = reader.ReadUInt64();
zip64EOCDRecord.VersionMadeBy = reader.ReadUInt16();
zip64EOCDRecord.VersionNeededToExtract = reader.ReadUInt16();
zip64EOCDRecord.NumberOfThisDisk = reader.ReadUInt32();
zip64EOCDRecord.NumberOfDiskWithStartOfCD = reader.ReadUInt32();
zip64EOCDRecord.NumberOfEntriesOnThisDisk = reader.ReadUInt64();
zip64EOCDRecord.NumberOfEntriesTotal = reader.ReadUInt64();
zip64EOCDRecord.SizeOfCentralDirectory = reader.ReadUInt64();
zip64EOCDRecord.OffsetOfCentralDirectory = reader.ReadUInt64();
return true;
}
public static void WriteBlock(Stream stream, Int64 numberOfEntries, Int64 startOfCentralDirectory, Int64 sizeOfCentralDirectory)
{
BinaryWriter writer = new BinaryWriter(stream);
//write Zip 64 EOCD record
writer.Write(SignatureConstant);
writer.Write(NormalSize);
writer.Write((UInt16)ZipVersionNeededValues.Zip64); //version needed is 45 for zip 64 support
writer.Write((UInt16)ZipVersionNeededValues.Zip64); //version made by: high byte is 0 for MS DOS, low byte is version needed
writer.Write((UInt32)0); //number of this disk is 0
writer.Write((UInt32)0); //number of disk with start of central directory is 0
writer.Write(numberOfEntries); //number of entries on this disk
writer.Write(numberOfEntries); //number of entries total
writer.Write(sizeOfCentralDirectory);
writer.Write(startOfCentralDirectory);
}
}
internal struct ZipLocalFileHeader
{
public const UInt32 DataDescriptorSignature = 0x08074B50;
public const UInt32 SignatureConstant = 0x04034B50;
public const Int32 OffsetToCrcFromHeaderStart = 14;
public const Int32 OffsetToBitFlagFromHeaderStart = 6;
public const Int32 SizeOfLocalHeader = 30;
static public List<ZipGenericExtraField> GetExtraFields(BinaryReader reader)
{
//assumes that TrySkipBlock has already been called, so we don't have to validate twice
List<ZipGenericExtraField> result;
const Int32 OffsetToFilenameLength = 26; //from the point before the signature
reader.BaseStream.Seek(OffsetToFilenameLength, SeekOrigin.Current);
UInt16 filenameLength = reader.ReadUInt16();
UInt16 extraFieldLength = reader.ReadUInt16();
reader.BaseStream.Seek(filenameLength, SeekOrigin.Current);
using (Stream str = new SubReadStream(reader.BaseStream, reader.BaseStream.Position, extraFieldLength))
{
result = ZipGenericExtraField.ParseExtraField(str);
}
Zip64ExtraField.RemoveZip64Blocks(result);
return result;
}
//will not throw end of stream exception
static public Boolean TrySkipBlock(BinaryReader reader)
{
const Int32 OffsetToFilenameLength = 22; //from the point after the signature
if (reader.ReadUInt32() != SignatureConstant)
return false;
if (reader.BaseStream.Length < reader.BaseStream.Position + OffsetToFilenameLength)
return false;
reader.BaseStream.Seek(OffsetToFilenameLength, SeekOrigin.Current);
UInt16 filenameLength = reader.ReadUInt16();
UInt16 extraFieldLength = reader.ReadUInt16();
if (reader.BaseStream.Length < reader.BaseStream.Position + filenameLength + extraFieldLength)
return false;
reader.BaseStream.Seek(filenameLength + extraFieldLength, SeekOrigin.Current);
return true;
}
}
internal struct ZipCentralDirectoryFileHeader
{
public const UInt32 SignatureConstant = 0x02014B50;
public UInt16 VersionMadeBy;
public UInt16 VersionNeededToExtract;
public UInt16 GeneralPurposeBitFlag;
public UInt16 CompressionMethod;
public UInt32 LastModified; //convert this on the fly
public UInt32 Crc32;
public Int64 CompressedSize;
public Int64 UncompressedSize;
public UInt16 FilenameLength;
public UInt16 ExtraFieldLength;
public UInt16 FileCommentLength;
public Int32 DiskNumberStart;
public UInt16 InternalFileAttributes;
public UInt32 ExternalFileAttributes;
public Int64 RelativeOffsetOfLocalHeader;
public Byte[] Filename;
public Byte[] FileComment;
public List<ZipGenericExtraField> ExtraFields;
//if saveExtraFieldsAndComments is false, FileComment and ExtraFields will be null
//in either case, the zip64 extra field info will be incorporated into other fields
static public Boolean TryReadBlock(BinaryReader reader, Boolean saveExtraFieldsAndComments, out ZipCentralDirectoryFileHeader header)
{
header = new ZipCentralDirectoryFileHeader();
if (reader.ReadUInt32() != SignatureConstant)
return false;
header.VersionMadeBy = reader.ReadUInt16();
header.VersionNeededToExtract = reader.ReadUInt16();
header.GeneralPurposeBitFlag = reader.ReadUInt16();
header.CompressionMethod = reader.ReadUInt16();
header.LastModified = reader.ReadUInt32();
header.Crc32 = reader.ReadUInt32();
UInt32 compressedSizeSmall = reader.ReadUInt32();
UInt32 uncompressedSizeSmall = reader.ReadUInt32();
header.FilenameLength = reader.ReadUInt16();
header.ExtraFieldLength = reader.ReadUInt16();
header.FileCommentLength = reader.ReadUInt16();
UInt16 diskNumberStartSmall = reader.ReadUInt16();
header.InternalFileAttributes = reader.ReadUInt16();
header.ExternalFileAttributes = reader.ReadUInt32();
UInt32 relativeOffsetOfLocalHeaderSmall = reader.ReadUInt32();
header.Filename = reader.ReadBytes(header.FilenameLength);
Boolean uncompressedSizeInZip64 = uncompressedSizeSmall == ZipHelper.Mask32Bit;
Boolean compressedSizeInZip64 = compressedSizeSmall == ZipHelper.Mask32Bit;
Boolean relativeOffsetInZip64 = relativeOffsetOfLocalHeaderSmall == ZipHelper.Mask32Bit;
Boolean diskNumberStartInZip64 = diskNumberStartSmall == ZipHelper.Mask16Bit;
Zip64ExtraField zip64;
long endExtraFields = reader.BaseStream.Position + header.ExtraFieldLength;
using (Stream str = new SubReadStream(reader.BaseStream, reader.BaseStream.Position, header.ExtraFieldLength))
{
if (saveExtraFieldsAndComments)
{
header.ExtraFields = ZipGenericExtraField.ParseExtraField(str);
zip64 = Zip64ExtraField.GetAndRemoveZip64Block(header.ExtraFields,
uncompressedSizeInZip64, compressedSizeInZip64,
relativeOffsetInZip64, diskNumberStartInZip64);
}
else
{
header.ExtraFields = null;
zip64 = Zip64ExtraField.GetJustZip64Block(str,
uncompressedSizeInZip64, compressedSizeInZip64,
relativeOffsetInZip64, diskNumberStartInZip64);
}
}
// There are zip files that have malformed ExtraField blocks in which GetJustZip64Block() silently bails out without reading all the way to the end
// of the ExtraField block. Thus we must force the stream's position to the proper place.
reader.BaseStream.AdvanceToPosition(endExtraFields);
if (saveExtraFieldsAndComments)
header.FileComment = reader.ReadBytes(header.FileCommentLength);
else
{
reader.BaseStream.Position += header.FileCommentLength;
header.FileComment = null;
}
header.UncompressedSize = zip64.UncompressedSize == null
? uncompressedSizeSmall
: zip64.UncompressedSize.Value;
header.CompressedSize = zip64.CompressedSize == null
? compressedSizeSmall
: zip64.CompressedSize.Value;
header.RelativeOffsetOfLocalHeader = zip64.LocalHeaderOffset == null
? relativeOffsetOfLocalHeaderSmall
: zip64.LocalHeaderOffset.Value;
header.DiskNumberStart = zip64.StartDiskNumber == null
? diskNumberStartSmall
: zip64.StartDiskNumber.Value;
return true;
}
}
internal struct ZipEndOfCentralDirectoryBlock
{
public const UInt32 SignatureConstant = 0x06054B50;
public const Int32 SizeOfBlockWithoutSignature = 18;
public UInt32 Signature;
public UInt16 NumberOfThisDisk;
public UInt16 NumberOfTheDiskWithTheStartOfTheCentralDirectory;
public UInt16 NumberOfEntriesInTheCentralDirectoryOnThisDisk;
public UInt16 NumberOfEntriesInTheCentralDirectory;
public UInt32 SizeOfCentralDirectory;
public UInt32 OffsetOfStartOfCentralDirectoryWithRespectToTheStartingDiskNumber;
public Byte[] ArchiveComment;
public static void WriteBlock(Stream stream, Int64 numberOfEntries, Int64 startOfCentralDirectory, Int64 sizeOfCentralDirectory, Byte[] archiveComment)
{
BinaryWriter writer = new BinaryWriter(stream);
UInt16 numberOfEntriesTruncated = numberOfEntries > UInt16.MaxValue ?
ZipHelper.Mask16Bit : (UInt16)numberOfEntries;
UInt32 startOfCentralDirectoryTruncated = startOfCentralDirectory > UInt32.MaxValue ?
ZipHelper.Mask32Bit : (UInt32)startOfCentralDirectory;
UInt32 sizeOfCentralDirectoryTruncated = sizeOfCentralDirectory > UInt32.MaxValue ?
ZipHelper.Mask32Bit : (UInt32)sizeOfCentralDirectory;
writer.Write(SignatureConstant);
writer.Write((UInt16)0); //number of this disk
writer.Write((UInt16)0); //number of disk with start of CD
writer.Write(numberOfEntriesTruncated); //number of entries on this disk's cd
writer.Write(numberOfEntriesTruncated); //number of entries in entire CD
writer.Write(sizeOfCentralDirectoryTruncated);
writer.Write(startOfCentralDirectoryTruncated);
//Should be valid because of how we read archiveComment in TryReadBlock:
Debug.Assert((archiveComment == null) || (archiveComment.Length < UInt16.MaxValue));
writer.Write(archiveComment != null ? (UInt16)archiveComment.Length : (UInt16)0); //zip file comment length
if (archiveComment != null)
writer.Write(archiveComment);
}
public static Boolean TryReadBlock(BinaryReader reader, out ZipEndOfCentralDirectoryBlock eocdBlock)
{
eocdBlock = new ZipEndOfCentralDirectoryBlock();
if (reader.ReadUInt32() != SignatureConstant)
return false;
eocdBlock.Signature = SignatureConstant;
eocdBlock.NumberOfThisDisk = reader.ReadUInt16();
eocdBlock.NumberOfTheDiskWithTheStartOfTheCentralDirectory = reader.ReadUInt16();
eocdBlock.NumberOfEntriesInTheCentralDirectoryOnThisDisk = reader.ReadUInt16();
eocdBlock.NumberOfEntriesInTheCentralDirectory = reader.ReadUInt16();
eocdBlock.SizeOfCentralDirectory = reader.ReadUInt32();
eocdBlock.OffsetOfStartOfCentralDirectoryWithRespectToTheStartingDiskNumber = reader.ReadUInt32();
UInt16 commentLength = reader.ReadUInt16();
eocdBlock.ArchiveComment = reader.ReadBytes(commentLength);
return true;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
namespace RobotSlayer
{
/// <summary>
/// This is the main type for your game
/// </summary>
public class Game1 : Microsoft.Xna.Framework.Game
{
public static PlayerActor player = new PlayerActor();
HoverbotActor hover = new HoverbotActor();
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
public static Texture2D texSprites;
Texture2D texBackground;
public static SpriteFont font;
public static GameState GameState = GameState.SplashScreen;
public double TankSpawnFrequency = 15;
public double HoverSpawnFrequency = 5;
public double SecondsSinceTankSpawn = 999;
public double SecondsSinceHoverSpawn = 999;
public static Song theSong;
public static SoundEffect sfxHoverbotCreated;
public static SoundEffect sfxTankbotCreated;
public static SoundEffect sfxRocketLaunch;
public static SoundEffect sfxRocketImpact;
public static SoundEffect sfxRobotImpact; // (bot hits player)
public static SoundEffect sfxPowerup;
public static SoundEffect sfxStartButton;
public static SoundEffect sfxPlayerJump;
public static SoundEffect sfxPlayerDeath;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}
protected void InitGameData()
{
player.Location = new Vector2(360, Actor.BASE_Y);
player.Velocity = Vector2.Zero;
player.AnimationRectangles = PlayerActor.rectWalkSprites;
player.Tint = Color.Yellow;
player.AnimationDuration = 0.05;
player.CollisionRectangle = player.AnimationRectangles[0];
player.CollisionRectangleInflate = -12;
player.Health = 3;
player.GearCount = 0;
RobotActors.Clear();
//CreateHoverbot(650);
//CreateHoverbot(600);
//CreateHoverbot(550);
//CreateHoverbot(500);
//CreateHoverbot(450);
//CreateTankbot(700);
//CreateHoverbot(-114);
//CreateHoverbot(-214);
//CreateHoverbot(-264);
//CreateHoverbot(-164);
//CreateHoverbot(-64);
//CreateTankbot(-90);
player.Texture = texSprites;
}
protected override void Initialize()
{
base.Initialize();
}
public void CreateHoverbot(int x)
{
var hover = new HoverbotActor();
hover.Location = new Vector2(x, Actor.BASE_Y);
hover.Velocity = new Vector2(-1, 0);
if (x < player.Location.X)
{
hover.Velocity.X = 1.0f;
}
hover.AnimationRectangles =
new Rectangle[] { new Rectangle(192, 768, 64, 128) };
hover.Tint = Color.CornflowerBlue;
hover.AnimationDuration = 90.0;
hover.CollisionRectangle = hover.AnimationRectangles[0];
hover.CollisionRectangleInflate = -20;
hover.Texture = texSprites;
RobotActors.Add(hover);
sfxHoverbotCreated.Play();
}
public void CreateTankbot(int x)
{
var tank = new TankbotActor();
tank.Location = new Vector2(x, Actor.BASE_Y + 30);
tank.Velocity = new Vector2(-0.75f, 0.0f);
if (x < player.Location.X)
{
tank.Velocity.X = 0.75f;
}
tank.AnimationRectangles =
new Rectangle[] { new Rectangle(192, 926, 64, 98) };
tank.Tint = Color.Salmon;
tank.AnimationDuration = 90.0;
tank.CollisionRectangle = tank.AnimationRectangles[0];
tank.CollisionRectangleInflate = -2;
tank.Texture = texSprites;
tank.Health = 2;
RobotActors.Add(tank);
sfxTankbotCreated.Play();
}
public static List<Actor> RobotActors = new List<Actor>();
protected static void InitializePowerUp(PowerUpActor powerup, int x)
{
powerup.Location.X = x;
powerup.Location.Y = Actor.BASE_Y + 30;
powerup.AnimationDuration = 90.0;
powerup.CollisionRectangle = powerup.AnimationRectangles[0];
powerup.CollisionRectangleInflate = -2;
powerup.Texture = texSprites;
RobotActors.Add(powerup);
}
public static void CreateHeartPowerup(int x)
{
var powerup = new HeartActor();
powerup.AnimationRectangles =
new Rectangle[] { new Rectangle(384, 640, 64, 64) };
powerup.Tint = Color.Red;
InitializePowerUp(powerup, x);
}
public static void CreateGearPowerup(int x)
{
var powerup = new GearActor();
powerup.AnimationRectangles =
new Rectangle[] { new Rectangle(448, 640, 64, 64) };
powerup.Tint = Color.Gold;
InitializePowerUp(powerup, x);
}
public static void CreateMisslePowerup(int x)
{
var powerup = new MissleActor();
powerup.AnimationRectangles =
new Rectangle[] { new Rectangle(256, 640, 64, 64) };
powerup.Tint = Color.White;
powerup.Velocity.X = -3.0f;
if (x < player.Location.X)
{
powerup.Velocity.X = 3.0f;
}
InitializePowerUp(powerup, x);
sfxRocketLaunch.Play();
}
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
// TODO: use this.Content to load your game content here
texSprites = Content.Load<Texture2D>("Sprites");
texBackground = Content.Load<Texture2D>("Background");
font = Content.Load<SpriteFont>("SpriteFont1");
player.Texture = texSprites;
foreach (Actor actor in RobotActors)
{
actor.Texture = texSprites;
}
theSong = Content.Load<Song>(@"sound/music/Title");
MediaPlayer.IsRepeating = true;
MediaPlayer.Play(theSong);
sfxHoverbotCreated = Content.Load<SoundEffect>(@"sound/hoverbot-spawn");
sfxTankbotCreated = Content.Load<SoundEffect>(@"sound/tankbot-spawn");
sfxRocketLaunch = Content.Load<SoundEffect>(@"sound/rocket-launch");
sfxRocketImpact = Content.Load<SoundEffect>(@"sound/rocket-impact");
sfxRobotImpact = Content.Load<SoundEffect>(@"sound/robot-impact"); // (bot hits player)
sfxPowerup = Content.Load<SoundEffect>(@"sound/powerup-pickup");
sfxStartButton = Content.Load<SoundEffect>(@"sound/start-button");
sfxPlayerJump = Content.Load<SoundEffect>(@"sound/player-jump");
sfxPlayerDeath = Content.Load<SoundEffect>(@"sound/player-death");
}
Rectangle[] rectBackgrounds =
{
new Rectangle(512, 0, 256, 512),
new Rectangle(256, 512, 256, 512),
new Rectangle(256, 0, 256, 512),
new Rectangle( 0, 512, 256, 512),
new Rectangle( 0, 0, 256, 512),
};
/// <summary>
/// UnloadContent will be called once per game and is the place to unload
/// all content.
/// </summary>
protected override void UnloadContent()
{
// TODO: Unload any non ContentManager content here
}
/// <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)
{
// Allows the game to exit
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();
if (GameState == RobotSlayer.GameState.Initializing)
{
InitGameData();
GameState = RobotSlayer.GameState.Playing;
MediaPlayer.Stop();
theSong = Content.Load<Song>(@"sound/music/Playing");
MediaPlayer.IsRepeating = true;
MediaPlayer.Play(theSong);
}
else if (GameState == RobotSlayer.GameState.SplashScreen)
{
TitleScreen.Update(gameTime);
if (GamePad.GetState(PlayerIndex.One).Buttons.Start == ButtonState.Pressed)
{
GameState = RobotSlayer.GameState.Initializing;
sfxStartButton.Play();
}
}
else if (GameState == RobotSlayer.GameState.GameOver)
{
GamePad.SetVibration(PlayerIndex.One, 0, 0);
GameOverScreen.Update(gameTime);
if (GamePad.GetState(PlayerIndex.One).Buttons.Start == ButtonState.Pressed)
{
GameState = RobotSlayer.GameState.Initializing;
sfxStartButton.Play();
}
if (GameOverScreen.PlayMusic)
{
GameOverScreen.PlayMusic = false;
MediaPlayer.Stop();
theSong = Content.Load<Song>(@"sound/music/GameOver");
MediaPlayer.IsRepeating = true;
MediaPlayer.Play(theSong);
}
}
if (GameState == RobotSlayer.GameState.Playing)
{
player.Update(gameTime);
SecondsSinceTankSpawn += gameTime.ElapsedGameTime.TotalSeconds;
SecondsSinceHoverSpawn += gameTime.ElapsedGameTime.TotalSeconds;
if (SecondsSinceTankSpawn > TankSpawnFrequency)
{
double deltaX = HoverbotActor.rand.NextDouble() * 200;
CreateTankbot(-64 - (int)deltaX);
deltaX = HoverbotActor.rand.NextDouble() * 200;
CreateTankbot(800 + (int)deltaX);
SecondsSinceTankSpawn = 0;
}
if (SecondsSinceHoverSpawn > HoverSpawnFrequency)
{
double deltaX = HoverbotActor.rand.NextDouble() * 200;
CreateHoverbot(-64 - (int)deltaX);
deltaX = HoverbotActor.rand.NextDouble() * 200;
CreateHoverbot(800 + (int)deltaX);
SecondsSinceHoverSpawn = 0;
}
for (int i = 0; i < RobotActors.Count; i++)
{
if (!RobotActors[i].IsDead)
{
RobotActors[i].Update(gameTime);
}
}
if (player.IsTouching)
{
Actor.DebugTint = Actor.DebugTintTouching;
GamePad.SetVibration(player.PlayerIndex, 1.0f, 1.0f);
}
else
{
Actor.DebugTint = Actor.DebugTintNotTouching;
GamePad.SetVibration(player.PlayerIndex, 0.0f, 0.0f);
}
}
base.Update(gameTime);
}
float backgroundStart = 0.0f;
int backgroundIndex = 0;
/// <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)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
// TODO: Add your drawing code here
spriteBatch.Begin();
if (GameState == RobotSlayer.GameState.Initializing)
{
}
else if (GameState == RobotSlayer.GameState.SplashScreen)
{
TitleScreen.Draw(gameTime, texSprites, spriteBatch);
}
else if (GameState == RobotSlayer.GameState.GameOver)
{
GameOverScreen.Draw(gameTime, texSprites, spriteBatch);
}
else if (GameState == RobotSlayer.GameState.Playing)
{
for (int i = 0; i < 4; i++)
{
float x = backgroundStart + i * 256;
spriteBatch.Draw(
texBackground,
new Vector2(x, -32),
rectBackgrounds[(backgroundIndex + i) % rectBackgrounds.Length],
Color.White);
}
player.Draw(gameTime, spriteBatch);
for (int i = 0; i < RobotActors.Count; i++)
{
if (!RobotActors[i].IsDead)
{
RobotActors[i].Draw(gameTime, spriteBatch);
}
}
}
spriteBatch.End();
base.Draw(gameTime);
}
}
}
| |
/// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
/// <summary>
/// LocalResource
/// </summary>
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using Twilio.Base;
using Twilio.Clients;
using Twilio.Converters;
using Twilio.Exceptions;
using Twilio.Http;
using Twilio.Types;
namespace Twilio.Rest.Api.V2010.Account.IncomingPhoneNumber
{
public class LocalResource : Resource
{
public sealed class AddressRequirementEnum : StringEnum
{
private AddressRequirementEnum(string value) : base(value) {}
public AddressRequirementEnum() {}
public static implicit operator AddressRequirementEnum(string value)
{
return new AddressRequirementEnum(value);
}
public static readonly AddressRequirementEnum None = new AddressRequirementEnum("none");
public static readonly AddressRequirementEnum Any = new AddressRequirementEnum("any");
public static readonly AddressRequirementEnum Local = new AddressRequirementEnum("local");
public static readonly AddressRequirementEnum Foreign = new AddressRequirementEnum("foreign");
}
public sealed class EmergencyStatusEnum : StringEnum
{
private EmergencyStatusEnum(string value) : base(value) {}
public EmergencyStatusEnum() {}
public static implicit operator EmergencyStatusEnum(string value)
{
return new EmergencyStatusEnum(value);
}
public static readonly EmergencyStatusEnum Active = new EmergencyStatusEnum("Active");
public static readonly EmergencyStatusEnum Inactive = new EmergencyStatusEnum("Inactive");
}
public sealed class EmergencyAddressStatusEnum : StringEnum
{
private EmergencyAddressStatusEnum(string value) : base(value) {}
public EmergencyAddressStatusEnum() {}
public static implicit operator EmergencyAddressStatusEnum(string value)
{
return new EmergencyAddressStatusEnum(value);
}
public static readonly EmergencyAddressStatusEnum Registered = new EmergencyAddressStatusEnum("registered");
public static readonly EmergencyAddressStatusEnum Unregistered = new EmergencyAddressStatusEnum("unregistered");
public static readonly EmergencyAddressStatusEnum PendingRegistration = new EmergencyAddressStatusEnum("pending-registration");
public static readonly EmergencyAddressStatusEnum RegistrationFailure = new EmergencyAddressStatusEnum("registration-failure");
public static readonly EmergencyAddressStatusEnum PendingUnregistration = new EmergencyAddressStatusEnum("pending-unregistration");
public static readonly EmergencyAddressStatusEnum UnregistrationFailure = new EmergencyAddressStatusEnum("unregistration-failure");
}
public sealed class VoiceReceiveModeEnum : StringEnum
{
private VoiceReceiveModeEnum(string value) : base(value) {}
public VoiceReceiveModeEnum() {}
public static implicit operator VoiceReceiveModeEnum(string value)
{
return new VoiceReceiveModeEnum(value);
}
public static readonly VoiceReceiveModeEnum Voice = new VoiceReceiveModeEnum("voice");
public static readonly VoiceReceiveModeEnum Fax = new VoiceReceiveModeEnum("fax");
}
private static Request BuildReadRequest(ReadLocalOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Get,
Rest.Domain.Api,
"/2010-04-01/Accounts/" + (options.PathAccountSid ?? client.AccountSid) + "/IncomingPhoneNumbers/Local.json",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// read
/// </summary>
/// <param name="options"> Read Local parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Local </returns>
public static ResourceSet<LocalResource> Read(ReadLocalOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildReadRequest(options, client));
var page = Page<LocalResource>.FromJson("incoming_phone_numbers", response.Content);
return new ResourceSet<LocalResource>(page, options, client);
}
#if !NET35
/// <summary>
/// read
/// </summary>
/// <param name="options"> Read Local parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Local </returns>
public static async System.Threading.Tasks.Task<ResourceSet<LocalResource>> ReadAsync(ReadLocalOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildReadRequest(options, client));
var page = Page<LocalResource>.FromJson("incoming_phone_numbers", response.Content);
return new ResourceSet<LocalResource>(page, options, client);
}
#endif
/// <summary>
/// read
/// </summary>
/// <param name="pathAccountSid"> The SID of the Account that created the resources to read </param>
/// <param name="beta"> Whether to include new phone numbers </param>
/// <param name="friendlyName"> A string that identifies the resources to read </param>
/// <param name="phoneNumber"> The phone numbers of the resources to read </param>
/// <param name="origin"> Include phone numbers based on their origin. By default, phone numbers of all origin are
/// included. </param>
/// <param name="pageSize"> Page size </param>
/// <param name="limit"> Record limit </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Local </returns>
public static ResourceSet<LocalResource> Read(string pathAccountSid = null,
bool? beta = null,
string friendlyName = null,
Types.PhoneNumber phoneNumber = null,
string origin = null,
int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadLocalOptions(){PathAccountSid = pathAccountSid, Beta = beta, FriendlyName = friendlyName, PhoneNumber = phoneNumber, Origin = origin, PageSize = pageSize, Limit = limit};
return Read(options, client);
}
#if !NET35
/// <summary>
/// read
/// </summary>
/// <param name="pathAccountSid"> The SID of the Account that created the resources to read </param>
/// <param name="beta"> Whether to include new phone numbers </param>
/// <param name="friendlyName"> A string that identifies the resources to read </param>
/// <param name="phoneNumber"> The phone numbers of the resources to read </param>
/// <param name="origin"> Include phone numbers based on their origin. By default, phone numbers of all origin are
/// included. </param>
/// <param name="pageSize"> Page size </param>
/// <param name="limit"> Record limit </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Local </returns>
public static async System.Threading.Tasks.Task<ResourceSet<LocalResource>> ReadAsync(string pathAccountSid = null,
bool? beta = null,
string friendlyName = null,
Types.PhoneNumber phoneNumber = null,
string origin = null,
int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadLocalOptions(){PathAccountSid = pathAccountSid, Beta = beta, FriendlyName = friendlyName, PhoneNumber = phoneNumber, Origin = origin, PageSize = pageSize, Limit = limit};
return await ReadAsync(options, client);
}
#endif
/// <summary>
/// Fetch the target page of records
/// </summary>
/// <param name="targetUrl"> API-generated URL for the requested results page </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The target page of records </returns>
public static Page<LocalResource> GetPage(string targetUrl, ITwilioRestClient client)
{
client = client ?? TwilioClient.GetRestClient();
var request = new Request(
HttpMethod.Get,
targetUrl
);
var response = client.Request(request);
return Page<LocalResource>.FromJson("incoming_phone_numbers", response.Content);
}
/// <summary>
/// Fetch the next page of records
/// </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The next page of records </returns>
public static Page<LocalResource> NextPage(Page<LocalResource> page, ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetNextPageUrl(Rest.Domain.Api)
);
var response = client.Request(request);
return Page<LocalResource>.FromJson("incoming_phone_numbers", response.Content);
}
/// <summary>
/// Fetch the previous page of records
/// </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The previous page of records </returns>
public static Page<LocalResource> PreviousPage(Page<LocalResource> page, ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetPreviousPageUrl(Rest.Domain.Api)
);
var response = client.Request(request);
return Page<LocalResource>.FromJson("incoming_phone_numbers", response.Content);
}
private static Request BuildCreateRequest(CreateLocalOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Post,
Rest.Domain.Api,
"/2010-04-01/Accounts/" + (options.PathAccountSid ?? client.AccountSid) + "/IncomingPhoneNumbers/Local.json",
postParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// create
/// </summary>
/// <param name="options"> Create Local parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Local </returns>
public static LocalResource Create(CreateLocalOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildCreateRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// create
/// </summary>
/// <param name="options"> Create Local parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Local </returns>
public static async System.Threading.Tasks.Task<LocalResource> CreateAsync(CreateLocalOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildCreateRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// create
/// </summary>
/// <param name="phoneNumber"> The phone number to purchase in E.164 format </param>
/// <param name="pathAccountSid"> The SID of the Account that will create the resource </param>
/// <param name="apiVersion"> The API version to use for incoming calls made to the new phone number </param>
/// <param name="friendlyName"> A string to describe the new phone number </param>
/// <param name="smsApplicationSid"> The SID of the application to handle SMS messages </param>
/// <param name="smsFallbackMethod"> The HTTP method we use to call status_callback </param>
/// <param name="smsFallbackUrl"> The URL we call when an error occurs while executing TwiML </param>
/// <param name="smsMethod"> The HTTP method to use with sms url </param>
/// <param name="smsUrl"> The URL we should call when the new phone number receives an incoming SMS message </param>
/// <param name="statusCallback"> The URL we should call to send status information to your application </param>
/// <param name="statusCallbackMethod"> HTTP method we should use to call status_callback </param>
/// <param name="voiceApplicationSid"> The SID of the application to handle the new phone number </param>
/// <param name="voiceCallerIdLookup"> Whether to lookup the caller's name </param>
/// <param name="voiceFallbackMethod"> The HTTP method used with voice_fallback_url </param>
/// <param name="voiceFallbackUrl"> The URL we will call when an error occurs in TwiML </param>
/// <param name="voiceMethod"> The HTTP method used with the voice_url </param>
/// <param name="voiceUrl"> The URL we should call when the phone number receives a call </param>
/// <param name="identitySid"> The SID of the Identity resource to associate with the new phone number </param>
/// <param name="addressSid"> The SID of the Address resource associated with the phone number </param>
/// <param name="emergencyStatus"> Displays if emergency calling is enabled for this number. </param>
/// <param name="emergencyAddressSid"> The emergency address configuration to use for emergency calling </param>
/// <param name="trunkSid"> SID of the trunk to handle calls to the new phone number </param>
/// <param name="voiceReceiveMode"> Incoming call type: fax or voice </param>
/// <param name="bundleSid"> The SID of the Bundle resource associated with number </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Local </returns>
public static LocalResource Create(Types.PhoneNumber phoneNumber,
string pathAccountSid = null,
string apiVersion = null,
string friendlyName = null,
string smsApplicationSid = null,
Twilio.Http.HttpMethod smsFallbackMethod = null,
Uri smsFallbackUrl = null,
Twilio.Http.HttpMethod smsMethod = null,
Uri smsUrl = null,
Uri statusCallback = null,
Twilio.Http.HttpMethod statusCallbackMethod = null,
string voiceApplicationSid = null,
bool? voiceCallerIdLookup = null,
Twilio.Http.HttpMethod voiceFallbackMethod = null,
Uri voiceFallbackUrl = null,
Twilio.Http.HttpMethod voiceMethod = null,
Uri voiceUrl = null,
string identitySid = null,
string addressSid = null,
LocalResource.EmergencyStatusEnum emergencyStatus = null,
string emergencyAddressSid = null,
string trunkSid = null,
LocalResource.VoiceReceiveModeEnum voiceReceiveMode = null,
string bundleSid = null,
ITwilioRestClient client = null)
{
var options = new CreateLocalOptions(phoneNumber){PathAccountSid = pathAccountSid, ApiVersion = apiVersion, FriendlyName = friendlyName, SmsApplicationSid = smsApplicationSid, SmsFallbackMethod = smsFallbackMethod, SmsFallbackUrl = smsFallbackUrl, SmsMethod = smsMethod, SmsUrl = smsUrl, StatusCallback = statusCallback, StatusCallbackMethod = statusCallbackMethod, VoiceApplicationSid = voiceApplicationSid, VoiceCallerIdLookup = voiceCallerIdLookup, VoiceFallbackMethod = voiceFallbackMethod, VoiceFallbackUrl = voiceFallbackUrl, VoiceMethod = voiceMethod, VoiceUrl = voiceUrl, IdentitySid = identitySid, AddressSid = addressSid, EmergencyStatus = emergencyStatus, EmergencyAddressSid = emergencyAddressSid, TrunkSid = trunkSid, VoiceReceiveMode = voiceReceiveMode, BundleSid = bundleSid};
return Create(options, client);
}
#if !NET35
/// <summary>
/// create
/// </summary>
/// <param name="phoneNumber"> The phone number to purchase in E.164 format </param>
/// <param name="pathAccountSid"> The SID of the Account that will create the resource </param>
/// <param name="apiVersion"> The API version to use for incoming calls made to the new phone number </param>
/// <param name="friendlyName"> A string to describe the new phone number </param>
/// <param name="smsApplicationSid"> The SID of the application to handle SMS messages </param>
/// <param name="smsFallbackMethod"> The HTTP method we use to call status_callback </param>
/// <param name="smsFallbackUrl"> The URL we call when an error occurs while executing TwiML </param>
/// <param name="smsMethod"> The HTTP method to use with sms url </param>
/// <param name="smsUrl"> The URL we should call when the new phone number receives an incoming SMS message </param>
/// <param name="statusCallback"> The URL we should call to send status information to your application </param>
/// <param name="statusCallbackMethod"> HTTP method we should use to call status_callback </param>
/// <param name="voiceApplicationSid"> The SID of the application to handle the new phone number </param>
/// <param name="voiceCallerIdLookup"> Whether to lookup the caller's name </param>
/// <param name="voiceFallbackMethod"> The HTTP method used with voice_fallback_url </param>
/// <param name="voiceFallbackUrl"> The URL we will call when an error occurs in TwiML </param>
/// <param name="voiceMethod"> The HTTP method used with the voice_url </param>
/// <param name="voiceUrl"> The URL we should call when the phone number receives a call </param>
/// <param name="identitySid"> The SID of the Identity resource to associate with the new phone number </param>
/// <param name="addressSid"> The SID of the Address resource associated with the phone number </param>
/// <param name="emergencyStatus"> Displays if emergency calling is enabled for this number. </param>
/// <param name="emergencyAddressSid"> The emergency address configuration to use for emergency calling </param>
/// <param name="trunkSid"> SID of the trunk to handle calls to the new phone number </param>
/// <param name="voiceReceiveMode"> Incoming call type: fax or voice </param>
/// <param name="bundleSid"> The SID of the Bundle resource associated with number </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Local </returns>
public static async System.Threading.Tasks.Task<LocalResource> CreateAsync(Types.PhoneNumber phoneNumber,
string pathAccountSid = null,
string apiVersion = null,
string friendlyName = null,
string smsApplicationSid = null,
Twilio.Http.HttpMethod smsFallbackMethod = null,
Uri smsFallbackUrl = null,
Twilio.Http.HttpMethod smsMethod = null,
Uri smsUrl = null,
Uri statusCallback = null,
Twilio.Http.HttpMethod statusCallbackMethod = null,
string voiceApplicationSid = null,
bool? voiceCallerIdLookup = null,
Twilio.Http.HttpMethod voiceFallbackMethod = null,
Uri voiceFallbackUrl = null,
Twilio.Http.HttpMethod voiceMethod = null,
Uri voiceUrl = null,
string identitySid = null,
string addressSid = null,
LocalResource.EmergencyStatusEnum emergencyStatus = null,
string emergencyAddressSid = null,
string trunkSid = null,
LocalResource.VoiceReceiveModeEnum voiceReceiveMode = null,
string bundleSid = null,
ITwilioRestClient client = null)
{
var options = new CreateLocalOptions(phoneNumber){PathAccountSid = pathAccountSid, ApiVersion = apiVersion, FriendlyName = friendlyName, SmsApplicationSid = smsApplicationSid, SmsFallbackMethod = smsFallbackMethod, SmsFallbackUrl = smsFallbackUrl, SmsMethod = smsMethod, SmsUrl = smsUrl, StatusCallback = statusCallback, StatusCallbackMethod = statusCallbackMethod, VoiceApplicationSid = voiceApplicationSid, VoiceCallerIdLookup = voiceCallerIdLookup, VoiceFallbackMethod = voiceFallbackMethod, VoiceFallbackUrl = voiceFallbackUrl, VoiceMethod = voiceMethod, VoiceUrl = voiceUrl, IdentitySid = identitySid, AddressSid = addressSid, EmergencyStatus = emergencyStatus, EmergencyAddressSid = emergencyAddressSid, TrunkSid = trunkSid, VoiceReceiveMode = voiceReceiveMode, BundleSid = bundleSid};
return await CreateAsync(options, client);
}
#endif
/// <summary>
/// Converts a JSON string into a LocalResource object
/// </summary>
/// <param name="json"> Raw JSON string </param>
/// <returns> LocalResource object represented by the provided JSON </returns>
public static LocalResource FromJson(string json)
{
// Convert all checked exceptions to Runtime
try
{
return JsonConvert.DeserializeObject<LocalResource>(json);
}
catch (JsonException e)
{
throw new ApiException(e.Message, e);
}
}
/// <summary>
/// The SID of the Account that created the resource
/// </summary>
[JsonProperty("account_sid")]
public string AccountSid { get; private set; }
/// <summary>
/// The SID of the Address resource associated with the phone number
/// </summary>
[JsonProperty("address_sid")]
public string AddressSid { get; private set; }
/// <summary>
/// Whether the phone number requires an Address registered with Twilio.
/// </summary>
[JsonProperty("address_requirements")]
[JsonConverter(typeof(StringEnumConverter))]
public LocalResource.AddressRequirementEnum AddressRequirements { get; private set; }
/// <summary>
/// The API version used to start a new TwiML session
/// </summary>
[JsonProperty("api_version")]
public string ApiVersion { get; private set; }
/// <summary>
/// Whether the phone number is new to the Twilio platform
/// </summary>
[JsonProperty("beta")]
public bool? Beta { get; private set; }
/// <summary>
/// Indicate if a phone can receive calls or messages
/// </summary>
[JsonProperty("capabilities")]
public PhoneNumberCapabilities Capabilities { get; private set; }
/// <summary>
/// The RFC 2822 date and time in GMT that the resource was created
/// </summary>
[JsonProperty("date_created")]
public DateTime? DateCreated { get; private set; }
/// <summary>
/// The RFC 2822 date and time in GMT that the resource was last updated
/// </summary>
[JsonProperty("date_updated")]
public DateTime? DateUpdated { get; private set; }
/// <summary>
/// The string that you assigned to describe the resource
/// </summary>
[JsonProperty("friendly_name")]
public string FriendlyName { get; private set; }
/// <summary>
/// The SID of the Identity resource associated with number
/// </summary>
[JsonProperty("identity_sid")]
public string IdentitySid { get; private set; }
/// <summary>
/// The phone number in E.164 format
/// </summary>
[JsonProperty("phone_number")]
[JsonConverter(typeof(PhoneNumberConverter))]
public Types.PhoneNumber PhoneNumber { get; private set; }
/// <summary>
/// The phone number's origin. Can be twilio or hosted.
/// </summary>
[JsonProperty("origin")]
public string Origin { get; private set; }
/// <summary>
/// The unique string that identifies the resource
/// </summary>
[JsonProperty("sid")]
public string Sid { get; private set; }
/// <summary>
/// The SID of the Application resource to handle SMS messages
/// </summary>
[JsonProperty("sms_application_sid")]
public string SmsApplicationSid { get; private set; }
/// <summary>
/// The HTTP method used with sms_fallback_url
/// </summary>
[JsonProperty("sms_fallback_method")]
[JsonConverter(typeof(HttpMethodConverter))]
public Twilio.Http.HttpMethod SmsFallbackMethod { get; private set; }
/// <summary>
/// The URL that we call when an error occurs while retrieving or executing the TwiML
/// </summary>
[JsonProperty("sms_fallback_url")]
public Uri SmsFallbackUrl { get; private set; }
/// <summary>
/// The HTTP method to use with sms_url
/// </summary>
[JsonProperty("sms_method")]
[JsonConverter(typeof(HttpMethodConverter))]
public Twilio.Http.HttpMethod SmsMethod { get; private set; }
/// <summary>
/// The URL we call when the phone number receives an incoming SMS message
/// </summary>
[JsonProperty("sms_url")]
public Uri SmsUrl { get; private set; }
/// <summary>
/// The URL to send status information to your application
/// </summary>
[JsonProperty("status_callback")]
public Uri StatusCallback { get; private set; }
/// <summary>
/// The HTTP method we use to call status_callback
/// </summary>
[JsonProperty("status_callback_method")]
[JsonConverter(typeof(HttpMethodConverter))]
public Twilio.Http.HttpMethod StatusCallbackMethod { get; private set; }
/// <summary>
/// The SID of the Trunk that handles calls to the phone number
/// </summary>
[JsonProperty("trunk_sid")]
public string TrunkSid { get; private set; }
/// <summary>
/// The URI of the resource, relative to `https://api.twilio.com`
/// </summary>
[JsonProperty("uri")]
public string Uri { get; private set; }
/// <summary>
/// The voice_receive_mode
/// </summary>
[JsonProperty("voice_receive_mode")]
[JsonConverter(typeof(StringEnumConverter))]
public LocalResource.VoiceReceiveModeEnum VoiceReceiveMode { get; private set; }
/// <summary>
/// The SID of the application that handles calls to the phone number
/// </summary>
[JsonProperty("voice_application_sid")]
public string VoiceApplicationSid { get; private set; }
/// <summary>
/// Whether to lookup the caller's name
/// </summary>
[JsonProperty("voice_caller_id_lookup")]
public bool? VoiceCallerIdLookup { get; private set; }
/// <summary>
/// The HTTP method used with voice_fallback_url
/// </summary>
[JsonProperty("voice_fallback_method")]
[JsonConverter(typeof(HttpMethodConverter))]
public Twilio.Http.HttpMethod VoiceFallbackMethod { get; private set; }
/// <summary>
/// The URL we call when an error occurs in TwiML
/// </summary>
[JsonProperty("voice_fallback_url")]
public Uri VoiceFallbackUrl { get; private set; }
/// <summary>
/// The HTTP method used with the voice_url
/// </summary>
[JsonProperty("voice_method")]
[JsonConverter(typeof(HttpMethodConverter))]
public Twilio.Http.HttpMethod VoiceMethod { get; private set; }
/// <summary>
/// The URL we call when this phone number receives a call
/// </summary>
[JsonProperty("voice_url")]
public Uri VoiceUrl { get; private set; }
/// <summary>
/// Displays if emergency calling is enabled for this number.
/// </summary>
[JsonProperty("emergency_status")]
[JsonConverter(typeof(StringEnumConverter))]
public LocalResource.EmergencyStatusEnum EmergencyStatus { get; private set; }
/// <summary>
/// The emergency address configuration to use for emergency calling
/// </summary>
[JsonProperty("emergency_address_sid")]
public string EmergencyAddressSid { get; private set; }
/// <summary>
/// State of the emergency address configuration for the phone number
/// </summary>
[JsonProperty("emergency_address_status")]
[JsonConverter(typeof(StringEnumConverter))]
public LocalResource.EmergencyAddressStatusEnum EmergencyAddressStatus { get; private set; }
/// <summary>
/// The SID of the Bundle resource associated with number
/// </summary>
[JsonProperty("bundle_sid")]
public string BundleSid { get; private set; }
/// <summary>
/// The status
/// </summary>
[JsonProperty("status")]
public string Status { get; private set; }
private LocalResource()
{
}
}
}
| |
/*
* TestDES.cs - Test the DES algorithm.
*
* Copyright (C) 2002 Southern Storm Software, Pty Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
using CSUnit;
using System;
using System.Security.Cryptography;
#if CONFIG_CRYPTO
public class TestDES : CryptoTestCase
{
// Constructor.
public TestDES(String name)
: base(name)
{
// Nothing to do here.
}
// First test vector.
private static readonly byte[] desKey1 =
{0x10, 0x31, 0x6E, 0x02, 0x8C, 0x8F, 0x3B, 0x4A};
private static readonly byte[] desPlaintext1 =
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
private static readonly byte[] desExpected1 =
{0x82, 0xDC, 0xBA, 0xFB, 0xDE, 0xAB, 0x66, 0x02};
// Second test vector.
private static readonly byte[] desKey2 =
{0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01};
private static readonly byte[] desPlaintext2 =
{0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
private static readonly byte[] desExpected2 =
{0x95, 0xF8, 0xA5, 0xE5, 0xDD, 0x31, 0xD9, 0x00};
// Third test vector.
private static readonly byte[] desKey3 =
{0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01};
private static readonly byte[] desPlaintext3 =
{0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
private static readonly byte[] desExpected3 =
{0xDD, 0x7F, 0x12, 0x1C, 0xA5, 0x01, 0x56, 0x19};
// Fourth test vector.
private static readonly byte[] desKey4 =
{0x80, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01};
private static readonly byte[] desPlaintext4 =
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
private static readonly byte[] desExpected4 =
{0x95, 0xA8, 0xD7, 0x28, 0x13, 0xDA, 0xA9, 0x4D};
// Fifth test vector.
private static readonly byte[] desKey5 =
{0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef};
private static readonly byte[] desPlaintext5 =
{0x4e, 0x6f, 0x77, 0x20, 0x69, 0x73, 0x20, 0x74};
private static readonly byte[] desExpected5 =
{0x3f, 0xa4, 0x0e, 0x8a, 0x98, 0x4d, 0x48, 0x15};
// Test the default DES implementation.
public void TestDESDefault()
{
RunSymmetric("DES:", desKey1, desPlaintext1,
desExpected1);
}
// Test the various key vectors.
public void TestDESKey1()
{
RunSymmetric("DES", desKey1, desPlaintext1,
desExpected1);
}
public void TestDESKey2()
{
RunSymmetric("DES", desKey2, desPlaintext2,
desExpected2);
}
public void TestDESKey3()
{
RunSymmetric("DES", desKey3, desPlaintext3,
desExpected3);
}
public void TestDESKey4()
{
RunSymmetric("DES", desKey4, desPlaintext4,
desExpected4);
}
public void TestDESKey5()
{
RunSymmetric("DES", desKey5, desPlaintext5,
desExpected5);
}
// Test that the algorithm specific class cannot return
// an object of another algorithm.
public void TestDESCreateOther()
{
try
{
DES.Create("RC2");
Fail();
}
catch(InvalidCastException)
{
// Success case.
}
try
{
DES.Create("TripleDES");
Fail();
}
catch(InvalidCastException)
{
// Success case.
}
}
// Check that a key is weak.
private void CheckWeak(String name, byte[] key)
{
if(!DES.IsWeakKey(key))
{
Fail(name + ": key wasn't recognized as weak");
}
DES alg = DES.Create();
try
{
alg.Key = key;
Fail(name + ": key was supposed to be detected as weak");
}
catch(CryptographicException)
{
// Success
}
}
// Check that a key is non-weak.
private void CheckNonWeak(String name, byte[] key)
{
CheckNonWeak(name, key, false);
}
private void CheckNonWeak(String name, byte[] key, bool suppressCreate)
{
if(DES.IsWeakKey(key))
{
Fail(name + "key was recognized as weak");
}
if(!suppressCreate)
{
DES alg = DES.Create();
try
{
alg.Key = key;
}
catch(CryptographicException)
{
Fail(name +
": key was not supposed to be detected as weak");
}
}
}
// Check that a key is semi-weak.
private void CheckSemiWeak(String name, byte[] key)
{
if(!DES.IsSemiWeakKey(key))
{
Fail(name + ": key wasn't recognized as semi-weak");
}
DES alg = DES.Create();
try
{
alg.Key = key;
Fail(name +
": key was supposed to be detected as semi-weak");
}
catch(CryptographicException)
{
// Success
}
}
// Check that a key is non-semi-weak.
private void CheckNonSemiWeak(String name, byte[] key)
{
CheckNonSemiWeak(name, key, false);
}
private void CheckNonSemiWeak(String name, byte[] key, bool suppressCreate)
{
if(DES.IsSemiWeakKey(key))
{
Fail(name + "key was recognized as semi-weak");
}
if(!suppressCreate)
{
DES alg = DES.Create();
try
{
alg.Key = key;
}
catch(CryptographicException)
{
Fail(name +
": key was not supposed to be detected as semi-weak");
}
}
}
// Test for weak and semi-weak keys.
public void TestDESWeak()
{
// Test exception behaviour of "DES.IsWeakKey".
try
{
DES.IsWeakKey(null);
Fail("null");
}
catch(CryptographicException)
{
// success
}
try
{
DES.IsWeakKey(new byte [0]);
Fail("wrong size");
}
catch(CryptographicException)
{
// success
}
// These keys are weak.
CheckWeak("weak1", new byte[]
{0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01});
CheckWeak("weak2", new byte[]
{0x1F, 0x1F, 0x1F, 0x1F, 0x0E, 0x0E, 0x0E, 0x0E});
CheckWeak("weak3", new byte[]
{0xE0, 0xE0, 0xE0, 0xE0, 0xF1, 0xF1, 0xF1, 0xF1});
CheckWeak("weak4", new byte[]
{0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE});
// Test a semi-weak key.
CheckNonWeak("weak5", new byte[]
{0x01, 0xFE, 0x01, 0xFE, 0x01, 0xFE, 0x01, 0xFE}, true);
// Test a normal key.
CheckNonWeak("weak6", new byte[]
{0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef});
}
public void TestDESSemiWeak()
{
// Test exception behaviour of "DES.IsSemiWeakKey".
try
{
DES.IsSemiWeakKey(null);
Fail("null");
}
catch(CryptographicException)
{
// success
}
try
{
DES.IsSemiWeakKey(new byte [0]);
Fail("wrong size");
}
catch(CryptographicException)
{
// success
}
// These keys are semi-weak.
CheckSemiWeak("semi1", new byte[]
{0x01, 0xFE, 0x01, 0xFE, 0x01, 0xFE, 0x01, 0xFE});
CheckSemiWeak("semi2", new byte[]
{0xFE, 0x01, 0xFE, 0x01, 0xFE, 0x01, 0xFE, 0x01});
CheckSemiWeak("semi3", new byte[]
{0x1F, 0xE0, 0x1F, 0xE0, 0x0E, 0xF1, 0x0E, 0xF1});
CheckSemiWeak("semi4", new byte[]
{0xE0, 0x1F, 0xE0, 0x1F, 0xF1, 0x0E, 0xF1, 0x0E});
CheckSemiWeak("semi5", new byte[]
{0x01, 0xE0, 0x01, 0xE0, 0x01, 0xF1, 0x01, 0xF1});
CheckSemiWeak("semi6", new byte[]
{0xE0, 0x01, 0xE0, 0x01, 0xF1, 0x01, 0xF1, 0x01});
CheckSemiWeak("semi7", new byte[]
{0x1F, 0xFE, 0x1F, 0xFE, 0x0E, 0xFE, 0x0E, 0xFE});
CheckSemiWeak("semi8", new byte[]
{0xFE, 0x1F, 0xFE, 0x1F, 0xFE, 0x0E, 0xFE, 0x0E});
CheckSemiWeak("semi9", new byte[]
{0x01, 0x1F, 0x01, 0x1F, 0x01, 0x0E, 0x01, 0x0E});
CheckSemiWeak("semi10", new byte[]
{0x1F, 0x01, 0x1F, 0x01, 0x0E, 0x01, 0x0E, 0x01});
CheckSemiWeak("semi11", new byte[]
{0xE0, 0xFE, 0xE0, 0xFE, 0xF1, 0xFE, 0xF1, 0xFE});
CheckSemiWeak("semi12", new byte[]
{0xFE, 0xE0, 0xFE, 0xE0, 0xFE, 0xF1, 0xFE, 0xF1});
// Test a weak key.
CheckNonSemiWeak("semi13", new byte[]
{0xE0, 0xE0, 0xE0, 0xE0, 0xF1, 0xF1, 0xF1, 0xF1}, true);
// Test a normal key.
CheckNonSemiWeak("semi14", new byte[]
{0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef});
}
// Test the properties of the default algorithm instance.
public void TestDESProperties()
{
SymmetricPropertyTest(DES.Create(), 64, 64);
}
// Run mode tests.
public void TestDESECB()
{
RunModeTest(DES.Create(), CipherMode.ECB);
}
public void TestDESCBC()
{
RunModeTest(DES.Create(), CipherMode.CBC);
}
public void TestDESOFB()
{
RunModeTest(DES.Create(), CipherMode.OFB);
}
public void TestDESCFB()
{
RunModeTest(DES.Create(), CipherMode.CFB);
}
public void TestDESCTS()
{
RunModeTest(DES.Create(), CipherMode.CTS);
}
}; // TestDES
#endif // CONFIG_CRYPTO
| |
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 Edge.Router.API.Areas.HelpPage.ModelDescriptions;
using Edge.Router.API.Areas.HelpPage.Models;
namespace Edge.Router.API.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);
}
}
}
}
| |
//
// System.Net.ChunkedInputStream
//
// Authors:
// Gonzalo Paniagua Javier (gonzalo@novell.com)
//
// Copyright (c) 2005 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System;
using System.IO;
using System.Runtime.InteropServices;
namespace Reactor.Net
{
internal class ChunkedInputStream : RequestStream
{
private bool disposed;
private ChunkStream decoder;
private HttpListenerContext context;
private bool no_more_data;
class ReadBufferState
{
public byte[] Buffer;
public int Offset;
public int Count;
public int InitialCount;
public HttpStreamAsyncResult Ares;
public ReadBufferState(byte[] buffer, int offset, int count, HttpStreamAsyncResult ares)
{
Buffer = buffer;
Offset = offset;
Count = count;
InitialCount = count;
Ares = ares;
}
}
public ChunkedInputStream(HttpListenerContext context, Stream stream, byte[] buffer, int offset, int length) : base(stream, buffer, offset, length)
{
this.context = context;
WebHeaderCollection coll = (WebHeaderCollection)context.Request.Headers;
decoder = new ChunkStream(coll);
}
public ChunkStream Decoder
{
get
{
return decoder;
}
set
{
decoder = value;
}
}
public override int Read([In, Out] byte[] buffer, int offset, int count)
{
IAsyncResult ares = BeginRead(buffer, offset, count, null, null);
return EndRead(ares);
}
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback cback, object state)
{
if (disposed)
{
throw new ObjectDisposedException(GetType().ToString());
}
if (buffer == null)
{
throw new ArgumentNullException("buffer");
}
int len = buffer.Length;
if (offset < 0 || offset > len)
{
throw new ArgumentOutOfRangeException("offset exceeds the size of buffer");
}
if (count < 0 || offset > len - count)
{
throw new ArgumentOutOfRangeException("offset+size exceeds the size of buffer");
}
HttpStreamAsyncResult ares = new HttpStreamAsyncResult();
ares.Callback = cback;
ares.State = state;
if (no_more_data)
{
ares.Complete();
return ares;
}
int nread = decoder.Read(buffer, offset, count);
offset += nread;
count -= nread;
if (count == 0)
{
// got all we wanted, no need to bother the decoder yet
ares.Count = nread;
ares.Complete();
return ares;
}
if (!decoder.WantMore)
{
no_more_data = nread == 0;
ares.Count = nread;
ares.Complete();
return ares;
}
ares.Buffer = new byte[8192];
ares.Offset = 0;
ares.Count = 8192;
ReadBufferState rb = new ReadBufferState(buffer, offset, count, ares);
rb.InitialCount += nread;
base.BeginRead(ares.Buffer, ares.Offset, ares.Count, OnRead, rb);
return ares;
}
void OnRead(IAsyncResult base_ares)
{
ReadBufferState rb = (ReadBufferState)base_ares.AsyncState;
HttpStreamAsyncResult ares = rb.Ares;
try
{
int nread = base.EndRead(base_ares);
decoder.Write(ares.Buffer, ares.Offset, nread);
nread = decoder.Read(rb.Buffer, rb.Offset, rb.Count);
rb.Offset += nread;
rb.Count -= nread;
if (rb.Count == 0 || !decoder.WantMore || nread == 0)
{
no_more_data = !decoder.WantMore && nread == 0;
ares.Count = rb.InitialCount - rb.Count;
ares.Complete();
return;
}
ares.Offset = 0;
ares.Count = Math.Min(8192, decoder.ChunkLeft + 6);
base.BeginRead(ares.Buffer, ares.Offset, ares.Count, OnRead, rb);
}
catch (Exception e)
{
context.Connection.SendError(e.Message, 400);
ares.Complete(e);
}
}
public override int EndRead(IAsyncResult ares)
{
if (disposed)
{
throw new ObjectDisposedException(GetType().ToString());
}
HttpStreamAsyncResult my_ares = ares as HttpStreamAsyncResult;
if (ares == null)
{
throw new ArgumentException("Invalid IAsyncResult", "ares");
}
if (!ares.IsCompleted)
{
ares.AsyncWaitHandle.WaitOne();
}
if (my_ares.Error != null)
{
throw new HttpListenerException(400, "I/O operation aborted: " + my_ares.Error.Message);
}
return my_ares.Count;
}
public override void Close()
{
if (!disposed)
{
disposed = true;
base.Close();
}
}
}
}
| |
// This file contains the various event objects that are sent to the debugger from the sample engine via IDebugEventCallback2::Event.
// These are used in EngineCallback.cs.
// The events are how the engine tells the debugger about what is happening in the debuggee process.
// There are three base classe the other events derive from: AD7AsynchronousEvent, AD7StoppingEvent, and AD7SynchronousEvent. These
// each implement the IDebugEvent2.GetAttributes method for the type of event they represent.
// Most events sent the debugger are asynchronous events.
// For more info on events, see https://msdn.microsoft.com/en-us/library/bb161367.aspx
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Debugger.Interop;
namespace Cosmos.VS.DebugEngine.AD7.Impl
{
#region Event base classes
class AD7AsynchronousEvent : IDebugEvent2
{
public const uint Attributes = (uint)enum_EVENTATTRIBUTES.EVENT_ASYNCHRONOUS;
int IDebugEvent2.GetAttributes(out uint eventAttributes)
{
eventAttributes = Attributes;
return VSConstants.S_OK;
}
}
class AD7StoppingEvent : IDebugEvent2
{
public const uint Attributes = (uint)enum_EVENTATTRIBUTES.EVENT_ASYNC_STOP;
int IDebugEvent2.GetAttributes(out uint eventAttributes)
{
eventAttributes = Attributes;
return VSConstants.S_OK;
}
}
class AD7SynchronousEvent : IDebugEvent2
{
public const uint Attributes = (uint)enum_EVENTATTRIBUTES.EVENT_SYNCHRONOUS;
int IDebugEvent2.GetAttributes(out uint eventAttributes)
{
eventAttributes = Attributes;
return VSConstants.S_OK;
}
}
class AD7SynchronousStoppingEvent : IDebugEvent2
{
public const uint Attributes = (uint)enum_EVENTATTRIBUTES.EVENT_STOPPING | (uint)enum_EVENTATTRIBUTES.EVENT_SYNCHRONOUS;
int IDebugEvent2.GetAttributes(out uint eventAttributes)
{
eventAttributes = Attributes;
return VSConstants.S_OK;
}
}
#endregion
sealed class AD7StepCompletedEvent : IDebugEvent2, IDebugStepCompleteEvent2
{
public const string IID = "0F7F24C1-74D9-4EA6-A3EA-7EDB2D81441D";
public static void Send(AD7Engine engine)
{
var xEvent = new AD7StepCompletedEvent();
engine.Callback.Send(xEvent, IID, engine.mProcess.Thread);
}
#region IDebugEvent2 Members
public int GetAttributes(out uint pdwAttrib)
{
pdwAttrib = (uint)(enum_EVENTATTRIBUTES.EVENT_ASYNC_STOP);
return VSConstants.S_OK;
}
#endregion
}
// The debug engine (DE) sends this interface to the session debug manager (SDM) when an instance of the DE is created.
sealed class AD7EngineCreateEvent : AD7AsynchronousEvent, IDebugEngineCreateEvent2
{
public const string IID = "FE5B734C-759D-4E59-AB04-F103343BDD06";
private IDebugEngine2 m_engine;
AD7EngineCreateEvent(AD7Engine engine)
{
m_engine = engine;
}
public static void Send(AD7Engine engine)
{
AD7EngineCreateEvent eventObject = new AD7EngineCreateEvent(engine);
engine.Callback.Send(eventObject, IID, null, null);
}
int IDebugEngineCreateEvent2.GetEngine(out IDebugEngine2 engine)
{
engine = m_engine;
return VSConstants.S_OK;
}
}
// This interface is sent by the debug engine (DE) to the session debug manager (SDM) when a program is attached to.
sealed class AD7ProgramCreateEvent : AD7AsynchronousEvent, IDebugProgramCreateEvent2
{
public const string IID = "96CD11EE-ECD4-4E89-957E-B5D496FC4139";
internal static void Send(AD7Engine engine)
{
AD7ProgramCreateEvent eventObject = new AD7ProgramCreateEvent();
engine.Callback.Send(eventObject, IID, null);
}
}
// This interface is sent by the debug engine (DE) to the session debug manager (SDM) when a module is loaded or unloaded.
sealed class AD7ModuleLoadEvent : AD7AsynchronousEvent, IDebugModuleLoadEvent2
{
public const string IID = "989DB083-0D7C-40D1-A9D9-921BF611A4B2";
readonly AD7Module m_module;
readonly bool m_fLoad;
public AD7ModuleLoadEvent(AD7Module module, bool fLoad)
{
m_module = module;
m_fLoad = fLoad;
}
int IDebugModuleLoadEvent2.GetModule(out IDebugModule2 module, ref string debugMessage, ref int fIsLoad)
{
module = m_module;
if (m_fLoad)
{
//debugMessage = String.Concat("Loaded '", m_module.DebuggedModule.Name, "'");
fIsLoad = 1;
}
else
{
//debugMessage = String.Concat("Unloaded '", m_module.DebuggedModule.Name, "'");
fIsLoad = 0;
}
return VSConstants.S_OK;
}
internal static void Send(AD7Engine engine, AD7Module aModule, bool fLoad)
{
var eventObject = new AD7ModuleLoadEvent(aModule, fLoad);
engine.Callback.Send(eventObject, IID, null);
}
}
// This interface is sent by the debug engine (DE) to the session debug manager (SDM) when a program has run to completion
// or is otherwise destroyed.
sealed class AD7ProgramDestroyEvent : AD7SynchronousEvent, IDebugProgramDestroyEvent2
{
public const string IID = "E147E9E3-6440-4073-A7B7-A65592C714B5";
readonly uint m_exitCode;
public AD7ProgramDestroyEvent(uint exitCode)
{
m_exitCode = exitCode;
}
#region IDebugProgramDestroyEvent2 Members
int IDebugProgramDestroyEvent2.GetExitCode(out uint exitCode)
{
exitCode = m_exitCode;
return VSConstants.S_OK;
}
#endregion
}
// This interface is sent by the debug engine (DE) to the session debug manager (SDM) when a thread is created in a program being debugged.
sealed class AD7ThreadCreateEvent : AD7AsynchronousEvent, IDebugThreadCreateEvent2
{
public const string IID = "2090CCFC-70C5-491D-A5E8-BAD2DD9EE3EA";
internal static void Send(AD7Engine engine, IDebugThread2 aThread)
{
var eventObject = new AD7ThreadCreateEvent();
engine.Callback.Send(eventObject, IID, aThread);
}
}
// This interface is sent by the debug engine (DE) to the session debug manager (SDM) when a thread has exited.
sealed class AD7ThreadDestroyEvent : AD7AsynchronousEvent, IDebugThreadDestroyEvent2
{
public const string IID = "2C3B7532-A36F-4A6E-9072-49BE649B8541";
readonly uint m_exitCode;
public AD7ThreadDestroyEvent(uint exitCode)
{
m_exitCode = exitCode;
}
#region IDebugThreadDestroyEvent2 Members
int IDebugThreadDestroyEvent2.GetExitCode(out uint exitCode)
{
exitCode = m_exitCode;
return VSConstants.S_OK;
}
internal static void Send(AD7Engine aEngine, IDebugThread2 aThread, uint aExitCode)
{
var xObj = new AD7ThreadDestroyEvent(aExitCode);
aEngine.Callback.Send(xObj, IID, aThread);
}
#endregion
}
// This interface is sent by the debug engine (DE) to the session debug manager (SDM) when a program is loaded, but before any code is executed.
sealed class AD7LoadCompleteEvent : AD7StoppingEvent, IDebugLoadCompleteEvent2
{
public const string IID = "B1844850-1349-45D4-9F12-495212F5EB0B";
public AD7LoadCompleteEvent()
{
}
internal static void Send(AD7Engine aEngine, AD7Thread aThread)
{
var xMessage = new AD7LoadCompleteEvent();
aEngine.Callback.Send(xMessage, IID, aThread);
}
}
// This interface tells the session debug manager (SDM) that an asynchronous break has been successfully completed.
sealed class AD7AsyncBreakCompleteEvent : AD7StoppingEvent, IDebugBreakEvent2
{
public const string IID = "c7405d1d-e24b-44e0-b707-d8a5a4e1641b";
}
// This interface is sent by the debug engine (DE) to the session debug manager (SDM) to output a string for debug tracing.
sealed class AD7OutputDebugStringEvent : AD7AsynchronousEvent, IDebugOutputStringEvent2
{
public const string IID = "569c4bb1-7b82-46fc-ae28-4536ddad753e";
private string m_str;
public AD7OutputDebugStringEvent(string str)
{
m_str = str;
}
#region IDebugOutputStringEvent2 Members
int IDebugOutputStringEvent2.GetString(out string pbstrString)
{
pbstrString = m_str;
return VSConstants.S_OK;
}
#endregion
}
// This interface is sent by the debug engine (DE) to indicate the results of searching for symbols for a module in the debuggee
sealed class AD7SymbolSearchEvent : AD7AsynchronousEvent, IDebugSymbolSearchEvent2
{
public const string IID = "638F7C54-C160-4c7b-B2D0-E0337BC61F8C";
private AD7Module m_module;
private string m_searchInfo;
private enum_MODULE_INFO_FLAGS m_symbolFlags;
public AD7SymbolSearchEvent(AD7Module module, string searchInfo, enum_MODULE_INFO_FLAGS symbolFlags)
{
m_module = module;
m_searchInfo = searchInfo;
m_symbolFlags = symbolFlags;
}
#region IDebugSymbolSearchEvent2 Members
int IDebugSymbolSearchEvent2.GetSymbolSearchInfo(out IDebugModule3 pModule, ref string pbstrDebugMessage, enum_MODULE_INFO_FLAGS[] pdwModuleInfoFlags)
{
pModule = m_module;
pbstrDebugMessage = m_searchInfo;
pdwModuleInfoFlags[0] = m_symbolFlags;
return VSConstants.S_OK;
}
#endregion
}
// This interface is sent when a pending breakpoint has been bound in the debuggee.
sealed class AD7BreakpointBoundEvent : AD7AsynchronousEvent, IDebugBreakpointBoundEvent2
{
public const string IID = "1dddb704-cf99-4b8a-b746-dabb01dd13a0";
private AD7PendingBreakpoint m_pendingBreakpoint;
private AD7BoundBreakpoint m_boundBreakpoint;
public AD7BreakpointBoundEvent(AD7PendingBreakpoint pendingBreakpoint, AD7BoundBreakpoint boundBreakpoint)
{
m_pendingBreakpoint = pendingBreakpoint;
m_boundBreakpoint = boundBreakpoint;
}
#region IDebugBreakpointBoundEvent2 Members
int IDebugBreakpointBoundEvent2.EnumBoundBreakpoints(out IEnumDebugBoundBreakpoints2 ppEnum)
{
IDebugBoundBreakpoint2[] boundBreakpoints = new IDebugBoundBreakpoint2[1];
boundBreakpoints[0] = m_boundBreakpoint;
ppEnum = new AD7BoundBreakpointsEnum(boundBreakpoints);
return VSConstants.S_OK;
}
int IDebugBreakpointBoundEvent2.GetPendingBreakpoint(out IDebugPendingBreakpoint2 ppPendingBP)
{
ppPendingBP = m_pendingBreakpoint;
return VSConstants.S_OK;
}
#endregion
}
// This Event is sent when a breakpoint is hit in the debuggee
sealed class AD7BreakpointEvent : AD7StoppingEvent, IDebugBreakpointEvent2
{
public const string IID = "501C1E21-C557-48B8-BA30-A1EAB0BC4A74";
IEnumDebugBoundBreakpoints2 m_boundBreakpoints;
public AD7BreakpointEvent(IEnumDebugBoundBreakpoints2 boundBreakpoints)
{
m_boundBreakpoints = boundBreakpoints;
}
#region IDebugBreakpointEvent2 Members
int IDebugBreakpointEvent2.EnumBreakpoints(out IEnumDebugBoundBreakpoints2 ppEnum)
{
ppEnum = m_boundBreakpoints;
return VSConstants.S_OK;
}
#endregion
}
sealed class AD7EntrypointEvent : AD7StoppingEvent, IDebugEntryPointEvent2
{
public const string IID = "E8414A3E-1642-48EC-829E-5F4040E16DA9";
public static void Send(AD7Engine aEngine)
{
aEngine.Callback.Send(new AD7EntrypointEvent(), IID, null);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Text;
using System.Net;
using System.Net.Sockets;
using gov.va.medora.utils;
using gov.va.medora.mdo.src.mdo;
namespace gov.va.medora.mdo.dao.hl7.mpi
{
public class MpiConnection : AbstractConnection
{
const int DEFAULT_PORT = 15500;
const int DEFAULT_TIMEOUT = 60000;
const string END_MESSAGE = "\u001B\u001B\u001B";
string hostname;
int port;
int timeout;
Socket socket;
public MpiConnection(DataSource dataSource) : base(dataSource) { }
public override void connect()
{
IsConnected = false;
if (DataSource == null)
{
throw new Exception("No data source");
}
if (DataSource.Protocol != "HL7")
{
throw new Exception("Incorrect protocol: " + DataSource.Protocol + ". Should be HL7.");
}
if (DataSource.Modality != "MPI")
{
throw new Exception("Incorrect modality: " + DataSource.Modality + ". Should be MPI.");
}
hostname = DataSource.Provider;
if (StringUtils.isEmpty(hostname))
{
throw new Exception("No provider (hostname)");
}
port = DataSource.Port;
if (port == 0)
{
port = DEFAULT_PORT;
}
timeout = DEFAULT_TIMEOUT;
try
{
IPAddress mpiIP = (IPAddress)Dns.GetHostEntry(hostname).AddressList[0];
IPEndPoint mpiEndPoint = new IPEndPoint(mpiIP, port);
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, timeout);
socket.Connect(mpiEndPoint);
if (!socket.Connected)
{
throw new Exception("Unable to connect to " + hostname + ", port " + port);
}
}
catch (SocketException se)
{
Exception nse = new Exception(se.Message + ". Tried " + hostname + ", port " + port, se);
throw nse;
}
IsConnected = true;
}
public override void disconnect()
{
if (!IsConnected)
{
return;
}
socket.Close();
IsConnected = false;
}
public override object query(MdoQuery request, AbstractPermission permission = null)
{
throw new NotImplementedException();
}
public override object query(string request, AbstractPermission permission = null)
{
connect();
string msg = "HELO " + DataSource.SiteId.Id + "\r\n";
string reply = sendReceive(msg, "\r\n");
if (!reply.StartsWith("220"))
{
disconnect();
throw new Exception("ERROR sending HELO: " + reply);
}
string datamsg = "DATA PARAM=MPI\r\n";
string hl7msg = "";
string[] segments = StringUtils.split(request, "\r");
segments = StringUtils.trimArray(segments);
for (int i = 0; i < segments.Length; i++)
{
segments[i] += '\r'; //Gotta put the terminator back after splitting on it
hl7msg += StringUtils.strPack(segments[i], 3);
}
hl7msg += StringUtils.strPack(END_MESSAGE, 3);
send(datamsg);
reply = sendReceive(hl7msg, "\r\n");
if (!reply.StartsWith("220"))
{
disconnect();
throw new Exception("ERROR sending DATA PARAM=MPI: " + reply);
}
msg = "TURN\r\n";
reply = sendReceive(msg, "\r\n");
if (!reply.StartsWith("220"))
{
disconnect();
throw new Exception("ERROR sending HL7: " + reply);
}
reply = receive(END_MESSAGE);
msg = "QUIT\r\n";
send(msg);
disconnect();
return reply;
}
internal string sendReceive(string request, string terminateString)
{
send(request);
return receive(terminateString);
}
internal void send(string msg)
{
Byte[] bytesSent = Encoding.ASCII.GetBytes(msg);
socket.Send(bytesSent, bytesSent.Length, 0);
}
internal string receive(string terminateString)
{
Byte[] bytesReceived = new Byte[256];
int bytes = 0;
string reply = "";
int endIdx = -1;
do
{
bytes = socket.Receive(bytesReceived, bytesReceived.Length, 0);
string thisBatch = Encoding.ASCII.GetString(bytesReceived, 0, bytes);
endIdx = thisBatch.IndexOf(terminateString);
if (endIdx != -1)
{
thisBatch = thisBatch.Substring(0, endIdx);
}
reply += thisBatch;
}
while (endIdx == -1);
return reply;
}
public override string getWelcomeMessage()
{
return null;
}
public override ISystemFileHandler SystemFileHandler
{
get { return null; }
}
//public override object authorizedConnect(AbstractCredentials credentials, AbstractPermission permission)
//{
// return null;
//}
public override object authorizedConnect(AbstractCredentials credentials, AbstractPermission permission, DataSource validationDataSource = null)
{
return null;
}
public override bool hasPatch(string patchId)
{
throw new Exception("The method or operation is not implemented.");
}
public override string getServerTimeout()
{
return null;
}
public override object query(SqlQuery request, Delegate functionToInvoke, AbstractPermission permission = null)
{
throw new NotImplementedException();
}
public override Dictionary<string, object> getState()
{
throw new NotImplementedException();
}
public override void setState(Dictionary<string, object> session)
{
throw new NotImplementedException();
}
public override bool isAlive()
{
throw new NotImplementedException();
}
}
}
| |
// Copyright (c) 2015, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections.Generic;
using System.IO;
using System.Security.Principal;
using WebsitePanel.Providers.SharePoint;
using WebsitePanel.Providers.Utils;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
namespace WebsitePanel.Providers.HostedSolution
{
/// <summary>
/// Represents SharePoint management functionality implementation.
/// </summary>
public class HostedSharePointServerImpl : MarshalByRefObject
{
/// <summary>
/// Gets list of supported languages by this installation of SharePoint.
/// </summary>
/// <returns>List of supported languages</returns>
public int[] GetSupportedLanguages(string languagePacksPath)
{
List<int> languages = new List<int>();
try
{
WindowsImpersonationContext wic = WindowsIdentity.GetCurrent().Impersonate();
try
{
SPLanguageCollection installedLanguages = SPRegionalSettings.GlobalInstalledLanguages;
foreach (SPLanguage lang in installedLanguages)
{
languages.Add(lang.LCID);
}
return languages.ToArray();
}
finally
{
wic.Undo();
}
}
catch (Exception ex)
{
throw new InvalidOperationException("Failed to create site collection.", ex);
}
}
public long GetSiteCollectionSize(Uri root, string url)
{
WindowsImpersonationContext wic = null;
try
{
wic = WindowsIdentity.GetCurrent().Impersonate();
SPWebApplication rootWebApplication = SPWebApplication.Lookup(root);
SPSite site = rootWebApplication.Sites[url];
if (site != null)
site.RecalculateStorageUsed();
else
throw new ApplicationException(string.Format("SiteCollection {0} does not exist", url));
return site.Usage.Storage;
}
catch (Exception ex)
{
HostedSolutionLog.LogError(ex);
throw;
}
finally
{
if (wic != null)
wic.Undo();
}
}
public SharePointSiteDiskSpace[] CalculateSiteCollectionDiskSpace(Uri root, string[] urls)
{
WindowsImpersonationContext wic = null;
try
{
wic = WindowsIdentity.GetCurrent().Impersonate();
SPWebApplication rootWebApplication = SPWebApplication.Lookup(root);
List<SharePointSiteDiskSpace> ret = new List<SharePointSiteDiskSpace>();
foreach (string url in urls)
{
SharePointSiteDiskSpace siteDiskSpace = new SharePointSiteDiskSpace();
rootWebApplication.Sites[url].RecalculateStorageUsed();
siteDiskSpace.Url = url;
siteDiskSpace.DiskSpace = (long)Math.Round(rootWebApplication.Sites[url].Usage.Storage / 1024.0 / 1024.0);
ret.Add(siteDiskSpace);
}
return ret.ToArray();
}
catch (Exception ex)
{
HostedSolutionLog.LogError(ex);
throw;
}
finally
{
if (wic != null)
wic.Undo();
}
}
/// <summary>
/// Gets list of SharePoint collections within root web application.
/// </summary>
/// <param name="rootWebApplicationUri">Root web application uri.</param>
/// <returns>List of SharePoint collections within root web application.</returns>
public SharePointSiteCollection[] GetSiteCollections(Uri rootWebApplicationUri)
{
try
{
WindowsImpersonationContext wic = WindowsIdentity.GetCurrent().Impersonate();
try
{
SPWebApplication rootWebApplication = SPWebApplication.Lookup(rootWebApplicationUri);
List<SharePointSiteCollection> siteCollections = new List<SharePointSiteCollection>();
foreach (SPSite site in rootWebApplication.Sites)
{
SharePointSiteCollection loadedSiteCollection = new SharePointSiteCollection();
FillSiteCollection(loadedSiteCollection, site);
siteCollections.Add(loadedSiteCollection);
}
return siteCollections.ToArray();
}
finally
{
wic.Undo();
}
}
catch (Exception ex)
{
throw new InvalidOperationException("Failed to create site collection.", ex);
}
}
/// <summary>
/// Gets SharePoint collection within root web application with given name.
/// </summary>
/// <param name="rootWebApplicationUri">Root web application uri.</param>
/// <param name="url">Url that uniquely identifies site collection to be loaded.</param>
/// <returns>SharePoint collection within root web application with given name.</returns>
public SharePointSiteCollection GetSiteCollection(Uri rootWebApplicationUri, string url)
{
try
{
WindowsImpersonationContext wic = WindowsIdentity.GetCurrent().Impersonate();
try
{
SPWebApplication rootWebApplication = SPWebApplication.Lookup(rootWebApplicationUri);
string siteCollectionUrl = String.Format("{0}:{1}", url, rootWebApplicationUri.Port);
SPSite site = rootWebApplication.Sites[siteCollectionUrl];
if (site != null)
{
SharePointSiteCollection loadedSiteCollection = new SharePointSiteCollection();
FillSiteCollection(loadedSiteCollection, site);
return loadedSiteCollection;
}
return null;
}
finally
{
wic.Undo();
}
}
catch (Exception ex)
{
throw new InvalidOperationException("Failed to create site collection.", ex);
}
}
private static void DeleteQuotaTemplate(string name)
{
SPFarm farm = SPFarm.Local;
SPWebService webService = farm.Services.GetValue<SPWebService>("");
SPQuotaTemplateCollection quotaColl = webService.QuotaTemplates;
quotaColl.Delete(name);
}
public void UpdateQuotas(Uri root, string url, long maxStorage, long warningStorage)
{
WindowsImpersonationContext wic = null;
try
{
wic = WindowsIdentity.GetCurrent().Impersonate();
SPWebApplication rootWebApplication = SPWebApplication.Lookup(root);
SPQuota quota = new SPQuota();
if (maxStorage != -1)
quota.StorageMaximumLevel = maxStorage * 1024 * 1024;
else
quota.StorageMaximumLevel = 0;
if (warningStorage != -1 && maxStorage != -1)
quota.StorageWarningLevel = Math.Min(warningStorage, maxStorage) * 1024 * 1024;
else
quota.StorageWarningLevel = 0;
rootWebApplication.GrantAccessToProcessIdentity(WindowsIdentity.GetCurrent().Name);
rootWebApplication.Sites[url].Quota = quota;
}
catch (Exception ex)
{
HostedSolutionLog.LogError(ex);
throw;
}
finally
{
if (wic != null)
wic.Undo();
}
}
/// <summary>
/// Creates site collection within predefined root web application.
/// </summary>
/// <param name="rootWebApplicationUri">Root web application uri.</param>
/// <param name="siteCollection">Information about site coolection to be created.</param>
/// <exception cref="InvalidOperationException">Is thrown in case requested operation fails for any reason.</exception>
public void CreateSiteCollection(Uri rootWebApplicationUri, SharePointSiteCollection siteCollection)
{
WindowsImpersonationContext wic = null;
HostedSolutionLog.LogStart("CreateSiteCollection");
try
{
wic = WindowsIdentity.GetCurrent().Impersonate();
SPWebApplication rootWebApplication = SPWebApplication.Lookup(rootWebApplicationUri);
string siteCollectionUrl = String.Format("{0}:{1}", siteCollection.Url, rootWebApplicationUri.Port);
HostedSolutionLog.DebugInfo("rootWebApplicationUri: {0}", rootWebApplicationUri);
HostedSolutionLog.DebugInfo("siteCollectionUrl: {0}", siteCollectionUrl);
SPQuota spQuota;
SPSite spSite = rootWebApplication.Sites.Add(siteCollectionUrl,
siteCollection.Title, siteCollection.Description,
(uint)siteCollection.LocaleId, String.Empty,
siteCollection.OwnerLogin, siteCollection.OwnerName,
siteCollection.OwnerEmail,
null, null, null, true);
try
{
spQuota = new SPQuota();
if (siteCollection.MaxSiteStorage != -1)
spQuota.StorageMaximumLevel = siteCollection.MaxSiteStorage * 1024 * 1024;
if (siteCollection.WarningStorage != -1 && siteCollection.MaxSiteStorage != -1)
spQuota.StorageWarningLevel = Math.Min(siteCollection.WarningStorage, siteCollection.MaxSiteStorage) * 1024 * 1024;
}
catch (Exception)
{
rootWebApplication.Sites.Delete(siteCollectionUrl);
throw;
}
try
{
rootWebApplication.GrantAccessToProcessIdentity(WindowsIdentity.GetCurrent().Name);
spSite.Quota = spQuota;
}
catch (Exception)
{
rootWebApplication.Sites.Delete(siteCollectionUrl);
DeleteQuotaTemplate(siteCollection.Title);
throw;
}
rootWebApplication.Update(true);
try
{
if (siteCollection.RootWebApplicationInteralIpAddress != string.Empty)
{
string dirPath = FileUtils.EvaluateSystemVariables(@"%windir%\system32\drivers\etc");
string path = dirPath + "\\hosts";
if (FileUtils.FileExists(path))
{
string content = FileUtils.GetFileTextContent(path);
content = content.Replace("\r\n", "\n").Replace("\n\r", "\n");
string[] contentArr = content.Split(new char[] { '\n' });
bool bRecordExist = false;
foreach (string s in contentArr)
{
if (s != string.Empty)
{
string IPAddr = string.Empty;
string hostName = string.Empty;
if (s[0] != '#')
{
bool bSeperator = false;
foreach (char c in s)
{
if ((c != ' ') & (c != '\t'))
{
if (bSeperator)
hostName += c;
else
IPAddr += c;
}
else
bSeperator = true;
}
if (hostName.ToLower() == siteCollection.RootWebApplicationFQDN.ToLower())
{
bRecordExist = true;
break;
}
}
}
}
if (!bRecordExist)
{
string outPut = string.Empty;
foreach (string o in contentArr)
{
if (o != string.Empty)
outPut += o + "\r\n";
}
outPut += siteCollection.RootWebApplicationInteralIpAddress + '\t' + siteCollection.RootWebApplicationFQDN + "\r\n";
FileUtils.UpdateFileTextContent(path, outPut);
}
}
}
}
catch (Exception ex)
{
HostedSolutionLog.LogError(ex);
}
}
catch (Exception ex)
{
HostedSolutionLog.LogError(ex);
throw;
}
finally
{
if (wic != null)
wic.Undo();
HostedSolutionLog.LogEnd("CreateSiteCollection");
}
}
/// <summary>
/// Deletes site collection under given url.
/// </summary>
/// <param name="rootWebApplicationUri">Root web application uri.</param>
/// <param name="url">Url that uniquely identifies site collection to be deleted.</param>
/// <exception cref="InvalidOperationException">Is thrown in case requested operation fails for any reason.</exception>
public void DeleteSiteCollection(Uri rootWebApplicationUri, SharePointSiteCollection siteCollection)
{
try
{
WindowsIdentity identity = WindowsIdentity.GetCurrent();
WindowsImpersonationContext wic = identity.Impersonate();
try
{
SPWebApplication rootWebApplication = SPWebApplication.Lookup(rootWebApplicationUri);
string siteCollectionUrl = String.Format("{0}:{1}", siteCollection.Url, rootWebApplicationUri.Port);
//string args = String.Format("-o deletesite -url {0}", siteCollectionUrl);
//string stsadm = @"c:\Program Files\Common Files\Microsoft Shared\web server extensions\12\BIN\STSADM.EXE";
//// launch system process
//ProcessStartInfo startInfo = new ProcessStartInfo(stsadm, args);
//startInfo.WindowStyle = ProcessWindowStyle.Hidden;
//startInfo.RedirectStandardOutput = true;
//startInfo.UseShellExecute = false;
//Process proc = Process.Start(startInfo);
//// analyze results
//StreamReader reader = proc.StandardOutput;
//string output = reader.ReadToEnd();
//int exitCode = proc.ExitCode;
//reader.Close();
rootWebApplication.Sites.Delete(siteCollectionUrl, true);
rootWebApplication.Update(true);
try
{
if (siteCollection.RootWebApplicationInteralIpAddress != string.Empty)
{
string dirPath = FileUtils.EvaluateSystemVariables(@"%windir%\system32\drivers\etc");
string path = dirPath + "\\hosts";
if (FileUtils.FileExists(path))
{
string content = FileUtils.GetFileTextContent(path);
content = content.Replace("\r\n", "\n").Replace("\n\r", "\n");
string[] contentArr = content.Split(new char[] { '\n' });
string outPut = string.Empty;
foreach (string s in contentArr)
{
if (s != string.Empty)
{
string IPAddr = string.Empty;
string hostName = string.Empty;
if (s[0] != '#')
{
bool bSeperator = false;
foreach (char c in s)
{
if ((c != ' ') & (c != '\t'))
{
if (bSeperator)
hostName += c;
else
IPAddr += c;
}
else
bSeperator = true;
}
if (hostName.ToLower() != siteCollection.RootWebApplicationFQDN.ToLower())
{
outPut += s + "\r\n";
}
}
else
outPut += s + "\r\n";
}
}
FileUtils.UpdateFileTextContent(path, outPut);
}
}
}
catch (Exception ex)
{
HostedSolutionLog.LogError(ex);
}
}
finally
{
wic.Undo();
}
}
catch (Exception ex)
{
throw new InvalidOperationException("Failed to delete site collection.", ex);
}
}
/// <summary>
/// Backups site collection under give url.
/// </summary>
/// <param name="rootWebApplicationUri">Root web application uri.</param>
/// <param name="url">Url that uniquely identifies site collection to be deleted.</param>
/// <param name="filename">Resulting backup file name.</param>
/// <param name="zip">A value which shows whether created backup must be archived.</param>
/// <param name="tempPath">Custom temp path for backup</param>
/// <returns>Full path to created backup.</returns>
/// <exception cref="InvalidOperationException">Is thrown in case requested operation fails for any reason.</exception>
public string BackupSiteCollection(Uri rootWebApplicationUri, string url, string filename, bool zip, string tempPath)
{
try
{
WindowsImpersonationContext wic = WindowsIdentity.GetCurrent().Impersonate();
try
{
SPWebApplication rootWebApplication = SPWebApplication.Lookup(rootWebApplicationUri);
string siteCollectionUrl = String.Format("{0}:{1}", url, rootWebApplicationUri.Port);
if (String.IsNullOrEmpty(tempPath))
{
tempPath = Path.GetTempPath();
}
string backupFileName = Path.Combine(tempPath, (zip ? StringUtils.CleanIdentifier(siteCollectionUrl) + ".bsh" : StringUtils.CleanIdentifier(filename)));
// Backup requested site.
rootWebApplication.Sites.Backup(siteCollectionUrl, backupFileName, true);
if (zip)
{
string zipFile = Path.Combine(tempPath, filename);
string zipRoot = Path.GetDirectoryName(backupFileName);
FileUtils.ZipFiles(zipFile, zipRoot, new string[] { Path.GetFileName(backupFileName) });
FileUtils.DeleteFile(backupFileName);
backupFileName = zipFile;
}
return backupFileName;
}
finally
{
wic.Undo();
}
}
catch (Exception ex)
{
throw new InvalidOperationException("Failed to backup site collection.", ex);
}
}
/// <summary>
/// Restores site collection under given url from backup.
/// </summary>
/// <param name="rootWebApplicationUri">Root web application uri.</param>
/// <param name="siteCollection">Site collection to be restored.</param>
/// <param name="filename">Backup file name to restore from.</param>
/// <exception cref="InvalidOperationException">Is thrown in case requested operation fails for any reason.</exception>
public void RestoreSiteCollection(Uri rootWebApplicationUri, SharePointSiteCollection siteCollection, string filename)
{
string url = siteCollection.Url;
try
{
WindowsImpersonationContext wic = WindowsIdentity.GetCurrent().Impersonate();
try
{
SPWebApplication rootWebApplication = SPWebApplication.Lookup(rootWebApplicationUri);
string siteCollectionUrl = String.Format("{0}:{1}", url, rootWebApplicationUri.Port);
string tempPath = Path.GetTempPath();
// Unzip uploaded files if required.
string expandedFile = filename;
if (Path.GetExtension(filename).ToLower() == ".zip")
{
// Unpack file.
expandedFile = FileUtils.UnzipFiles(filename, tempPath)[0];
// Delete zip archive.
FileUtils.DeleteFile(filename);
}
// Delete existent site and restore new one.
rootWebApplication.Sites.Delete(siteCollectionUrl, false);
rootWebApplication.Sites.Restore(siteCollectionUrl, expandedFile, true, true);
SPSite restoredSite = rootWebApplication.Sites[siteCollectionUrl];
SPWeb web = restoredSite.OpenWeb();
SPUser owner = null;
try
{
owner = web.SiteUsers[siteCollection.OwnerLogin];
}
catch
{
// Ignore this error.
}
if (owner == null)
{
web.SiteUsers.Add(siteCollection.OwnerLogin, siteCollection.OwnerEmail, siteCollection.OwnerName, String.Empty);
owner = web.SiteUsers[siteCollection.OwnerLogin];
}
restoredSite.Owner = owner;
web.Close();
rootWebApplication.Update();
// Delete expanded file.
FileUtils.DeleteFile(expandedFile);
}
finally
{
wic.Undo();
}
}
catch (Exception ex)
{
throw new InvalidOperationException("Failed to restore site collection.", ex);
}
}
/// <summary>
/// Fills custom site collection with information from administration object.
/// </summary>
/// <param name="customSiteCollection">Custom site collection to fill.</param>
/// <param name="site">Administration object.</param>
private static void FillSiteCollection(SharePointSiteCollection customSiteCollection, SPSite site)
{
Uri siteUri = new Uri(site.Url);
string url = (siteUri.Port > 0) ? site.Url.Replace(String.Format(":{0}", siteUri.Port), String.Empty) : site.Url;
customSiteCollection.Url = url;
customSiteCollection.OwnerLogin = site.Owner.LoginName;
customSiteCollection.OwnerName = site.Owner.Name;
customSiteCollection.OwnerEmail = site.Owner.Email;
customSiteCollection.LocaleId = site.RootWeb.Locale.LCID;
customSiteCollection.Title = site.RootWeb.Title;
customSiteCollection.Description = site.RootWeb.Description;
customSiteCollection.Bandwidth = site.Usage.Bandwidth;
customSiteCollection.Diskspace = site.Usage.Storage;
customSiteCollection.MaxSiteStorage = site.Quota.StorageMaximumLevel;
customSiteCollection.WarningStorage = site.Quota.StorageWarningLevel;
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
namespace System {
using System;
using System.Reflection;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Globalization;
using System.Diagnostics.Contracts;
using System.Security;
using System.Security.Permissions;
[Serializable]
[AttributeUsageAttribute(AttributeTargets.All, Inherited = true, AllowMultiple=false)]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof(_Attribute))]
[System.Runtime.InteropServices.ComVisible(true)]
public abstract class Attribute : _Attribute
{
#region Private Statics
#region PropertyInfo
private static Attribute[] InternalGetCustomAttributes(PropertyInfo element, Type type, bool inherit)
{
Contract.Requires(element != null);
Contract.Requires(type != null);
Contract.Requires(type.IsSubclassOf(typeof(Attribute)) || type == typeof(Attribute));
// walk up the hierarchy chain
Attribute[] attributes = (Attribute[])element.GetCustomAttributes(type, inherit);
if (!inherit)
return attributes;
// create the hashtable that keeps track of inherited types
Dictionary<Type, AttributeUsageAttribute> types = new Dictionary<Type, AttributeUsageAttribute>(11);
// create an array list to collect all the requested attibutes
List<Attribute> attributeList = new List<Attribute>();
CopyToArrayList(attributeList, attributes, types);
//if this is an index we need to get the parameter types to help disambiguate
Type[] indexParamTypes = GetIndexParameterTypes(element);
PropertyInfo baseProp = GetParentDefinition(element, indexParamTypes);
while (baseProp != null)
{
attributes = GetCustomAttributes(baseProp, type, false);
AddAttributesToList(attributeList, attributes, types);
baseProp = GetParentDefinition(baseProp, indexParamTypes);
}
Array array = CreateAttributeArrayHelper(type, attributeList.Count);
Array.Copy(attributeList.ToArray(), 0, array, 0, attributeList.Count);
return (Attribute[])array;
}
private static bool InternalIsDefined(PropertyInfo element, Type attributeType, bool inherit)
{
// walk up the hierarchy chain
if (element.IsDefined(attributeType, inherit))
return true;
if (inherit)
{
AttributeUsageAttribute usage = InternalGetAttributeUsage(attributeType);
if (!usage.Inherited)
return false;
//if this is an index we need to get the parameter types to help disambiguate
Type[] indexParamTypes = GetIndexParameterTypes(element);
PropertyInfo baseProp = GetParentDefinition(element, indexParamTypes);
while (baseProp != null)
{
if (baseProp.IsDefined(attributeType, false))
return true;
baseProp = GetParentDefinition(baseProp, indexParamTypes);
}
}
return false;
}
private static PropertyInfo GetParentDefinition(PropertyInfo property, Type[] propertyParameters)
{
Contract.Requires(property != null);
// for the current property get the base class of the getter and the setter, they might be different
// note that this only works for RuntimeMethodInfo
MethodInfo propAccessor = property.GetGetMethod(true);
if (propAccessor == null)
propAccessor = property.GetSetMethod(true);
RuntimeMethodInfo rtPropAccessor = propAccessor as RuntimeMethodInfo;
if (rtPropAccessor != null)
{
rtPropAccessor = rtPropAccessor.GetParentDefinition();
if (rtPropAccessor != null)
{
#if FEATURE_LEGACYNETCF
// Mimicing NetCF which only looks for public properties.
if (CompatibilitySwitches.IsAppEarlierThanWindowsPhone8)
return rtPropAccessor.DeclaringType.GetProperty(property.Name, property.PropertyType);
#endif //FEATURE_LEGACYNETCF
// There is a public overload of Type.GetProperty that takes both a BingingFlags enum and a return type.
// However, we cannot use that because it doesn't accept null for "types".
return rtPropAccessor.DeclaringType.GetProperty(
property.Name,
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly,
null, //will use default binder
property.PropertyType,
propertyParameters, //used for index properties
null);
}
}
return null;
}
#endregion
#region EventInfo
private static Attribute[] InternalGetCustomAttributes(EventInfo element, Type type, bool inherit)
{
Contract.Requires(element != null);
Contract.Requires(type != null);
Contract.Requires(type.IsSubclassOf(typeof(Attribute)) || type == typeof(Attribute));
// walk up the hierarchy chain
Attribute[] attributes = (Attribute[])element.GetCustomAttributes(type, inherit);
if (inherit)
{
// create the hashtable that keeps track of inherited types
Dictionary<Type, AttributeUsageAttribute> types = new Dictionary<Type, AttributeUsageAttribute>(11);
// create an array list to collect all the requested attibutes
List<Attribute> attributeList = new List<Attribute>();
CopyToArrayList(attributeList, attributes, types);
EventInfo baseEvent = GetParentDefinition(element);
while (baseEvent != null)
{
attributes = GetCustomAttributes(baseEvent, type, false);
AddAttributesToList(attributeList, attributes, types);
baseEvent = GetParentDefinition(baseEvent);
}
Array array = CreateAttributeArrayHelper(type, attributeList.Count);
Array.Copy(attributeList.ToArray(), 0, array, 0, attributeList.Count);
return (Attribute[])array;
}
else
return attributes;
}
private static EventInfo GetParentDefinition(EventInfo ev)
{
Contract.Requires(ev != null);
// note that this only works for RuntimeMethodInfo
MethodInfo add = ev.GetAddMethod(true);
RuntimeMethodInfo rtAdd = add as RuntimeMethodInfo;
if (rtAdd != null)
{
rtAdd = rtAdd.GetParentDefinition();
if (rtAdd != null)
return rtAdd.DeclaringType.GetEvent(ev.Name);
}
return null;
}
private static bool InternalIsDefined (EventInfo element, Type attributeType, bool inherit)
{
Contract.Requires(element != null);
// walk up the hierarchy chain
if (element.IsDefined(attributeType, inherit))
return true;
if (inherit)
{
AttributeUsageAttribute usage = InternalGetAttributeUsage(attributeType);
if (!usage.Inherited)
return false;
EventInfo baseEvent = GetParentDefinition(element);
while (baseEvent != null)
{
if (baseEvent.IsDefined(attributeType, false))
return true;
baseEvent = GetParentDefinition(baseEvent);
}
}
return false;
}
#endregion
#region ParameterInfo
private static ParameterInfo GetParentDefinition(ParameterInfo param)
{
Contract.Requires(param != null);
// note that this only works for RuntimeMethodInfo
RuntimeMethodInfo rtMethod = param.Member as RuntimeMethodInfo;
if (rtMethod != null)
{
rtMethod = rtMethod.GetParentDefinition();
if (rtMethod != null)
{
// Find the ParameterInfo on this method
ParameterInfo[] parameters = rtMethod.GetParameters();
return parameters[param.Position]; // Point to the correct ParameterInfo of the method
}
}
return null;
}
private static Attribute[] InternalParamGetCustomAttributes(ParameterInfo param, Type type, bool inherit)
{
Contract.Requires(param != null);
// For ParameterInfo's we need to make sure that we chain through all the MethodInfo's in the inheritance chain that
// have this ParameterInfo defined. .We pick up all the CustomAttributes for the starting ParameterInfo. We need to pick up only attributes
// that are marked inherited from the remainder of the MethodInfo's in the inheritance chain.
// For MethodInfo's on an interface we do not do an inheritance walk so the default ParameterInfo attributes are returned.
// For MethodInfo's on a class we walk up the inheritance chain but do not look at the MethodInfo's on the interfaces that the
// class inherits from and return the respective ParameterInfo attributes
List<Type> disAllowMultiple = new List<Type>();
Object [] objAttr;
if (type == null)
type = typeof(Attribute);
objAttr = param.GetCustomAttributes(type, false);
for (int i =0;i < objAttr.Length;i++)
{
Type objType = objAttr[i].GetType();
AttributeUsageAttribute attribUsage = InternalGetAttributeUsage(objType);
if (attribUsage.AllowMultiple == false)
disAllowMultiple.Add(objType);
}
// Get all the attributes that have Attribute as the base class
Attribute [] ret = null;
if (objAttr.Length == 0)
ret = CreateAttributeArrayHelper(type,0);
else
ret = (Attribute[])objAttr;
if (param.Member.DeclaringType == null) // This is an interface so we are done.
return ret;
if (!inherit)
return ret;
ParameterInfo baseParam = GetParentDefinition(param);
while (baseParam != null)
{
objAttr = baseParam.GetCustomAttributes(type, false);
int count = 0;
for (int i =0;i < objAttr.Length;i++)
{
Type objType = objAttr[i].GetType();
AttributeUsageAttribute attribUsage = InternalGetAttributeUsage(objType);
if ((attribUsage.Inherited) && (disAllowMultiple.Contains(objType) == false))
{
if (attribUsage.AllowMultiple == false)
disAllowMultiple.Add(objType);
count++;
}
else
objAttr[i] = null;
}
// Get all the attributes that have Attribute as the base class
Attribute [] attributes = CreateAttributeArrayHelper(type,count);
count = 0;
for (int i =0;i < objAttr.Length;i++)
{
if (objAttr[i] != null)
{
attributes[count] = (Attribute)objAttr[i];
count++;
}
}
Attribute [] temp = ret;
ret = CreateAttributeArrayHelper(type,temp.Length + count);
Array.Copy(temp,ret,temp.Length);
int offset = temp.Length;
for (int i =0;i < attributes.Length;i++)
ret[offset + i] = attributes[i];
baseParam = GetParentDefinition(baseParam);
}
return ret;
}
private static bool InternalParamIsDefined(ParameterInfo param, Type type, bool inherit)
{
Contract.Requires(param != null);
Contract.Requires(type != null);
// For ParameterInfo's we need to make sure that we chain through all the MethodInfo's in the inheritance chain.
// We pick up all the CustomAttributes for the starting ParameterInfo. We need to pick up only attributes
// that are marked inherited from the remainder of the ParameterInfo's in the inheritance chain.
// For MethodInfo's on an interface we do not do an inheritance walk. For ParameterInfo's on a
// Class we walk up the inheritance chain but do not look at the MethodInfo's on the interfaces that the class inherits from.
if (param.IsDefined(type, false))
return true;
if (param.Member.DeclaringType == null || !inherit) // This is an interface so we are done.
return false;
ParameterInfo baseParam = GetParentDefinition(param);
while (baseParam != null)
{
Object[] objAttr = baseParam.GetCustomAttributes(type, false);
for (int i =0; i < objAttr.Length; i++)
{
Type objType = objAttr[i].GetType();
AttributeUsageAttribute attribUsage = InternalGetAttributeUsage(objType);
if ((objAttr[i] is Attribute) && (attribUsage.Inherited))
return true;
}
baseParam = GetParentDefinition(baseParam);
}
return false;
}
#endregion
#region Utility
private static void CopyToArrayList(List<Attribute> attributeList,Attribute[] attributes,Dictionary<Type, AttributeUsageAttribute> types)
{
for (int i = 0; i < attributes.Length; i++)
{
attributeList.Add(attributes[i]);
Type attrType = attributes[i].GetType();
if (!types.ContainsKey(attrType))
types[attrType] = InternalGetAttributeUsage(attrType);
}
}
private static Type[] GetIndexParameterTypes(PropertyInfo element)
{
ParameterInfo[] indexParams = element.GetIndexParameters();
if (indexParams.Length > 0)
{
Type[] indexParamTypes = new Type[indexParams.Length];
for (int i = 0; i < indexParams.Length; i++)
{
indexParamTypes[i] = indexParams[i].ParameterType;
}
return indexParamTypes;
}
return Array.Empty<Type>();
}
private static void AddAttributesToList(List<Attribute> attributeList, Attribute[] attributes, Dictionary<Type, AttributeUsageAttribute> types)
{
for (int i = 0; i < attributes.Length; i++)
{
Type attrType = attributes[i].GetType();
AttributeUsageAttribute usage = null;
types.TryGetValue(attrType, out usage);
if (usage == null)
{
// the type has never been seen before if it's inheritable add it to the list
usage = InternalGetAttributeUsage(attrType);
types[attrType] = usage;
if (usage.Inherited)
attributeList.Add(attributes[i]);
}
else if (usage.Inherited && usage.AllowMultiple)
{
// we saw this type already add it only if it is inheritable and it does allow multiple
attributeList.Add(attributes[i]);
}
}
}
private static AttributeUsageAttribute InternalGetAttributeUsage(Type type)
{
// Check if the custom attributes is Inheritable
Object [] obj = type.GetCustomAttributes(typeof(AttributeUsageAttribute), false);
if (obj.Length == 1)
return (AttributeUsageAttribute)obj[0];
if (obj.Length == 0)
return AttributeUsageAttribute.Default;
throw new FormatException(
Environment.GetResourceString("Format_AttributeUsage", type));
}
[System.Security.SecuritySafeCritical]
private static Attribute[] CreateAttributeArrayHelper(Type elementType, int elementCount)
{
return (Attribute[])Array.UnsafeCreateInstance(elementType, elementCount);
}
#endregion
#endregion
#region Public Statics
#region MemberInfo
public static Attribute[] GetCustomAttributes(MemberInfo element, Type type)
{
return GetCustomAttributes(element, type, true);
}
public static Attribute[] GetCustomAttributes(MemberInfo element, Type type, bool inherit)
{
if (element == null)
throw new ArgumentNullException("element");
if (type == null)
throw new ArgumentNullException("type");
if (!type.IsSubclassOf(typeof(Attribute)) && type != typeof(Attribute))
throw new ArgumentException(Environment.GetResourceString("Argument_MustHaveAttributeBaseClass"));
Contract.EndContractBlock();
switch (element.MemberType)
{
case MemberTypes.Property:
return InternalGetCustomAttributes((PropertyInfo)element, type, inherit);
case MemberTypes.Event:
return InternalGetCustomAttributes((EventInfo)element, type, inherit);
default:
return element.GetCustomAttributes(type, inherit) as Attribute[];
}
}
public static Attribute[] GetCustomAttributes(MemberInfo element)
{
return GetCustomAttributes(element, true);
}
public static Attribute[] GetCustomAttributes(MemberInfo element, bool inherit)
{
if (element == null)
throw new ArgumentNullException("element");
Contract.EndContractBlock();
switch (element.MemberType)
{
case MemberTypes.Property:
return InternalGetCustomAttributes((PropertyInfo)element, typeof(Attribute), inherit);
case MemberTypes.Event:
return InternalGetCustomAttributes((EventInfo)element, typeof(Attribute), inherit);
default:
return element.GetCustomAttributes(typeof(Attribute), inherit) as Attribute[];
}
}
public static bool IsDefined(MemberInfo element, Type attributeType)
{
return IsDefined(element, attributeType, true);
}
public static bool IsDefined(MemberInfo element, Type attributeType, bool inherit)
{
// Returns true if a custom attribute subclass of attributeType class/interface with inheritance walk
if (element == null)
throw new ArgumentNullException("element");
if (attributeType == null)
throw new ArgumentNullException("attributeType");
if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute))
throw new ArgumentException(Environment.GetResourceString("Argument_MustHaveAttributeBaseClass"));
Contract.EndContractBlock();
switch(element.MemberType)
{
case MemberTypes.Property:
return InternalIsDefined((PropertyInfo)element, attributeType, inherit);
case MemberTypes.Event:
return InternalIsDefined((EventInfo)element, attributeType, inherit);
default:
return element.IsDefined(attributeType, inherit);
}
}
public static Attribute GetCustomAttribute(MemberInfo element, Type attributeType)
{
return GetCustomAttribute(element, attributeType, true);
}
public static Attribute GetCustomAttribute(MemberInfo element, Type attributeType, bool inherit)
{
Attribute[] attrib = GetCustomAttributes(element, attributeType, inherit);
if (attrib == null || attrib.Length == 0)
return null;
if (attrib.Length == 1)
return attrib[0];
throw new AmbiguousMatchException(Environment.GetResourceString("RFLCT.AmbigCust"));
}
#endregion
#region ParameterInfo
public static Attribute[] GetCustomAttributes(ParameterInfo element)
{
return GetCustomAttributes(element, true);
}
public static Attribute[] GetCustomAttributes(ParameterInfo element, Type attributeType)
{
return (Attribute[])GetCustomAttributes(element, attributeType, true);
}
public static Attribute[] GetCustomAttributes(ParameterInfo element, Type attributeType, bool inherit)
{
if (element == null)
throw new ArgumentNullException("element");
if (attributeType == null)
throw new ArgumentNullException("attributeType");
if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute))
throw new ArgumentException(Environment.GetResourceString("Argument_MustHaveAttributeBaseClass"));
if (element.Member == null)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidParameterInfo"), "element");
Contract.EndContractBlock();
MemberInfo member = element.Member;
if (member.MemberType == MemberTypes.Method && inherit)
return InternalParamGetCustomAttributes(element, attributeType, inherit) as Attribute[];
return element.GetCustomAttributes(attributeType, inherit) as Attribute[];
}
public static Attribute[] GetCustomAttributes(ParameterInfo element, bool inherit)
{
if (element == null)
throw new ArgumentNullException("element");
if (element.Member == null)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidParameterInfo"), "element");
Contract.EndContractBlock();
MemberInfo member = element.Member;
if (member.MemberType == MemberTypes.Method && inherit)
return InternalParamGetCustomAttributes(element, null, inherit) as Attribute[];
return element.GetCustomAttributes(typeof(Attribute), inherit) as Attribute[];
}
public static bool IsDefined(ParameterInfo element, Type attributeType)
{
return IsDefined(element, attributeType, true);
}
public static bool IsDefined(ParameterInfo element, Type attributeType, bool inherit)
{
// Returns true is a custom attribute subclass of attributeType class/interface with inheritance walk
if (element == null)
throw new ArgumentNullException("element");
if (attributeType == null)
throw new ArgumentNullException("attributeType");
if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute))
throw new ArgumentException(Environment.GetResourceString("Argument_MustHaveAttributeBaseClass"));
Contract.EndContractBlock();
MemberInfo member = element.Member;
switch(member.MemberType)
{
case MemberTypes.Method: // We need to climb up the member hierarchy
return InternalParamIsDefined(element, attributeType, inherit);
case MemberTypes.Constructor:
return element.IsDefined(attributeType, false);
case MemberTypes.Property:
return element.IsDefined(attributeType, false);
default:
Contract.Assert(false, "Invalid type for ParameterInfo member in Attribute class");
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidParamInfo"));
}
}
public static Attribute GetCustomAttribute(ParameterInfo element, Type attributeType)
{
return GetCustomAttribute(element, attributeType, true);
}
public static Attribute GetCustomAttribute(ParameterInfo element, Type attributeType, bool inherit)
{
// Returns an Attribute of base class/inteface attributeType on the ParameterInfo or null if none exists.
// throws an AmbiguousMatchException if there are more than one defined.
Attribute[] attrib = GetCustomAttributes(element, attributeType, inherit);
if (attrib == null || attrib.Length == 0)
return null;
if (attrib.Length == 0)
return null;
if (attrib.Length == 1)
return attrib[0];
throw new AmbiguousMatchException(Environment.GetResourceString("RFLCT.AmbigCust"));
}
#endregion
#region Module
public static Attribute[] GetCustomAttributes(Module element, Type attributeType)
{
return GetCustomAttributes (element, attributeType, true);
}
public static Attribute[] GetCustomAttributes(Module element)
{
return GetCustomAttributes(element, true);
}
public static Attribute[] GetCustomAttributes(Module element, bool inherit)
{
if (element == null)
throw new ArgumentNullException("element");
Contract.EndContractBlock();
return (Attribute[])element.GetCustomAttributes(typeof(Attribute), inherit);
}
public static Attribute[] GetCustomAttributes(Module element, Type attributeType, bool inherit)
{
if (element == null)
throw new ArgumentNullException("element");
if (attributeType == null)
throw new ArgumentNullException("attributeType");
if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute))
throw new ArgumentException(Environment.GetResourceString("Argument_MustHaveAttributeBaseClass"));
Contract.EndContractBlock();
return (Attribute[])element.GetCustomAttributes(attributeType, inherit);
}
public static bool IsDefined(Module element, Type attributeType)
{
return IsDefined(element, attributeType, false);
}
public static bool IsDefined(Module element, Type attributeType, bool inherit)
{
// Returns true is a custom attribute subclass of attributeType class/interface with no inheritance walk
if (element == null)
throw new ArgumentNullException("element");
if (attributeType == null)
throw new ArgumentNullException("attributeType");
if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute))
throw new ArgumentException(Environment.GetResourceString("Argument_MustHaveAttributeBaseClass"));
Contract.EndContractBlock();
return element.IsDefined(attributeType,false);
}
public static Attribute GetCustomAttribute(Module element, Type attributeType)
{
return GetCustomAttribute(element, attributeType, true);
}
public static Attribute GetCustomAttribute(Module element, Type attributeType, bool inherit)
{
// Returns an Attribute of base class/inteface attributeType on the Module or null if none exists.
// throws an AmbiguousMatchException if there are more than one defined.
Attribute[] attrib = GetCustomAttributes(element,attributeType,inherit);
if (attrib == null || attrib.Length == 0)
return null;
if (attrib.Length == 1)
return attrib[0];
throw new AmbiguousMatchException(Environment.GetResourceString("RFLCT.AmbigCust"));
}
#endregion
#region Assembly
public static Attribute[] GetCustomAttributes(Assembly element, Type attributeType)
{
return GetCustomAttributes(element, attributeType, true);
}
public static Attribute[] GetCustomAttributes(Assembly element, Type attributeType, bool inherit)
{
if (element == null)
throw new ArgumentNullException("element");
if (attributeType == null)
throw new ArgumentNullException("attributeType");
if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute))
throw new ArgumentException(Environment.GetResourceString("Argument_MustHaveAttributeBaseClass"));
Contract.EndContractBlock();
return (Attribute[])element.GetCustomAttributes(attributeType, inherit);
}
public static Attribute[] GetCustomAttributes(Assembly element)
{
return GetCustomAttributes(element, true);
}
public static Attribute[] GetCustomAttributes(Assembly element, bool inherit)
{
if (element == null)
throw new ArgumentNullException("element");
Contract.EndContractBlock();
return (Attribute[])element.GetCustomAttributes(typeof(Attribute), inherit);
}
public static bool IsDefined (Assembly element, Type attributeType)
{
return IsDefined (element, attributeType, true);
}
public static bool IsDefined (Assembly element, Type attributeType, bool inherit)
{
// Returns true is a custom attribute subclass of attributeType class/interface with no inheritance walk
if (element == null)
throw new ArgumentNullException("element");
if (attributeType == null)
throw new ArgumentNullException("attributeType");
if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute))
throw new ArgumentException(Environment.GetResourceString("Argument_MustHaveAttributeBaseClass"));
Contract.EndContractBlock();
return element.IsDefined(attributeType, false);
}
public static Attribute GetCustomAttribute(Assembly element, Type attributeType)
{
return GetCustomAttribute (element, attributeType, true);
}
public static Attribute GetCustomAttribute(Assembly element, Type attributeType, bool inherit)
{
// Returns an Attribute of base class/inteface attributeType on the Assembly or null if none exists.
// throws an AmbiguousMatchException if there are more than one defined.
Attribute[] attrib = GetCustomAttributes(element,attributeType,inherit);
if (attrib == null || attrib.Length == 0)
return null;
if (attrib.Length == 1)
return attrib[0];
throw new AmbiguousMatchException(Environment.GetResourceString("RFLCT.AmbigCust"));
}
#endregion
#endregion
#region Constructor
protected Attribute() { }
#endregion
#region Object Overrides
[SecuritySafeCritical]
public override bool Equals(Object obj)
{
if (obj == null)
return false;
RuntimeType thisType = (RuntimeType)this.GetType();
RuntimeType thatType = (RuntimeType)obj.GetType();
if (thatType != thisType)
return false;
Object thisObj = this;
Object thisResult, thatResult;
FieldInfo[] thisFields = thisType.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
for (int i = 0; i < thisFields.Length; i++)
{
// Visibility check and consistency check are not necessary.
thisResult = ((RtFieldInfo)thisFields[i]).UnsafeGetValue(thisObj);
thatResult = ((RtFieldInfo)thisFields[i]).UnsafeGetValue(obj);
if (!AreFieldValuesEqual(thisResult, thatResult))
{
return false;
}
}
return true;
}
// Compares values of custom-attribute fields.
private static bool AreFieldValuesEqual(Object thisValue, Object thatValue)
{
if (thisValue == null && thatValue == null)
return true;
if (thisValue == null || thatValue == null)
return false;
if (thisValue.GetType().IsArray)
{
// Ensure both are arrays of the same type.
if (!thisValue.GetType().Equals(thatValue.GetType()))
{
return false;
}
Array thisValueArray = thisValue as Array;
Array thatValueArray = thatValue as Array;
if (thisValueArray.Length != thatValueArray.Length)
{
return false;
}
// Attributes can only contain single-dimension arrays, so we don't need to worry about
// multidimensional arrays.
Contract.Assert(thisValueArray.Rank == 1 && thatValueArray.Rank == 1);
for (int j = 0; j < thisValueArray.Length; j++)
{
if (!AreFieldValuesEqual(thisValueArray.GetValue(j), thatValueArray.GetValue(j)))
{
return false;
}
}
}
else
{
// An object of type Attribute will cause a stack overflow.
// However, this should never happen because custom attributes cannot contain values other than
// constants, single-dimensional arrays and typeof expressions.
Contract.Assert(!(thisValue is Attribute));
if (!thisValue.Equals(thatValue))
return false;
}
return true;
}
[SecuritySafeCritical]
public override int GetHashCode()
{
Type type = GetType();
FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
Object vThis = null;
for (int i = 0; i < fields.Length; i++)
{
// Visibility check and consistency check are not necessary.
Object fieldValue = ((RtFieldInfo)fields[i]).UnsafeGetValue(this);
// The hashcode of an array ignores the contents of the array, so it can produce
// different hashcodes for arrays with the same contents.
// Since we do deep comparisons of arrays in Equals(), this means Equals and GetHashCode will
// be inconsistent for arrays. Therefore, we ignore hashes of arrays.
if (fieldValue != null && !fieldValue.GetType().IsArray)
vThis = fieldValue;
if (vThis != null)
break;
}
if (vThis != null)
return vThis.GetHashCode();
return type.GetHashCode();
}
#endregion
#region Public Virtual Members
public virtual Object TypeId { get { return GetType(); } }
public virtual bool Match(Object obj) { return Equals(obj); }
#endregion
#region Public Members
public virtual bool IsDefaultAttribute() { return false; }
#endregion
#if !FEATURE_CORECLR
void _Attribute.GetTypeInfoCount(out uint pcTInfo)
{
throw new NotImplementedException();
}
void _Attribute.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
{
throw new NotImplementedException();
}
void _Attribute.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
{
throw new NotImplementedException();
}
void _Attribute.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
{
throw new NotImplementedException();
}
#endif
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
namespace System.IO.Tests
{
public partial class PathTests_Windows : PathTestsBase
{
[Theory,
MemberData(nameof(TestData_GetPathRoot_Windows)),
MemberData(nameof(TestData_GetPathRoot_Unc)),
MemberData(nameof(TestData_GetPathRoot_DevicePaths))]
public void GetPathRoot_Span(string value, string expected)
{
Assert.Equal(expected, new string(Path.GetPathRoot(value.AsSpan())));
Assert.True(Path.IsPathRooted(value.AsSpan()));
}
[Theory, MemberData(nameof(TestData_UnicodeWhiteSpace))]
public void GetFullPath_UnicodeWhiteSpaceStays(string component)
{
// When not NetFX full path should not cut off component
string path = "C:\\Test" + component;
Assert.Equal(path, Path.GetFullPath(path));
}
[Theory, MemberData(nameof(TestData_Periods))]
public void GetFullPath_TrailingPeriodsCut(string component)
{
// Windows cuts off any simple white space added to a path
string path = "C:\\Test" + component;
Assert.Equal("C:\\Test", Path.GetFullPath(path));
}
public static TheoryData<string, string, string> GetFullPath_Windows_FullyQualified => new TheoryData<string, string, string>
{
{ @"C:\git\corefx", @"C:\git\corefx", @"C:\git\corefx" },
{ @"C:\git\corefx.\.\.\.\.\.", @"C:\git\corefx", @"C:\git\corefx" },
{ @"C:\git\corefx\\\.", @"C:\git\corefx", @"C:\git\corefx" },
{ @"C:\git\corefx\..\corefx\.\..\corefx", @"C:\git\corefx", @"C:\git\corefx" },
{ @"C:\somedir\..", @"C:\git\corefx", @"C:\" },
{ @"C:\", @"C:\git\corefx", @"C:\" },
{ @"..\..\..\..", @"C:\git\corefx", @"C:\" },
{ @"C:\\\", @"C:\git\corefx", @"C:\" },
{ @"C:\..\..\", @"C:\git\corefx", @"C:\" },
{ @"C:\..\git\..\.\", @"C:\git\corefx", @"C:\" },
{ @"C:\git\corefx\..\..\..\", @"C:\git\corefx", @"C:\" },
{ @"C:\.\corefx\", @"C:\git\corefx", @"C:\corefx\" },
};
[Theory,
MemberData(nameof(GetFullPath_Windows_FullyQualified))]
public void GetFullPath_BasicExpansions_Windows(string path, string basePath, string expected)
{
Assert.Equal(expected, Path.GetFullPath(path, basePath));
}
public static TheoryData<string, string, string> GetFullPath_Windows_PathIsDevicePath => new TheoryData<string, string, string>
{
// Device Paths with \\?\ wont get normalized i.e. relative segments wont get removed.
{ @"\\?\C:\git\corefx.\.\.\.\.\.", @"C:\git\corefx", @"\\?\C:\git\corefx.\.\.\.\.\." },
{ @"\\?\C:\git\corefx\\\.", @"C:\git\corefx", @"\\?\C:\git\corefx\\\." },
{ @"\\?\C:\git\corefx\..\corefx\.\..\corefx", @"C:\git\corefx", @"\\?\C:\git\corefx\..\corefx\.\..\corefx" },
{ @"\\?\\somedir\..", @"C:\git\corefx", @"\\?\\somedir\.." },
{ @"\\?\", @"C:\git\corefx", @"\\?\" },
{ @"\\?\..\..\..\..", @"C:\git\corefx", @"\\?\..\..\..\.." },
{ @"\\?\\\\" , @"C:\git\corefx", @"\\?\\\\" },
{ @"\\?\C:\Foo." , @"C:\git\corefx", @"\\?\C:\Foo." },
{ @"\\?\C:\Foo " , @"C:\git\corefx", @"\\?\C:\Foo " },
{ @"\\.\C:\git\corefx.\.\.\.\.\.", @"C:\git\corefx", @"\\.\C:\git\corefx" },
{ @"\\.\C:\git\corefx\\\.", @"C:\git\corefx", @"\\.\C:\git\corefx" },
{ @"\\.\C:\git\corefx\..\corefx\.\..\corefx", @"C:\git\corefx", @"\\.\C:\git\corefx" },
{ @"\\.\\somedir\..", @"C:\git\corefx", @"\\.\" },
{ @"\\.\", @"C:\git\corefx", @"\\.\" },
{ @"\\.\..\..\..\..", @"C:\git\corefx", @"\\.\" },
{ @"\\.\", @"C:\git\corefx", @"\\.\" },
{ @"\\.\C:\Foo." , @"C:\git\corefx", @"\\.\C:\Foo" },
{ @"\\.\C:\Foo " , @"C:\git\corefx", @"\\.\C:\Foo" },
};
[Theory,
MemberData(nameof(GetFullPath_Windows_PathIsDevicePath))]
public void GetFullPath_BasicExpansions_Windows_PathIsDevicePath(string path, string basePath, string expected)
{
Assert.Equal(expected, Path.GetFullPath(path, basePath));
Assert.Equal(expected, Path.GetFullPath(path, @"\\.\" + basePath));
Assert.Equal(expected, Path.GetFullPath(path, @"\\?\" + basePath));
}
public static TheoryData<string, string, string> GetFullPath_Windows_UNC => new TheoryData<string, string, string>
{
{ @"foo", @"", @"foo" },
{ @"foo", @"server1", @"server1\foo" },
{ @"\foo", @"server2", @"server2\foo" },
{ @"foo", @"server3\", @"server3\foo" },
{ @"..\foo", @"server4", @"server4\..\foo" },
{ @".\foo", @"server5\share", @"server5\share\foo" },
{ @"..\foo", @"server6\share", @"server6\share\foo" },
{ @"\foo", @"a\b\\", @"a\b\foo" },
{ @"foo", @"LOCALHOST\share8\test.txt.~SS", @"LOCALHOST\share8\test.txt.~SS\foo" },
{ @"foo", @"LOCALHOST\share9", @"LOCALHOST\share9\foo" },
{ @"foo", @"LOCALHOST\shareA\dir", @"LOCALHOST\shareA\dir\foo" },
{ @". \foo", @"LOCALHOST\shareB\", @"LOCALHOST\shareB\. \foo" },
{ @".. \foo", @"LOCALHOST\shareC\", @"LOCALHOST\shareC\.. \foo" },
{ @" \foo", @"LOCALHOST\shareD\", @"LOCALHOST\shareD\ \foo" },
{ "foo", @"LOCALHOST\ shareE\", @"LOCALHOST\ shareE\foo" },
{ "foo", @"LOCALHOST\shareF\test.txt.~SS", @"LOCALHOST\shareF\test.txt.~SS\foo" },
{ "foo", @"LOCALHOST\shareG", @"LOCALHOST\shareG\foo" },
{ "foo", @"LOCALHOST\shareH\dir", @"LOCALHOST\shareH\dir\foo" },
{ "foo", @"LOCALHOST\shareK\", @"LOCALHOST\shareK\foo" },
{ "foo", @"LOCALHOST\ shareL\", @"LOCALHOST\ shareL\foo" },
// Relative segments eating into the root
{ @".\..\foo\..\", @"server\share", @"server\share\" },
{ @"..\foo\tmp\..\..\", @"server\share", @"server\share\" },
{ @"..\..\..\foo", @"server\share", @"server\share\foo" },
{ @"..\foo\..\..\tmp", @"server\share", @"server\share\tmp" },
{ @"..\foo", @"server\share", @"server\share\foo" },
{ @"...\\foo", @"server\share", @"server\share\...\foo" },
{ @"...\..\.\foo", @"server\share", @"server\share\foo" },
{ @"..\foo\tmp\..\..\..\..\..\", @"server\share", @"server\share\" },
{ @"..\..\..\..\foo", @"server\share", @"server\share\foo" },
};
[Theory,
MemberData(nameof(GetFullPath_Windows_UNC))]
public void GetFullPath_CommonUnc_Windows(string path, string basePath, string expected)
{
Assert.Equal(@"\\" + expected, Path.GetFullPath(path, @"\\" + basePath));
Assert.Equal(@"\\.\UNC\" + expected, Path.GetFullPath(path, @"\\.\UNC\" + basePath));
Assert.Equal(@"\\?\UNC\" + expected, Path.GetFullPath(path, @"\\?\UNC\" + basePath));
}
public static TheoryData<string, string, string> GetFullPath_Windows_CommonDevicePaths => new TheoryData<string, string, string>
{
// Device paths
{ "foo", @"C:\ ", @"C:\ \foo" },
{ @" \ \foo", @"C:\", @"C:\ \ \foo" },
{ @" .\foo", @"C:\", @"C:\ .\foo" },
{ @" ..\foo", @"C:\", @"C:\ ..\foo" },
{ @"...\foo", @"C:\", @"C:\...\foo" },
{ @"foo", @"C:\\", @"C:\foo" },
{ @"foo.", @"C:\\", @"C:\foo." },
{ @"foo \git", @"C:\\", @"C:\foo \git" },
{ @"foo. \git", @"C:\\", @"C:\foo. \git" },
{ @" foo \git", @"C:\\", @"C:\ foo \git" },
{ @"foo ", @"C:\\", @"C:\foo " },
{ @"|\foo", @"C:\", @"C:\|\foo" },
{ @".\foo", @"C:\", @"C:\foo" },
{ @"..\foo", @"C:\", @"C:\foo" },
{ @"\Foo1\.\foo", @"C:\", @"C:\Foo1\foo" },
{ @"\Foo2\..\foo", @"C:\", @"C:\foo" },
{ @"foo", @"GLOBALROOT\", @"GLOBALROOT\foo" },
{ @"foo", @"", @"foo" },
{ @".\foo", @"", @".\foo" },
{ @"..\foo", @"", @"..\foo" },
{ @"C:", @"", @"C:\"},
// Relative segments eating into the root
{ @"foo", @"GLOBALROOT\", @"GLOBALROOT\foo" },
{ @"..\..\foo\..\..\", @"", @"..\" },
{ @".\..\..\..\..\foo", @"", @".\foo" },
{ @"..\foo\..\..\..\", @"", @"..\" },
{ @"\.\.\..\", @"C:\", @"C:\"},
{ @"..\..\..\foo", @"GLOBALROOT\", @"GLOBALROOT\foo" },
{ @"foo\..\..\", @"", @"foo\" },
{ @".\.\foo\..\", @"", @".\" },
};
[Theory,
MemberData(nameof(GetFullPath_Windows_CommonDevicePaths))]
public void GetFullPath_CommonDevice_Windows(string path, string basePath, string expected)
{
Assert.Equal(@"\\.\" + expected, Path.GetFullPath(path, @"\\.\" + basePath));
Assert.Equal(@"\\?\" + expected, Path.GetFullPath(path, @"\\?\" + basePath));
}
public static TheoryData<string, string, string> GetFullPath_CommonRootedWindowsData => new TheoryData<string, string, string>
{
{ "", @"C:\git\corefx", @"C:\git\corefx" },
{ "..", @"C:\git\corefx", @"C:\git" },
// Current drive rooted
{ @"\tmp\bar", @"C:\git\corefx", @"C:\tmp\bar" },
{ @"\.\bar", @"C:\git\corefx", @"C:\bar" },
{ @"\tmp\..", @"C:\git\corefx", @"C:\" },
{ @"\tmp\bar\..", @"C:\git\corefx", @"C:\tmp" },
{ @"\tmp\bar\..", @"C:\git\corefx", @"C:\tmp" },
{ @"\", @"C:\git\corefx", @"C:\" },
{ @"..\..\tmp\bar", @"C:\git\corefx", @"C:\tmp\bar" },
{ @"..\..\.\bar", @"C:\git\corefx", @"C:\bar" },
{ @"..\..\..\..\tmp\..", @"C:\git\corefx", @"C:\" },
{ @"\tmp\..\bar..\..\..", @"C:\git\corefx", @"C:\" },
{ @"\tmp\..\bar\..", @"C:\git\corefx", @"C:\" },
{ @"\.\.\..\..\", @"C:\git\corefx", @"C:\" },
// Specific drive rooted
{ @"C:tmp\foo\..", @"C:\git\corefx", @"C:\git\corefx\tmp" },
{ @"C:tmp\foo\.", @"C:\git\corefx", @"C:\git\corefx\tmp\foo" },
{ @"C:tmp\foo\..", @"C:\git\corefx", @"C:\git\corefx\tmp" },
{ @"C:tmp", @"C:\git\corefx", @"C:\git\corefx\tmp" },
{ @"C:", @"C:\git\corefx", @"C:\git\corefx" },
{ @"C", @"C:\git\corefx", @"C:\git\corefx\C" },
{ @"Z:tmp\foo\..", @"C:\git\corefx", @"Z:\tmp" },
{ @"Z:tmp\foo\.", @"C:\git\corefx", @"Z:\tmp\foo" },
{ @"Z:tmp\foo\..", @"C:\git\corefx", @"Z:\tmp" },
{ @"Z:tmp", @"C:\git\corefx", @"Z:\tmp" },
{ @"Z:", @"C:\git\corefx", @"Z:\" },
{ @"Z", @"C:\git\corefx", @"C:\git\corefx\Z" },
// Relative segments eating into the root
{ @"C:..\..\..\tmp\foo\..", @"C:\git\corefx", @"C:\tmp" },
{ @"C:tmp\..\..\foo\.", @"C:\git\corefx", @"C:\git\foo" },
{ @"C:..\..\tmp\foo\..", @"C:\git\corefx", @"C:\tmp" },
{ @"C:tmp\..\", @"C:\git\corefx", @"C:\git\corefx\" },
{ @"C:", @"C:\git\corefx", @"C:\git\corefx" },
{ @"C", @"C:\git\corefx", @"C:\git\corefx\C" },
{ @"C:tmp\..\..\..\..\foo\..", @"C:\git\corefx", @"C:\" },
{ @"C:tmp\..\..\foo\.", @"C:\", @"C:\foo" },
{ @"C:..\..\tmp\..\foo\..", @"C:\", @"C:\" },
{ @"C:tmp\..\", @"C:\", @"C:\" },
{ @"Z:tmp\foo\..", @"C:\git\corefx", @"Z:\tmp" },
{ @"Z:tmp\foo\.", @"C:\git\corefx", @"Z:\tmp\foo" },
{ @"Z:tmp\foo\..", @"C:\git\corefx", @"Z:\tmp" },
{ @"Z:tmp", @"C:\git\corefx", @"Z:\tmp" },
{ @"Z:", @"C:\git\corefx", @"Z:\" },
{ @"Z", @"C:\git\corefx", @"C:\git\corefx\Z" },
{ @"Z:..\..\..\tmp\foo\..", @"C:\git\corefx", @"Z:\tmp" },
{ @"Z:tmp\..\..\foo\.", @"C:\git\corefx", @"Z:\foo" },
{ @"Z:..\..\tmp\foo\..", @"C:\git\corefx", @"Z:\tmp" },
{ @"Z:tmp\..\", @"C:\git\corefx", @"Z:\" },
{ @"Z:", @"C:\git\corefx", @"Z:\" },
{ @"Z", @"C:\git\corefx", @"C:\git\corefx\Z" },
{ @"Z:tmp\..\..\..\..\foo\..", @"C:\git\corefx", @"Z:\" },
{ @"Z:tmp\..\..\foo\.", @"C:\", @"Z:\foo" },
{ @"Z:..\..\tmp\..\foo\..", @"C:\", @"Z:\" },
{ @"Z:tmp\..\", @"C:\", @"Z:\" },
};
[Theory,
MemberData(nameof(GetFullPath_CommonRootedWindowsData))]
public void GetFullPath_CommonUnRooted_Windows(string path, string basePath, string expected)
{
Assert.Equal(expected, Path.GetFullPath(path, basePath));
Assert.Equal(@"\\.\" + expected, Path.GetFullPath(path, @"\\.\" + basePath));
Assert.Equal(@"\\?\" + expected, Path.GetFullPath(path, @"\\?\" + basePath));
}
[Fact]
public void GetFullPath_ThrowsOnEmbeddedNulls()
{
Assert.Throws<ArgumentException>(null, () => Path.GetFullPath("/gi\0t", @"C:\foo\bar"));
}
public static TheoryData<string, string> TestData_TrimEndingDirectorySeparator => new TheoryData<string, string>
{
{ @"C:\folder\", @"C:\folder" },
{ @"C:/folder/", @"C:/folder" },
{ @"/folder/", @"/folder" },
{ @"\folder\", @"\folder" },
{ @"folder\", @"folder" },
{ @"folder/", @"folder" },
{ @"C:\", @"C:\" },
{ @"C:/", @"C:/" },
{ @"", @"" },
{ @"/", @"/" },
{ @"\", @"\" },
{ @"\\server\share\", @"\\server\share" },
{ @"\\server\share\folder\", @"\\server\share\folder" },
{ @"\\?\C:\", @"\\?\C:\" },
{ @"\\?\C:\folder\", @"\\?\C:\folder" },
{ @"\\?\UNC\", @"\\?\UNC\" },
{ @"\\?\UNC\a\", @"\\?\UNC\a\" },
{ @"\\?\UNC\a\folder\", @"\\?\UNC\a\folder" },
{ null, null }
};
public static TheoryData<string, bool> TestData_EndsInDirectorySeparator => new TheoryData<string, bool>
{
{ @"\", true },
{ @"/", true },
{ @"C:\folder\", true },
{ @"C:/folder/", true },
{ @"C:\", true },
{ @"C:/", true },
{ @"\\", true },
{ @"//", true },
{ @"\\server\share\", true },
{ @"\\?\UNC\a\", true },
{ @"\\?\C:\", true },
{ @"\\?\UNC\", true },
{ @"folder\", true },
{ @"folder", false },
{ @"", false },
{ null, false }
};
[Theory,
MemberData(nameof(TestData_TrimEndingDirectorySeparator))]
public void TrimEndingDirectorySeparator_String(string path, string expected)
{
string trimmed = Path.TrimEndingDirectorySeparator(path);
Assert.Equal(expected, trimmed);
Assert.Same(trimmed, Path.TrimEndingDirectorySeparator(trimmed));
}
[Theory,
MemberData(nameof(TestData_TrimEndingDirectorySeparator))]
public void TrimEndingDirectorySeparator_ReadOnlySpan(string path, string expected)
{
ReadOnlySpan<char> trimmed = Path.TrimEndingDirectorySeparator(path.AsSpan());
PathAssert.Equal(expected, trimmed);
PathAssert.Equal(trimmed, Path.TrimEndingDirectorySeparator(trimmed));
}
[Theory,
MemberData(nameof(TestData_EndsInDirectorySeparator))]
public void EndsInDirectorySeparator_String(string path, bool expected)
{
Assert.Equal(expected, Path.EndsInDirectorySeparator(path));
}
[Theory,
MemberData(nameof(TestData_EndsInDirectorySeparator))]
public void EndsInDirectorySeparator_ReadOnlySpan(string path, bool expected)
{
Assert.Equal(expected, Path.EndsInDirectorySeparator(path.AsSpan()));
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
namespace System.Linq.Tests
{
public class CastTests : EnumerableBasedTests
{
[Fact]
public void CastIntToLongThrows()
{
var q = from x in new[] { 9999, 0, 888, -1, 66, -777, 1, 2, -12345 }
where x > Int32.MinValue
select x;
var rst = q.AsQueryable().Cast<long>();
Assert.Throws<InvalidCastException>(() => { foreach (var t in rst) ; });
}
[Fact]
public void CastByteToUShortThrows()
{
var q = from x in new byte[] { 0, 255, 127, 128, 1, 33, 99 }
select x;
var rst = q.AsQueryable().Cast<ushort>();
Assert.Throws<InvalidCastException>(() => { foreach (var t in rst) ; });
}
[Fact]
public void EmptySource()
{
object[] source = { };
Assert.Empty(source.AsQueryable().Cast<int>());
}
[Fact]
public void NullableIntFromAppropriateObjects()
{
int? i = 10;
object[] source = { -4, 1, 2, 3, 9, i };
int?[] expected = { -4, 1, 2, 3, 9, i };
Assert.Equal(expected, source.AsQueryable().Cast<int?>());
}
[Fact]
public void LongFromNullableIntInObjectsThrows()
{
int? i = 10;
object[] source = { -4, 1, 2, 3, 9, i };
IQueryable<long> cast = source.AsQueryable().Cast<long>();
Assert.Throws<InvalidCastException>(() => cast.ToList());
}
[Fact]
public void LongFromNullableIntInObjectsIncludingNullThrows()
{
int? i = 10;
object[] source = { -4, 1, 2, 3, 9, null, i };
IQueryable<long?> cast = source.AsQueryable().Cast<long?>();
Assert.Throws<InvalidCastException>(() => cast.ToList());
}
[Fact]
public void NullableIntFromAppropriateObjectsIncludingNull()
{
int? i = 10;
object[] source = { -4, 1, 2, 3, 9, null, i };
int?[] expected = { -4, 1, 2, 3, 9, null, i };
Assert.Equal(expected, source.AsQueryable().Cast<int?>());
}
[Fact]
public void ThrowOnUncastableItem()
{
object[] source = { -4, 1, 2, 3, 9, "45" };
int[] expectedBeginning = { -4, 1, 2, 3, 9 };
IQueryable<int> cast = source.AsQueryable().Cast<int>();
Assert.Throws<InvalidCastException>(() => cast.ToList());
Assert.Equal(expectedBeginning, cast.Take(5));
Assert.Throws<InvalidCastException>(() => cast.ElementAt(5));
}
[Fact]
public void ThrowCastingIntToDouble()
{
int[] source = new int[] { -4, 1, 2, 9 };
IQueryable<double> cast = source.AsQueryable().Cast<double>();
Assert.Throws<InvalidCastException>(() => cast.ToList());
}
private static void TestCastThrow<T>(object o)
{
byte? i = 10;
object[] source = { -1, 0, o, i };
IQueryable<T> cast = source.AsQueryable().Cast<T>();
Assert.Throws<InvalidCastException>(() => cast.ToList());
}
[Fact]
public void ThrowOnHeterogenousSource()
{
TestCastThrow<long?>(null);
TestCastThrow<long>(9L);
}
[Fact]
public void CastToString()
{
object[] source = { "Test1", "4.5", null, "Test2" };
string[] expected = { "Test1", "4.5", null, "Test2" };
Assert.Equal(expected, source.AsQueryable().Cast<string>());
}
[Fact]
public void ArrayConversionThrows()
{
Assert.Throws<InvalidCastException>(() => new[] { -4 }.AsQueryable().Cast<long>().ToList());
}
[Fact]
public void FirstElementInvalidForCast()
{
object[] source = { "Test", 3, 5, 10 };
IQueryable<int> cast = source.AsQueryable().Cast<int>();
Assert.Throws<InvalidCastException>(() => cast.ToList());
}
[Fact]
public void LastElementInvalidForCast()
{
object[] source = { -5, 9, 0, 5, 9, "Test" };
IQueryable<int> cast = source.AsQueryable().Cast<int>();
Assert.Throws<InvalidCastException>(() => cast.ToList());
}
[Fact]
public void NullableIntFromNullsAndInts()
{
object[] source = { 3, null, 5, -4, 0, null, 9 };
int?[] expected = { 3, null, 5, -4, 0, null, 9 };
Assert.Equal(expected, source.Cast<int?>());
}
[Fact]
public void ThrowCastingIntToLong()
{
int[] source = new int[] { -4, 1, 2, 3, 9 };
IQueryable<long> cast = source.AsQueryable().Cast<long>();
Assert.Throws<InvalidCastException>(() => cast.ToList());
}
[Fact]
public void ThrowCastingIntToNullableLong()
{
int[] source = new int[] { -4, 1, 2, 3, 9 };
IQueryable<long?> cast = source.AsQueryable().Cast<long?>();
Assert.Throws<InvalidCastException>(() => cast.ToList());
}
[Fact]
public void ThrowCastingNullableIntToLong()
{
int?[] source = new int?[] { -4, 1, 2, 3, 9 };
IQueryable<long> cast = source.AsQueryable().Cast<long>();
Assert.Throws<InvalidCastException>(() => cast.ToList());
}
[Fact]
public void ThrowCastingNullableIntToNullableLong()
{
int?[] source = new int?[] { -4, 1, 2, 3, 9, null };
IQueryable<long?> cast = source.AsQueryable().Cast<long?>();
Assert.Throws<InvalidCastException>(() => cast.ToList());
}
[Fact]
public void CastingNullToNonnullableIsNullReferenceException()
{
int?[] source = new int?[] { -4, 1, null, 3 };
IQueryable<int> cast = source.AsQueryable().Cast<int>();
Assert.Throws<NullReferenceException>(() => cast.ToList());
}
[Fact]
public void NullSource()
{
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IQueryable<object>)null).Cast<string>());
}
[Fact]
public void Cast()
{
var count = (new object[] { 0, 1, 2 }).AsQueryable().Cast<int>().Count();
Assert.Equal(3, count);
}
}
}
| |
using System;
using System.Collections.Generic;
namespace LinqToDB.SqlQuery
{
/// <summary>
/// This is internal API and is not intended for use by Linq To DB applications.
/// It may change or be removed without further notice.
/// </summary>
public class QueryInformation
{
private readonly SelectQuery _rootQuery;
private Dictionary<SelectQuery, HierarchyInfo>? _parents;
private Dictionary<SelectQuery, List<SelectQuery>>? _tree;
/// <summary>
/// This is internal API and is not intended for use by Linq To DB applications.
/// It may change or be removed without further notice.
/// </summary>
public QueryInformation(SelectQuery rootQuery)
{
_rootQuery = rootQuery ?? throw new ArgumentNullException(nameof(rootQuery));
}
/// <summary>
/// Returns parent query if query is subquery for select
/// </summary>
/// <param name="selectQuery"></param>
/// <returns></returns>
public SelectQuery? GetParentQuery(SelectQuery selectQuery)
{
var info = GetHierarchyInfo(selectQuery);
return info?.HierarchyType == HierarchyType.From ? info.MasterQuery : null;
}
/// <summary>
/// Returns HirarchyInfo for specific selectQuery
/// </summary>
/// <param name="selectQuery"></param>
/// <returns></returns>
public HierarchyInfo? GetHierarchyInfo(SelectQuery selectQuery)
{
CheckInitialized();
_parents!.TryGetValue(selectQuery, out var result);
return result;
}
private void CheckInitialized()
{
if (_parents == null)
{
_parents = new Dictionary<SelectQuery, HierarchyInfo>();
_tree = new Dictionary<SelectQuery, List<SelectQuery>>();
BuildParentHierarchy(_rootQuery);
}
}
/// <summary>
/// Resync tree info. Can be called also during enumeration.
/// </summary>
public void Resync()
{
_parents = null;
_tree = null;
}
public IEnumerable<SelectQuery> GetQueriesParentFirst()
{
return GetQueriesParentFirst(_rootQuery);
}
public IEnumerable<SelectQuery> GetQueriesParentFirst(SelectQuery root)
{
yield return root;
CheckInitialized();
if (_tree!.TryGetValue(root, out var list))
{
// assuming that list at this stage is immutable
foreach (var item in list)
foreach (var subItem in GetQueriesParentFirst(item))
{
yield return subItem;
}
}
}
public IEnumerable<SelectQuery> GetQueriesChildFirst()
{
return GetQueriesChildFirst(_rootQuery);
}
public IEnumerable<SelectQuery> GetQueriesChildFirst(SelectQuery root)
{
CheckInitialized();
if (_tree!.TryGetValue(root, out var list))
{
foreach (var item in list)
foreach (var subItem in GetQueriesChildFirst(item))
{
yield return subItem;
}
// assuming that list at this stage is immutable
foreach (var item in list)
{
yield return item;
}
}
yield return root;
}
void RegisterHierachry(SelectQuery parent, SelectQuery child, HierarchyInfo info)
{
_parents![child] = info;
if (!_tree!.TryGetValue(parent, out var list))
{
list = new List<SelectQuery>();
_tree.Add(parent, list);
}
list.Add(child);
}
void BuildParentHierarchy(SelectQuery selectQuery)
{
foreach (var table in selectQuery.From.Tables)
{
if (table.Source is SelectQuery s)
{
RegisterHierachry(selectQuery, s, new HierarchyInfo(selectQuery, HierarchyType.From, selectQuery));
foreach (var setOperator in s.SetOperators)
{
RegisterHierachry(selectQuery, setOperator.SelectQuery, new HierarchyInfo(selectQuery, HierarchyType.SetOperator, setOperator));
BuildParentHierarchy(setOperator.SelectQuery);
}
BuildParentHierarchy(s);
}
foreach (var joinedTable in table.Joins)
{
if (joinedTable.Table.Source is SelectQuery joinQuery)
{
RegisterHierachry(selectQuery, joinQuery,
new HierarchyInfo(selectQuery, HierarchyType.Join, joinedTable));
BuildParentHierarchy(joinQuery);
}
}
}
var items = new List<IQueryElement>
{
selectQuery.GroupBy,
selectQuery.Having,
selectQuery.Where,
selectQuery.OrderBy
};
items.AddRange(selectQuery.Select.Columns);
if (!selectQuery.Where.IsEmpty)
items.Add(selectQuery.Where);
foreach (var item in items)
{
IQueryElement? parent = null;
new QueryVisitor().VisitParentFirst(item, e =>
{
if (e is SelectQuery q)
{
RegisterHierachry(selectQuery, q, new HierarchyInfo(selectQuery, HierarchyType.InnerQuery, parent));
BuildParentHierarchy(q);
return false;
}
parent = e;
return true;
});
}
}
public enum HierarchyType
{
From,
Join,
SetOperator,
InnerQuery
}
public class HierarchyInfo
{
public HierarchyInfo(SelectQuery masterQuery, HierarchyType hierarchyType, IQueryElement? parentElement)
{
MasterQuery = masterQuery;
HierarchyType = hierarchyType;
ParentElement = parentElement;
}
public SelectQuery MasterQuery { get; }
public HierarchyType HierarchyType { get; }
public IQueryElement? ParentElement { get; }
}
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Collections;
using System.Collections.Generic;
using QuantConnect.Data;
using QuantConnect.Data.Market;
using QuantConnect.Securities;
using QuantConnect.Util;
namespace QuantConnect.Lean.Engine.DataFeeds.Enumerators
{
/// <summary>
/// The FillForwardEnumerator wraps an existing base data enumerator and inserts extra 'base data' instances
/// on a specified fill forward resolution
/// </summary>
public class FillForwardEnumerator : IEnumerator<BaseData>
{
private DateTime? _delistedTime;
private BaseData _previous;
private bool _isFillingForward;
private bool _emittedAuxilliaryData;
private readonly TimeSpan _dataResolution;
private readonly bool _isExtendedMarketHours;
private readonly DateTime _subscriptionEndTime;
private readonly IEnumerator<BaseData> _enumerator;
private readonly IReadOnlyRef<TimeSpan> _fillForwardResolution;
protected readonly SecurityExchange Exchange;
/// <summary>
/// Initializes a new instance of the <see cref="FillForwardEnumerator"/> class that accepts
/// a reference to the fill forward resolution, useful if the fill forward resolution is dynamic
/// and changing as the enumeration progresses
/// </summary>
/// <param name="enumerator">The source enumerator to be filled forward</param>
/// <param name="exchange">The exchange used to determine when to insert fill forward data</param>
/// <param name="fillForwardResolution">The resolution we'd like to receive data on</param>
/// <param name="isExtendedMarketHours">True to use the exchange's extended market hours, false to use the regular market hours</param>
/// <param name="subscriptionEndTime">The end time of the subscrition, once passing this date the enumerator will stop</param>
/// <param name="dataResolution">The source enumerator's data resolution</param>
public FillForwardEnumerator(IEnumerator<BaseData> enumerator,
SecurityExchange exchange,
IReadOnlyRef<TimeSpan> fillForwardResolution,
bool isExtendedMarketHours,
DateTime subscriptionEndTime,
TimeSpan dataResolution
)
{
_subscriptionEndTime = subscriptionEndTime;
Exchange = exchange;
_enumerator = enumerator;
_dataResolution = dataResolution;
_fillForwardResolution = fillForwardResolution;
_isExtendedMarketHours = isExtendedMarketHours;
}
/// <summary>
/// Initializes a new instance of the <see cref="FillForwardEnumerator"/> class
/// </summary>
/// <param name="enumerator">The source enumerator to be filled forward</param>
/// <param name="exchange">The exchange used to determine when to insert fill forward data</param>
/// <param name="fillForwardResolution">The resolution we'd like to receive data on</param>
/// <param name="isExtendedMarketHours">True to use the exchange's extended market hours, false to use the regular market hours</param>
/// <param name="subscriptionEndTime">The end time of the subscrition, once passing this date the enumerator will stop</param>
/// <param name="dataResolution">The source enumerator's data resolution</param>
public FillForwardEnumerator(IEnumerator<BaseData> enumerator,
SecurityExchange exchange,
TimeSpan fillForwardResolution,
bool isExtendedMarketHours,
DateTime subscriptionEndTime,
TimeSpan dataResolution
)
{
_subscriptionEndTime = subscriptionEndTime;
Exchange = exchange;
_enumerator = enumerator;
_dataResolution = dataResolution;
_fillForwardResolution = Ref.CreateReadOnly(() => fillForwardResolution);
_isExtendedMarketHours = isExtendedMarketHours;
}
/// <summary>
/// Gets the element in the collection at the current position of the enumerator.
/// </summary>
/// <returns>
/// The element in the collection at the current position of the enumerator.
/// </returns>
public BaseData Current
{
get;
private set;
}
/// <summary>
/// Gets the current element in the collection.
/// </summary>
/// <returns>
/// The current element in the collection.
/// </returns>
/// <filterpriority>2</filterpriority>
object IEnumerator.Current
{
get { return Current; }
}
/// <summary>
/// Advances the enumerator to the next element of the collection.
/// </summary>
/// <returns>
/// true if the enumerator was successfully advanced to the next element; false if the enumerator has passed the end of the collection.
/// </returns>
/// <exception cref="T:System.InvalidOperationException">The collection was modified after the enumerator was created. </exception><filterpriority>2</filterpriority>
public bool MoveNext()
{
if (_delistedTime.HasValue)
{
// don't fill forward after data after the delisted date
if (_previous == null || _previous.EndTime >= _delistedTime.Value)
{
return false;
}
}
if (!_emittedAuxilliaryData && Current != null)
{
// only set the _previous if the last item we emitted was NOT auxilliary data,
// since _previous is used for fill forward behavior
_previous = Current;
}
BaseData fillForward;
if (!_isFillingForward)
{
// if we're filling forward we don't need to move next since we haven't emitted _enumerator.Current yet
if (!_enumerator.MoveNext())
{
if (_delistedTime.HasValue)
{
// don't fill forward delisted data
return false;
}
// check to see if we ran out of data before the end of the subscription
if (_previous == null || _previous.EndTime >= _subscriptionEndTime)
{
// we passed the end of subscription, we're finished
return false;
}
// we can fill forward the rest of this subscription if required
var endOfSubscription = (Current ?? _previous).Clone(true);
endOfSubscription.Time = _subscriptionEndTime.RoundDown(_dataResolution);
if (RequiresFillForwardData(_fillForwardResolution.Value, _previous, endOfSubscription, out fillForward))
{
// don't mark as filling forward so we come back into this block, subscription is done
//_isFillingForward = true;
Current = fillForward;
_emittedAuxilliaryData = false;
return true;
}
// don't emit the last bar if the market isn't considered open!
if (!Exchange.IsOpenDuringBar(endOfSubscription.Time, endOfSubscription.EndTime, _isExtendedMarketHours))
{
return false;
}
Current = endOfSubscription;
_emittedAuxilliaryData = false;
return true;
}
}
var underlyingCurrent = _enumerator.Current;
if (_previous == null)
{
// first data point we dutifully emit without modification
Current = underlyingCurrent;
return true;
}
if (underlyingCurrent != null && underlyingCurrent.DataType == MarketDataType.Auxiliary)
{
_emittedAuxilliaryData = true;
Current = underlyingCurrent;
var delisting = Current as Delisting;
if (delisting != null && delisting.Type == DelistingType.Delisted)
{
_delistedTime = delisting.EndTime;
}
return true;
}
_emittedAuxilliaryData = false;
if (RequiresFillForwardData(_fillForwardResolution.Value, _previous, underlyingCurrent, out fillForward))
{
// we require fill forward data because the _enumerator.Current is too far in future
_isFillingForward = true;
Current = fillForward;
return true;
}
_isFillingForward = false;
Current = underlyingCurrent;
return true;
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
/// <filterpriority>2</filterpriority>
public void Dispose()
{
_enumerator.Dispose();
}
/// <summary>
/// Sets the enumerator to its initial position, which is before the first element in the collection.
/// </summary>
/// <exception cref="T:System.InvalidOperationException">The collection was modified after the enumerator was created. </exception><filterpriority>2</filterpriority>
public void Reset()
{
_enumerator.Reset();
}
/// <summary>
/// Determines whether or not fill forward is required, and if true, will produce the new fill forward data
/// </summary>
/// <param name="fillForwardResolution"></param>
/// <param name="previous">The last piece of data emitted by this enumerator</param>
/// <param name="next">The next piece of data on the source enumerator</param>
/// <param name="fillForward">When this function returns true, this will have a non-null value, null when the function returns false</param>
/// <returns>True when a new fill forward piece of data was produced and should be emitted by this enumerator</returns>
protected virtual bool RequiresFillForwardData(TimeSpan fillForwardResolution, BaseData previous, BaseData next, out BaseData fillForward)
{
if (next.EndTime < previous.Time)
{
throw new ArgumentException("FillForwardEnumerator received data out of order.");
}
// check to see if the gap between previous and next warrants fill forward behavior
if (next.Time - previous.Time <= fillForwardResolution)
{
fillForward = null;
return false;
}
// is the bar after previous in market hours?
var barAfterPreviousEndTime = previous.EndTime + fillForwardResolution;
if (Exchange.IsOpenDuringBar(previous.EndTime, barAfterPreviousEndTime, _isExtendedMarketHours))
{
// this is the normal case where we had a hole in the middle of the day
fillForward = previous.Clone(true);
fillForward.Time = (previous.Time + fillForwardResolution).RoundDown(fillForwardResolution);
return true;
}
// find the next fill forward time after the next market open
var nextFillForwardTime = Exchange.Hours.GetNextMarketOpen(previous.EndTime, _isExtendedMarketHours) + fillForwardResolution;
if (_dataResolution == Time.OneDay)
{
// special case for daily, we need to emit a midnight bar even though markets are closed
var dailyBarEnd = GetNextOpenDateAfter(previous.Time.Date) + Time.OneDay;
if (dailyBarEnd < nextFillForwardTime)
{
// only emit the midnight bar if it's the next bar to be emitted
nextFillForwardTime = dailyBarEnd;
}
}
if (nextFillForwardTime < next.EndTime)
{
// if next is still in the future then we need to emit a fill forward for market open
fillForward = previous.Clone(true);
fillForward.Time = (nextFillForwardTime - _dataResolution).RoundDown(fillForwardResolution);
return true;
}
// the next is before the next fill forward time, so do nothing
fillForward = null;
return false;
}
/// <summary>
/// Finds the next open date that follows the specified date, this functions expects a date, not a date time
/// </summary>
private DateTime GetNextOpenDateAfter(DateTime date)
{
do
{
date = date + Time.OneDay;
}
while (!Exchange.DateIsOpen(date));
return date;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using Microsoft.CSharp.RuntimeBinder.Errors;
using Microsoft.CSharp.RuntimeBinder.Syntax;
namespace Microsoft.CSharp.RuntimeBinder.Semantics
{
internal sealed class TypeManager
{
private BSYMMGR _BSymmgr;
private PredefinedTypes _predefTypes;
private readonly TypeFactory _typeFactory;
private readonly TypeTable _typeTable;
private SymbolTable _symbolTable;
// Special types
private readonly VoidType _voidType;
private readonly NullType _nullType;
private readonly OpenTypePlaceholderType _typeUnit;
private readonly BoundLambdaType _typeAnonMeth;
private readonly MethodGroupType _typeMethGrp;
private readonly ArgumentListType _argListType;
private readonly ErrorType _errorType;
private readonly StdTypeVarColl _stvcMethod;
private readonly StdTypeVarColl _stvcClass;
public TypeManager()
{
_predefTypes = null; // Initialized via the Init call.
_BSymmgr = null; // Initialized via the Init call.
_typeFactory = new TypeFactory();
_typeTable = new TypeTable();
// special types with their own symbol kind.
_errorType = _typeFactory.CreateError(null, null, null, null, null);
_voidType = _typeFactory.CreateVoid();
_nullType = _typeFactory.CreateNull();
_typeUnit = _typeFactory.CreateUnit();
_typeAnonMeth = _typeFactory.CreateAnonMethod();
_typeMethGrp = _typeFactory.CreateMethodGroup();
_argListType = _typeFactory.CreateArgList();
InitType(_errorType);
_errorType.SetErrors(true);
InitType(_voidType);
InitType(_nullType);
InitType(_typeUnit);
InitType(_typeAnonMeth);
InitType(_typeMethGrp);
_stvcMethod = new StdTypeVarColl();
_stvcClass = new StdTypeVarColl();
}
public void InitTypeFactory(SymbolTable table)
{
_symbolTable = table;
}
private void InitType(CType at)
{
}
private sealed class StdTypeVarColl
{
private readonly List<TypeParameterType> prgptvs;
public StdTypeVarColl()
{
prgptvs = new List<TypeParameterType>();
}
////////////////////////////////////////////////////////////////////////////////
// Get the standard type variable (eg, !0, !1, or !!0, !!1).
//
// iv is the index.
// pbsm is the containing symbol manager
// fMeth designates whether this is a method type var or class type var
//
// The standard class type variables are useful during emit, but not for type
// comparison when binding. The standard method type variables are useful during
// binding for signature comparison.
public TypeParameterType GetTypeVarSym(int iv, TypeManager pTypeManager, bool fMeth)
{
Debug.Assert(iv >= 0);
TypeParameterType tpt = null;
if (iv >= this.prgptvs.Count)
{
TypeParameterSymbol pTypeParameter = new TypeParameterSymbol();
pTypeParameter.SetIsMethodTypeParameter(fMeth);
pTypeParameter.SetIndexInOwnParameters(iv);
pTypeParameter.SetIndexInTotalParameters(iv);
pTypeParameter.SetAccess(ACCESS.ACC_PRIVATE);
tpt = pTypeManager.GetTypeParameter(pTypeParameter);
this.prgptvs.Add(tpt);
}
else
{
tpt = this.prgptvs[iv];
}
Debug.Assert(tpt != null);
return tpt;
}
}
public ArrayType GetArray(CType elementType, int args, bool isSZArray)
{
Name name;
Debug.Assert(args > 0 && args < 32767);
Debug.Assert(args == 1 || !isSZArray);
switch (args)
{
case 1:
if (isSZArray)
{
goto case 2;
}
else
{
goto default;
}
case 2:
name = NameManager.GetPredefinedName(PredefinedName.PN_ARRAY0 + args);
break;
default:
name = _BSymmgr.GetNameManager().Add("[X" + args + 1);
break;
}
// See if we already have an array type of this element type and rank.
ArrayType pArray = _typeTable.LookupArray(name, elementType);
if (pArray == null)
{
// No existing array symbol. Create a new one.
pArray = _typeFactory.CreateArray(name, elementType, args, isSZArray);
pArray.InitFromParent();
_typeTable.InsertArray(name, elementType, pArray);
}
else
{
Debug.Assert(pArray.HasErrors() == elementType.HasErrors());
}
Debug.Assert(pArray.rank == args);
Debug.Assert(pArray.GetElementType() == elementType);
return pArray;
}
public AggregateType GetAggregate(AggregateSymbol agg, AggregateType atsOuter, TypeArray typeArgs)
{
Debug.Assert(agg.GetTypeManager() == this);
Debug.Assert(atsOuter == null || atsOuter.getAggregate() == agg.Parent, "");
if (typeArgs == null)
{
typeArgs = BSYMMGR.EmptyTypeArray();
}
Debug.Assert(agg.GetTypeVars().Count == typeArgs.Count);
Name name = _BSymmgr.GetNameFromPtrs(typeArgs, atsOuter);
Debug.Assert(name != null);
AggregateType pAggregate = _typeTable.LookupAggregate(name, agg);
if (pAggregate == null)
{
pAggregate = _typeFactory.CreateAggregateType(
name,
agg,
typeArgs,
atsOuter
);
Debug.Assert(!pAggregate.fConstraintsChecked && !pAggregate.fConstraintError);
pAggregate.SetErrors(false);
_typeTable.InsertAggregate(name, agg, pAggregate);
// If we have a generic type definition, then we need to set the
// base class to be our current base type, and use that to calculate
// our agg type and its base, then set it to be the generic version of the
// base type. This is because:
//
// Suppose we have Foo<T> : IFoo<T>
//
// Initially, the BaseType will be IFoo<Foo.T>, which gives us the substitution
// that we want to use for our agg type's base type. However, in the Symbol chain,
// we want the base type to be IFoo<IFoo.T>. Thats why we need to do this little trick.
//
// If we don't have a generic type definition, then we just need to set our base
// class. This is so that if we have a base type that's generic, we'll be
// getting the correctly instantiated base type.
var baseType = pAggregate.AssociatedSystemType?.BaseType;
if (baseType != null)
{
// Store the old base class.
AggregateType oldBaseType = agg.GetBaseClass();
agg.SetBaseClass(_symbolTable.GetCTypeFromType(baseType).AsAggregateType());
pAggregate.GetBaseClass(); // Get the base type for the new agg type we're making.
agg.SetBaseClass(oldBaseType);
}
}
else
{
Debug.Assert(!pAggregate.HasErrors());
}
Debug.Assert(pAggregate.getAggregate() == agg);
Debug.Assert(pAggregate.GetTypeArgsThis() != null && pAggregate.GetTypeArgsAll() != null);
Debug.Assert(pAggregate.GetTypeArgsThis() == typeArgs);
return pAggregate;
}
public AggregateType GetAggregate(AggregateSymbol agg, TypeArray typeArgsAll)
{
Debug.Assert(typeArgsAll != null && typeArgsAll.Count == agg.GetTypeVarsAll().Count);
if (typeArgsAll.Count == 0)
return agg.getThisType();
AggregateSymbol aggOuter = agg.GetOuterAgg();
if (aggOuter == null)
return GetAggregate(agg, null, typeArgsAll);
int cvarOuter = aggOuter.GetTypeVarsAll().Count;
Debug.Assert(cvarOuter <= typeArgsAll.Count);
TypeArray typeArgsOuter = _BSymmgr.AllocParams(cvarOuter, typeArgsAll, 0);
TypeArray typeArgsInner = _BSymmgr.AllocParams(agg.GetTypeVars().Count, typeArgsAll, cvarOuter);
AggregateType atsOuter = GetAggregate(aggOuter, typeArgsOuter);
return GetAggregate(agg, atsOuter, typeArgsInner);
}
public PointerType GetPointer(CType baseType)
{
PointerType pPointer = _typeTable.LookupPointer(baseType);
if (pPointer == null)
{
// No existing type. Create a new one.
Name namePtr = NameManager.GetPredefinedName(PredefinedName.PN_PTR);
pPointer = _typeFactory.CreatePointer(namePtr, baseType);
pPointer.InitFromParent();
_typeTable.InsertPointer(baseType, pPointer);
}
else
{
Debug.Assert(pPointer.HasErrors() == baseType.HasErrors());
}
Debug.Assert(pPointer.GetReferentType() == baseType);
return pPointer;
}
public NullableType GetNullable(CType pUnderlyingType)
{
if (pUnderlyingType is NullableType nt)
{
Debug.Fail("Attempt to make nullable of nullable");
return nt;
}
NullableType pNullableType = _typeTable.LookupNullable(pUnderlyingType);
if (pNullableType == null)
{
Name pName = NameManager.GetPredefinedName(PredefinedName.PN_NUB);
pNullableType = _typeFactory.CreateNullable(pName, pUnderlyingType, _BSymmgr, this);
pNullableType.InitFromParent();
_typeTable.InsertNullable(pUnderlyingType, pNullableType);
}
return pNullableType;
}
public NullableType GetNubFromNullable(AggregateType ats)
{
Debug.Assert(ats.isPredefType(PredefinedType.PT_G_OPTIONAL));
return GetNullable(ats.GetTypeArgsAll()[0]);
}
public ParameterModifierType GetParameterModifier(CType paramType, bool isOut)
{
Name name = NameManager.GetPredefinedName(isOut ? PredefinedName.PN_OUTPARAM : PredefinedName.PN_REFPARAM);
ParameterModifierType pParamModifier = _typeTable.LookupParameterModifier(name, paramType);
if (pParamModifier == null)
{
// No existing parammod symbol. Create a new one.
pParamModifier = _typeFactory.CreateParameterModifier(name, paramType);
pParamModifier.isOut = isOut;
pParamModifier.InitFromParent();
_typeTable.InsertParameterModifier(name, paramType, pParamModifier);
}
else
{
Debug.Assert(pParamModifier.HasErrors() == paramType.HasErrors());
}
Debug.Assert(pParamModifier.GetParameterType() == paramType);
return pParamModifier;
}
public ErrorType GetErrorType(
CType pParentType,
AssemblyQualifiedNamespaceSymbol pParentNS,
Name nameText,
TypeArray typeArgs)
{
Debug.Assert(nameText != null);
Debug.Assert(pParentType == null || pParentNS == null);
if (pParentType == null && pParentNS == null)
{
// Use the root namespace as the parent.
pParentNS = _BSymmgr.GetRootNsAid();
}
if (typeArgs == null)
{
typeArgs = BSYMMGR.EmptyTypeArray();
}
Name name = _BSymmgr.GetNameFromPtrs(nameText, typeArgs);
Debug.Assert(name != null);
ErrorType pError = null;
if (pParentType != null)
{
pError = _typeTable.LookupError(name, pParentType);
}
else
{
Debug.Assert(pParentNS != null);
pError = _typeTable.LookupError(name, pParentNS);
}
if (pError == null)
{
// No existing error symbol. Create a new one.
pError = _typeFactory.CreateError(name, pParentType, pParentNS, nameText, typeArgs);
pError.SetErrors(true);
if (pParentType != null)
{
_typeTable.InsertError(name, pParentType, pError);
}
else
{
_typeTable.InsertError(name, pParentNS, pError);
}
}
else
{
Debug.Assert(pError.HasErrors());
Debug.Assert(pError.nameText == nameText);
Debug.Assert(pError.typeArgs == typeArgs);
}
return pError;
}
public VoidType GetVoid()
{
return _voidType;
}
public NullType GetNullType()
{
return _nullType;
}
private OpenTypePlaceholderType GetUnitType()
{
return _typeUnit;
}
public BoundLambdaType GetAnonMethType()
{
return _typeAnonMeth;
}
public MethodGroupType GetMethGrpType()
{
return _typeMethGrp;
}
public ArgumentListType GetArgListType()
{
return _argListType;
}
public ErrorType GetErrorSym()
{
return _errorType;
}
public AggregateSymbol GetNullable()
{
return this.GetOptPredefAgg(PredefinedType.PT_G_OPTIONAL);
}
private CType SubstType(CType typeSrc, TypeArray typeArgsCls, TypeArray typeArgsMeth, SubstTypeFlags grfst)
{
if (typeSrc == null)
return null;
var ctx = new SubstContext(typeArgsCls, typeArgsMeth, grfst);
return ctx.FNop() ? typeSrc : SubstTypeCore(typeSrc, ctx);
}
public CType SubstType(CType typeSrc, TypeArray typeArgsCls)
{
return SubstType(typeSrc, typeArgsCls, null, SubstTypeFlags.NormNone);
}
private CType SubstType(CType typeSrc, TypeArray typeArgsCls, TypeArray typeArgsMeth)
{
return SubstType(typeSrc, typeArgsCls, typeArgsMeth, SubstTypeFlags.NormNone);
}
public TypeArray SubstTypeArray(TypeArray taSrc, SubstContext pctx)
{
if (taSrc == null || taSrc.Count == 0 || pctx == null || pctx.FNop())
return taSrc;
CType[] prgpts = new CType[taSrc.Count];
for (int ipts = 0; ipts < taSrc.Count; ipts++)
{
prgpts[ipts] = this.SubstTypeCore(taSrc[ipts], pctx);
}
return _BSymmgr.AllocParams(taSrc.Count, prgpts);
}
private TypeArray SubstTypeArray(TypeArray taSrc, TypeArray typeArgsCls, TypeArray typeArgsMeth, SubstTypeFlags grfst)
{
if (taSrc == null || taSrc.Count == 0)
return taSrc;
var ctx = new SubstContext(typeArgsCls, typeArgsMeth, grfst);
if (ctx.FNop())
return taSrc;
CType[] prgpts = new CType[taSrc.Count];
for (int ipts = 0; ipts < taSrc.Count; ipts++)
{
prgpts[ipts] = SubstTypeCore(taSrc[ipts], ctx);
}
return _BSymmgr.AllocParams(taSrc.Count, prgpts);
}
public TypeArray SubstTypeArray(TypeArray taSrc, TypeArray typeArgsCls, TypeArray typeArgsMeth)
{
return this.SubstTypeArray(taSrc, typeArgsCls, typeArgsMeth, SubstTypeFlags.NormNone);
}
public TypeArray SubstTypeArray(TypeArray taSrc, TypeArray typeArgsCls)
{
return this.SubstTypeArray(taSrc, typeArgsCls, (TypeArray)null, SubstTypeFlags.NormNone);
}
private CType SubstTypeCore(CType type, SubstContext pctx)
{
CType typeSrc;
CType typeDst;
switch (type.GetTypeKind())
{
default:
Debug.Assert(false);
return type;
case TypeKind.TK_NullType:
case TypeKind.TK_VoidType:
case TypeKind.TK_OpenTypePlaceholderType:
case TypeKind.TK_MethodGroupType:
case TypeKind.TK_BoundLambdaType:
case TypeKind.TK_UnboundLambdaType:
case TypeKind.TK_NaturalIntegerType:
case TypeKind.TK_ArgumentListType:
return type;
case TypeKind.TK_ParameterModifierType:
typeDst = SubstTypeCore(typeSrc = type.AsParameterModifierType().GetParameterType(), pctx);
return (typeDst == typeSrc) ? type : GetParameterModifier(typeDst, type.AsParameterModifierType().isOut);
case TypeKind.TK_ArrayType:
typeDst = SubstTypeCore(typeSrc = type.AsArrayType().GetElementType(), pctx);
return (typeDst == typeSrc) ? type : GetArray(typeDst, type.AsArrayType().rank, type.AsArrayType().IsSZArray);
case TypeKind.TK_PointerType:
typeDst = SubstTypeCore(typeSrc = type.AsPointerType().GetReferentType(), pctx);
return (typeDst == typeSrc) ? type : GetPointer(typeDst);
case TypeKind.TK_NullableType:
typeDst = SubstTypeCore(typeSrc = type.AsNullableType().GetUnderlyingType(), pctx);
return (typeDst == typeSrc) ? type : GetNullable(typeDst);
case TypeKind.TK_AggregateType:
if (type.AsAggregateType().GetTypeArgsAll().Count > 0)
{
AggregateType ats = type.AsAggregateType();
TypeArray typeArgs = SubstTypeArray(ats.GetTypeArgsAll(), pctx);
if (ats.GetTypeArgsAll() != typeArgs)
return GetAggregate(ats.getAggregate(), typeArgs);
}
return type;
case TypeKind.TK_ErrorType:
if (type.AsErrorType().HasParent())
{
ErrorType err = type.AsErrorType();
Debug.Assert(err.nameText != null && err.typeArgs != null);
CType pParentType = null;
if (err.HasTypeParent())
{
pParentType = SubstTypeCore(err.GetTypeParent(), pctx);
}
TypeArray typeArgs = SubstTypeArray(err.typeArgs, pctx);
if (typeArgs != err.typeArgs || (err.HasTypeParent() && pParentType != err.GetTypeParent()))
{
return GetErrorType(pParentType, err.GetNSParent(), err.nameText, typeArgs);
}
}
return type;
case TypeKind.TK_TypeParameterType:
{
TypeParameterSymbol tvs = type.AsTypeParameterType().GetTypeParameterSymbol();
int index = tvs.GetIndexInTotalParameters();
if (tvs.IsMethodTypeParameter())
{
if ((pctx.grfst & SubstTypeFlags.DenormMeth) != 0 && tvs.parent != null)
return type;
Debug.Assert(tvs.GetIndexInOwnParameters() == tvs.GetIndexInTotalParameters());
if (index < pctx.ctypeMeth)
{
Debug.Assert(pctx.prgtypeMeth != null);
return pctx.prgtypeMeth[index];
}
else
{
return ((pctx.grfst & SubstTypeFlags.NormMeth) != 0 ? GetStdMethTypeVar(index) : type);
}
}
if ((pctx.grfst & SubstTypeFlags.DenormClass) != 0 && tvs.parent != null)
return type;
return index < pctx.ctypeCls ? pctx.prgtypeCls[index] :
((pctx.grfst & SubstTypeFlags.NormClass) != 0 ? GetStdClsTypeVar(index) : type);
}
}
}
public bool SubstEqualTypes(CType typeDst, CType typeSrc, TypeArray typeArgsCls, TypeArray typeArgsMeth, SubstTypeFlags grfst)
{
if (typeDst.Equals(typeSrc))
{
Debug.Assert(typeDst.Equals(SubstType(typeSrc, typeArgsCls, typeArgsMeth, grfst)));
return true;
}
var ctx = new SubstContext(typeArgsCls, typeArgsMeth, grfst);
return !ctx.FNop() && SubstEqualTypesCore(typeDst, typeSrc, ctx);
}
public bool SubstEqualTypeArrays(TypeArray taDst, TypeArray taSrc, TypeArray typeArgsCls, TypeArray typeArgsMeth, SubstTypeFlags grfst)
{
// Handle the simple common cases first.
if (taDst == taSrc || (taDst != null && taDst.Equals(taSrc)))
{
// The following assertion is not always true and indicates a problem where
// the signature of override method does not match the one inherited from
// the base class. The method match we have found does not take the type
// arguments of the base class into account. So actually we are not overriding
// the method that we "intend" to.
// Debug.Assert(taDst == SubstTypeArray(taSrc, typeArgsCls, typeArgsMeth, grfst));
return true;
}
if (taDst.Count != taSrc.Count)
return false;
if (taDst.Count == 0)
return true;
var ctx = new SubstContext(typeArgsCls, typeArgsMeth, grfst);
if (ctx.FNop())
return false;
for (int i = 0; i < taDst.Count; i++)
{
if (!SubstEqualTypesCore(taDst[i], taSrc[i], ctx))
return false;
}
return true;
}
private bool SubstEqualTypesCore(CType typeDst, CType typeSrc, SubstContext pctx)
{
LRecurse: // Label used for "tail" recursion.
if (typeDst == typeSrc || typeDst.Equals(typeSrc))
{
return true;
}
switch (typeSrc.GetTypeKind())
{
default:
Debug.Assert(false, "Bad Symbol kind in SubstEqualTypesCore");
return false;
case TypeKind.TK_NullType:
case TypeKind.TK_VoidType:
case TypeKind.TK_OpenTypePlaceholderType:
// There should only be a single instance of these.
Debug.Assert(typeDst.GetTypeKind() != typeSrc.GetTypeKind());
return false;
case TypeKind.TK_ArrayType:
if (typeDst.GetTypeKind() != TypeKind.TK_ArrayType || typeDst.AsArrayType().rank != typeSrc.AsArrayType().rank || typeDst.AsArrayType().IsSZArray != typeSrc.AsArrayType().IsSZArray)
return false;
goto LCheckBases;
case TypeKind.TK_ParameterModifierType:
if (typeDst.GetTypeKind() != TypeKind.TK_ParameterModifierType ||
((pctx.grfst & SubstTypeFlags.NoRefOutDifference) == 0 &&
typeDst.AsParameterModifierType().isOut != typeSrc.AsParameterModifierType().isOut))
return false;
goto LCheckBases;
case TypeKind.TK_PointerType:
case TypeKind.TK_NullableType:
if (typeDst.GetTypeKind() != typeSrc.GetTypeKind())
return false;
LCheckBases:
typeSrc = typeSrc.GetBaseOrParameterOrElementType();
typeDst = typeDst.GetBaseOrParameterOrElementType();
goto LRecurse;
case TypeKind.TK_AggregateType:
if (typeDst.GetTypeKind() != TypeKind.TK_AggregateType)
return false;
{ // BLOCK
AggregateType atsSrc = typeSrc.AsAggregateType();
AggregateType atsDst = typeDst.AsAggregateType();
if (atsSrc.getAggregate() != atsDst.getAggregate())
return false;
Debug.Assert(atsSrc.GetTypeArgsAll().Count == atsDst.GetTypeArgsAll().Count);
// All the args must unify.
for (int i = 0; i < atsSrc.GetTypeArgsAll().Count; i++)
{
if (!SubstEqualTypesCore(atsDst.GetTypeArgsAll()[i], atsSrc.GetTypeArgsAll()[i], pctx))
return false;
}
}
return true;
case TypeKind.TK_ErrorType:
if (!typeDst.IsErrorType() || !typeSrc.AsErrorType().HasParent() || !typeDst.AsErrorType().HasParent())
return false;
{
ErrorType errSrc = typeSrc.AsErrorType();
ErrorType errDst = typeDst.AsErrorType();
Debug.Assert(errSrc.nameText != null && errSrc.typeArgs != null);
Debug.Assert(errDst.nameText != null && errDst.typeArgs != null);
if (errSrc.nameText != errDst.nameText || errSrc.typeArgs.Count != errDst.typeArgs.Count)
return false;
if (errSrc.HasTypeParent() != errDst.HasTypeParent())
{
return false;
}
if (errSrc.HasTypeParent())
{
if (errSrc.GetTypeParent() != errDst.GetTypeParent())
{
return false;
}
if (!SubstEqualTypesCore(errDst.GetTypeParent(), errSrc.GetTypeParent(), pctx))
{
return false;
}
}
else
{
if (errSrc.GetNSParent() != errDst.GetNSParent())
{
return false;
}
}
// All the args must unify.
for (int i = 0; i < errSrc.typeArgs.Count; i++)
{
if (!SubstEqualTypesCore(errDst.typeArgs[i], errSrc.typeArgs[i], pctx))
return false;
}
}
return true;
case TypeKind.TK_TypeParameterType:
{ // BLOCK
TypeParameterSymbol tvs = typeSrc.AsTypeParameterType().GetTypeParameterSymbol();
int index = tvs.GetIndexInTotalParameters();
if (tvs.IsMethodTypeParameter())
{
if ((pctx.grfst & SubstTypeFlags.DenormMeth) != 0 && tvs.parent != null)
{
// typeDst == typeSrc was handled above.
Debug.Assert(typeDst != typeSrc);
return false;
}
Debug.Assert(tvs.GetIndexInOwnParameters() == tvs.GetIndexInTotalParameters());
Debug.Assert(pctx.prgtypeMeth == null || tvs.GetIndexInTotalParameters() < pctx.ctypeMeth);
if (index < pctx.ctypeMeth && pctx.prgtypeMeth != null)
{
return typeDst == pctx.prgtypeMeth[index];
}
if ((pctx.grfst & SubstTypeFlags.NormMeth) != 0)
{
return typeDst == GetStdMethTypeVar(index);
}
}
else
{
if ((pctx.grfst & SubstTypeFlags.DenormClass) != 0 && tvs.parent != null)
{
// typeDst == typeSrc was handled above.
Debug.Assert(typeDst != typeSrc);
return false;
}
Debug.Assert(pctx.prgtypeCls == null || tvs.GetIndexInTotalParameters() < pctx.ctypeCls);
if (index < pctx.ctypeCls)
return typeDst == pctx.prgtypeCls[index];
if ((pctx.grfst & SubstTypeFlags.NormClass) != 0)
return typeDst == GetStdClsTypeVar(index);
}
}
return false;
}
}
public static bool TypeContainsType(CType type, CType typeFind)
{
LRecurse: // Label used for "tail" recursion.
if (type == typeFind || type.Equals(typeFind))
return true;
switch (type.GetTypeKind())
{
default:
Debug.Assert(false, "Bad Symbol kind in TypeContainsType");
return false;
case TypeKind.TK_NullType:
case TypeKind.TK_VoidType:
case TypeKind.TK_OpenTypePlaceholderType:
// There should only be a single instance of these.
Debug.Assert(typeFind.GetTypeKind() != type.GetTypeKind());
return false;
case TypeKind.TK_ArrayType:
case TypeKind.TK_NullableType:
case TypeKind.TK_ParameterModifierType:
case TypeKind.TK_PointerType:
type = type.GetBaseOrParameterOrElementType();
goto LRecurse;
case TypeKind.TK_AggregateType:
{ // BLOCK
AggregateType ats = type.AsAggregateType();
for (int i = 0; i < ats.GetTypeArgsAll().Count; i++)
{
if (TypeContainsType(ats.GetTypeArgsAll()[i], typeFind))
return true;
}
}
return false;
case TypeKind.TK_ErrorType:
if (type.AsErrorType().HasParent())
{
ErrorType err = type.AsErrorType();
Debug.Assert(err.nameText != null && err.typeArgs != null);
for (int i = 0; i < err.typeArgs.Count; i++)
{
if (TypeContainsType(err.typeArgs[i], typeFind))
return true;
}
if (err.HasTypeParent())
{
type = err.GetTypeParent();
goto LRecurse;
}
}
return false;
case TypeKind.TK_TypeParameterType:
return false;
}
}
public static bool TypeContainsTyVars(CType type, TypeArray typeVars)
{
LRecurse: // Label used for "tail" recursion.
switch (type.GetTypeKind())
{
default:
Debug.Assert(false, "Bad Symbol kind in TypeContainsTyVars");
return false;
case TypeKind.TK_UnboundLambdaType:
case TypeKind.TK_BoundLambdaType:
case TypeKind.TK_NullType:
case TypeKind.TK_VoidType:
case TypeKind.TK_OpenTypePlaceholderType:
case TypeKind.TK_MethodGroupType:
return false;
case TypeKind.TK_ArrayType:
case TypeKind.TK_NullableType:
case TypeKind.TK_ParameterModifierType:
case TypeKind.TK_PointerType:
type = type.GetBaseOrParameterOrElementType();
goto LRecurse;
case TypeKind.TK_AggregateType:
{ // BLOCK
AggregateType ats = type.AsAggregateType();
for (int i = 0; i < ats.GetTypeArgsAll().Count; i++)
{
if (TypeContainsTyVars(ats.GetTypeArgsAll()[i], typeVars))
{
return true;
}
}
}
return false;
case TypeKind.TK_ErrorType:
if (type.AsErrorType().HasParent())
{
ErrorType err = type.AsErrorType();
Debug.Assert(err.nameText != null && err.typeArgs != null);
for (int i = 0; i < err.typeArgs.Count; i++)
{
if (TypeContainsTyVars(err.typeArgs[i], typeVars))
{
return true;
}
}
if (err.HasTypeParent())
{
type = err.GetTypeParent();
goto LRecurse;
}
}
return false;
case TypeKind.TK_TypeParameterType:
if (typeVars != null && typeVars.Count > 0)
{
int ivar = type.AsTypeParameterType().GetIndexInTotalParameters();
return ivar < typeVars.Count && type == typeVars[ivar];
}
return true;
}
}
public static bool ParametersContainTyVar(TypeArray @params, TypeParameterType typeFind)
{
Debug.Assert(@params != null);
Debug.Assert(typeFind != null);
for (int p = 0; p < @params.Count; p++)
{
CType sym = @params[p];
if (TypeContainsType(sym, typeFind))
{
return true;
}
}
return false;
}
public AggregateSymbol GetReqPredefAgg(PredefinedType pt)
{
return _predefTypes.GetReqPredefAgg(pt);
}
public AggregateSymbol GetOptPredefAgg(PredefinedType pt)
{
return _predefTypes.GetOptPredefAgg(pt);
}
public TypeArray CreateArrayOfUnitTypes(int cSize)
{
CType[] ppArray = new CType[cSize];
for (int i = 0; i < cSize; i++)
{
ppArray[i] = GetUnitType();
}
return _BSymmgr.AllocParams(cSize, ppArray);
}
public TypeArray ConcatenateTypeArrays(TypeArray pTypeArray1, TypeArray pTypeArray2)
{
return _BSymmgr.ConcatParams(pTypeArray1, pTypeArray2);
}
public TypeArray GetStdMethTyVarArray(int cTyVars)
{
TypeParameterType[] prgvar = new TypeParameterType[cTyVars];
for (int ivar = 0; ivar < cTyVars; ivar++)
{
prgvar[ivar] = GetStdMethTypeVar(ivar);
}
return _BSymmgr.AllocParams(cTyVars, (CType[])prgvar);
}
public CType SubstType(CType typeSrc, SubstContext pctx)
{
return (pctx == null || pctx.FNop()) ? typeSrc : SubstTypeCore(typeSrc, pctx);
}
public CType SubstType(CType typeSrc, AggregateType atsCls)
{
return SubstType(typeSrc, atsCls, (TypeArray)null);
}
public CType SubstType(CType typeSrc, AggregateType atsCls, TypeArray typeArgsMeth)
{
return SubstType(typeSrc, atsCls?.GetTypeArgsAll(), typeArgsMeth);
}
public CType SubstType(CType typeSrc, CType typeCls, TypeArray typeArgsMeth)
{
return SubstType(typeSrc, typeCls.IsAggregateType() ? typeCls.AsAggregateType().GetTypeArgsAll() : null, typeArgsMeth);
}
public TypeArray SubstTypeArray(TypeArray taSrc, AggregateType atsCls, TypeArray typeArgsMeth)
{
return SubstTypeArray(taSrc, atsCls?.GetTypeArgsAll(), typeArgsMeth);
}
public TypeArray SubstTypeArray(TypeArray taSrc, AggregateType atsCls)
{
return this.SubstTypeArray(taSrc, atsCls, (TypeArray)null);
}
private bool SubstEqualTypes(CType typeDst, CType typeSrc, CType typeCls, TypeArray typeArgsMeth)
{
return SubstEqualTypes(typeDst, typeSrc, typeCls.IsAggregateType() ? typeCls.AsAggregateType().GetTypeArgsAll() : null, typeArgsMeth, SubstTypeFlags.NormNone);
}
public bool SubstEqualTypes(CType typeDst, CType typeSrc, CType typeCls)
{
return SubstEqualTypes(typeDst, typeSrc, typeCls, (TypeArray)null);
}
//public bool SubstEqualTypeArrays(TypeArray taDst, TypeArray taSrc, AggregateType atsCls, TypeArray typeArgsMeth)
//{
// return SubstEqualTypeArrays(taDst, taSrc, atsCls != null ? atsCls.GetTypeArgsAll() : (TypeArray)null, typeArgsMeth, SubstTypeFlags.NormNone);
//}
public TypeParameterType GetStdMethTypeVar(int iv)
{
return _stvcMethod.GetTypeVarSym(iv, this, true);
}
private TypeParameterType GetStdClsTypeVar(int iv)
{
return _stvcClass.GetTypeVarSym(iv, this, false);
}
public TypeParameterType GetTypeParameter(TypeParameterSymbol pSymbol)
{
// These guys should be singletons for each.
TypeParameterType pTypeParameter = _typeTable.LookupTypeParameter(pSymbol);
if (pTypeParameter == null)
{
pTypeParameter = _typeFactory.CreateTypeParameter(pSymbol);
_typeTable.InsertTypeParameter(pSymbol, pTypeParameter);
}
return pTypeParameter;
}
internal void Init(BSYMMGR bsymmgr, PredefinedTypes predefTypes)
{
_BSymmgr = bsymmgr;
_predefTypes = predefTypes;
}
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// RUNTIME BINDER ONLY CHANGE
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
internal bool GetBestAccessibleType(CSemanticChecker semanticChecker, BindingContext bindingContext, CType typeSrc, out CType typeDst)
{
// This method implements the "best accessible type" algorithm for determining the type
// of untyped arguments in the runtime binder. It is also used in method type inference
// to fix type arguments to types that are accessible.
// The new type is returned in an out parameter. The result will be true (and the out param
// non-null) only when the algorithm could find a suitable accessible type.
Debug.Assert(semanticChecker != null);
Debug.Assert(bindingContext != null);
Debug.Assert(typeSrc != null);
typeDst = null;
if (semanticChecker.CheckTypeAccess(typeSrc, bindingContext.ContextForMemberLookup))
{
// If we already have an accessible type, then use it. This is the terminal point of the recursion.
typeDst = typeSrc;
return true;
}
// These guys have no accessibility concerns.
Debug.Assert(!typeSrc.IsVoidType() && !typeSrc.IsErrorType() && !typeSrc.IsTypeParameterType());
if (typeSrc.IsParameterModifierType() || typeSrc.IsPointerType())
{
// We cannot vary these.
return false;
}
CType intermediateType;
if ((typeSrc.isInterfaceType() || typeSrc.isDelegateType()) && TryVarianceAdjustmentToGetAccessibleType(semanticChecker, bindingContext, typeSrc.AsAggregateType(), out intermediateType))
{
// If we have an interface or delegate type, then it can potentially be varied by its type arguments
// to produce an accessible type, and if that's the case, then return that.
// Example: IEnumerable<PrivateConcreteFoo> --> IEnumerable<PublicAbstractFoo>
typeDst = intermediateType;
Debug.Assert(semanticChecker.CheckTypeAccess(typeDst, bindingContext.ContextForMemberLookup));
return true;
}
if (typeSrc.IsArrayType() && TryArrayVarianceAdjustmentToGetAccessibleType(semanticChecker, bindingContext, typeSrc.AsArrayType(), out intermediateType))
{
// Similarly to the interface and delegate case, arrays are covariant in their element type and
// so we can potentially produce an array type that is accessible.
// Example: PrivateConcreteFoo[] --> PublicAbstractFoo[]
typeDst = intermediateType;
Debug.Assert(semanticChecker.CheckTypeAccess(typeDst, bindingContext.ContextForMemberLookup));
return true;
}
if (typeSrc.IsNullableType())
{
// We have an inaccessible nullable type, which means that the best we can do is System.ValueType.
typeDst = this.GetOptPredefAgg(PredefinedType.PT_VALUE).getThisType();
Debug.Assert(semanticChecker.CheckTypeAccess(typeDst, bindingContext.ContextForMemberLookup));
return true;
}
if (typeSrc.IsArrayType())
{
// We have an inaccessible array type for which we could not earlier find a better array type
// with a covariant conversion, so the best we can do is System.Array.
typeDst = this.GetReqPredefAgg(PredefinedType.PT_ARRAY).getThisType();
Debug.Assert(semanticChecker.CheckTypeAccess(typeDst, bindingContext.ContextForMemberLookup));
return true;
}
Debug.Assert(typeSrc.IsAggregateType());
if (typeSrc.IsAggregateType())
{
// We have an AggregateType, so recurse on its base class.
AggregateType aggType = typeSrc.AsAggregateType();
AggregateType baseType = aggType.GetBaseClass();
if (baseType == null)
{
// This happens with interfaces, for instance. But in that case, the
// conversion to object does exist, is an implicit reference conversion,
// and so we will use it.
baseType = this.GetReqPredefAgg(PredefinedType.PT_OBJECT).getThisType();
}
return GetBestAccessibleType(semanticChecker, bindingContext, baseType, out typeDst);
}
return false;
}
private bool TryVarianceAdjustmentToGetAccessibleType(CSemanticChecker semanticChecker, BindingContext bindingContext, AggregateType typeSrc, out CType typeDst)
{
Debug.Assert(typeSrc != null);
Debug.Assert(typeSrc.isInterfaceType() || typeSrc.isDelegateType());
typeDst = null;
AggregateSymbol aggSym = typeSrc.GetOwningAggregate();
AggregateType aggOpenType = aggSym.getThisType();
if (!semanticChecker.CheckTypeAccess(aggOpenType, bindingContext.ContextForMemberLookup))
{
// if the aggregate symbol itself is not accessible, then forget it, there is no
// variance that will help us arrive at an accessible type.
return false;
}
TypeArray typeArgs = typeSrc.GetTypeArgsThis();
TypeArray typeParams = aggOpenType.GetTypeArgsThis();
CType[] newTypeArgsTemp = new CType[typeArgs.Count];
for (int i = 0; i < typeArgs.Count; i++)
{
if (semanticChecker.CheckTypeAccess(typeArgs[i], bindingContext.ContextForMemberLookup))
{
// we have an accessible argument, this position is not a problem.
newTypeArgsTemp[i] = typeArgs[i];
continue;
}
if (!typeArgs[i].IsRefType() || !typeParams[i].AsTypeParameterType().Covariant)
{
// This guy is inaccessible, and we are not going to be able to vary him, so we need to fail.
return false;
}
CType intermediateTypeArg;
if (GetBestAccessibleType(semanticChecker, bindingContext, typeArgs[i], out intermediateTypeArg))
{
// now we either have a value type (which must be accessible due to the above
// check, OR we have an inaccessible type (which must be a ref type). In either
// case, the recursion worked out and we are OK to vary this argument.
newTypeArgsTemp[i] = intermediateTypeArg;
continue;
}
else
{
Debug.Assert(false, "GetBestAccessibleType unexpectedly failed on a type that was used as a type parameter");
return false;
}
}
TypeArray newTypeArgs = semanticChecker.getBSymmgr().AllocParams(typeArgs.Count, newTypeArgsTemp);
CType intermediateType = this.GetAggregate(aggSym, typeSrc.outerType, newTypeArgs);
// All type arguments were varied successfully, which means now we must be accessible. But we could
// have violated constraints. Let's check that out.
if (!TypeBind.CheckConstraints(semanticChecker, null/*ErrorHandling*/, intermediateType, CheckConstraintsFlags.NoErrors))
{
return false;
}
typeDst = intermediateType;
Debug.Assert(semanticChecker.CheckTypeAccess(typeDst, bindingContext.ContextForMemberLookup));
return true;
}
private bool TryArrayVarianceAdjustmentToGetAccessibleType(CSemanticChecker semanticChecker, BindingContext bindingContext, ArrayType typeSrc, out CType typeDst)
{
Debug.Assert(typeSrc != null);
typeDst = null;
// We are here because we have an array type with an inaccessible element type. If possible,
// we should create a new array type that has an accessible element type for which a
// conversion exists.
CType elementType = typeSrc.GetElementType();
if (!elementType.IsRefType())
{
// Covariant array conversions exist for reference types only.
return false;
}
CType intermediateType;
if (GetBestAccessibleType(semanticChecker, bindingContext, elementType, out intermediateType))
{
typeDst = this.GetArray(intermediateType, typeSrc.rank, typeSrc.IsSZArray);
Debug.Assert(semanticChecker.CheckTypeAccess(typeDst, bindingContext.ContextForMemberLookup));
return true;
}
return false;
}
public AggregateType ObjectAggregateType => (AggregateType)_symbolTable.GetCTypeFromType(typeof(object));
private readonly Dictionary<Tuple<Assembly, Assembly>, bool> _internalsVisibleToCalculated
= new Dictionary<Tuple<Assembly, Assembly>, bool>();
internal bool InternalsVisibleTo(Assembly assemblyThatDefinesAttribute, Assembly assemblyToCheck)
{
bool result;
var key = Tuple.Create(assemblyThatDefinesAttribute, assemblyToCheck);
if (!_internalsVisibleToCalculated.TryGetValue(key, out result))
{
AssemblyName assyName = null;
// Assembly.GetName() requires FileIOPermission to FileIOPermissionAccess.PathDiscovery.
// If we don't have that (we're in low trust), then we are going to effectively turn off
// InternalsVisibleTo. The alternative is to crash when this happens.
try
{
assyName = assemblyToCheck.GetName();
}
catch (System.Security.SecurityException)
{
result = false;
goto SetMemo;
}
result = assemblyThatDefinesAttribute.GetCustomAttributes()
.OfType<InternalsVisibleToAttribute>()
.Select(ivta => new AssemblyName(ivta.AssemblyName))
.Any(an => AssemblyName.ReferenceMatchesDefinition(an, assyName));
SetMemo:
_internalsVisibleToCalculated[key] = result;
}
return result;
}
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// END RUNTIME BINDER ONLY CHANGE
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using log4net;
using Mono.Addins;
using NDesk.Options;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
namespace OpenSim.Region.CoreModules.World.Archiver
{
/// <summary>
/// This module loads and saves OpenSimulator region archives
/// </summary>
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "ArchiverModule")]
public class ArchiverModule : INonSharedRegionModule, IRegionArchiverModule
{
private static readonly ILog m_log =
LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public Scene Scene { get; private set; }
public IRegionCombinerModule RegionCombinerModule { get; private set; }
/// <value>
/// The file used to load and save an opensimulator archive if no filename has been specified
/// </value>
protected const string DEFAULT_OAR_BACKUP_FILENAME = "region.oar";
public string Name
{
get { return "RegionArchiverModule"; }
}
public Type ReplaceableInterface
{
get { return null; }
}
public void Initialise(IConfigSource source)
{
//m_log.Debug("[ARCHIVER] Initialising");
}
public void AddRegion(Scene scene)
{
Scene = scene;
Scene.RegisterModuleInterface<IRegionArchiverModule>(this);
//m_log.DebugFormat("[ARCHIVER]: Enabled for region {0}", scene.RegionInfo.RegionName);
}
public void RegionLoaded(Scene scene)
{
RegionCombinerModule = scene.RequestModuleInterface<IRegionCombinerModule>();
}
public void RemoveRegion(Scene scene)
{
}
public void Close()
{
}
/// <summary>
/// Load a whole region from an opensimulator archive.
/// </summary>
/// <param name="cmdparams"></param>
public void HandleLoadOarConsoleCommand(string module, string[] cmdparams)
{
bool mergeOar = false;
bool skipAssets = false;
bool forceTerrain = false;
bool forceParcels = false;
bool noObjects = false;
bool persistUuids = false;
Vector3 displacement = new Vector3(0f, 0f, 0f);
String defaultUser = "";
float rotation = 0f;
Vector3 rotationCenter = new Vector3(Constants.RegionSize / 2f, Constants.RegionSize / 2f, 0);
OptionSet options = new OptionSet();
options.Add("m|merge", delegate (string v) { mergeOar = (v != null); });
options.Add("persist-uuids", delegate(string v) { persistUuids = (v != null); });
options.Add("s|skip-assets", delegate (string v) { skipAssets = (v != null); });
options.Add("force-terrain", delegate (string v) { forceTerrain = (v != null); });
options.Add("forceterrain", delegate (string v) { forceTerrain = (v != null); }); // downward compatibility
options.Add("force-parcels", delegate (string v) { forceParcels = (v != null); });
options.Add("forceparcels", delegate (string v) { forceParcels = (v != null); }); // downward compatibility
options.Add("no-objects", delegate (string v) { noObjects = (v != null); });
options.Add("default-user=", delegate(string v) { defaultUser = (v == null) ? "" : v; });
options.Add("displacement=", delegate (string v) {
try
{
displacement = v == null ? Vector3.Zero : Vector3.Parse(v);
}
catch
{
m_log.ErrorFormat("[ARCHIVER MODULE] failure parsing displacement");
m_log.ErrorFormat("[ARCHIVER MODULE] Must be represented as vector3: --displacement \"<128,128,0>\"");
return;
}
});
options.Add("rotation=", delegate(string v)
{
try
{
rotation = v == null ? 0f : float.Parse(v);
}
catch
{
m_log.ErrorFormat("[ARCHIVER MODULE] failure parsing rotation");
m_log.ErrorFormat("[ARCHIVER MODULE] Must be an angle in degrees between -360 and +360: --rotation 45");
return;
}
// Convert to radians for internals
rotation = Util.Clamp<float>(rotation, -359f, 359f) / 180f * (float)Math.PI;
});
options.Add("rotation-center=", delegate (string v) {
try
{
rotationCenter = v == null ? Vector3.Zero : Vector3.Parse(v);
}
catch
{
m_log.ErrorFormat("[ARCHIVER MODULE] failure parsing rotation displacement");
m_log.ErrorFormat("[ARCHIVER MODULE] Must be represented as vector3: --rotation-center \"<128,128,0>\"");
return;
}
});
// Send a message to the region ready module
/* bluewall* Disable this for the time being
IRegionReadyModule rready = m_scene.RequestModuleInterface<IRegionReadyModule>();
if (rready != null)
{
rready.OarLoadingAlert("load");
}
*/
List<string> mainParams = options.Parse(cmdparams);
// m_log.DebugFormat("MERGE OAR IS [{0}]", mergeOar);
//
// foreach (string param in mainParams)
// m_log.DebugFormat("GOT PARAM [{0}]", param);
Dictionary<string, object> archiveOptions = new Dictionary<string, object>();
if (mergeOar) archiveOptions.Add("merge", null);
if (skipAssets) archiveOptions.Add("skipAssets", null);
if (forceTerrain) archiveOptions.Add("force-terrain", null);
if (forceParcels) archiveOptions.Add("force-parcels", null);
if (noObjects) archiveOptions.Add("no-objects", null);
if (persistUuids) archiveOptions.Add("persist-uuids", null);
if (defaultUser != "")
{
UUID defaultUserUUID = UUID.Zero;
try
{
defaultUserUUID = Scene.UserManagementModule.GetUserIdByName(defaultUser);
}
catch
{
m_log.ErrorFormat("[ARCHIVER MODULE] default user must be in format \"First Last\"", defaultUser);
}
if (defaultUserUUID == UUID.Zero)
{
m_log.ErrorFormat("[ARCHIVER MODULE] cannot find specified default user {0}", defaultUser);
return;
}
else
{
archiveOptions.Add("default-user", defaultUserUUID);
}
}
archiveOptions.Add("displacement", displacement);
archiveOptions.Add("rotation", rotation);
archiveOptions.Add("rotation-center", rotationCenter);
if (mainParams.Count > 2)
{
DearchiveRegion(mainParams[2], Guid.Empty, archiveOptions);
}
else
{
DearchiveRegion(DEFAULT_OAR_BACKUP_FILENAME, Guid.Empty, archiveOptions);
}
}
/// <summary>
/// Save a region to a file, including all the assets needed to restore it.
/// </summary>
/// <param name="cmdparams"></param>
public void HandleSaveOarConsoleCommand(string module, string[] cmdparams)
{
Dictionary<string, object> options = new Dictionary<string, object>();
OptionSet ops = new OptionSet();
// legacy argument [obsolete]
ops.Add("p|profile=", delegate(string v) { Console.WriteLine("\n WARNING: -profile option is obsolete and it will not work. Use -home instead.\n"); });
// preferred
ops.Add("h|home=", delegate(string v) { options["home"] = v; });
ops.Add("noassets", delegate(string v) { options["noassets"] = v != null; });
ops.Add("publish", v => options["wipe-owners"] = v != null);
ops.Add("perm=", delegate(string v) { options["checkPermissions"] = v; });
ops.Add("all", delegate(string v) { options["all"] = v != null; });
List<string> mainParams = ops.Parse(cmdparams);
string path;
if (mainParams.Count > 2)
path = mainParams[2];
else
path = DEFAULT_OAR_BACKUP_FILENAME;
// Not doing this right now as this causes some problems with auto-backup systems. Maybe a force flag is
// needed
// if (!ConsoleUtil.CheckFileDoesNotExist(MainConsole.Instance, path))
// return;
ArchiveRegion(path, options);
}
public void ArchiveRegion(string savePath, Dictionary<string, object> options)
{
ArchiveRegion(savePath, Guid.Empty, options);
}
public void ArchiveRegion(string savePath, Guid requestId, Dictionary<string, object> options)
{
m_log.InfoFormat(
"[ARCHIVER]: Writing archive for region {0} to {1}", Scene.RegionInfo.RegionName, savePath);
new ArchiveWriteRequest(Scene, savePath, requestId).ArchiveRegion(options);
}
public void ArchiveRegion(Stream saveStream)
{
ArchiveRegion(saveStream, Guid.Empty);
}
public void ArchiveRegion(Stream saveStream, Guid requestId)
{
ArchiveRegion(saveStream, requestId, new Dictionary<string, object>());
}
public void ArchiveRegion(Stream saveStream, Guid requestId, Dictionary<string, object> options)
{
new ArchiveWriteRequest(Scene, saveStream, requestId).ArchiveRegion(options);
}
public void DearchiveRegion(string loadPath)
{
Dictionary<string, object> archiveOptions = new Dictionary<string, object>();
DearchiveRegion(loadPath, Guid.Empty, archiveOptions);
}
public void DearchiveRegion(string loadPath, Guid requestId, Dictionary<string,object> options)
{
m_log.InfoFormat(
"[ARCHIVER]: Loading archive to region {0} from {1}", Scene.RegionInfo.RegionName, loadPath);
new ArchiveReadRequest(Scene, loadPath, requestId, options).DearchiveRegion();
}
public void DearchiveRegion(Stream loadStream)
{
Dictionary<string, object> archiveOptions = new Dictionary<string, object>();
DearchiveRegion(loadStream, Guid.Empty, archiveOptions);
}
public void DearchiveRegion(Stream loadStream, Guid requestId, Dictionary<string, object> options)
{
new ArchiveReadRequest(Scene, loadStream, requestId, options).DearchiveRegion();
}
}
}
| |
// This file has been generated by the GUI designer. Do not modify.
namespace MonoDevelop.ValaBinding
{
public partial class EditPackagesDialog
{
private global::Gtk.VPaned vpaned1;
private global::Gtk.HBox hbox1;
private global::Gtk.Notebook notebook1;
private global::Gtk.ScrolledWindow scrolledwindow1;
private global::Gtk.TreeView normalPackageTreeView;
private global::Gtk.Label label1;
private global::Gtk.ScrolledWindow scrolledwindow3;
private global::Gtk.TreeView projectPackageTreeView;
private global::Gtk.Label label2;
private global::Gtk.VBox vbox3;
private global::Gtk.Fixed fixed1;
private global::Gtk.Button detailsButton;
private global::Gtk.Table table1;
private global::Gtk.Label label3;
private global::Gtk.ScrolledWindow scrolledwindow2;
private global::Gtk.TreeView selectedPackageTreeView;
private global::Gtk.VBox vbox2;
private global::Gtk.Button removeButton;
private global::Gtk.Button buttonCancel;
private global::Gtk.Button buttonOk;
protected virtual void Build ()
{
global::Stetic.Gui.Initialize (this);
// Widget MonoDevelop.ValaBinding.EditPackagesDialog
this.Name = "MonoDevelop.ValaBinding.EditPackagesDialog";
this.Title = global::Mono.Unix.Catalog.GetString ("Edit packages");
this.Modal = true;
// Internal child MonoDevelop.ValaBinding.EditPackagesDialog.VBox
global::Gtk.VBox w1 = this.VBox;
w1.Name = "dialog1_VBox";
w1.BorderWidth = ((uint)(2));
// Container child dialog1_VBox.Gtk.Box+BoxChild
this.vpaned1 = new global::Gtk.VPaned ();
this.vpaned1.CanFocus = true;
this.vpaned1.Name = "vpaned1";
this.vpaned1.Position = 183;
this.vpaned1.BorderWidth = ((uint)(6));
// Container child vpaned1.Gtk.Paned+PanedChild
this.hbox1 = new global::Gtk.HBox ();
this.hbox1.Name = "hbox1";
this.hbox1.Spacing = 6;
// Container child hbox1.Gtk.Box+BoxChild
this.notebook1 = new global::Gtk.Notebook ();
this.notebook1.CanFocus = true;
this.notebook1.Name = "notebook1";
this.notebook1.CurrentPage = 0;
// Container child notebook1.Gtk.Notebook+NotebookChild
this.scrolledwindow1 = new global::Gtk.ScrolledWindow ();
this.scrolledwindow1.CanFocus = true;
this.scrolledwindow1.Name = "scrolledwindow1";
this.scrolledwindow1.ShadowType = ((global::Gtk.ShadowType)(1));
// Container child scrolledwindow1.Gtk.Container+ContainerChild
this.normalPackageTreeView = new global::Gtk.TreeView ();
this.normalPackageTreeView.CanFocus = true;
this.normalPackageTreeView.Name = "normalPackageTreeView";
this.scrolledwindow1.Add (this.normalPackageTreeView);
this.notebook1.Add (this.scrolledwindow1);
// Notebook tab
this.label1 = new global::Gtk.Label ();
this.label1.Name = "label1";
this.label1.LabelProp = global::Mono.Unix.Catalog.GetString ("System Packages");
this.notebook1.SetTabLabel (this.scrolledwindow1, this.label1);
this.label1.ShowAll ();
// Container child notebook1.Gtk.Notebook+NotebookChild
this.scrolledwindow3 = new global::Gtk.ScrolledWindow ();
this.scrolledwindow3.CanFocus = true;
this.scrolledwindow3.Name = "scrolledwindow3";
this.scrolledwindow3.ShadowType = ((global::Gtk.ShadowType)(1));
// Container child scrolledwindow3.Gtk.Container+ContainerChild
this.projectPackageTreeView = new global::Gtk.TreeView ();
this.projectPackageTreeView.CanFocus = true;
this.projectPackageTreeView.Name = "projectPackageTreeView";
this.scrolledwindow3.Add (this.projectPackageTreeView);
this.notebook1.Add (this.scrolledwindow3);
global::Gtk.Notebook.NotebookChild w5 = ((global::Gtk.Notebook.NotebookChild)(this.notebook1[this.scrolledwindow3]));
w5.Position = 1;
// Notebook tab
this.label2 = new global::Gtk.Label ();
this.label2.Name = "label2";
this.label2.LabelProp = global::Mono.Unix.Catalog.GetString ("Project Packages");
this.notebook1.SetTabLabel (this.scrolledwindow3, this.label2);
this.label2.ShowAll ();
this.hbox1.Add (this.notebook1);
global::Gtk.Box.BoxChild w6 = ((global::Gtk.Box.BoxChild)(this.hbox1[this.notebook1]));
w6.Position = 0;
// Container child hbox1.Gtk.Box+BoxChild
this.vbox3 = new global::Gtk.VBox ();
this.vbox3.Name = "vbox3";
this.vbox3.Spacing = 6;
// Container child vbox3.Gtk.Box+BoxChild
this.fixed1 = new global::Gtk.Fixed ();
this.fixed1.HeightRequest = 21;
this.fixed1.Name = "fixed1";
this.fixed1.HasWindow = false;
this.vbox3.Add (this.fixed1);
global::Gtk.Box.BoxChild w7 = ((global::Gtk.Box.BoxChild)(this.vbox3[this.fixed1]));
w7.Position = 0;
w7.Expand = false;
w7.Fill = false;
// Container child vbox3.Gtk.Box+BoxChild
this.detailsButton = new global::Gtk.Button ();
this.detailsButton.WidthRequest = 33;
this.detailsButton.HeightRequest = 33;
this.detailsButton.Sensitive = false;
this.detailsButton.CanFocus = true;
this.detailsButton.Name = "detailsButton";
this.detailsButton.UseUnderline = true;
this.detailsButton.Label = global::Mono.Unix.Catalog.GetString ("...");
this.vbox3.Add (this.detailsButton);
global::Gtk.Box.BoxChild w8 = ((global::Gtk.Box.BoxChild)(this.vbox3[this.detailsButton]));
w8.Position = 1;
w8.Expand = false;
w8.Fill = false;
this.hbox1.Add (this.vbox3);
global::Gtk.Box.BoxChild w9 = ((global::Gtk.Box.BoxChild)(this.hbox1[this.vbox3]));
w9.Position = 1;
w9.Expand = false;
w9.Fill = false;
this.vpaned1.Add (this.hbox1);
global::Gtk.Paned.PanedChild w10 = ((global::Gtk.Paned.PanedChild)(this.vpaned1[this.hbox1]));
w10.Resize = false;
// Container child vpaned1.Gtk.Paned+PanedChild
this.table1 = new global::Gtk.Table (((uint)(2)), ((uint)(2)), false);
this.table1.Name = "table1";
this.table1.RowSpacing = ((uint)(6));
this.table1.ColumnSpacing = ((uint)(6));
// Container child table1.Gtk.Table+TableChild
this.label3 = new global::Gtk.Label ();
this.label3.Name = "label3";
this.label3.Xalign = 0f;
this.label3.Yalign = 0f;
this.label3.LabelProp = global::Mono.Unix.Catalog.GetString ("Selected packages:");
this.table1.Add (this.label3);
global::Gtk.Table.TableChild w11 = ((global::Gtk.Table.TableChild)(this.table1[this.label3]));
w11.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child table1.Gtk.Table+TableChild
this.scrolledwindow2 = new global::Gtk.ScrolledWindow ();
this.scrolledwindow2.CanFocus = true;
this.scrolledwindow2.Name = "scrolledwindow2";
this.scrolledwindow2.ShadowType = ((global::Gtk.ShadowType)(1));
// Container child scrolledwindow2.Gtk.Container+ContainerChild
this.selectedPackageTreeView = new global::Gtk.TreeView ();
this.selectedPackageTreeView.CanFocus = true;
this.selectedPackageTreeView.Name = "selectedPackageTreeView";
this.scrolledwindow2.Add (this.selectedPackageTreeView);
this.table1.Add (this.scrolledwindow2);
global::Gtk.Table.TableChild w13 = ((global::Gtk.Table.TableChild)(this.table1[this.scrolledwindow2]));
w13.TopAttach = ((uint)(1));
w13.BottomAttach = ((uint)(2));
w13.XOptions = ((global::Gtk.AttachOptions)(4));
// Container child table1.Gtk.Table+TableChild
this.vbox2 = new global::Gtk.VBox ();
this.vbox2.Name = "vbox2";
this.vbox2.Spacing = 6;
// Container child vbox2.Gtk.Box+BoxChild
this.removeButton = new global::Gtk.Button ();
this.removeButton.TooltipMarkup = "Remove selected package from the project.";
this.removeButton.WidthRequest = 33;
this.removeButton.HeightRequest = 33;
this.removeButton.Sensitive = false;
this.removeButton.CanFocus = true;
this.removeButton.Name = "removeButton";
this.removeButton.UseUnderline = true;
// Container child removeButton.Gtk.Container+ContainerChild
global::Gtk.Alignment w14 = new global::Gtk.Alignment (0.5f, 0.5f, 0f, 0f);
// Container child GtkAlignment.Gtk.Container+ContainerChild
global::Gtk.HBox w15 = new global::Gtk.HBox ();
w15.Spacing = 2;
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Image w16 = new global::Gtk.Image ();
w16.Pixbuf = global::Stetic.IconLoader.LoadIcon (this, "gtk-remove", global::Gtk.IconSize.Menu);
w15.Add (w16);
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Label w18 = new global::Gtk.Label ();
w15.Add (w18);
w14.Add (w15);
this.removeButton.Add (w14);
this.vbox2.Add (this.removeButton);
global::Gtk.Box.BoxChild w22 = ((global::Gtk.Box.BoxChild)(this.vbox2[this.removeButton]));
w22.Position = 0;
w22.Expand = false;
w22.Fill = false;
this.table1.Add (this.vbox2);
global::Gtk.Table.TableChild w23 = ((global::Gtk.Table.TableChild)(this.table1[this.vbox2]));
w23.TopAttach = ((uint)(1));
w23.BottomAttach = ((uint)(2));
w23.LeftAttach = ((uint)(1));
w23.RightAttach = ((uint)(2));
w23.XOptions = ((global::Gtk.AttachOptions)(4));
this.vpaned1.Add (this.table1);
w1.Add (this.vpaned1);
global::Gtk.Box.BoxChild w25 = ((global::Gtk.Box.BoxChild)(w1[this.vpaned1]));
w25.Position = 0;
w25.Padding = ((uint)(3));
// Internal child MonoDevelop.ValaBinding.EditPackagesDialog.ActionArea
global::Gtk.HButtonBox w26 = this.ActionArea;
w26.Name = "dialog1_ActionArea";
w26.Spacing = 6;
w26.BorderWidth = ((uint)(5));
w26.LayoutStyle = ((global::Gtk.ButtonBoxStyle)(4));
// Container child dialog1_ActionArea.Gtk.ButtonBox+ButtonBoxChild
this.buttonCancel = new global::Gtk.Button ();
this.buttonCancel.CanDefault = true;
this.buttonCancel.CanFocus = true;
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.UseStock = true;
this.buttonCancel.UseUnderline = true;
this.buttonCancel.Label = "gtk-cancel";
this.AddActionWidget (this.buttonCancel, -6);
global::Gtk.ButtonBox.ButtonBoxChild w27 = ((global::Gtk.ButtonBox.ButtonBoxChild)(w26[this.buttonCancel]));
w27.Expand = false;
w27.Fill = false;
// Container child dialog1_ActionArea.Gtk.ButtonBox+ButtonBoxChild
this.buttonOk = new global::Gtk.Button ();
this.buttonOk.CanDefault = true;
this.buttonOk.CanFocus = true;
this.buttonOk.Name = "buttonOk";
this.buttonOk.UseStock = true;
this.buttonOk.UseUnderline = true;
this.buttonOk.Label = "gtk-ok";
this.AddActionWidget (this.buttonOk, -5);
global::Gtk.ButtonBox.ButtonBoxChild w28 = ((global::Gtk.ButtonBox.ButtonBoxChild)(w26[this.buttonOk]));
w28.Position = 1;
w28.Expand = false;
w28.Fill = false;
if ((this.Child != null)) {
this.Child.ShowAll ();
}
this.DefaultWidth = 580;
this.DefaultHeight = 449;
this.Show ();
this.normalPackageTreeView.CursorChanged += new global::System.EventHandler (this.OnNonSelectedPackageCursorChanged);
this.projectPackageTreeView.CursorChanged += new global::System.EventHandler (this.OnNonSelectedPackageCursorChanged);
this.detailsButton.Clicked += new global::System.EventHandler (this.OnDetailsButtonClicked);
this.removeButton.Clicked += new global::System.EventHandler (this.OnRemoveButtonClicked);
this.removeButton.Clicked += new global::System.EventHandler (this.OnRemoveButtonClick);
this.selectedPackageTreeView.CursorChanged += new global::System.EventHandler (this.OnSelectedPackagesTreeViewCursorChanged);
this.buttonCancel.Clicked += new global::System.EventHandler (this.OnCancelButtonClick);
this.buttonOk.Clicked += new global::System.EventHandler (this.OnOkButtonClick);
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace Gorge.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
using UnityEngine;
using Cinemachine.Utility;
using System.Collections.Generic;
namespace Cinemachine
{
/// <summary>
/// The output of the Cinemachine engine for a specific virtual camera. The information
/// in this struct can be blended, and provides what is needed to calculate an
/// appropriate camera position, orientation, and lens setting.
///
/// Raw values are what the Cinemachine behaviours generate. The correction channel
/// holds perturbations to the raw values - e.g. noise or smoothing, or obstacle
/// avoidance corrections. Coirrections are not considered when making time-based
/// calculations such as damping.
///
/// The Final position and orientation is the comination of the raw values and
/// their corrections.
/// </summary>
public struct CameraState
{
/// <summary>
/// Camera Lens Settings.
/// </summary>
public LensSettings Lens { get; set; }
/// <summary>
/// Which way is up. World space unit vector.
/// </summary>
public Vector3 ReferenceUp { get; set; }
/// <summary>
/// The world space focus point of the camera. What the camera wants to look at.
/// There is a special constant define to represent "nothing". Be careful to
/// check for that (or check the HasLookAt property).
/// </summary>
public Vector3 ReferenceLookAt { get; set; }
/// <summary>
/// Returns true if this state has a valid ReferenceLookAt value.
/// </summary>
public bool HasLookAt { get { return ReferenceLookAt == ReferenceLookAt; } } // will be false if NaN
/// <summary>
/// This constant represents "no point in space" or "no direction".
/// </summary>
public static Vector3 kNoPoint = new Vector3(float.NaN, float.NaN, float.NaN);
/// <summary>
/// Raw (un-corrected) world space position of this camera
/// </summary>
public Vector3 RawPosition { get; set; }
/// <summary>
/// Raw (un-corrected) world space orientation of this camera
/// </summary>
public Quaternion RawOrientation { get; set; }
/// <summary>This is a way for the Body component to bypass aim damping,
/// useful for when the body need to rotate its point of view, but does not
/// want interference from the aim damping</summary>
internal Vector3 PositionDampingBypass { get; set; }
/// <summary>
/// Subjective estimation of how "good" the shot is.
/// Larger values mean better quality. Default is 1.
/// </summary>
public float ShotQuality { get; set; }
/// <summary>
/// Position correction. This will be added to the raw position.
/// This value doesn't get fed back into the system when calculating the next frame.
/// Can be noise, or smoothing, or both, or something else.
/// </summary>
public Vector3 PositionCorrection { get; set; }
/// <summary>
/// Orientation correction. This will be added to the raw orientation.
/// This value doesn't get fed back into the system when calculating the next frame.
/// Can be noise, or smoothing, or both, or something else.
/// </summary>
public Quaternion OrientationCorrection { get; set; }
/// <summary>
/// Position with correction applied.
/// </summary>
public Vector3 CorrectedPosition { get { return RawPosition + PositionCorrection; } }
/// <summary>
/// Orientation with correction applied.
/// </summary>
public Quaternion CorrectedOrientation { get { return RawOrientation * OrientationCorrection; } }
/// <summary>
/// Position with correction applied. This is what the final camera gets.
/// </summary>
public Vector3 FinalPosition { get { return RawPosition + PositionCorrection; } }
/// <summary>
/// Orientation with correction and dutch applied. This is what the final camera gets.
/// </summary>
public Quaternion FinalOrientation
{
get
{
if (Mathf.Abs(Lens.Dutch) > UnityVectorExtensions.Epsilon)
return CorrectedOrientation * Quaternion.AngleAxis(Lens.Dutch, Vector3.forward);
return CorrectedOrientation;
}
}
/// <summary>
/// State with default values
/// </summary>
public static CameraState Default
{
get
{
CameraState state = new CameraState();
state.Lens = LensSettings.Default;
state.ReferenceUp = Vector3.up;
state.ReferenceLookAt = kNoPoint;
state.RawPosition = Vector3.zero;
state.RawOrientation = Quaternion.identity;
state.ShotQuality = 1;
state.PositionCorrection = Vector3.zero;
state.OrientationCorrection = Quaternion.identity;
state.PositionDampingBypass = Vector3.zero;
return state;
}
}
/// <summary>Opaque structure represent extra blendable stuff and its weight.
/// The base system ignores this data - it is intended for extension modules</summary>
public struct CustomBlendable
{
/// <summary>The custom stuff that the extention module will consider</summary>
public Object m_Custom;
/// <summary>The weight of the custom stuff. Must be 0...1</summary>
public float m_Weight;
/// <summary>Constructor with specific values</summary>
/// <param name="custom">The custom stuff that the extention module will consider</param>
/// <param name="weight">The weight of the custom stuff. Must be 0...1</param>
public CustomBlendable(Object custom, float weight)
{ m_Custom = custom; m_Weight = weight; }
};
// This is to avoid excessive GC allocs
CustomBlendable mCustom0;
CustomBlendable mCustom1;
CustomBlendable mCustom2;
CustomBlendable mCustom3;
List<CustomBlendable> m_CustomOverflow;
/// <summary>The number of custom blendables that will be applied to the camera.
/// The base system manages but otherwise ignores this data - it is intended for
/// extension modules</summary>
public int NumCustomBlendables { get; private set; }
/// <summary>Get a custom blendable that will be applied to the camera.
/// The base system manages but otherwise ignores this data - it is intended for
/// extension modules</summary>
/// <param name="index">Which one to get. Must be in range [0...NumCustomBlendables)</param>
/// <returns>The custom blendable at the specified index.</returns>
public CustomBlendable GetCustomBlendable(int index)
{
switch (index)
{
case 0: return mCustom0;
case 1: return mCustom1;
case 2: return mCustom2;
case 3: return mCustom3;
default:
{
index -= 4;
if (m_CustomOverflow != null && index < m_CustomOverflow.Count)
return m_CustomOverflow[index];
return new CustomBlendable(null, 0);
}
}
}
int FindCustomBlendable(Object custom)
{
if (mCustom0.m_Custom == custom)
return 0;
if (mCustom1.m_Custom == custom)
return 1;
if (mCustom2.m_Custom == custom)
return 2;
if (mCustom3.m_Custom == custom)
return 3;
if (m_CustomOverflow != null)
{
for (int i = 0; i < m_CustomOverflow.Count; ++i)
if (m_CustomOverflow[i].m_Custom == custom)
return i + 4;
}
return -1;
}
/// <summary>Add a custom blendable to the pot for eventual application to the camera.
/// The base system manages but otherwise ignores this data - it is intended for
/// extension modules</summary>
/// <param name="b">The custom blendable to add. If b.m_Custom is the same as an
/// already-added custom blendable, then they will be merged and the weights combined.</param>
public void AddCustomBlendable(CustomBlendable b)
{
// Attempt to merge common blendables to avoid growth
int index = FindCustomBlendable(b.m_Custom);
if (index >= 0)
b.m_Weight += GetCustomBlendable(index).m_Weight;
else
{
index = NumCustomBlendables;
NumCustomBlendables = index + 1;
}
switch (index)
{
case 0: mCustom0 = b; break;
case 1: mCustom1 = b; break;
case 2: mCustom2 = b; break;
case 3: mCustom3 = b; break;
default:
{
if (m_CustomOverflow == null)
m_CustomOverflow = new List<CustomBlendable>();
m_CustomOverflow.Add(b);
break;
}
}
}
/// <summary>Intelligently blend the contents of two states.</summary>
/// <param name="stateA">The first state, corresponding to t=0</param>
/// <param name="stateB">The second state, corresponding to t=1</param>
/// <param name="t">How much to interpolate. Internally clamped to 0..1</param>
/// <returns>Linearly interpolated CameraState</returns>
public static CameraState Lerp(CameraState stateA, CameraState stateB, float t)
{
t = Mathf.Clamp01(t);
float adjustedT = t;
CameraState state = new CameraState();
state.Lens = LensSettings.Lerp(stateA.Lens, stateB.Lens, t);
state.ReferenceUp = Vector3.Slerp(stateA.ReferenceUp, stateB.ReferenceUp, t);
state.RawPosition = Vector3.Lerp(stateA.RawPosition, stateB.RawPosition, t);
state.ShotQuality = Mathf.Lerp(stateA.ShotQuality, stateB.ShotQuality, t);
state.PositionCorrection = Vector3.Lerp(
stateA.PositionCorrection, stateB.PositionCorrection, t);
// GML todo: is this right? Can it introduce a roll?
state.OrientationCorrection = Quaternion.Slerp(
stateA.OrientationCorrection, stateB.OrientationCorrection, t);
Vector3 dirTarget = Vector3.zero;
if (!stateA.HasLookAt || !stateB.HasLookAt)
state.ReferenceLookAt = kNoPoint; // can't interpolate if undefined
else
{
// Re-interpolate FOV to preserve target composition, if possible
float fovA = stateA.Lens.FieldOfView;
float fovB = stateB.Lens.FieldOfView;
if (!state.Lens.Orthographic && !Mathf.Approximately(fovA, fovB))
{
LensSettings lens = state.Lens;
lens.FieldOfView = state.InterpolateFOV(
fovA, fovB,
Mathf.Max((stateA.ReferenceLookAt - stateA.CorrectedPosition).magnitude, stateA.Lens.NearClipPlane),
Mathf.Max((stateB.ReferenceLookAt - stateB.CorrectedPosition).magnitude, stateB.Lens.NearClipPlane), t);
state.Lens = lens;
// Make sure we preserve the screen composition through FOV changes
adjustedT = Mathf.Abs((lens.FieldOfView - fovA) / (fovB - fovA));
}
// Linear interpolation of lookAt target point
state.ReferenceLookAt = Vector3.Lerp(
stateA.ReferenceLookAt, stateB.ReferenceLookAt, adjustedT);
// If orientations are different, use LookAt to blend them
float angle = Quaternion.Angle(stateA.RawOrientation, stateB.RawOrientation);
if (angle > UnityVectorExtensions.Epsilon)
dirTarget = state.ReferenceLookAt - state.CorrectedPosition;
}
// Clever orientation interpolation
if (dirTarget.AlmostZero())
{
// Don't know what we're looking at - can only slerp
state.RawOrientation = UnityQuaternionExtensions.SlerpWithReferenceUp(
stateA.RawOrientation, stateB.RawOrientation, t, state.ReferenceUp);
}
else
{
// Rotate while preserving our lookAt target
dirTarget = dirTarget.normalized;
if ((dirTarget - state.ReferenceUp).AlmostZero()
|| (dirTarget + state.ReferenceUp).AlmostZero())
{
// Looking up or down at the pole
state.RawOrientation = UnityQuaternionExtensions.SlerpWithReferenceUp(
stateA.RawOrientation, stateB.RawOrientation, t, state.ReferenceUp);
}
else
{
// Put the target in the center
state.RawOrientation = Quaternion.LookRotation(dirTarget, state.ReferenceUp);
// Blend the desired offsets from center
Vector2 deltaA = -stateA.RawOrientation.GetCameraRotationToTarget(
stateA.ReferenceLookAt - stateA.CorrectedPosition, stateA.ReferenceUp);
Vector2 deltaB = -stateB.RawOrientation.GetCameraRotationToTarget(
stateB.ReferenceLookAt - stateB.CorrectedPosition, stateB.ReferenceUp);
state.RawOrientation = state.RawOrientation.ApplyCameraRotation(
Vector2.Lerp(deltaA, deltaB, adjustedT), state.ReferenceUp);
}
}
// Accumulate the custom blendables and apply the weights
for (int i = 0; i < stateA.NumCustomBlendables; ++i)
{
CustomBlendable b = stateA.GetCustomBlendable(i);
b.m_Weight *= (1-t);
if (b.m_Weight > UnityVectorExtensions.Epsilon)
state.AddCustomBlendable(b);
}
for (int i = 0; i < stateB.NumCustomBlendables; ++i)
{
CustomBlendable b = stateB.GetCustomBlendable(i);
b.m_Weight *= t;
if (b.m_Weight > UnityVectorExtensions.Epsilon)
state.AddCustomBlendable(b);
}
return state;
}
float InterpolateFOV(float fovA, float fovB, float dA, float dB, float t)
{
// We interpolate shot height
float hA = dA * 2f * Mathf.Tan(fovA * Mathf.Deg2Rad / 2f);
float hB = dB * 2f * Mathf.Tan(fovB * Mathf.Deg2Rad / 2f);
float h = Mathf.Lerp(hA, hB, t);
float fov = 179f;
float d = Mathf.Lerp(dA, dB, t);
if (d > UnityVectorExtensions.Epsilon)
fov = 2f * Mathf.Atan(h / (2 * d)) * Mathf.Rad2Deg;
return Mathf.Clamp(fov, Mathf.Min(fovA, fovB), Mathf.Max(fovA, fovB));
}
}
}
| |
/*
* Copyright (c) Contributors, http://aurora-sim.org/, 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 Aurora-Sim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Serialization;
using Aurora.Framework;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
namespace Aurora.Framework
{
/// <summary>
/// Details of a Parcel of land
/// </summary>
public class LandData : IDataTransferable
{
private Vector3 _AABBMax;
private Vector3 _AABBMin;
private int _Maturity;
private float _MediaLoopSet;
private int _area;
private uint _auctionID;
private UUID _authBuyerID = UUID.Zero;
private byte[] _bitmap = new byte[512];
private ParcelCategory _category = ParcelCategory.None;
private bool _firstParty = false;
private int _claimDate;
private int _claimPrice;
private string _description = String.Empty;
private int _dwell;
private uint _flags = (uint) ParcelFlags.AllowFly | (uint) ParcelFlags.AllowLandmark |
(uint) ParcelFlags.AllowAPrimitiveEntry |
(uint) ParcelFlags.AllowDeedToGroup | (uint) ParcelFlags.AllowTerraform |
(uint) ParcelFlags.CreateObjects | (uint) ParcelFlags.AllowOtherScripts |
(uint) ParcelFlags.SoundLocal | (uint) ParcelFlags.AllowVoiceChat;
private UUID _globalID = UUID.Zero;
private UUID _groupID = UUID.Zero;
protected UUID _infoUUID;
private bool _isGroupOwned;
private byte _landingType = 2;
private int _localID;
private byte _mediaAutoScale;
private string _mediaDescription = "";
private int _mediaHeight;
private UUID _mediaID = UUID.Zero;
private bool _mediaLoop;
private string _mediaType = "none/none";
private string _mediaURL = String.Empty;
private int _mediaWidth;
private string _musicURL = String.Empty;
private string _name = "Your Parcel";
private bool _obscureMedia;
private bool _obscureMusic;
private int _otherCleanTime;
private UUID _ownerID = UUID.Zero;
private List<ParcelManager.ParcelAccessEntry> _parcelAccessList = new List<ParcelManager.ParcelAccessEntry>();
private float _passHours;
private int _passPrice;
private bool _private;
private ulong _regionHandle;
private UUID _regionID;
private UUID _scopeID;
private int _salePrice;
private UUID _snapshotID = UUID.Zero;
private ParcelStatus _status = ParcelStatus.Leased;
private Vector3 _userLocation;
private Vector3 _userLookAt;
private OSDMap m_GenericMap = new OSDMap();
#region constructor
public LandData()
{
_globalID = UUID.Random();
}
public LandData(OSDMap map)
{
FromOSD(map);
}
#endregion
#region properties
/// <summary>
/// Whether to obscure parcel media URL
/// </summary>
[XmlIgnore]
public bool ObscureMedia
{
get { return _obscureMedia; }
set { _obscureMedia = value; }
}
/// <summary>
/// Whether to obscure parcel music URL
/// </summary>
[XmlIgnore]
public bool ObscureMusic
{
get { return _obscureMusic; }
set { _obscureMusic = value; }
}
/// <summary>
/// Whether to loop parcel media
/// </summary>
[XmlIgnore]
public bool MediaLoop
{
get { return _mediaLoop; }
set { _mediaLoop = value; }
}
/// <summary>
/// Height of parcel media render
/// </summary>
[XmlIgnore]
public int MediaHeight
{
get { return _mediaHeight; }
set { _mediaHeight = value; }
}
public float MediaLoopSet
{
get { return _MediaLoopSet; }
set { _MediaLoopSet = value; }
}
/// <summary>
/// Width of parcel media render
/// </summary>
[XmlIgnore]
public int MediaWidth
{
get { return _mediaWidth; }
set { _mediaWidth = value; }
}
/// <summary>
/// Upper corner of the AABB for the parcel
/// </summary>
[XmlIgnore]
public Vector3 AABBMax
{
get { return _AABBMax; }
set { _AABBMax = value; }
}
/// <summary>
/// Lower corner of the AABB for the parcel
/// </summary>
[XmlIgnore]
public Vector3 AABBMin
{
get { return _AABBMin; }
set { _AABBMin = value; }
}
/// <summary>
/// Area in meters^2 the parcel contains
/// </summary>
public int Area
{
get { return _area; }
set { _area = value; }
}
/// <summary>
/// ID of auction (3rd Party Integration) when parcel is being auctioned
/// </summary>
public uint AuctionID
{
get { return _auctionID; }
set { _auctionID = value; }
}
/// <summary>
/// UUID of authorized buyer of parcel. This is UUID.Zero if anyone can buy it.
/// </summary>
public UUID AuthBuyerID
{
get { return _authBuyerID; }
set { _authBuyerID = value; }
}
/// <summary>
/// Category of parcel. Used for classifying the parcel in classified listings
/// </summary>
public ParcelCategory Category
{
get { return _category; }
set {
_category = value;
}
}
public bool FirstParty
{
get { return _firstParty; }
set { _firstParty = value; }
}
/// <summary>
/// Date that the current owner purchased or claimed the parcel
/// </summary>
public int ClaimDate
{
get { return _claimDate; }
set { _claimDate = value; }
}
/// <summary>
/// The last price that the parcel was sold at
/// </summary>
public int ClaimPrice
{
get { return _claimPrice; }
set { _claimPrice = value; }
}
/// <summary>
/// Global ID for the parcel. (3rd Party Integration)
/// </summary>
public UUID GlobalID
{
get { return _globalID; }
set { _globalID = value; }
}
/// <summary>
/// Grid Wide ID for the parcel.
/// </summary>
public UUID InfoUUID
{
get { return _infoUUID; }
set { _infoUUID = value; }
}
/// <summary>
/// Unique ID of the Group that owns
/// </summary>
public UUID GroupID
{
get { return _groupID; }
set { _groupID = value; }
}
/// <summary>
/// Returns true if the Land Parcel is owned by a group
/// </summary>
public bool IsGroupOwned
{
get { return _isGroupOwned; }
set { _isGroupOwned = value; }
}
/// <summary>
/// jp2 data for the image representative of the parcel in the parcel dialog
/// </summary>
public byte[] Bitmap
{
get { return _bitmap; }
set { _bitmap = value; }
}
/// <summary>
/// Parcel Description
/// </summary>
public string Description
{
get { return _description; }
set { _description = value; }
}
/// <summary>
/// Parcel settings. Access flags, Fly, NoPush, Voice, Scripts allowed, etc. ParcelFlags
/// </summary>
public uint Flags
{
get { return _flags | (uint) ParcelFlags.AllowVoiceChat; }//Force add allow voice chat
set { _flags = value; }
}
/// <summary>
/// Determines if people are able to teleport where they please on the parcel or if they
/// get constrainted to a specific point on teleport within the parcel
/// </summary>
public byte LandingType
{
get { return _landingType; }
set { _landingType = value; }
}
public int Maturity
{
get { return _Maturity; }
set { _Maturity = value; }
}
public int Dwell
{
get { return _dwell; }
set { _dwell = value; }
}
/// <summary>
/// Parcel Name
/// </summary>
public string Name
{
get { return _name; }
set { _name = value; }
}
/// <summary>
/// Status of Parcel, Leased, Abandoned, For Sale
/// </summary>
public ParcelStatus Status
{
get { return _status; }
set { _status = value; }
}
/// <summary>
/// Internal ID of the parcel. Sometimes the client will try to use this value
/// </summary>
public int LocalID
{
get { return _localID; }
set { _localID = value; }
}
public ulong RegionHandle
{
get { return _regionHandle; }
set { _regionHandle = value; }
}
[XmlIgnore]
public OSDMap GenericData
{
get { return m_GenericMap; }
set { m_GenericMap = value; }
}
public UUID RegionID
{
get { return _regionID; }
set { _regionID = value; }
}
public UUID ScopeID
{
get { return _scopeID; }
set { _scopeID = value; }
}
/// <summary>
/// Determines if we scale the media based on the surface it's on
/// </summary>
public byte MediaAutoScale
{
get { return _mediaAutoScale; }
set { _mediaAutoScale = value; }
}
/// <summary>
/// Texture Guid to replace with the output of the media stream
/// </summary>
public UUID MediaID
{
get { return _mediaID; }
set { _mediaID = value; }
}
/// <summary>
/// URL to the media file to display
/// </summary>
public string MediaURL
{
get { return _mediaURL; }
set { _mediaURL = value; }
}
public string MediaType
{
get { return _mediaType; }
set { _mediaType = value; }
}
/// <summary>
/// URL to the shoutcast music stream to play on the parcel
/// </summary>
public string MusicURL
{
get { return _musicURL; }
set { _musicURL = value; }
}
/// <summary>
/// Owner Avatar or Group of the parcel. Naturally, all land masses must be
/// owned by someone
/// </summary>
public UUID OwnerID
{
get { return _ownerID; }
set { _ownerID = value; }
}
/// <summary>
/// List of access data for the parcel. User data, some bitflags, and a time
/// </summary>
public List<ParcelManager.ParcelAccessEntry> ParcelAccessList
{
get { return _parcelAccessList; }
set { _parcelAccessList = value; }
}
/// <summary>
/// How long in hours a Pass to the parcel is given
/// </summary>
public float PassHours
{
get { return _passHours; }
set { _passHours = value; }
}
/// <summary>
/// Price to purchase a Pass to a restricted parcel
/// </summary>
public int PassPrice
{
get { return _passPrice; }
set { _passPrice = value; }
}
/// <summary>
/// When the parcel is being sold, this is the price to purchase the parcel
/// </summary>
public int SalePrice
{
get { return _salePrice; }
set { _salePrice = value; }
}
/// <summary>
/// Number of meters^2 in the Simulator
/// </summary>
[XmlIgnore]
public int SimwideArea { get; set; }
/// <summary>
/// ID of the snapshot used in the client parcel dialog of the parcel
/// </summary>
public UUID SnapshotID
{
get { return _snapshotID; }
set { _snapshotID = value; }
}
/// <summary>
/// When teleporting is restricted to a certain point, this is the location
/// that the user will be redirected to
/// </summary>
public Vector3 UserLocation
{
get { return _userLocation; }
set { _userLocation = value; }
}
/// <summary>
/// When teleporting is restricted to a certain point, this is the rotation
/// that the user will be positioned
/// </summary>
public Vector3 UserLookAt
{
get { return _userLookAt; }
set { _userLookAt = value; }
}
/// <summary>
/// Number of minutes to return SceneObjectGroup that are owned by someone who doesn't own
/// the parcel and isn't set to the same 'group' as the parcel.
/// </summary>
public int OtherCleanTime
{
get { return _otherCleanTime; }
set { _otherCleanTime = value; }
}
/// <summary>
/// parcel media description
/// </summary>
public string MediaDescription
{
get { return _mediaDescription; }
set { _mediaDescription = value; }
}
public bool Private
{
get { return _private; }
set { _private = value; }
}
#endregion
public void AddGenericData(string Key, object Value)
{
if (Value is OSD)
m_GenericMap[Key] = Value as OSD;
else
m_GenericMap[Key] = OSD.FromObject(Value);
}
public void RemoveGenericData(string Key)
{
if (m_GenericMap.ContainsKey(Key))
m_GenericMap.Remove(Key);
}
/// <summary>
/// Make a new copy of the land data
/// </summary>
/// <returns></returns>
public LandData Copy()
{
LandData landData = new LandData
{
_AABBMax = _AABBMax,
_AABBMin = _AABBMin,
_area = _area,
_auctionID = _auctionID,
_authBuyerID = _authBuyerID,
_category = _category,
_claimDate = _claimDate,
_claimPrice = _claimPrice,
_globalID = _globalID,
_groupID = _groupID,
_isGroupOwned = _isGroupOwned,
_localID = _localID,
_landingType = _landingType,
_mediaAutoScale = _mediaAutoScale,
_mediaID = _mediaID,
_mediaURL = _mediaURL,
_musicURL = _musicURL,
_ownerID = _ownerID,
_bitmap = (byte[]) _bitmap.Clone(),
_description = _description,
_flags = _flags,
_name = _name,
_status = _status,
_passHours = _passHours,
_passPrice = _passPrice,
_salePrice = _salePrice,
_snapshotID = _snapshotID,
_userLocation = _userLocation,
_userLookAt = _userLookAt,
_otherCleanTime = _otherCleanTime,
_dwell = _dwell,
_mediaType = _mediaType,
_mediaDescription = _mediaDescription,
_mediaWidth = _mediaWidth,
_mediaHeight = _mediaHeight,
_mediaLoop = _mediaLoop,
_MediaLoopSet = _MediaLoopSet,
_obscureMusic = _obscureMusic,
_obscureMedia = _obscureMedia,
_regionID = _regionID,
_regionHandle = _regionHandle,
_infoUUID = _infoUUID,
_Maturity = _Maturity,
_private = _private
};
landData._parcelAccessList.Clear();
#if (!ISWIN)
foreach (ParcelManager.ParcelAccessEntry entry in _parcelAccessList)
{
ParcelManager.ParcelAccessEntry newEntry = new ParcelManager.ParcelAccessEntry
{
AgentID = entry.AgentID, Flags = entry.Flags, Time = entry.Time
};
landData._parcelAccessList.Add(newEntry);
}
#else
foreach (ParcelManager.ParcelAccessEntry newEntry in _parcelAccessList.Select(entry => new ParcelManager.ParcelAccessEntry
{
AgentID = entry.AgentID,
Flags = entry.Flags,
Time = entry.Time
}))
{
landData._parcelAccessList.Add(newEntry);
}
#endif
return landData;
}
#region IDataTransferable
public override Dictionary<string, object> ToKVP()
{
return Util.OSDToDictionary(ToOSD());
}
public override OSDMap ToOSD()
{
OSDMap map = new OSDMap();
map["GroupID"] = OSD.FromUUID(GroupID);
map["IsGroupOwned"] = OSD.FromBoolean(IsGroupOwned);
map["OwnerID"] = OSD.FromUUID(OwnerID);
map["Maturity"] = OSD.FromInteger(Maturity);
map["Area"] = OSD.FromInteger(Area);
map["AuctionID"] = OSD.FromUInteger(AuctionID);
map["SalePrice"] = OSD.FromInteger(SalePrice);
map["InfoUUID"] = OSD.FromUUID(InfoUUID);
map["Dwell"] = OSD.FromInteger(Dwell);
map["Flags"] = OSD.FromInteger((int) Flags);
map["Name"] = OSD.FromString(Name);
map["Description"] = OSD.FromString(Description);
map["UserLocation"] = OSD.FromVector3(UserLocation);
map["LocalID"] = OSD.FromInteger(LocalID);
map["GlobalID"] = OSD.FromUUID(GlobalID);
map["RegionID"] = OSD.FromUUID(RegionID);
map["ScopeID"] = OSD.FromUUID(ScopeID);
map["MediaDescription"] = OSD.FromString(MediaDescription);
map["MediaWidth"] = OSD.FromInteger(MediaWidth);
map["MediaHeight"] = OSD.FromInteger(MediaHeight);
map["MediaLoop"] = OSD.FromBoolean(MediaLoop);
map["MediaType"] = OSD.FromString(MediaType);
map["ObscureMedia"] = OSD.FromBoolean(ObscureMedia);
map["ObscureMusic"] = OSD.FromBoolean(ObscureMusic);
map["SnapshotID"] = OSD.FromUUID(SnapshotID);
map["MediaAutoScale"] = OSD.FromInteger(MediaAutoScale);
map["MediaLoopSet"] = OSD.FromReal(MediaLoopSet);
map["MediaURL"] = OSD.FromString(MediaURL);
map["MusicURL"] = OSD.FromString(MusicURL);
map["Bitmap"] = OSD.FromBinary(Bitmap);
map["Category"] = OSD.FromInteger((int) Category);
map["FirstParty"] = OSD.FromBoolean(FirstParty);
map["ClaimDate"] = OSD.FromInteger(ClaimDate);
map["ClaimPrice"] = OSD.FromInteger(ClaimPrice);
map["Status"] = OSD.FromInteger((int) Status);
map["LandingType"] = OSD.FromInteger(LandingType);
map["PassHours"] = OSD.FromReal(PassHours);
map["PassPrice"] = OSD.FromInteger(PassPrice);
map["UserLookAt"] = OSD.FromVector3(UserLookAt);
map["AuthBuyerID"] = OSD.FromUUID(AuthBuyerID);
map["OtherCleanTime"] = OSD.FromInteger(OtherCleanTime);
map["RegionHandle"] = OSD.FromULong(RegionHandle);
map["Private"] = OSD.FromBoolean(Private);
map["GenericDataMap"] = GenericData;
return map;
}
public override void FromOSD(OSDMap map)
{
RegionID = map["RegionID"].AsUUID();
ScopeID = map["ScopeID"].AsUUID();
GlobalID = map["GlobalID"].AsUUID();
LocalID = map["LocalID"].AsInteger();
SalePrice = map["SalePrice"].AsInteger();
UserLocation = map["UserLocation"].AsVector3();
UserLookAt = map["UserLookAt"].AsVector3();
Name = map["Name"].AsString();
Description = map["Description"].AsString();
Flags = (uint) map["Flags"].AsInteger();
Dwell = map["Dwell"].AsInteger();
InfoUUID = map["InfoUUID"].AsUUID();
AuctionID = map["AuctionID"].AsUInteger();
Area = map["Area"].AsInteger();
Maturity = map["Maturity"].AsInteger();
OwnerID = map["OwnerID"].AsUUID();
GroupID = map["GroupID"].AsUUID();
IsGroupOwned = (GroupID != UUID.Zero);
SnapshotID = map["SnapshotID"].AsUUID();
MediaDescription = map["MediaDescription"].AsString();
MediaWidth = map["MediaWidth"].AsInteger();
MediaHeight = map["MediaHeight"].AsInteger();
MediaLoop = map["MediaLoop"].AsBoolean();
MediaType = map["MediaType"].AsString();
ObscureMedia = map["ObscureMedia"].AsBoolean();
ObscureMusic = map["ObscureMusic"].AsBoolean();
MediaLoopSet = (float) map["MediaLoopSet"].AsReal();
MediaAutoScale = (byte) map["MediaAutoScale"].AsInteger();
MediaURL = map["MediaURL"].AsString();
MusicURL = map["MusicURL"].AsString();
Bitmap = map["Bitmap"].AsBinary();
Category = (ParcelCategory) map["Category"].AsInteger();
FirstParty = map["FirstParty"].AsBoolean();
ClaimDate = map["ClaimDate"].AsInteger();
ClaimPrice = map["ClaimPrice"].AsInteger();
Status = (ParcelStatus) map["Status"].AsInteger();
LandingType = (byte) map["LandingType"].AsInteger();
PassHours = (float) map["PassHours"].AsReal();
PassPrice = map["PassPrice"].AsInteger();
AuthBuyerID = map["AuthBuyerID"].AsUUID();
OtherCleanTime = map["OtherCleanTime"].AsInteger();
RegionHandle = map["RegionHandle"].AsULong();
Private = map["Private"].AsBoolean();
GenericData = map.ContainsKey("GenericDataMap") && map["GenericDataMap"].Type == OSDType.Map ?
(OSDMap)map["GenericDataMap"] : new OSDMap();
if ((IsGroupOwned) && (GroupID != OwnerID)) OwnerID = GroupID;
}
public override void FromKVP(Dictionary<string, object> KVP)
{
FromOSD(Util.DictionaryToOSD(KVP));
}
#endregion
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// File System.Web.UI.WebControls.TreeNodeBinding.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.Web.UI.WebControls
{
sealed public partial class TreeNodeBinding : System.Web.UI.IStateManager, ICloneable, System.Web.UI.IDataSourceViewSchemaAccessor
{
#region Methods and constructors
Object System.ICloneable.Clone()
{
return default(Object);
}
void System.Web.UI.IStateManager.LoadViewState(Object state)
{
}
Object System.Web.UI.IStateManager.SaveViewState()
{
return default(Object);
}
void System.Web.UI.IStateManager.TrackViewState()
{
}
public override string ToString()
{
return default(string);
}
public TreeNodeBinding()
{
}
#endregion
#region Properties and indexers
public string DataMember
{
get
{
return default(string);
}
set
{
}
}
public int Depth
{
get
{
return default(int);
}
set
{
}
}
public string FormatString
{
get
{
return default(string);
}
set
{
}
}
public string ImageToolTip
{
get
{
return default(string);
}
set
{
}
}
public string ImageToolTipField
{
get
{
return default(string);
}
set
{
}
}
public string ImageUrl
{
get
{
return default(string);
}
set
{
}
}
public string ImageUrlField
{
get
{
return default(string);
}
set
{
}
}
public string NavigateUrl
{
get
{
return default(string);
}
set
{
}
}
public string NavigateUrlField
{
get
{
return default(string);
}
set
{
}
}
public bool PopulateOnDemand
{
get
{
return default(bool);
}
set
{
}
}
public TreeNodeSelectAction SelectAction
{
get
{
return default(TreeNodeSelectAction);
}
set
{
}
}
public Nullable<bool> ShowCheckBox
{
get
{
return default(Nullable<bool>);
}
set
{
}
}
Object System.Web.UI.IDataSourceViewSchemaAccessor.DataSourceViewSchema
{
get
{
return default(Object);
}
set
{
}
}
bool System.Web.UI.IStateManager.IsTrackingViewState
{
get
{
return default(bool);
}
}
public string Target
{
get
{
return default(string);
}
set
{
}
}
public string TargetField
{
get
{
return default(string);
}
set
{
}
}
public string Text
{
get
{
return default(string);
}
set
{
}
}
public string TextField
{
get
{
return default(string);
}
set
{
}
}
public string ToolTip
{
get
{
return default(string);
}
set
{
}
}
public string ToolTipField
{
get
{
return default(string);
}
set
{
}
}
public string Value
{
get
{
return default(string);
}
set
{
}
}
public string ValueField
{
get
{
return default(string);
}
set
{
}
}
#endregion
}
}
| |
// 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.Diagnostics;
using System.IO;
using System.Text;
namespace OpenLiveWriter.CoreServices
{
public class StreamHelper
{
private StreamHelper()
{
}
public static long Transfer(Stream inStream, Stream outStream)
{
return Transfer(inStream, outStream, 8192, true);
}
public static long Transfer(Stream inStream, Stream outStream, int bufferSize, bool flush)
{
long totalBytes = 0;
byte[] buffer = new byte[bufferSize];
int bytesRead;
while (0 != (bytesRead = inStream.Read(buffer, 0, bufferSize)))
{
if (bytesRead < 0)
{
Debug.Fail("bytesRead was negative! " + bytesRead);
break;
}
outStream.Write(buffer, 0, bytesRead);
totalBytes += bytesRead;
}
if (flush)
outStream.Flush();
return totalBytes;
}
/// <summary>
///
/// </summary>
/// <param name="inStream"></param>
/// <param name="outStream"></param>
/// <param name="buffer"></param>
/// <returns>True if something was transferred, false if transferring is complete.</returns>
public static bool TransferIncremental(Stream inStream, Stream outStream, ref byte[] buffer, out long byteCount)
{
if (buffer == null)
buffer = new byte[8192];
int bytesRead;
bytesRead = inStream.Read(buffer, 0, buffer.Length);
if (bytesRead != 0)
{
outStream.Write(buffer, 0, bytesRead);
byteCount = bytesRead;
return true;
}
else
{
byteCount = 0;
return false;
}
}
/// <summary>
/// Read and discard the contents of the stream until EOF.
/// </summary>
public static void DiscardRest(Stream stream)
{
if (stream.CanSeek)
stream.Seek(0, SeekOrigin.End);
else
{
byte[] buf = new byte[4096];
while (stream.Read(buf, 0, buf.Length) != 0)
; // do nothing
}
}
public static byte[] AsBytes(Stream inStream)
{
MemoryStream outStr = new MemoryStream();
Transfer(inStream, outStr);
return outStr.ToArray();
}
public static string AsString(Stream inStream, Encoding enc)
{
using (StreamReader reader = new StreamReader(inStream, enc))
{
return reader.ReadToEnd();
}
}
/// <summary>
/// Return up to <c>count</c> bytes from the stream.
///
/// If EOF has been reached, returns null. Otherwise,
/// returns a byte array exactly long enough to hold
/// the actual number of bytes read (will not exceed
/// <c>count</c>).
/// </summary>
public static byte[] AsBytes(Stream inStream, int count)
{
byte[] buf = new byte[count];
int bytesRead = inStream.Read(buf, 0, count);
if (bytesRead == buf.Length)
{
return buf;
}
else if (bytesRead == -1)
{
return null;
}
else
{
byte[] shortBuf = new byte[bytesRead];
Array.Copy(buf, shortBuf, shortBuf.Length);
return shortBuf;
}
}
public static Stream AsStream(byte[] data)
{
MemoryStream inStr = new MemoryStream(data);
return inStr;
}
public static Stream CopyToMemoryStream(Stream s)
{
if (s.CanSeek)
{
// If we can find out the stream length, we can copy it in a way
// that only results in a single byte array getting instantiated.
return new MemoryStream(AsBytes(s, checked((int)s.Length)));
}
else
{
MemoryStream memStream = new MemoryStream();
Transfer(s, memStream);
memStream.Seek(0, SeekOrigin.Begin);
return memStream;
}
}
/// <summary>
/// Returns the set of bytes between a sequence of start and end bytes (including the start/end bytes).
/// </summary>
/// <param name="startBytes"></param>
/// <param name="endBytes"></param>
/// <param name="s"></param>
/// <returns></returns>
public static byte[] ExtractByteRegion(byte[] startBytes, byte[] endBytes, Stream s)
{
int b = s.ReadByte();
long startIndex = -1;
while (b != -1 && startIndex == -1)
{
if (b == startBytes[0])
{
long position = s.Position;
bool tokenMaybeFound = true;
for (int i = 1; tokenMaybeFound && i < startBytes.Length; i++)
{
b = s.ReadByte();
tokenMaybeFound = b == startBytes[i];
}
if (tokenMaybeFound)
{
b = s.ReadByte(); //move past the last byte in the startBytes
startIndex = position;
}
else
{
//move back to the last known good position
s.Seek(position, SeekOrigin.Begin);
b = s.ReadByte(); //advance to the next byte
}
}
else
b = s.ReadByte();
}
if (startIndex == -1)
return new byte[0];
MemoryStream memStream = new MemoryStream();
memStream.Write(startBytes, 0, startBytes.Length);
while (b != -1)
{
memStream.WriteByte((byte)b);
if (b == endBytes[0])
{
bool tokenMaybeFound = true;
for (int i = 1; tokenMaybeFound && i < endBytes.Length; i++)
{
b = s.ReadByte();
memStream.WriteByte((byte)b);
tokenMaybeFound = b == endBytes[i];
}
if (tokenMaybeFound)
break;
}
b = s.ReadByte();
}
return memStream.ToArray();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.Data.Common;
using System.Threading;
using System.Threading.Tasks;
#if CLUSTERING_ADONET
namespace Orleans.Clustering.AdoNet.Storage
#elif PERSISTENCE_ADONET
namespace Orleans.Persistence.AdoNet.Storage
#elif REMINDERS_ADONET
namespace Orleans.Reminders.AdoNet.Storage
#elif TESTER_SQLUTILS
namespace Orleans.Tests.SqlUtils
#else
// No default namespace intentionally to cause compile errors if something is not defined
#endif
{
/// <summary>
/// Contains some convenience methods to use in conjunction with <see cref="IRelationalStorage">IRelationalStorage</see> and <see cref="RelationalStorage">GenericRelationalStorage</see>.
/// </summary>
internal static class DbExtensions
{
/// <summary>
/// An explicit map of type CLR viz database type conversions.
/// </summary>
/// <summary>
/// An explicit map of type CLR viz database type conversions.
/// </summary>
static readonly ReadOnlyDictionary<Type, DbType> typeMap = new ReadOnlyDictionary<Type, DbType>(new Dictionary<Type, DbType>
{
{ typeof(object), DbType.Object },
{ typeof(int), DbType.Int32 },
{ typeof(int?), DbType.Int32 },
{ typeof(uint), DbType.UInt32 },
{ typeof(uint?), DbType.UInt32 },
{ typeof(long), DbType.Int64 },
{ typeof(long?), DbType.Int64 },
{ typeof(ulong), DbType.UInt64 },
{ typeof(ulong?), DbType.UInt64 },
{ typeof(float), DbType.Single },
{ typeof(float?), DbType.Single },
{ typeof(double), DbType.Double },
{ typeof(double?), DbType.Double },
{ typeof(decimal), DbType.Decimal },
{ typeof(decimal?), DbType.Decimal },
{ typeof(short), DbType.Int16 },
{ typeof(short?), DbType.Int16 },
{ typeof(ushort), DbType.UInt16 },
{ typeof(ushort?), DbType.UInt16 },
{ typeof(byte), DbType.Byte },
{ typeof(byte?), DbType.Byte },
{ typeof(sbyte), DbType.SByte },
{ typeof(sbyte?), DbType.SByte },
{ typeof(bool), DbType.Boolean },
{ typeof(bool?), DbType.Boolean },
{ typeof(string), DbType.String },
{ typeof(char), DbType.StringFixedLength },
{ typeof(char?), DbType.StringFixedLength },
{ typeof(Guid), DbType.Guid },
{ typeof(Guid?), DbType.Guid },
//Using DateTime for cross DB compatibility. The underlying DB table column type can be DateTime or DateTime2
{ typeof(DateTime), DbType.DateTime },
{ typeof(DateTime?), DbType.DateTime },
{ typeof(TimeSpan), DbType.Time },
{ typeof(byte[]), DbType.Binary },
{ typeof(TimeSpan?), DbType.Time },
{ typeof(DateTimeOffset), DbType.DateTimeOffset },
{ typeof(DateTimeOffset?), DbType.DateTimeOffset },
});
/// <summary>
/// Creates a new SQL parameter using the given arguments.
/// </summary>
/// <typeparam name="T">The type of the parameter.</typeparam>
/// <param name="command">The command to use to create the parameter.</param>
/// <param name="direction">The direction of the parameter.</param>
/// <param name="parameterName">The name of the parameter.</param>
/// <param name="value">The value of the parameter.</param>
/// <param name="size">The size of the parameter value.</param>
/// <param name="dbType">the <see cref="DbType"/> of the parameter.</param>
/// <returns>A parameter created using the given arguments.</returns>
public static IDbDataParameter CreateParameter<T>(this IDbCommand command, ParameterDirection direction, string parameterName, T value, int? size = null, DbType? dbType = null)
{
//There should be no boxing for value types. See at:
//http://stackoverflow.com/questions/8823239/comparing-a-generic-against-null-that-could-be-a-value-or-reference-type
var parameter = command.CreateParameter();
parameter.ParameterName = parameterName;
parameter.Value = (object)value ?? DBNull.Value;
parameter.DbType = dbType ?? typeMap[typeof(T)];
parameter.Direction = direction;
if (size != null) { parameter.Size = size.Value; }
return parameter;
}
/// <summary>
/// Creates and adds a new SQL parameter to the command.
/// </summary>
/// <typeparam name="T">The type of the parameter.</typeparam>
/// <param name="command">The command to use to create the parameter.</param>
/// <param name="direction">The direction of the parameter.</param>
/// <param name="parameterName">The name of the parameter.</param>
/// <param name="value">The value of the parameter.</param>
/// <param name="size">The size of the parameter value.</param>
/// <param name="dbType">the <see cref="DbType"/> of the parameter.</param>
/// <returns>A parameter created using the given arguments.</returns>
public static void AddParameter<T>(this IDbCommand command, string parameterName, T value, ParameterDirection direction = ParameterDirection.Input, int? size = null, DbType? dbType = null)
{
command.Parameters.Add(command.CreateParameter(direction, parameterName, value, size));
}
/// <summary>
/// Returns a value if it is not <see cref="System.DBNull"/>, <em>default(TValue)</em> otherwise.
/// </summary>
/// <typeparam name="TValue">The type of the value to request.</typeparam>
/// <param name="record">The record from which to retrieve the value.</param>
/// <param name="fieldName">The name of the field to retrieve.</param>
/// <param name="default">The default value if value in position is <see cref="System.DBNull"/>.</param>
/// <returns>Either the given value or the default for the requested type.</returns>
/// <exception cref="DataException"/>
/// <remarks>This function throws if the given <see paramref="fieldName"/> does not exist.</remarks>
public static TValue GetValueOrDefault<TValue>(this IDataRecord record, string fieldName, TValue @default = default(TValue))
{
try
{
var ordinal = record.GetOrdinal(fieldName);
return record.IsDBNull(ordinal) ? @default : (TValue)record.GetValue(ordinal);
}
catch (IndexOutOfRangeException e)
{
throw new DataException($"Field '{fieldName}' not found in data record.", e);
}
}
/// <summary>
/// Returns a value if it is not <see cref="System.DBNull"/>, <em>default(TValue)</em> otherwise.
/// </summary>
/// <typeparam name="TValue">The type of the value to request.</typeparam>
/// <param name="record">The record from which to retrieve the value.</param>
/// <param name="fieldName">The name of the field to retrieve.</param>
/// <param name="default">The default value if value in position is <see cref="System.DBNull"/>.</param>
/// <returns>Either the given value or the default for the requested type.</returns>
/// <exception cref="DataException"/>
/// <remarks>This function throws if the given <see paramref="fieldName"/> does not exist.</remarks>
public static async Task<TValue> GetValueOrDefaultAsync<TValue>(this DbDataReader record, string fieldName, TValue @default = default(TValue))
{
try
{
var ordinal = record.GetOrdinal(fieldName);
return (await record.IsDBNullAsync(ordinal).ConfigureAwait(false))
? @default
: (await record.GetFieldValueAsync<TValue>(ordinal).ConfigureAwait(false));
}
catch (IndexOutOfRangeException e)
{
throw new DataException($"Field '{fieldName}' not found in data record.", e);
}
}
/// <summary>
/// Returns a value if it is not <see cref="System.DBNull"/>, <em>default(TValue)</em> otherwise.
/// </summary>
/// <typeparam name="TValue">The type of the value to request.</typeparam>
/// <param name="record">The record from which to retrieve the value.</param>
/// <param name="ordinal">The ordinal of the fieldname.</param>
/// <param name="default">The default value if value in position is <see cref="System.DBNull"/>.</param>
/// <returns>Either the given value or the default for the requested type.</returns>
/// <exception cref="IndexOutOfRangeException"/>
public static TValue GetValueOrDefault<TValue>(this IDataRecord record, int ordinal, TValue @default = default(TValue))
{
return record.IsDBNull(ordinal) ? @default : (TValue)record.GetValue(ordinal);
}
/// <summary>
/// Returns a value if it is not <see cref="System.DBNull"/>, <em>default(TValue)</em> otherwise.
/// </summary>
/// <typeparam name="TValue">The type of the value to request.</typeparam>
/// <param name="record">The record from which to retrieve the value.</param>
/// <param name="ordinal">The ordinal of the fieldname.</param>
/// <param name="default">The default value if value in position is <see cref="System.DBNull"/>.</param>
/// <returns>Either the given value or the default for the requested type.</returns>
/// <exception cref="IndexOutOfRangeException"/>
public static async Task<TValue> GetValueOrDefaultAsync<TValue>(this DbDataReader record, int ordinal, TValue @default = default(TValue))
{
return (await record.IsDBNullAsync(ordinal).ConfigureAwait(false)) ? @default : (await record.GetFieldValueAsync<TValue>(ordinal).ConfigureAwait(false));
}
/// <summary>
/// Returns a value with the given <see paramref="fieldName"/>.
/// </summary>
/// <typeparam name="TValue">The type of value to retrieve.</typeparam>
/// <param name="record">The record from which to retrieve the value.</param>
/// <param name="fieldName">The name of the field.</param>
/// <returns>Value in the given field indicated by <see paramref="fieldName"/>.</returns>
/// <exception cref="DataException"/>
/// <remarks>This function throws if the given <see paramref="fieldName"/> does not exist.</remarks>
public static TValue GetValue<TValue>(this IDataRecord record, string fieldName)
{
try
{
var ordinal = record.GetOrdinal(fieldName);
return (TValue)record.GetValue(ordinal);
}
catch (IndexOutOfRangeException e)
{
throw new DataException($"Field '{fieldName}' not found in data record.", e);
}
}
/// <summary>
/// Returns a value with the given <see paramref="fieldName"/> as int.
/// </summary>
/// <param name="record">The record from which to retrieve the value.</param>
/// <param name="fieldName">The name of the field.</param>
/// <exception cref="DataException"/>
/// <returns>Integer value in the given field indicated by <see paramref="fieldName"/>.</returns>
public static int GetInt32(this IDataRecord record, string fieldName)
{
try
{
var ordinal = record.GetOrdinal(fieldName);
return record.GetInt32(ordinal);
}
catch (IndexOutOfRangeException e)
{
throw new DataException($"Field '{fieldName}' not found in data record.", e);
}
}
/// <summary>
/// Returns a value with the given <see paramref="fieldName"/> as long.
/// </summary>
/// <param name="record">The record from which to retrieve the value.</param>
/// <param name="fieldName">The name of the field.</param>
/// <exception cref="DataException"/>
/// <returns>Integer value in the given field indicated by <see paramref="fieldName"/>.</returns>
public static long GetInt64(this IDataRecord record, string fieldName)
{
try
{
var ordinal = record.GetOrdinal(fieldName);
// Original casting when old schema is used. Here to maintain backwards compatibility
return record.GetFieldType(ordinal) == typeof(int) ? record.GetInt32(ordinal) : record.GetInt64(ordinal);
}
catch (IndexOutOfRangeException e)
{
throw new DataException($"Field '{fieldName}' not found in data record.", e);
}
}
/// <summary>
/// Returns a value with the given <see paramref="fieldName"/> as nullable int.
/// </summary>
/// <param name="record">The record from which to retrieve the value.</param>
/// <param name="fieldName">The name of the field.</param>
/// <exception cref="DataException"/>
/// <returns>Nullable int value in the given field indicated by <see paramref="fieldName"/>.</returns>
public static int? GetNullableInt32(this IDataRecord record, string fieldName)
{
try
{
var ordinal = record.GetOrdinal(fieldName);
var value = record.GetValue(ordinal);
if (value == DBNull.Value)
return null;
return Convert.ToInt32(value);
}
catch (IndexOutOfRangeException e)
{
throw new DataException($"Field '{fieldName}' not found in data record.", e);
}
}
/// <summary>
/// Returns a value with the given <see paramref="fieldName"/>.
/// </summary>
/// <typeparam name="TValue">The type of value to retrieve.</typeparam>
/// <param name="record">The record from which to retrieve the value.</param>
/// <param name="fieldName">The name of the field.</param>
/// <param name="cancellationToken">The cancellation token. Defaults to <see cref="CancellationToken.None"/>.</param>
/// <returns>Value in the given field indicated by <see paramref="fieldName"/>.</returns>
/// <exception cref="DataException"/>
/// <remarks>This function throws if the given <see paramref="fieldName"/> does not exist.</remarks>
public static async Task<TValue> GetValueAsync<TValue>(this DbDataReader record, string fieldName, CancellationToken cancellationToken = default(CancellationToken))
{
try
{
var ordinal = record.GetOrdinal(fieldName);
return await record.GetFieldValueAsync<TValue>(ordinal, cancellationToken).ConfigureAwait(false);
}
catch (IndexOutOfRangeException e)
{
throw new DataException($"Field '{fieldName}' not found in data record.", e);
}
}
/// <summary>
/// Adds given parameters to a command using reflection.
/// </summary>
/// <typeparam name="T">The type of the parameters.</typeparam>
/// <param name="command">The command.</param>
/// <param name="parameters">The parameters.</param>
/// <param name="nameMap">Maps a given property name to another one defined in the map.</param>
/// <remarks>Does not support collection parameters currently. Does not cache reflection results.</remarks>
public static void ReflectionParameterProvider<T>(this IDbCommand command, T parameters, IReadOnlyDictionary<string, string> nameMap = null)
{
if (!EqualityComparer<T>.Default.Equals(parameters, default(T)))
{
var properties = parameters.GetType().GetProperties();
for (int i = 0; i < properties.Length; ++i)
{
var property = properties[i];
var value = property.GetValue(parameters, null);
var parameter = command.CreateParameter();
parameter.Value = value ?? DBNull.Value;
parameter.Direction = ParameterDirection.Input;
parameter.ParameterName = nameMap != null && nameMap.ContainsKey(properties[i].Name) ? nameMap[property.Name] : properties[i].Name;
parameter.DbType = typeMap[property.PropertyType];
command.Parameters.Add(parameter);
}
}
}
/// <summary>
/// Creates object of the given type from the results of a query.
/// </summary>
/// <typeparam name="TResult">The type to construct.</typeparam>
/// <param name="record">The record from which to read the results.</param>
/// <returns>And object of type <see typeparam="TResult"/>.</returns>
/// <remarks>Does not support <see typeparam="TResult"/> of type <em>dynamic</em>.</remarks>
public static TResult ReflectionSelector<TResult>(this IDataRecord record)
{
//This is done like this in order to box value types.
//Otherwise property.SetValue() would have a copy of the struct, which would
//get garbage collected. Consequently the original struct value would not be set.
object obj = Activator.CreateInstance<TResult>();
var properties = obj.GetType().GetProperties();
for (int i = 0; i < properties.Length; ++i)
{
var rp = record[properties[i].Name];
if (!Equals(rp, DBNull.Value))
{
properties[i].SetValue(obj, rp, null);
}
}
return (TResult)obj;
}
}
}
| |
#region License
/*
* ChunkStream.cs
*
* This code is derived from ChunkStream.cs (System.Net) of Mono
* (http://www.mono-project.com).
*
* The MIT License
*
* Copyright (c) 2003 Ximian, Inc (http://www.ximian.com)
* 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 Authors
/*
* Authors:
* - Gonzalo Paniagua Javier <gonzalo@ximian.com>
*/
#endregion
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
namespace WebSocketSharp.Net
{
internal class ChunkStream
{
#region Private Fields
private int _chunkRead;
private int _chunkSize;
private List<Chunk> _chunks;
private bool _gotIt;
private WebHeaderCollection _headers;
private StringBuilder _saved;
private bool _sawCr;
private InputChunkState _state;
private int _trailerState;
#endregion
#region Public Constructors
public ChunkStream (WebHeaderCollection headers)
{
_headers = headers;
_chunkSize = -1;
_chunks = new List<Chunk> ();
_saved = new StringBuilder ();
}
public ChunkStream (byte[] buffer, int offset, int count, WebHeaderCollection headers)
: this (headers)
{
Write (buffer, offset, count);
}
#endregion
#region Internal Properties
internal WebHeaderCollection Headers {
get {
return _headers;
}
}
#endregion
#region Public Properties
public int ChunkLeft {
get {
return _chunkSize - _chunkRead;
}
}
public bool WantMore {
get {
return _state != InputChunkState.End;
}
}
#endregion
#region Private Methods
private int read (byte[] buffer, int offset, int count)
{
var nread = 0;
var cnt = _chunks.Count;
for (var i = 0; i < cnt; i++) {
var chunk = _chunks[i];
if (chunk == null)
continue;
if (chunk.ReadLeft == 0) {
_chunks[i] = null;
continue;
}
nread += chunk.Read (buffer, offset + nread, count - nread);
if (nread == count)
break;
}
return nread;
}
private static string removeChunkExtension (string value)
{
var idx = value.IndexOf (';');
return idx > -1 ? value.Substring (0, idx) : value;
}
private InputChunkState seekCrLf (byte[] buffer, ref int offset, int length)
{
if (!_sawCr) {
if (buffer[offset++] != 13)
throwProtocolViolation ("CR is expected.");
_sawCr = true;
if (offset == length)
return InputChunkState.DataEnded;
}
if (buffer[offset++] != 10)
throwProtocolViolation ("LF is expected.");
return InputChunkState.None;
}
private InputChunkState setChunkSize (byte[] buffer, ref int offset, int length)
{
byte b = 0;
while (offset < length) {
b = buffer[offset++];
if (_sawCr) {
if (b != 10)
throwProtocolViolation ("LF is expected.");
break;
}
if (b == 13) {
_sawCr = true;
continue;
}
if (b == 10)
throwProtocolViolation ("LF is unexpected.");
if (b == 32) // SP
_gotIt = true;
if (!_gotIt)
_saved.Append ((char) b);
if (_saved.Length > 20)
throwProtocolViolation ("The chunk size is too long.");
}
if (!_sawCr || b != 10)
return InputChunkState.None;
_chunkRead = 0;
try {
_chunkSize = Int32.Parse (
removeChunkExtension (_saved.ToString ()), NumberStyles.HexNumber);
}
catch {
throwProtocolViolation ("The chunk size cannot be parsed.");
}
if (_chunkSize == 0) {
_trailerState = 2;
return InputChunkState.Trailer;
}
return InputChunkState.Data;
}
private InputChunkState setTrailer (byte[] buffer, ref int offset, int length)
{
// Check if no trailer.
if (_trailerState == 2 && buffer[offset] == 13 && _saved.Length == 0) {
offset++;
if (offset < length && buffer[offset] == 10) {
offset++;
return InputChunkState.End;
}
offset--;
}
while (offset < length && _trailerState < 4) {
var b = buffer[offset++];
_saved.Append ((char) b);
if (_saved.Length > 4196)
throwProtocolViolation ("The trailer is too long.");
if (_trailerState == 1 || _trailerState == 3) {
if (b != 10)
throwProtocolViolation ("LF is expected.");
_trailerState++;
continue;
}
if (b == 13) {
_trailerState++;
continue;
}
if (b == 10)
throwProtocolViolation ("LF is unexpected.");
_trailerState = 0;
}
if (_trailerState < 4)
return InputChunkState.Trailer;
_saved.Length -= 2;
var reader = new StringReader (_saved.ToString ());
string line;
while ((line = reader.ReadLine ()) != null && line.Length > 0)
_headers.Add (line);
return InputChunkState.End;
}
private static void throwProtocolViolation (string message)
{
throw new WebException (message, null, WebExceptionStatus.ServerProtocolViolation, null);
}
private void write (byte[] buffer, ref int offset, int length)
{
if (_state == InputChunkState.End)
throwProtocolViolation ("The chunks were ended.");
if (_state == InputChunkState.None) {
_state = setChunkSize (buffer, ref offset, length);
if (_state == InputChunkState.None)
return;
_saved.Length = 0;
_sawCr = false;
_gotIt = false;
}
if (_state == InputChunkState.Data && offset < length) {
_state = writeData (buffer, ref offset, length);
if (_state == InputChunkState.Data)
return;
}
if (_state == InputChunkState.DataEnded && offset < length) {
_state = seekCrLf (buffer, ref offset, length);
if (_state == InputChunkState.DataEnded)
return;
_sawCr = false;
}
if (_state == InputChunkState.Trailer && offset < length) {
_state = setTrailer (buffer, ref offset, length);
if (_state == InputChunkState.Trailer)
return;
_saved.Length = 0;
}
if (offset < length)
write (buffer, ref offset, length);
}
private InputChunkState writeData (byte[] buffer, ref int offset, int length)
{
var cnt = length - offset;
var left = _chunkSize - _chunkRead;
if (cnt > left)
cnt = left;
var data = new byte[cnt];
Buffer.BlockCopy (buffer, offset, data, 0, cnt);
_chunks.Add (new Chunk (data));
offset += cnt;
_chunkRead += cnt;
return _chunkRead == _chunkSize ? InputChunkState.DataEnded : InputChunkState.Data;
}
#endregion
#region Internal Methods
internal void ResetBuffer ()
{
_chunkRead = 0;
_chunkSize = -1;
_chunks.Clear ();
}
internal int WriteAndReadBack (byte[] buffer, int offset, int writeCount, int readCount)
{
Write (buffer, offset, writeCount);
return Read (buffer, offset, readCount);
}
#endregion
#region Public Methods
public int Read (byte[] buffer, int offset, int count)
{
if (count <= 0)
return 0;
return read (buffer, offset, count);
}
public void Write (byte[] buffer, int offset, int count)
{
if (count <= 0)
return;
write (buffer, ref offset, offset + count);
}
#endregion
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.ScriptEngine.Shared;
using OpenSim.Region.ScriptEngine.Interfaces;
using log4net;
namespace OpenSim.Region.ScriptEngine.XEngine
{
/// <summary>
/// Prepares events so they can be directly executed upon a script by EventQueueManager, then queues it.
/// </summary>
public class EventManager
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private XEngine myScriptEngine;
public EventManager(XEngine _ScriptEngine)
{
myScriptEngine = _ScriptEngine;
// m_log.Info("[XEngine] Hooking up to server events");
myScriptEngine.World.EventManager.OnAttach += attach;
myScriptEngine.World.EventManager.OnObjectGrab += touch_start;
myScriptEngine.World.EventManager.OnObjectGrabbing += touch;
myScriptEngine.World.EventManager.OnObjectDeGrab += touch_end;
myScriptEngine.World.EventManager.OnScriptChangedEvent += changed;
myScriptEngine.World.EventManager.OnScriptAtTargetEvent += at_target;
myScriptEngine.World.EventManager.OnScriptNotAtTargetEvent += not_at_target;
myScriptEngine.World.EventManager.OnScriptAtRotTargetEvent += at_rot_target;
myScriptEngine.World.EventManager.OnScriptNotAtRotTargetEvent += not_at_rot_target;
myScriptEngine.World.EventManager.OnScriptMovingStartEvent += moving_start;
myScriptEngine.World.EventManager.OnScriptMovingEndEvent += moving_end;
myScriptEngine.World.EventManager.OnScriptControlEvent += control;
myScriptEngine.World.EventManager.OnScriptColliderStart += collision_start;
myScriptEngine.World.EventManager.OnScriptColliding += collision;
myScriptEngine.World.EventManager.OnScriptCollidingEnd += collision_end;
myScriptEngine.World.EventManager.OnScriptLandColliderStart += land_collision_start;
myScriptEngine.World.EventManager.OnScriptLandColliding += land_collision;
myScriptEngine.World.EventManager.OnScriptLandColliderEnd += land_collision_end;
IMoneyModule money = myScriptEngine.World.RequestModuleInterface<IMoneyModule>();
if (money != null)
{
money.OnObjectPaid+=HandleObjectPaid;
}
}
/// <summary>
/// When an object gets paid by an avatar and generates the paid event,
/// this will pipe it to the script engine
/// </summary>
/// <param name="objectID">Object ID that got paid</param>
/// <param name="agentID">Agent Id that did the paying</param>
/// <param name="amount">Amount paid</param>
private void HandleObjectPaid(UUID objectID, UUID agentID,
int amount)
{
// Since this is an event from a shared module, all scenes will
// get it. But only one has the object in question. The others
// just ignore it.
//
SceneObjectPart part =
myScriptEngine.World.GetSceneObjectPart(objectID);
if (part == null)
return;
if ((part.ScriptEvents & scriptEvents.money) == 0)
part = part.ParentGroup.RootPart;
m_log.Debug("Paid: " + objectID + " from " + agentID + ", amount " + amount);
// part = part.ParentGroup.RootPart;
money(part.LocalId, agentID, amount);
}
/// <summary>
/// Handles piping the proper stuff to The script engine for touching
/// Including DetectedParams
/// </summary>
/// <param name="localID"></param>
/// <param name="originalID"></param>
/// <param name="offsetPos"></param>
/// <param name="remoteClient"></param>
/// <param name="surfaceArgs"></param>
public void touch_start(uint localID, uint originalID, Vector3 offsetPos,
IClientAPI remoteClient, SurfaceTouchEventArgs surfaceArgs)
{
// Add to queue for all scripts in ObjectID object
DetectParams[] det = new DetectParams[1];
det[0] = new DetectParams();
det[0].Key = remoteClient.AgentId;
det[0].Populate(myScriptEngine.World);
if (originalID == 0)
{
SceneObjectPart part = myScriptEngine.World.GetSceneObjectPart(localID);
if (part == null)
return;
det[0].LinkNum = part.LinkNum;
}
else
{
SceneObjectPart originalPart = myScriptEngine.World.GetSceneObjectPart(originalID);
det[0].LinkNum = originalPart.LinkNum;
}
if (surfaceArgs != null)
{
det[0].SurfaceTouchArgs = surfaceArgs;
}
myScriptEngine.PostObjectEvent(localID, new EventParams(
"touch_start", new Object[] { new LSL_Types.LSLInteger(1) },
det));
}
public void touch(uint localID, uint originalID, Vector3 offsetPos,
IClientAPI remoteClient, SurfaceTouchEventArgs surfaceArgs)
{
// Add to queue for all scripts in ObjectID object
DetectParams[] det = new DetectParams[1];
det[0] = new DetectParams();
det[0].Key = remoteClient.AgentId;
det[0].Populate(myScriptEngine.World);
det[0].OffsetPos = offsetPos;
if (originalID == 0)
{
SceneObjectPart part = myScriptEngine.World.GetSceneObjectPart(localID);
if (part == null)
return;
det[0].LinkNum = part.LinkNum;
}
else
{
SceneObjectPart originalPart = myScriptEngine.World.GetSceneObjectPart(originalID);
det[0].LinkNum = originalPart.LinkNum;
}
if (surfaceArgs != null)
{
det[0].SurfaceTouchArgs = surfaceArgs;
}
myScriptEngine.PostObjectEvent(localID, new EventParams(
"touch", new Object[] { new LSL_Types.LSLInteger(1) },
det));
}
public void touch_end(uint localID, uint originalID, IClientAPI remoteClient,
SurfaceTouchEventArgs surfaceArgs)
{
// Add to queue for all scripts in ObjectID object
DetectParams[] det = new DetectParams[1];
det[0] = new DetectParams();
det[0].Key = remoteClient.AgentId;
det[0].Populate(myScriptEngine.World);
if (originalID == 0)
{
SceneObjectPart part = myScriptEngine.World.GetSceneObjectPart(localID);
if (part == null)
return;
det[0].LinkNum = part.LinkNum;
}
else
{
SceneObjectPart originalPart = myScriptEngine.World.GetSceneObjectPart(originalID);
det[0].LinkNum = originalPart.LinkNum;
}
if (surfaceArgs != null)
{
det[0].SurfaceTouchArgs = surfaceArgs;
}
myScriptEngine.PostObjectEvent(localID, new EventParams(
"touch_end", new Object[] { new LSL_Types.LSLInteger(1) },
det));
}
public void changed(uint localID, uint change)
{
// Add to queue for all scripts in localID, Object pass change.
myScriptEngine.PostObjectEvent(localID, new EventParams(
"changed",new object[] { new LSL_Types.LSLInteger(change) },
new DetectParams[0]));
}
// state_entry: not processed here
// state_exit: not processed here
public void money(uint localID, UUID agentID, int amount)
{
myScriptEngine.PostObjectEvent(localID, new EventParams(
"money", new object[] {
new LSL_Types.LSLString(agentID.ToString()),
new LSL_Types.LSLInteger(amount) },
new DetectParams[0]));
}
public void collision_start(uint localID, ColliderArgs col)
{
// Add to queue for all scripts in ObjectID object
List<DetectParams> det = new List<DetectParams>();
foreach (DetectedObject detobj in col.Colliders)
{
DetectParams d = new DetectParams();
d.Key =detobj.keyUUID;
d.Populate(myScriptEngine.World, detobj);
d.LinkNum = detobj.linkNumber; // do it here since currently linknum is collided part
det.Add(d);
}
if (det.Count > 0)
myScriptEngine.PostObjectEvent(localID, new EventParams(
"collision_start",
new Object[] { new LSL_Types.LSLInteger(det.Count) },
det.ToArray()));
}
public void collision(uint localID, ColliderArgs col)
{
// Add to queue for all scripts in ObjectID object
List<DetectParams> det = new List<DetectParams>();
foreach (DetectedObject detobj in col.Colliders)
{
DetectParams d = new DetectParams();
d.Populate(myScriptEngine.World, detobj);
det.Add(d);
}
if (det.Count > 0)
myScriptEngine.PostObjectEvent(localID, new EventParams(
"collision", new Object[] { new LSL_Types.LSLInteger(det.Count) },
det.ToArray()));
}
public void collision_end(uint localID, ColliderArgs col)
{
// Add to queue for all scripts in ObjectID object
List<DetectParams> det = new List<DetectParams>();
foreach (DetectedObject detobj in col.Colliders)
{
DetectParams d = new DetectParams();
d.Populate(myScriptEngine.World, detobj);
det.Add(d);
}
if (det.Count > 0)
myScriptEngine.PostObjectEvent(localID, new EventParams(
"collision_end",
new Object[] { new LSL_Types.LSLInteger(det.Count) },
det.ToArray()));
}
public void land_collision_start(uint localID, ColliderArgs col)
{
List<DetectParams> det = new List<DetectParams>();
foreach (DetectedObject detobj in col.Colliders)
{
DetectParams d = new DetectParams();
d.Populate(myScriptEngine.World, detobj);
det.Add(d);
myScriptEngine.PostObjectEvent(localID, new EventParams(
"land_collision_start",
new Object[] { new LSL_Types.Vector3(d.Position) },
det.ToArray()));
}
}
public void land_collision(uint localID, ColliderArgs col)
{
List<DetectParams> det = new List<DetectParams>();
foreach (DetectedObject detobj in col.Colliders)
{
DetectParams d = new DetectParams();
d.Populate(myScriptEngine.World,detobj);
det.Add(d);
myScriptEngine.PostObjectEvent(localID, new EventParams(
"land_collision",
new Object[] { new LSL_Types.Vector3(d.Position) },
det.ToArray()));
}
}
public void land_collision_end(uint localID, ColliderArgs col)
{
List<DetectParams> det = new List<DetectParams>();
foreach (DetectedObject detobj in col.Colliders)
{
DetectParams d = new DetectParams();
d.Populate(myScriptEngine.World,detobj);
det.Add(d);
myScriptEngine.PostObjectEvent(localID, new EventParams(
"land_collision_end",
new Object[] { new LSL_Types.Vector3(d.Position) },
det.ToArray()));
}
}
// timer: not handled here
// listen: not handled here
public void control(UUID itemID, UUID agentID, uint held, uint change)
{
myScriptEngine.PostScriptEvent(itemID, new EventParams(
"control",new object[] {
new LSL_Types.LSLString(agentID.ToString()),
new LSL_Types.LSLInteger(held),
new LSL_Types.LSLInteger(change)},
new DetectParams[0]));
}
public void email(uint localID, UUID itemID, string timeSent,
string address, string subject, string message, int numLeft)
{
myScriptEngine.PostObjectEvent(localID, new EventParams(
"email",new object[] {
new LSL_Types.LSLString(timeSent),
new LSL_Types.LSLString(address),
new LSL_Types.LSLString(subject),
new LSL_Types.LSLString(message),
new LSL_Types.LSLInteger(numLeft)},
new DetectParams[0]));
}
public void at_target(uint localID, uint handle, Vector3 targetpos,
Vector3 atpos)
{
myScriptEngine.PostObjectEvent(localID, new EventParams(
"at_target", new object[] {
new LSL_Types.LSLInteger(handle),
new LSL_Types.Vector3(targetpos),
new LSL_Types.Vector3(atpos) },
new DetectParams[0]));
}
public void not_at_target(uint localID)
{
myScriptEngine.PostObjectEvent(localID, new EventParams(
"not_at_target",new object[0],
new DetectParams[0]));
}
public void at_rot_target(uint localID, uint handle, Quaternion targetrot,
Quaternion atrot)
{
myScriptEngine.PostObjectEvent(localID, new EventParams(
"at_rot_target", new object[] {
new LSL_Types.LSLInteger(handle),
new LSL_Types.Quaternion(targetrot),
new LSL_Types.Quaternion(atrot) },
new DetectParams[0]));
}
public void not_at_rot_target(uint localID)
{
myScriptEngine.PostObjectEvent(localID, new EventParams(
"not_at_rot_target",new object[0],
new DetectParams[0]));
}
// run_time_permissions: not handled here
public void attach(uint localID, UUID itemID, UUID avatar)
{
SceneObjectGroup grp = myScriptEngine.World.GetSceneObjectGroup(localID);
if(grp == null)
return;
foreach(SceneObjectPart part in grp.Parts)
{
myScriptEngine.PostObjectEvent(part.LocalId, new EventParams(
"attach",new object[] {
new LSL_Types.LSLString(avatar.ToString()) },
new DetectParams[0]));
}
}
// dataserver: not handled here
// link_message: not handled here
public void moving_start(uint localID)
{
myScriptEngine.PostObjectEvent(localID, new EventParams(
"moving_start",new object[0],
new DetectParams[0]));
}
public void moving_end(uint localID)
{
myScriptEngine.PostObjectEvent(localID, new EventParams(
"moving_end",new object[0],
new DetectParams[0]));
}
// object_rez: not handled here
// remote_data: not handled here
// http_response: not handled here
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King; 2014 Extesla, LLC.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections;
using System.Globalization;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections.Generic;
#if NET20
using OpenGamingLibrary.Json.Utilities.LinqBridge;
#else
using System.Linq;
#endif
namespace OpenGamingLibrary.Json.Utilities
{
internal static class JavaScriptUtils
{
internal static readonly bool[] SingleQuoteCharEscapeFlags = new bool[128];
internal static readonly bool[] DoubleQuoteCharEscapeFlags = new bool[128];
internal static readonly bool[] HtmlCharEscapeFlags = new bool[128];
static JavaScriptUtils()
{
IList<char> escapeChars = new List<char>
{
'\n', '\r', '\t', '\\', '\f', '\b',
};
for (int i = 0; i < ' '; i++)
{
escapeChars.Add((char)i);
}
foreach (var escapeChar in escapeChars.Union(new[] { '\'' }))
{
SingleQuoteCharEscapeFlags[escapeChar] = true;
}
foreach (var escapeChar in escapeChars.Union(new[] { '"' }))
{
DoubleQuoteCharEscapeFlags[escapeChar] = true;
}
foreach (var escapeChar in escapeChars.Union(new[] { '"', '\'', '<', '>', '&' }))
{
HtmlCharEscapeFlags[escapeChar] = true;
}
}
private const string EscapedUnicodeText = "!";
public static bool[] GetCharEscapeFlags(StringEscapeHandling stringEscapeHandling, char quoteChar)
{
if (stringEscapeHandling == StringEscapeHandling.EscapeHtml)
return HtmlCharEscapeFlags;
if (quoteChar == '"')
return DoubleQuoteCharEscapeFlags;
return SingleQuoteCharEscapeFlags;
}
public static bool ShouldEscapeJavaScriptString(string s, bool[] charEscapeFlags)
{
if (s == null)
return false;
foreach (char c in s)
{
if (c >= charEscapeFlags.Length || charEscapeFlags[c])
return true;
}
return false;
}
public static void WriteEscapedJavaScriptString(TextWriter writer, string s, char delimiter, bool appendDelimiters,
bool[] charEscapeFlags, StringEscapeHandling stringEscapeHandling, ref char[] writeBuffer)
{
// leading delimiter
if (appendDelimiters)
writer.Write(delimiter);
if (s != null)
{
int lastWritePosition = 0;
for (int i = 0; i < s.Length; i++)
{
var c = s[i];
if (c < charEscapeFlags.Length && !charEscapeFlags[c])
continue;
string escapedValue;
switch (c)
{
case '\t':
escapedValue = @"\t";
break;
case '\n':
escapedValue = @"\n";
break;
case '\r':
escapedValue = @"\r";
break;
case '\f':
escapedValue = @"\f";
break;
case '\b':
escapedValue = @"\b";
break;
case '\\':
escapedValue = @"\\";
break;
case '\u0085': // Next Line
escapedValue = @"\u0085";
break;
case '\u2028': // Line Separator
escapedValue = @"\u2028";
break;
case '\u2029': // Paragraph Separator
escapedValue = @"\u2029";
break;
default:
if (c < charEscapeFlags.Length || stringEscapeHandling == StringEscapeHandling.EscapeNonAscii)
{
if (c == '\'' && stringEscapeHandling != StringEscapeHandling.EscapeHtml)
{
escapedValue = @"\'";
}
else if (c == '"' && stringEscapeHandling != StringEscapeHandling.EscapeHtml)
{
escapedValue = @"\""";
}
else
{
if (writeBuffer == null)
writeBuffer = new char[6];
StringUtils.ToCharAsUnicode(c, writeBuffer);
// slightly hacky but it saves multiple conditions in if test
escapedValue = EscapedUnicodeText;
}
}
else
{
escapedValue = null;
}
break;
}
if (escapedValue == null)
continue;
bool isEscapedUnicodeText = string.Equals(escapedValue, EscapedUnicodeText);
if (i > lastWritePosition)
{
int length = i - lastWritePosition + ((isEscapedUnicodeText) ? 6 : 0);
int start = (isEscapedUnicodeText) ? 6 : 0;
if (writeBuffer == null || writeBuffer.Length < length)
{
char[] newBuffer = new char[length];
// the unicode text is already in the buffer
// copy it over when creating new buffer
if (isEscapedUnicodeText)
Array.Copy(writeBuffer, newBuffer, 6);
writeBuffer = newBuffer;
}
s.CopyTo(lastWritePosition, writeBuffer, start, length - start);
// write unchanged chars before writing escaped text
writer.Write(writeBuffer, start, length - start);
}
lastWritePosition = i + 1;
if (!isEscapedUnicodeText)
writer.Write(escapedValue);
else
writer.Write(writeBuffer, 0, 6);
}
if (lastWritePosition == 0)
{
// no escaped text, write entire string
writer.Write(s);
}
else
{
int length = s.Length - lastWritePosition;
if (writeBuffer == null || writeBuffer.Length < length)
writeBuffer = new char[length];
s.CopyTo(lastWritePosition, writeBuffer, 0, length);
// write remaining text
writer.Write(writeBuffer, 0, length);
}
}
// trailing delimiter
if (appendDelimiters)
writer.Write(delimiter);
}
public static string ToEscapedJavaScriptString(string value, char delimiter, bool appendDelimiters)
{
return ToEscapedJavaScriptString(value, delimiter, appendDelimiters, StringEscapeHandling.Default);
}
public static string ToEscapedJavaScriptString(string value, char delimiter, bool appendDelimiters, StringEscapeHandling stringEscapeHandling)
{
bool[] charEscapeFlags = GetCharEscapeFlags(stringEscapeHandling, delimiter);
using (StringWriter w = StringUtils.CreateStringWriter(StringUtils.GetLength(value) ?? 16))
{
char[] buffer = null;
WriteEscapedJavaScriptString(w, value, delimiter, appendDelimiters, charEscapeFlags, stringEscapeHandling, ref buffer);
return w.ToString();
}
}
}
}
| |
/* Generated SBE (Simple Binary Encoding) message codec */
using System;
using System.Text;
using System.Collections.Generic;
using Adaptive.Agrona;
namespace Adaptive.Archiver.Codecs {
public class ExtendRecordingRequest2Encoder
{
public const ushort BLOCK_LENGTH = 36;
public const ushort TEMPLATE_ID = 64;
public const ushort SCHEMA_ID = 101;
public const ushort SCHEMA_VERSION = 6;
private ExtendRecordingRequest2Encoder _parentMessage;
private IMutableDirectBuffer _buffer;
protected int _offset;
protected int _limit;
public ExtendRecordingRequest2Encoder()
{
_parentMessage = this;
}
public ushort SbeBlockLength()
{
return BLOCK_LENGTH;
}
public ushort SbeTemplateId()
{
return TEMPLATE_ID;
}
public ushort SbeSchemaId()
{
return SCHEMA_ID;
}
public ushort SbeSchemaVersion()
{
return SCHEMA_VERSION;
}
public string SbeSemanticType()
{
return "";
}
public IMutableDirectBuffer Buffer()
{
return _buffer;
}
public int Offset()
{
return _offset;
}
public ExtendRecordingRequest2Encoder Wrap(IMutableDirectBuffer buffer, int offset)
{
this._buffer = buffer;
this._offset = offset;
Limit(offset + BLOCK_LENGTH);
return this;
}
public ExtendRecordingRequest2Encoder WrapAndApplyHeader(
IMutableDirectBuffer buffer, int offset, MessageHeaderEncoder headerEncoder)
{
headerEncoder
.Wrap(buffer, offset)
.BlockLength(BLOCK_LENGTH)
.TemplateId(TEMPLATE_ID)
.SchemaId(SCHEMA_ID)
.Version(SCHEMA_VERSION);
return Wrap(buffer, offset + MessageHeaderEncoder.ENCODED_LENGTH);
}
public int EncodedLength()
{
return _limit - _offset;
}
public int Limit()
{
return _limit;
}
public void Limit(int limit)
{
this._limit = limit;
}
public static int ControlSessionIdEncodingOffset()
{
return 0;
}
public static int ControlSessionIdEncodingLength()
{
return 8;
}
public static long ControlSessionIdNullValue()
{
return -9223372036854775808L;
}
public static long ControlSessionIdMinValue()
{
return -9223372036854775807L;
}
public static long ControlSessionIdMaxValue()
{
return 9223372036854775807L;
}
public ExtendRecordingRequest2Encoder ControlSessionId(long value)
{
_buffer.PutLong(_offset + 0, value, ByteOrder.LittleEndian);
return this;
}
public static int CorrelationIdEncodingOffset()
{
return 8;
}
public static int CorrelationIdEncodingLength()
{
return 8;
}
public static long CorrelationIdNullValue()
{
return -9223372036854775808L;
}
public static long CorrelationIdMinValue()
{
return -9223372036854775807L;
}
public static long CorrelationIdMaxValue()
{
return 9223372036854775807L;
}
public ExtendRecordingRequest2Encoder CorrelationId(long value)
{
_buffer.PutLong(_offset + 8, value, ByteOrder.LittleEndian);
return this;
}
public static int RecordingIdEncodingOffset()
{
return 16;
}
public static int RecordingIdEncodingLength()
{
return 8;
}
public static long RecordingIdNullValue()
{
return -9223372036854775808L;
}
public static long RecordingIdMinValue()
{
return -9223372036854775807L;
}
public static long RecordingIdMaxValue()
{
return 9223372036854775807L;
}
public ExtendRecordingRequest2Encoder RecordingId(long value)
{
_buffer.PutLong(_offset + 16, value, ByteOrder.LittleEndian);
return this;
}
public static int StreamIdEncodingOffset()
{
return 24;
}
public static int StreamIdEncodingLength()
{
return 4;
}
public static int StreamIdNullValue()
{
return -2147483648;
}
public static int StreamIdMinValue()
{
return -2147483647;
}
public static int StreamIdMaxValue()
{
return 2147483647;
}
public ExtendRecordingRequest2Encoder StreamId(int value)
{
_buffer.PutInt(_offset + 24, value, ByteOrder.LittleEndian);
return this;
}
public static int SourceLocationEncodingOffset()
{
return 28;
}
public static int SourceLocationEncodingLength()
{
return 4;
}
public ExtendRecordingRequest2Encoder SourceLocation(SourceLocation value)
{
_buffer.PutInt(_offset + 28, (int)value, ByteOrder.LittleEndian);
return this;
}
public static int AutoStopEncodingOffset()
{
return 32;
}
public static int AutoStopEncodingLength()
{
return 4;
}
public ExtendRecordingRequest2Encoder AutoStop(BooleanType value)
{
_buffer.PutInt(_offset + 32, (int)value, ByteOrder.LittleEndian);
return this;
}
public static int ChannelId()
{
return 7;
}
public static string ChannelCharacterEncoding()
{
return "US-ASCII";
}
public static string ChannelMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static int ChannelHeaderLength()
{
return 4;
}
public ExtendRecordingRequest2Encoder PutChannel(IDirectBuffer src, int srcOffset, int length)
{
if (length > 1073741824)
{
throw new InvalidOperationException("length > maxValue for type: " + length);
}
int headerLength = 4;
int limit = _parentMessage.Limit();
_parentMessage.Limit(limit + headerLength + length);
_buffer.PutInt(limit, unchecked((int)length), ByteOrder.LittleEndian);
_buffer.PutBytes(limit + headerLength, src, srcOffset, length);
return this;
}
public ExtendRecordingRequest2Encoder PutChannel(byte[] src, int srcOffset, int length)
{
if (length > 1073741824)
{
throw new InvalidOperationException("length > maxValue for type: " + length);
}
int headerLength = 4;
int limit = _parentMessage.Limit();
_parentMessage.Limit(limit + headerLength + length);
_buffer.PutInt(limit, unchecked((int)length), ByteOrder.LittleEndian);
_buffer.PutBytes(limit + headerLength, src, srcOffset, length);
return this;
}
public ExtendRecordingRequest2Encoder Channel(string value)
{
int length = value.Length;
if (length > 1073741824)
{
throw new InvalidOperationException("length > maxValue for type: " + length);
}
int headerLength = 4;
int limit = _parentMessage.Limit();
_parentMessage.Limit(limit + headerLength + length);
_buffer.PutInt(limit, unchecked((int)length), ByteOrder.LittleEndian);
_buffer.PutStringWithoutLengthAscii(limit + headerLength, value);
return this;
}
public override string ToString()
{
return AppendTo(new StringBuilder(100)).ToString();
}
public StringBuilder AppendTo(StringBuilder builder)
{
ExtendRecordingRequest2Decoder writer = new ExtendRecordingRequest2Decoder();
writer.Wrap(_buffer, _offset, BLOCK_LENGTH, SCHEMA_VERSION);
return writer.AppendTo(builder);
}
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using osu.Game.Audio;
using osu.Game.Beatmaps;
using osu.Game.Beatmaps.ControlPoints;
using osu.Game.Beatmaps.Legacy;
using osu.Game.Rulesets.Edit;
using osu.Game.Rulesets.Edit.Checks;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Osu.Objects;
using osu.Game.Tests.Beatmaps;
namespace osu.Game.Tests.Editing.Checks
{
[TestFixture]
public class CheckMutedObjectsTest
{
private CheckMutedObjects check;
private ControlPointInfo cpi;
private const int volume_regular = 50;
private const int volume_low = 15;
private const int volume_muted = 5;
[SetUp]
public void Setup()
{
check = new CheckMutedObjects();
cpi = new LegacyControlPointInfo();
cpi.Add(0, new SampleControlPoint { SampleVolume = volume_regular });
cpi.Add(1000, new SampleControlPoint { SampleVolume = volume_low });
cpi.Add(2000, new SampleControlPoint { SampleVolume = volume_muted });
}
[Test]
public void TestNormalControlPointVolume()
{
var hitcircle = new HitCircle
{
StartTime = 0,
Samples = new List<HitSampleInfo> { new HitSampleInfo(HitSampleInfo.HIT_NORMAL) }
};
hitcircle.ApplyDefaults(cpi, new BeatmapDifficulty());
assertOk(new List<HitObject> { hitcircle });
}
[Test]
public void TestLowControlPointVolume()
{
var hitcircle = new HitCircle
{
StartTime = 1000,
Samples = new List<HitSampleInfo> { new HitSampleInfo(HitSampleInfo.HIT_NORMAL) }
};
hitcircle.ApplyDefaults(cpi, new BeatmapDifficulty());
assertLowVolume(new List<HitObject> { hitcircle });
}
[Test]
public void TestMutedControlPointVolume()
{
var hitcircle = new HitCircle
{
StartTime = 2000,
Samples = new List<HitSampleInfo> { new HitSampleInfo(HitSampleInfo.HIT_NORMAL) }
};
hitcircle.ApplyDefaults(cpi, new BeatmapDifficulty());
assertMuted(new List<HitObject> { hitcircle });
}
[Test]
public void TestNormalSampleVolume()
{
// The sample volume should take precedence over the control point volume.
var hitcircle = new HitCircle
{
StartTime = 2000,
Samples = new List<HitSampleInfo> { new HitSampleInfo(HitSampleInfo.HIT_NORMAL, volume: volume_regular) }
};
hitcircle.ApplyDefaults(cpi, new BeatmapDifficulty());
assertOk(new List<HitObject> { hitcircle });
}
[Test]
public void TestLowSampleVolume()
{
var hitcircle = new HitCircle
{
StartTime = 2000,
Samples = new List<HitSampleInfo> { new HitSampleInfo(HitSampleInfo.HIT_NORMAL, volume: volume_low) }
};
hitcircle.ApplyDefaults(cpi, new BeatmapDifficulty());
assertLowVolume(new List<HitObject> { hitcircle });
}
[Test]
public void TestMutedSampleVolume()
{
var hitcircle = new HitCircle
{
StartTime = 0,
Samples = new List<HitSampleInfo> { new HitSampleInfo(HitSampleInfo.HIT_NORMAL, volume: volume_muted) }
};
hitcircle.ApplyDefaults(cpi, new BeatmapDifficulty());
assertMuted(new List<HitObject> { hitcircle });
}
[Test]
public void TestNormalSampleVolumeSlider()
{
var sliderHead = new SliderHeadCircle
{
StartTime = 0,
Samples = new List<HitSampleInfo> { new HitSampleInfo(HitSampleInfo.HIT_NORMAL) }
};
sliderHead.ApplyDefaults(cpi, new BeatmapDifficulty());
var sliderTick = new SliderTick
{
StartTime = 250,
Samples = new List<HitSampleInfo> { new HitSampleInfo("slidertick", volume: volume_muted) } // Should be fine.
};
sliderTick.ApplyDefaults(cpi, new BeatmapDifficulty());
var slider = new MockNestableHitObject(new List<HitObject> { sliderHead, sliderTick, }, startTime: 0, endTime: 500)
{
Samples = new List<HitSampleInfo> { new HitSampleInfo(HitSampleInfo.HIT_NORMAL) }
};
slider.ApplyDefaults(cpi, new BeatmapDifficulty());
assertOk(new List<HitObject> { slider });
}
[Test]
public void TestMutedSampleVolumeSliderHead()
{
var sliderHead = new SliderHeadCircle
{
StartTime = 0,
Samples = new List<HitSampleInfo> { new HitSampleInfo(HitSampleInfo.HIT_NORMAL, volume: volume_muted) }
};
sliderHead.ApplyDefaults(cpi, new BeatmapDifficulty());
var sliderTick = new SliderTick
{
StartTime = 250,
Samples = new List<HitSampleInfo> { new HitSampleInfo("slidertick") }
};
sliderTick.ApplyDefaults(cpi, new BeatmapDifficulty());
var slider = new MockNestableHitObject(new List<HitObject> { sliderHead, sliderTick, }, startTime: 0, endTime: 500)
{
Samples = new List<HitSampleInfo> { new HitSampleInfo(HitSampleInfo.HIT_NORMAL) } // Applies to the tail.
};
slider.ApplyDefaults(cpi, new BeatmapDifficulty());
assertMuted(new List<HitObject> { slider });
}
[Test]
public void TestMutedSampleVolumeSliderTail()
{
var sliderHead = new SliderHeadCircle
{
StartTime = 0,
Samples = new List<HitSampleInfo> { new HitSampleInfo(HitSampleInfo.HIT_NORMAL) }
};
sliderHead.ApplyDefaults(cpi, new BeatmapDifficulty());
var sliderTick = new SliderTick
{
StartTime = 250,
Samples = new List<HitSampleInfo> { new HitSampleInfo("slidertick") }
};
sliderTick.ApplyDefaults(cpi, new BeatmapDifficulty());
var slider = new MockNestableHitObject(new List<HitObject> { sliderHead, sliderTick, }, startTime: 0, endTime: 2500)
{
Samples = new List<HitSampleInfo> { new HitSampleInfo(HitSampleInfo.HIT_NORMAL, volume: volume_muted) } // Applies to the tail.
};
slider.ApplyDefaults(cpi, new BeatmapDifficulty());
assertMutedPassive(new List<HitObject> { slider });
}
[Test]
public void TestMutedControlPointVolumeSliderHead()
{
var sliderHead = new SliderHeadCircle
{
StartTime = 2000,
Samples = new List<HitSampleInfo> { new HitSampleInfo(HitSampleInfo.HIT_NORMAL) }
};
sliderHead.ApplyDefaults(cpi, new BeatmapDifficulty());
var sliderTick = new SliderTick
{
StartTime = 2250,
Samples = new List<HitSampleInfo> { new HitSampleInfo("slidertick") }
};
sliderTick.ApplyDefaults(cpi, new BeatmapDifficulty());
var slider = new MockNestableHitObject(new List<HitObject> { sliderHead, sliderTick, }, startTime: 2000, endTime: 2500)
{
Samples = new List<HitSampleInfo> { new HitSampleInfo(HitSampleInfo.HIT_NORMAL, volume: volume_regular) }
};
slider.ApplyDefaults(cpi, new BeatmapDifficulty());
assertMuted(new List<HitObject> { slider });
}
[Test]
public void TestMutedControlPointVolumeSliderTail()
{
var sliderHead = new SliderHeadCircle
{
StartTime = 0,
Samples = new List<HitSampleInfo> { new HitSampleInfo(HitSampleInfo.HIT_NORMAL) }
};
sliderHead.ApplyDefaults(cpi, new BeatmapDifficulty());
var sliderTick = new SliderTick
{
StartTime = 250,
Samples = new List<HitSampleInfo> { new HitSampleInfo("slidertick") }
};
sliderTick.ApplyDefaults(cpi, new BeatmapDifficulty());
// Ends after the 5% control point.
var slider = new MockNestableHitObject(new List<HitObject> { sliderHead, sliderTick, }, startTime: 0, endTime: 2500)
{
Samples = new List<HitSampleInfo> { new HitSampleInfo(HitSampleInfo.HIT_NORMAL) }
};
slider.ApplyDefaults(cpi, new BeatmapDifficulty());
assertMutedPassive(new List<HitObject> { slider });
}
private void assertOk(List<HitObject> hitObjects)
{
Assert.That(check.Run(getContext(hitObjects)), Is.Empty);
}
private void assertLowVolume(List<HitObject> hitObjects, int count = 1)
{
var issues = check.Run(getContext(hitObjects)).ToList();
Assert.That(issues, Has.Count.EqualTo(count));
Assert.That(issues.All(issue => issue.Template is CheckMutedObjects.IssueTemplateLowVolumeActive));
}
private void assertMuted(List<HitObject> hitObjects, int count = 1)
{
var issues = check.Run(getContext(hitObjects)).ToList();
Assert.That(issues, Has.Count.EqualTo(count));
Assert.That(issues.All(issue => issue.Template is CheckMutedObjects.IssueTemplateMutedActive));
}
private void assertMutedPassive(List<HitObject> hitObjects)
{
var issues = check.Run(getContext(hitObjects)).ToList();
Assert.That(issues, Has.Count.EqualTo(1));
Assert.That(issues.Any(issue => issue.Template is CheckMutedObjects.IssueTemplateMutedPassive));
}
private BeatmapVerifierContext getContext(List<HitObject> hitObjects)
{
var beatmap = new Beatmap<HitObject>
{
ControlPointInfo = cpi,
HitObjects = hitObjects
};
return new BeatmapVerifierContext(beatmap, new TestWorkingBeatmap(beatmap));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Mime;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Umbraco.Cms.Core;
using Umbraco.Cms.Core.Dictionary;
using Umbraco.Cms.Core.Editors;
using Umbraco.Cms.Core.Hosting;
using Umbraco.Cms.Core.Mapping;
using Umbraco.Cms.Core.Models;
using Umbraco.Cms.Core.Models.ContentEditing;
using Umbraco.Cms.Core.PropertyEditors;
using Umbraco.Cms.Core.Security;
using Umbraco.Cms.Core.Services;
using Umbraco.Cms.Core.Strings;
using Umbraco.Cms.Infrastructure.Packaging;
using Umbraco.Cms.Web.Common.ActionsResults;
using Umbraco.Cms.Web.Common.Attributes;
using Umbraco.Cms.Web.Common.Authorization;
using Umbraco.Extensions;
using Constants = Umbraco.Cms.Core.Constants;
using ContentType = Umbraco.Cms.Core.Models.ContentType;
namespace Umbraco.Cms.Web.BackOffice.Controllers
{
/// <summary>
/// An API controller used for dealing with content types
/// </summary>
[PluginController(Constants.Web.Mvc.BackOfficeApiArea)]
[ParameterSwapControllerActionSelector(nameof(GetById), "id", typeof(int), typeof(Guid), typeof(Udi))]
public class ContentTypeController : ContentTypeControllerBase<IContentType>
{
// TODO: Split this controller apart so that authz is consistent, currently we need to authz each action individually.
// It would be possible to have something like a ContentTypeInfoController for the GetAllPropertyTypeAliases/GetCount/GetAllowedChildren/etc... actions
private readonly IEntityXmlSerializer _serializer;
private readonly PropertyEditorCollection _propertyEditors;
private readonly IContentTypeService _contentTypeService;
private readonly IUmbracoMapper _umbracoMapper;
private readonly IBackOfficeSecurityAccessor _backofficeSecurityAccessor;
private readonly IDataTypeService _dataTypeService;
private readonly IShortStringHelper _shortStringHelper;
private readonly ILocalizedTextService _localizedTextService;
private readonly IFileService _fileService;
private readonly ILogger<ContentTypeController> _logger;
private readonly IContentService _contentService;
private readonly IContentTypeBaseServiceProvider _contentTypeBaseServiceProvider;
private readonly IHostingEnvironment _hostingEnvironment;
private readonly PackageDataInstallation _packageDataInstallation;
public ContentTypeController(
ICultureDictionary cultureDictionary,
IContentTypeService contentTypeService,
IMediaTypeService mediaTypeService,
IMemberTypeService memberTypeService,
IUmbracoMapper umbracoMapper,
ILocalizedTextService localizedTextService,
IEntityXmlSerializer serializer,
PropertyEditorCollection propertyEditors,
IBackOfficeSecurityAccessor backofficeSecurityAccessor,
IDataTypeService dataTypeService,
IShortStringHelper shortStringHelper,
IFileService fileService,
ILogger<ContentTypeController> logger,
IContentService contentService,
IContentTypeBaseServiceProvider contentTypeBaseServiceProvider,
IHostingEnvironment hostingEnvironment,
EditorValidatorCollection editorValidatorCollection,
PackageDataInstallation packageDataInstallation)
: base(cultureDictionary,
editorValidatorCollection,
contentTypeService,
mediaTypeService,
memberTypeService,
umbracoMapper,
localizedTextService)
{
_serializer = serializer;
_propertyEditors = propertyEditors;
_contentTypeService = contentTypeService;
_umbracoMapper = umbracoMapper;
_backofficeSecurityAccessor = backofficeSecurityAccessor;
_dataTypeService = dataTypeService;
_shortStringHelper = shortStringHelper;
_localizedTextService = localizedTextService;
_fileService = fileService;
_logger = logger;
_contentService = contentService;
_contentTypeBaseServiceProvider = contentTypeBaseServiceProvider;
_hostingEnvironment = hostingEnvironment;
_packageDataInstallation = packageDataInstallation;
}
[Authorize(Policy = AuthorizationPolicies.TreeAccessDocumentTypes)]
public int GetCount()
{
return _contentTypeService.Count();
}
[HttpGet]
[Authorize(Policy = AuthorizationPolicies.TreeAccessDocumentTypes)]
public bool HasContentNodes(int id)
{
return _contentTypeService.HasContentNodes(id);
}
/// <summary>
/// Gets the document type a given id
/// </summary>
[Authorize(Policy = AuthorizationPolicies.TreeAccessDocumentTypes)]
public ActionResult<DocumentTypeDisplay> GetById(int id)
{
var ct = _contentTypeService.Get(id);
if (ct == null)
{
return NotFound();
}
var dto = _umbracoMapper.Map<IContentType, DocumentTypeDisplay>(ct);
return dto;
}
/// <summary>
/// Gets the document type a given guid
/// </summary>
[Authorize(Policy = AuthorizationPolicies.TreeAccessDocumentTypes)]
public ActionResult<DocumentTypeDisplay> GetById(Guid id)
{
var contentType = _contentTypeService.Get(id);
if (contentType == null)
{
return NotFound();
}
var dto = _umbracoMapper.Map<IContentType, DocumentTypeDisplay>(contentType);
return dto;
}
/// <summary>
/// Gets the document type a given udi
/// </summary>
[Authorize(Policy = AuthorizationPolicies.TreeAccessDocumentTypes)]
public ActionResult<DocumentTypeDisplay> GetById(Udi id)
{
var guidUdi = id as GuidUdi;
if (guidUdi == null)
return NotFound();
var contentType = _contentTypeService.Get(guidUdi.Guid);
if (contentType == null)
{
return NotFound();
}
var dto = _umbracoMapper.Map<IContentType, DocumentTypeDisplay>(contentType);
return dto;
}
/// <summary>
/// Deletes a document type with a given ID
/// </summary>
[HttpDelete]
[HttpPost]
[Authorize(Policy = AuthorizationPolicies.TreeAccessDocumentTypes)]
public IActionResult DeleteById(int id)
{
var foundType = _contentTypeService.Get(id);
if (foundType == null)
{
return NotFound();
}
_contentTypeService.Delete(foundType, _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.Id);
return Ok();
}
/// <summary>
/// Gets all user defined properties.
/// </summary>
[Authorize(Policy = AuthorizationPolicies.TreeAccessAnyContentOrTypes)]
public IEnumerable<string> GetAllPropertyTypeAliases()
{
return _contentTypeService.GetAllPropertyTypeAliases();
}
/// <summary>
/// Gets all the standard fields.
/// </summary>
[Authorize(Policy = AuthorizationPolicies.TreeAccessAnyContentOrTypes)]
public IEnumerable<string> GetAllStandardFields()
{
string[] preValuesSource = { "createDate", "creatorName", "level", "nodeType", "nodeTypeAlias", "pageID", "pageName", "parentID", "path", "template", "updateDate", "writerID", "writerName" };
return preValuesSource;
}
/// <summary>
/// Returns the available compositions for this content type
/// This has been wrapped in a dto instead of simple parameters to support having multiple parameters in post request body
/// </summary>
[HttpPost]
[Authorize(Policy = AuthorizationPolicies.TreeAccessDocumentTypes)]
public ActionResult GetAvailableCompositeContentTypes(GetAvailableCompositionsFilter filter)
{
var actionResult = PerformGetAvailableCompositeContentTypes(filter.ContentTypeId,
UmbracoObjectTypes.DocumentType, filter.FilterContentTypes, filter.FilterPropertyTypes,
filter.IsElement);
if (!(actionResult.Result is null))
{
return actionResult.Result;
}
var result = actionResult.Value
.Select(x => new
{
contentType = x.Item1,
allowed = x.Item2
});
return Ok(result);
}
/// <summary>
/// Returns true if any content types have culture variation enabled
/// </summary>
[HttpGet]
[Authorize(Policy = AuthorizationPolicies.BackOfficeAccess)]
public bool AllowsCultureVariation()
{
IEnumerable<IContentType> contentTypes = _contentTypeService.GetAll();
return contentTypes.Any(contentType => contentType.VariesByCulture());
}
/// <summary>
/// Returns where a particular composition has been used
/// This has been wrapped in a dto instead of simple parameters to support having multiple parameters in post request body
/// </summary>
[HttpPost]
[Authorize(Policy = AuthorizationPolicies.TreeAccessDocumentTypes)]
public IActionResult GetWhereCompositionIsUsedInContentTypes(GetAvailableCompositionsFilter filter)
{
var result = PerformGetWhereCompositionIsUsedInContentTypes(filter.ContentTypeId, UmbracoObjectTypes.DocumentType).Value
.Select(x => new
{
contentType = x
});
return Ok(result);
}
[Authorize(Policy = AuthorizationPolicies.TreeAccessAnyContentOrTypes)]
public ActionResult<ContentPropertyDisplay> GetPropertyTypeScaffold(int id)
{
var dataTypeDiff = _dataTypeService.GetDataType(id);
if (dataTypeDiff == null)
{
return NotFound();
}
var configuration = _dataTypeService.GetDataType(id).Configuration;
var editor = _propertyEditors[dataTypeDiff.EditorAlias];
return new ContentPropertyDisplay()
{
Editor = dataTypeDiff.EditorAlias,
Validation = new PropertyTypeValidation(),
View = editor.GetValueEditor().View,
Config = editor.GetConfigurationEditor().ToConfigurationEditor(configuration)
};
}
/// <summary>
/// Deletes a document type container with a given ID
/// </summary>
[HttpDelete]
[HttpPost]
[Authorize(Policy = AuthorizationPolicies.TreeAccessDocumentTypes)]
public IActionResult DeleteContainer(int id)
{
_contentTypeService.DeleteContainer(id, _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.Id);
return Ok();
}
[Authorize(Policy = AuthorizationPolicies.TreeAccessDocumentTypes)]
public IActionResult PostCreateContainer(int parentId, string name)
{
var result = _contentTypeService.CreateContainer(parentId, Guid.NewGuid(), name, _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.Id);
if (result.Success)
return Ok(result.Result); //return the id
else
return ValidationProblem(result.Exception.Message);
}
[Authorize(Policy = AuthorizationPolicies.TreeAccessDocumentTypes)]
public IActionResult PostRenameContainer(int id, string name)
{
var result = _contentTypeService.RenameContainer(id, name, _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.Id);
if (result.Success)
return Ok(result.Result); //return the id
else
return ValidationProblem(result.Exception.Message);
}
[Authorize(Policy = AuthorizationPolicies.TreeAccessDocumentTypes)]
public ActionResult<DocumentTypeDisplay> PostSave(DocumentTypeSave contentTypeSave)
{
//Before we send this model into this saving/mapping pipeline, we need to do some cleanup on variations.
//If the doc type does not allow content variations, we need to update all of it's property types to not allow this either
//else we may end up with ysods. I'm unsure if the service level handles this but we'll make sure it is updated here
if (!contentTypeSave.AllowCultureVariant)
{
foreach(var prop in contentTypeSave.Groups.SelectMany(x => x.Properties))
{
prop.AllowCultureVariant = false;
}
}
var savedCt = PerformPostSave<DocumentTypeDisplay, DocumentTypeSave, PropertyTypeBasic>(
contentTypeSave: contentTypeSave,
getContentType: i => _contentTypeService.Get(i),
saveContentType: type => _contentTypeService.Save(type),
beforeCreateNew: ctSave =>
{
//create a default template if it doesn't exist -but only if default template is == to the content type
if (ctSave.DefaultTemplate.IsNullOrWhiteSpace() == false && ctSave.DefaultTemplate == ctSave.Alias)
{
var template = CreateTemplateForContentType(ctSave.Alias, ctSave.Name);
// If the alias has been manually updated before the first save,
// make sure to also update the first allowed template, as the
// name will come back as a SafeAlias of the document type name,
// not as the actual document type alias.
// For more info: http://issues.umbraco.org/issue/U4-11059
if (ctSave.DefaultTemplate != template.Alias)
{
var allowedTemplates = ctSave.AllowedTemplates.ToArray();
if (allowedTemplates.Any())
allowedTemplates[0] = template.Alias;
ctSave.AllowedTemplates = allowedTemplates;
}
//make sure the template alias is set on the default and allowed template so we can map it back
ctSave.DefaultTemplate = template.Alias;
}
});
if (!(savedCt.Result is null))
{
return savedCt.Result;
}
var display = _umbracoMapper.Map<DocumentTypeDisplay>(savedCt.Value);
display.AddSuccessNotification(
_localizedTextService.Localize("speechBubbles","contentTypeSavedHeader"),
string.Empty);
return display;
}
[Authorize(Policy = AuthorizationPolicies.TreeAccessDocumentTypes)]
public ActionResult<TemplateDisplay> PostCreateDefaultTemplate(int id)
{
var contentType = _contentTypeService.Get(id);
if (contentType == null)
{
return NotFound("No content type found with id " + id);
}
var template = CreateTemplateForContentType(contentType.Alias, contentType.Name);
if (template == null)
{
throw new InvalidOperationException("Could not create default template for content type with id " + id);
}
return _umbracoMapper.Map<TemplateDisplay>(template);
}
private ITemplate CreateTemplateForContentType(string contentTypeAlias, string contentTypeName)
{
var template = _fileService.GetTemplate(contentTypeAlias);
if (template == null)
{
var tryCreateTemplate = _fileService.CreateTemplateForContentType(contentTypeAlias, contentTypeName);
if (tryCreateTemplate == false)
{
_logger.LogWarning("Could not create a template for Content Type: \"{ContentTypeAlias}\", status: {Status}",
contentTypeAlias, tryCreateTemplate.Result.Result);
}
template = tryCreateTemplate.Result.Entity;
}
return template;
}
/// <summary>
/// Returns an empty content type for use as a scaffold when creating a new type
/// </summary>
/// <param name="parentId"></param>
/// <returns></returns>
[Authorize(Policy = AuthorizationPolicies.TreeAccessDocumentTypes)]
public DocumentTypeDisplay GetEmpty(int parentId)
{
IContentType ct;
if (parentId != Constants.System.Root)
{
var parent = _contentTypeService.Get(parentId);
ct = parent != null ? new ContentType(_shortStringHelper, parent, string.Empty) : new ContentType(_shortStringHelper, parentId);
}
else
ct = new ContentType(_shortStringHelper, parentId);
ct.Icon = Constants.Icons.Content;
var dto = _umbracoMapper.Map<IContentType, DocumentTypeDisplay>(ct);
return dto;
}
/// <summary>
/// Returns all content type objects
/// </summary>
[Authorize(Policy = AuthorizationPolicies.TreeAccessDocumentsOrDocumentTypes)]
public IEnumerable<ContentTypeBasic> GetAll()
{
var types = _contentTypeService.GetAll();
var basics = types.Select(_umbracoMapper.Map<IContentType, ContentTypeBasic>);
return basics.Select(basic =>
{
basic.Name = TranslateItem(basic.Name);
basic.Description = TranslateItem(basic.Description);
return basic;
});
}
/// <summary>
/// Returns the allowed child content type objects for the content item id passed in
/// </summary>
/// <param name="contentId"></param>
[Authorize(Policy = AuthorizationPolicies.TreeAccessDocumentsOrDocumentTypes)]
public IEnumerable<ContentTypeBasic> GetAllowedChildren(int contentId)
{
if (contentId == Constants.System.RecycleBinContent)
return Enumerable.Empty<ContentTypeBasic>();
IEnumerable<IContentType> types;
if (contentId == Constants.System.Root)
{
types = _contentTypeService.GetAll().Where(x => x.AllowedAsRoot).ToList();
}
else
{
var contentItem = _contentService.GetById(contentId);
if (contentItem == null)
{
return Enumerable.Empty<ContentTypeBasic>();
}
var contentType = _contentTypeBaseServiceProvider.GetContentTypeOf(contentItem);
var ids = contentType.AllowedContentTypes.OrderBy(c => c.SortOrder).Select(x => x.Id.Value).ToArray();
if (ids.Any() == false) return Enumerable.Empty<ContentTypeBasic>();
types = _contentTypeService.GetAll(ids).OrderBy(c => ids.IndexOf(c.Id)).ToList();
}
var basics = types.Where(type => type.IsElement == false).Select(_umbracoMapper.Map<IContentType, ContentTypeBasic>).ToList();
var localizedTextService = _localizedTextService;
foreach (var basic in basics)
{
basic.Name = localizedTextService.UmbracoDictionaryTranslate(CultureDictionary, basic.Name);
basic.Description = localizedTextService.UmbracoDictionaryTranslate(CultureDictionary, basic.Description);
}
//map the blueprints
var blueprints = _contentService.GetBlueprintsForContentTypes(types.Select(x => x.Id).ToArray()).ToArray();
foreach (var basic in basics)
{
var docTypeBluePrints = blueprints.Where(x => x.ContentTypeId == (int) basic.Id).ToArray();
foreach (var blueprint in docTypeBluePrints)
{
basic.Blueprints[blueprint.Id] = blueprint.Name;
}
}
return basics.OrderBy(c => contentId == Constants.System.Root ? c.Name : string.Empty);
}
/// <summary>
/// Move the content type
/// </summary>
/// <param name="move"></param>
/// <returns></returns>
[Authorize(Policy = AuthorizationPolicies.TreeAccessDocumentTypes)]
public IActionResult PostMove(MoveOrCopy move)
{
return PerformMove(
move,
getContentType: i => _contentTypeService.Get(i),
doMove: (type, i) => _contentTypeService.Move(type, i));
}
/// <summary>
/// Copy the content type
/// </summary>
/// <param name="copy"></param>
/// <returns></returns>
[Authorize(Policy = AuthorizationPolicies.TreeAccessDocumentTypes)]
public IActionResult PostCopy(MoveOrCopy copy)
{
return PerformCopy(
copy,
getContentType: i => _contentTypeService.Get(i),
doCopy: (type, i) => _contentTypeService.Copy(type, i));
}
[HttpGet]
[Authorize(Policy = AuthorizationPolicies.TreeAccessDocumentTypes)]
public IActionResult Export(int id)
{
var contentType = _contentTypeService.Get(id);
if (contentType == null) throw new NullReferenceException("No content type found with id " + id);
var xml = _serializer.Serialize(contentType);
var fileName = $"{contentType.Alias}.udt";
// Set custom header so umbRequestHelper.downloadFile can save the correct filename
HttpContext.Response.Headers.Add("x-filename", fileName);
return File( Encoding.UTF8.GetBytes(xml.ToDataString()), MediaTypeNames.Application.Octet, fileName);
}
[HttpPost]
[Authorize(Policy = AuthorizationPolicies.TreeAccessDocumentTypes)]
public IActionResult Import(string file)
{
var filePath = Path.Combine(_hostingEnvironment.MapPathContentRoot(Constants.SystemDirectories.Data), file);
if (string.IsNullOrEmpty(file) || !System.IO.File.Exists(filePath))
{
return NotFound();
}
var xd = new XmlDocument {XmlResolver = null};
xd.Load(filePath);
var userId = _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().ResultOr(0);
var element = XElement.Parse(xd.InnerXml);
_packageDataInstallation.ImportDocumentType(element, userId);
// Try to clean up the temporary file.
try
{
System.IO.File.Delete(filePath);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error cleaning up temporary udt file in {File}", filePath);
}
return Ok();
}
[HttpPost]
[Authorize(Policy = AuthorizationPolicies.TreeAccessDocumentTypes)]
public ActionResult<ContentTypeImportModel> Upload(List<IFormFile> file)
{
var model = new ContentTypeImportModel();
foreach (var formFile in file)
{
var fileName = formFile.FileName.Trim(Constants.CharArrays.DoubleQuote);
var ext = fileName.Substring(fileName.LastIndexOf('.') + 1).ToLower();
var root = _hostingEnvironment.MapPathContentRoot(Constants.SystemDirectories.TempFileUploads);
var tempPath = Path.Combine(root,fileName);
if (Path.GetFullPath(tempPath).StartsWith(Path.GetFullPath(root)))
{
using (var stream = System.IO.File.Create(tempPath))
{
formFile.CopyToAsync(stream).GetAwaiter().GetResult();
}
if (ext.InvariantEquals("udt"))
{
model.TempFileName = Path.Combine(root, fileName);
var xd = new XmlDocument
{
XmlResolver = null
};
xd.Load(model.TempFileName);
model.Alias = xd.DocumentElement?.SelectSingleNode("//DocumentType/Info/Alias")?.FirstChild.Value;
model.Name = xd.DocumentElement?.SelectSingleNode("//DocumentType/Info/Name")?.FirstChild.Value;
}
else
{
model.Notifications.Add(new BackOfficeNotification(
_localizedTextService.Localize("speechBubbles","operationFailedHeader"),
_localizedTextService.Localize("media","disallowedFileType"),
NotificationStyle.Warning));
}
}
else
{
model.Notifications.Add(new BackOfficeNotification(
_localizedTextService.Localize("speechBubbles", "operationFailedHeader"),
_localizedTextService.Localize("media", "invalidFileName"),
NotificationStyle.Warning));
}
}
return model;
}
}
}
| |
using CodeTorch.Mobile.Data.Rest.Android;
using ModernHttpClient;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using CodeTorch.Mobile.Data.Rest;
using Newtonsoft.Json;
[assembly: Xamarin.Forms.Dependency (typeof (AndroidRestClient))]
namespace CodeTorch.Mobile.Data.Rest.Android
{
public class AndroidRestClient: IRestClient
{
public async void MakeAsyncRequest(RestRequest restRequest, Action<RestResponse> successAction, Action<Exception> errorAction)
{
try
{
//Build RestSharp request
var restSharpRequest = BuildRestSharpRequest(restRequest);
//Create the RestSharp client
var restSharpClient = GetRestClient(restRequest.Url);
restSharpClient.ExecuteAsync(restSharpRequest, (r, h) =>
{
bool success = false;
Exception e = null;
var restResponse = BuildRestResponse(r);
var responseStatus = restResponse.ResponseStatus;
var responseStatusCode = restResponse.StatusCode;
var responseException = restResponse.ErrorException;
var responseErrorMessage = restResponse.ErrorMessage;
var responseContent = restResponse.Content;
HandleAsyncError(ref success, ref e, responseStatus, responseStatusCode, responseException, responseErrorMessage, responseContent);
if (success)
{
successAction(restResponse);
}
else
{
errorAction(e);
}
});
}
catch (Exception ex)
{
errorAction(ex);
}
}
private static void HandleAsyncError(ref bool success, ref Exception e, ResponseStatus responseStatus, ResponseHttpStatusCode responseStatusCode, Exception responseException, string responseErrorMessage, string responseContent)
{
Exception inner = null;
if (
(responseStatus == ResponseStatus.Aborted) ||
(responseStatus == ResponseStatus.Error) ||
(responseStatus == ResponseStatus.TimedOut)
)
{
//something bad happened with connection
success = false;
if (
(responseException != null) ||
(!String.IsNullOrEmpty(responseErrorMessage))
)
{
if (responseException != null)
{
inner = responseException;
}
else
{
inner= new Exception(responseErrorMessage);
}
}
switch (responseStatus)
{
case ResponseStatus.Aborted:
e = new Exception("Error - Connection Aborted",inner);
break;
case ResponseStatus.Error:
e = new Exception("Error - Connection Error", inner);
break;
case ResponseStatus.TimedOut:
e = new Exception("Error - Connection Timed Out", inner);
break;
default:
e = new Exception("Error - Connection - Error", inner);
break;
}
}
else
{
//something bad happened with server side code from services
if (Convert.ToInt32(responseStatusCode) >= 400)
{
success = false;
//attempt to serialize error
ServiceResponse errorResponse = SerializeServiceError(responseContent);
if(errorResponse == null)
{
e = new Exception(responseContent);
}
else
{
e = new Exception(errorResponse.Message);
}
switch (responseStatusCode)
{
case ResponseHttpStatusCode.BadGateway:
e = new Exception("Error - Bad Gateway", inner);
break;
case ResponseHttpStatusCode.BadRequest:
e = new Exception("Error - Bad Request", inner);
break;
case ResponseHttpStatusCode.Forbidden:
e = new Exception("Error - Forbidden", inner);
break;
case ResponseHttpStatusCode.GatewayTimeout:
e = new Exception("Error - Gateway Timeout", inner);
break;
case ResponseHttpStatusCode.HttpVersionNotSupported:
e = new Exception("Error - Http Version Not Supported", inner);
break;
case ResponseHttpStatusCode.MethodNotAllowed:
e = new Exception("Error - Method Not Allowed", inner);
break;
case ResponseHttpStatusCode.NotFound:
e = new Exception("Error - Not Found", inner);
break;
case ResponseHttpStatusCode.NotImplemented:
e = new Exception("Error - Not Implemented", inner);
break;
case ResponseHttpStatusCode.ProxyAuthenticationRequired:
e = new Exception("Error - Proxy Authentication Required", inner);
break;
case ResponseHttpStatusCode.RequestEntityTooLarge:
e = new Exception("Error - Request Entity Too Large", inner);
break;
case ResponseHttpStatusCode.RequestTimeout:
e = new Exception("Error - Request Timeout", inner);
break;
case ResponseHttpStatusCode.ServiceUnavailable:
e = new Exception("Error - Service Unavailable", inner);
break;
case ResponseHttpStatusCode.Unauthorized:
e = new Exception("Error - Unauthorized", inner);
break;
case ResponseHttpStatusCode.InternalServerError:
//special case to handle web service errors
break;
default:
e = new Exception("Error - Server Error", inner);
break;
}
}
else
{
//we are good
success = true;
}
}
}
public static ServiceResponse SerializeServiceError(string json)
{
ServiceResponse error = null;
try
{
error = JsonConvert.DeserializeObject<ServiceResponse>(json);
}
catch { }
return error;
}
private RestResponse BuildRestResponse(RestSharp.IRestResponse restSharpResponse)
{
var restResponse = new RestResponse();
restResponse.Content = restSharpResponse.Content;
restResponse.ContentEncoding = restSharpResponse.ContentEncoding;
restResponse.ContentLength = restSharpResponse.ContentLength;
restResponse.ContentType = restSharpResponse.ContentType;
//TODO: solve this mapping
//toReturn.Cookies = restSharpResponse.Cookies;
restResponse.ErrorException = restSharpResponse.ErrorException;
restResponse.ErrorMessage = restSharpResponse.ErrorMessage;
//TODO: solve this mapping
//toReturn.Headers = restSharpResponse.Headers,
restResponse.RawBytes = restSharpResponse.RawBytes;
//TODO: solve this mapping
//toReturn.Request = restRequest;
restResponse.ResponseStatus = (ResponseStatus)Enum.Parse(typeof(ResponseStatus), restSharpResponse.ResponseStatus.ToString());
restResponse.ResponseUri = restSharpResponse.ResponseUri;
restResponse.Server = restSharpResponse.Server;
restResponse.StatusCode = (ResponseHttpStatusCode)Enum.Parse(typeof(ResponseHttpStatusCode), restSharpResponse.StatusCode.ToString());
restResponse.StatusDescription = restSharpResponse.StatusDescription;
return restResponse;
}
private RestSharp.IRestClient GetRestClient(string url)
{
//TODO: maybe we could use allways the same instance...
var restClient = new RestSharp.RestClient(url);
return restClient;
}
private RestSharp.IRestRequest BuildRestSharpRequest(RestRequest restRequest)
{
var restSharpRequest = new RestSharp.RestRequest(restRequest.Resource);
restSharpRequest.Method = (RestSharp.Method)Enum.Parse(typeof(RestSharp.Method), restRequest.Method.ToString());
restSharpRequest.RequestFormat = (RestSharp.DataFormat)Enum.Parse(typeof(RestSharp.DataFormat), restRequest.RequestFormat.ToString());
restSharpRequest.DateFormat = restRequest.DateFormat;
//added by philip to force timeout within 15 seconds for connect
restSharpRequest.Timeout = 15000;
//TODO: solve this mapping
//restSharpRequest.Credentials = restRequest.Credentials;
if (restRequest.Body != null)
restSharpRequest.AddBody(restRequest.Body);
foreach (var item in restRequest.Cookies)
restSharpRequest.AddCookie(item.Key, item.Value);
foreach (var item in restRequest.Files)
{
if (!string.IsNullOrEmpty(item.Path))
{
restSharpRequest.AddFile(item.Name, item.Path);
}
else
{
if (String.IsNullOrEmpty(item.ContentType))
{
restSharpRequest.AddFile(item.Name, item.Bytes, item.FileName);
}
else
{
restSharpRequest.AddFile(item.Name, item.Bytes, item.FileName, item.ContentType);
}
}
}
foreach (var item in restRequest.Headers)
restSharpRequest.AddHeader(item.Key, item.Value);
foreach (var item in restRequest.UrlSegments)
restSharpRequest.AddUrlSegment(item.Key, item.Value);
foreach (var item in restRequest.Objects)
restSharpRequest.AddObject(item.Key, item.Value);
foreach (var item in restRequest.Parameters)
{
RestSharp.ParameterType t = (RestSharp.ParameterType) Enum.Parse(typeof(RestSharp.ParameterType), item.Type.ToString());
restSharpRequest.AddParameter(
item.Name,
item.Value,
t
);
}
return restSharpRequest;
}
}
}
| |
// 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.Buffers;
using System.Diagnostics;
using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
namespace System.Net.Sockets
{
public partial class SocketAsyncEventArgs : EventArgs, IDisposable
{
// Single buffer
private MemoryHandle _singleBufferHandle;
private volatile SingleBufferHandleState _singleBufferHandleState;
private enum SingleBufferHandleState : byte { None, InProcess, Set }
// BufferList property variables.
// Note that these arrays are allocated and then grown as necessary, but never shrunk.
// Thus the actual in-use length is defined by _bufferListInternal.Count, not the length of these arrays.
private WSABuffer[] _wsaBufferArray;
private GCHandle[] _multipleBufferGCHandles;
// Internal buffers for WSARecvMsg
private byte[] _wsaMessageBuffer;
private GCHandle _wsaMessageBufferGCHandle;
private byte[] _controlBuffer;
private GCHandle _controlBufferGCHandle;
private WSABuffer[] _wsaRecvMsgWSABufferArray;
private GCHandle _wsaRecvMsgWSABufferArrayGCHandle;
// Internal SocketAddress buffer
private GCHandle _socketAddressGCHandle;
private Internals.SocketAddress _pinnedSocketAddress;
// SendPacketsElements property variables.
private FileStream[] _sendPacketsFileStreams;
// Overlapped object related variables.
private PreAllocatedOverlapped _preAllocatedOverlapped;
private readonly StrongBox<SocketAsyncEventArgs> _strongThisRef = new StrongBox<SocketAsyncEventArgs>(); // state for _preAllocatedOverlapped; .Value set to this while operations in flight
// Cancellation support
private CancellationTokenRegistration _registrationToCancelPendingIO;
private unsafe NativeOverlapped* _pendingOverlappedForCancellation;
private PinState _pinState;
private enum PinState : byte { None = 0, MultipleBuffer, SendPackets }
private void InitializeInternals()
{
// PreAllocatedOverlapped captures ExecutionContext, but SocketAsyncEventArgs ensures
// that context is properly flowed if necessary, and thus we don't need the overlapped
// infrastructure capturing and flowing as well.
bool suppressFlow = !ExecutionContext.IsFlowSuppressed();
try
{
if (suppressFlow) ExecutionContext.SuppressFlow();
_preAllocatedOverlapped = new PreAllocatedOverlapped(s_completionPortCallback, _strongThisRef, null);
}
finally
{
if (suppressFlow) ExecutionContext.RestoreFlow();
}
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"new PreAllocatedOverlapped {_preAllocatedOverlapped}");
}
private void FreeInternals()
{
FreePinHandles();
FreeOverlapped();
}
private unsafe NativeOverlapped* AllocateNativeOverlapped()
{
Debug.Assert(_operating == InProgress, $"Expected {nameof(_operating)} == {nameof(InProgress)}, got {_operating}");
Debug.Assert(_currentSocket != null, "_currentSocket is null");
Debug.Assert(_currentSocket.SafeHandle != null, "_currentSocket.SafeHandle is null");
Debug.Assert(_preAllocatedOverlapped != null, "_preAllocatedOverlapped is null");
ThreadPoolBoundHandle boundHandle = _currentSocket.GetOrAllocateThreadPoolBoundHandle();
return boundHandle.AllocateNativeOverlapped(_preAllocatedOverlapped);
}
private unsafe void FreeNativeOverlapped(NativeOverlapped* overlapped)
{
Debug.Assert(overlapped != null, "overlapped is null");
Debug.Assert(_operating == InProgress, $"Expected _operating == InProgress, got {_operating}");
Debug.Assert(_currentSocket != null, "_currentSocket is null");
Debug.Assert(_currentSocket.SafeHandle != null, "_currentSocket.SafeHandle is null");
Debug.Assert(_currentSocket.SafeHandle.IOCPBoundHandle != null, "_currentSocket.SafeHandle.IOCPBoundHandle is null");
Debug.Assert(_preAllocatedOverlapped != null, "_preAllocatedOverlapped is null");
_currentSocket.SafeHandle.IOCPBoundHandle.FreeNativeOverlapped(overlapped);
}
private unsafe void RegisterToCancelPendingIO(NativeOverlapped* overlapped, CancellationToken cancellationToken)
{
Debug.Assert(_singleBufferHandleState == SingleBufferHandleState.InProcess);
Debug.Assert(_pendingOverlappedForCancellation == null);
_pendingOverlappedForCancellation = overlapped;
_registrationToCancelPendingIO = cancellationToken.UnsafeRegister(s =>
{
// Try to cancel the I/O. We ignore the return value (other than for logging), as cancellation
// is opportunistic and we don't want to fail the operation because we couldn't cancel it.
var thisRef = (SocketAsyncEventArgs)s;
SafeSocketHandle handle = thisRef._currentSocket.SafeHandle;
if (!handle.IsClosed)
{
try
{
bool canceled = Interop.Kernel32.CancelIoEx(handle, thisRef._pendingOverlappedForCancellation);
if (NetEventSource.IsEnabled)
{
NetEventSource.Info(thisRef, canceled ?
"Socket operation canceled." :
$"CancelIoEx failed with error '{Marshal.GetLastWin32Error()}'.");
}
}
catch (ObjectDisposedException)
{
// Ignore errors resulting from the SafeHandle being closed concurrently.
}
}
}, this);
}
partial void StartOperationCommonCore()
{
// Store the reference to this instance so that it's kept alive by the preallocated
// overlapped during the asynchronous operation and so that it's available in the
// I/O completion callback. Once the operation completes, we null this out so
// that the SocketAsyncEventArgs instance isn't kept alive unnecessarily.
_strongThisRef.Value = this;
}
/// <summary>Handles the result of an IOCP operation.</summary>
/// <param name="success">true if the operation completed synchronously and successfully; otherwise, false.</param>
/// <param name="bytesTransferred">The number of bytes transferred, if the operation completed synchronously and successfully.</param>
/// <param name="overlapped">The overlapped to be freed if the operation completed synchronously.</param>
/// <returns>The result status of the operation.</returns>
private unsafe SocketError ProcessIOCPResult(bool success, int bytesTransferred, NativeOverlapped* overlapped)
{
// Note: We need to dispose of the overlapped iff the operation completed synchronously,
// and if we do, we must do so before we mark the operation as completed.
if (success)
{
// Synchronous success.
if (_currentSocket.SafeHandle.SkipCompletionPortOnSuccess)
{
// The socket handle is configured to skip completion on success,
// so we can set the results right now.
FreeNativeOverlapped(overlapped);
FinishOperationSyncSuccess(bytesTransferred, SocketFlags.None);
return SocketError.Success;
}
// Completed synchronously, but the handle wasn't marked as skip completion port on success,
// so we still need to fall through and behave as if the IO was pending.
}
else
{
// Get the socket error (which may be IOPending)
SocketError socketError = SocketPal.GetLastSocketError();
if (socketError != SocketError.IOPending)
{
// Completed synchronously with a failure.
FreeNativeOverlapped(overlapped);
FinishOperationSyncFailure(socketError, bytesTransferred, SocketFlags.None);
return socketError;
}
// Fall through to IOPending handling for asynchronous completion.
}
// Socket handle is going to post a completion to the completion port (may have done so already).
// Return pending and we will continue in the completion port callback.
return SocketError.IOPending;
}
/// <summary>Handles the result of an IOCP operation.</summary>
/// <param name="socketError">The result status of the operation, as returned from the API call.</param>
/// <param name="bytesTransferred">The number of bytes transferred, if the operation completed synchronously and successfully.</param>
/// <param name="overlapped">The overlapped to be freed if the operation completed synchronously.</param>
/// <param name="cancellationToken">The cancellation token to use to cancel the operation.</param>
/// <returns>The result status of the operation.</returns>
private unsafe SocketError ProcessIOCPResultWithSingleBufferHandle(SocketError socketError, int bytesTransferred, NativeOverlapped* overlapped, CancellationToken cancellationToken = default)
{
// Note: We need to dispose of the overlapped iff the operation completed synchronously,
// and if we do, we must do so before we mark the operation as completed.
if (socketError == SocketError.Success)
{
// Synchronous success.
if (_currentSocket.SafeHandle.SkipCompletionPortOnSuccess)
{
// The socket handle is configured to skip completion on success,
// so we can set the results right now.
_singleBufferHandleState = SingleBufferHandleState.None;
FreeNativeOverlapped(overlapped);
FinishOperationSyncSuccess(bytesTransferred, SocketFlags.None);
return SocketError.Success;
}
// Completed synchronously, but the handle wasn't marked as skip completion port on success,
// so we still need to fall through and behave as if the IO was pending.
}
else
{
// Get the socket error (which may be IOPending)
socketError = SocketPal.GetLastSocketError();
if (socketError != SocketError.IOPending)
{
// Completed synchronously with a failure.
_singleBufferHandleState = SingleBufferHandleState.None;
FreeNativeOverlapped(overlapped);
FinishOperationSyncFailure(socketError, bytesTransferred, SocketFlags.None);
return socketError;
}
// Fall through to IOPending handling for asynchronous completion.
}
// Socket handle is going to post a completion to the completion port (may have done so already).
// Return pending and we will continue in the completion port callback.
if (_singleBufferHandleState == SingleBufferHandleState.InProcess)
{
RegisterToCancelPendingIO(overlapped, cancellationToken); // must happen before we change state to Set to avoid race conditions
_singleBufferHandle = _buffer.Pin();
_singleBufferHandleState = SingleBufferHandleState.Set;
}
return SocketError.IOPending;
}
internal unsafe SocketError DoOperationAccept(Socket socket, SafeSocketHandle handle, SafeSocketHandle acceptHandle)
{
bool userBuffer = _count != 0;
Debug.Assert(!userBuffer || (!_buffer.Equals(default) && _count >= _acceptAddressBufferCount));
Memory<byte> buffer = userBuffer ? _buffer : _acceptBuffer;
Debug.Assert(_singleBufferHandleState == SingleBufferHandleState.None);
NativeOverlapped* overlapped = AllocateNativeOverlapped();
try
{
_singleBufferHandle = buffer.Pin();
_singleBufferHandleState = SingleBufferHandleState.Set;
bool success = socket.AcceptEx(
handle,
acceptHandle,
userBuffer ? (IntPtr)((byte*)_singleBufferHandle.Pointer + _offset) : (IntPtr)_singleBufferHandle.Pointer,
userBuffer ? _count - _acceptAddressBufferCount : 0,
_acceptAddressBufferCount / 2,
_acceptAddressBufferCount / 2,
out int bytesTransferred,
overlapped);
return ProcessIOCPResult(success, bytesTransferred, overlapped);
}
catch
{
_singleBufferHandleState = SingleBufferHandleState.None;
FreeNativeOverlapped(overlapped);
_singleBufferHandle.Dispose();
throw;
}
}
internal unsafe SocketError DoOperationConnect(Socket socket, SafeSocketHandle handle)
{
// ConnectEx uses a sockaddr buffer containing the remote address to which to connect.
// It can also optionally take a single buffer of data to send after the connection is complete.
// The sockaddr is pinned with a GCHandle to avoid having to use the object array form of UnsafePack.
PinSocketAddressBuffer();
NativeOverlapped* overlapped = AllocateNativeOverlapped();
try
{
Debug.Assert(_singleBufferHandleState == SingleBufferHandleState.None);
_singleBufferHandle = _buffer.Pin();
_singleBufferHandleState = SingleBufferHandleState.Set;
bool success = socket.ConnectEx(
handle,
PtrSocketAddressBuffer,
_socketAddress.Size,
(IntPtr)((byte*)_singleBufferHandle.Pointer + _offset),
_count,
out int bytesTransferred,
overlapped);
return ProcessIOCPResult(success, bytesTransferred, overlapped);
}
catch
{
_singleBufferHandleState = SingleBufferHandleState.None;
FreeNativeOverlapped(overlapped);
_singleBufferHandle.Dispose();
throw;
}
}
internal unsafe SocketError DoOperationDisconnect(Socket socket, SafeSocketHandle handle)
{
NativeOverlapped* overlapped = AllocateNativeOverlapped();
try
{
bool success = socket.DisconnectEx(
handle,
overlapped,
(int)(DisconnectReuseSocket ? TransmitFileOptions.ReuseSocket : 0),
0);
return ProcessIOCPResult(success, 0, overlapped);
}
catch
{
FreeNativeOverlapped(overlapped);
throw;
}
}
internal SocketError DoOperationReceive(SafeSocketHandle handle, CancellationToken cancellationToken) => _bufferList == null ?
DoOperationReceiveSingleBuffer(handle, cancellationToken) :
DoOperationReceiveMultiBuffer(handle);
internal unsafe SocketError DoOperationReceiveSingleBuffer(SafeSocketHandle handle, CancellationToken cancellationToken)
{
fixed (byte* bufferPtr = &MemoryMarshal.GetReference(_buffer.Span))
{
NativeOverlapped* overlapped = AllocateNativeOverlapped();
try
{
Debug.Assert(_singleBufferHandleState == SingleBufferHandleState.None, $"Expected None, got {_singleBufferHandleState}");
_singleBufferHandleState = SingleBufferHandleState.InProcess;
var wsaBuffer = new WSABuffer { Length = _count, Pointer = (IntPtr)(bufferPtr + _offset) };
SocketFlags flags = _socketFlags;
SocketError socketError = Interop.Winsock.WSARecv(
handle,
ref wsaBuffer,
1,
out int bytesTransferred,
ref flags,
overlapped,
IntPtr.Zero);
return ProcessIOCPResultWithSingleBufferHandle(socketError, bytesTransferred, overlapped, cancellationToken);
}
catch
{
_singleBufferHandleState = SingleBufferHandleState.None;
FreeNativeOverlapped(overlapped);
throw;
}
}
}
internal unsafe SocketError DoOperationReceiveMultiBuffer(SafeSocketHandle handle)
{
NativeOverlapped* overlapped = AllocateNativeOverlapped();
try
{
SocketFlags flags = _socketFlags;
SocketError socketError = Interop.Winsock.WSARecv(
handle,
_wsaBufferArray,
_bufferListInternal.Count,
out int bytesTransferred,
ref flags,
overlapped,
IntPtr.Zero);
return ProcessIOCPResult(socketError == SocketError.Success, bytesTransferred, overlapped);
}
catch
{
FreeNativeOverlapped(overlapped);
throw;
}
}
internal unsafe SocketError DoOperationReceiveFrom(SafeSocketHandle handle)
{
// WSARecvFrom uses a WSABuffer array describing buffers in which to
// receive data and from which to send data respectively. Single and multiple buffers
// are handled differently so as to optimize performance for the more common single buffer case.
// WSARecvFrom and WSASendTo also uses a sockaddr buffer in which to store the address from which the data was received.
// The sockaddr is pinned with a GCHandle to avoid having to use the object array form of UnsafePack.
PinSocketAddressBuffer();
return _bufferList == null ?
DoOperationReceiveFromSingleBuffer(handle) :
DoOperationReceiveFromMultiBuffer(handle);
}
internal unsafe SocketError DoOperationReceiveFromSingleBuffer(SafeSocketHandle handle)
{
fixed (byte* bufferPtr = &MemoryMarshal.GetReference(_buffer.Span))
{
NativeOverlapped* overlapped = AllocateNativeOverlapped();
try
{
Debug.Assert(_singleBufferHandleState == SingleBufferHandleState.None);
_singleBufferHandleState = SingleBufferHandleState.InProcess;
var wsaBuffer = new WSABuffer { Length = _count, Pointer = (IntPtr)(bufferPtr + _offset) };
SocketFlags flags = _socketFlags;
SocketError socketError = Interop.Winsock.WSARecvFrom(
handle,
ref wsaBuffer,
1,
out int bytesTransferred,
ref flags,
PtrSocketAddressBuffer,
PtrSocketAddressBufferSize,
overlapped,
IntPtr.Zero);
return ProcessIOCPResultWithSingleBufferHandle(socketError, bytesTransferred, overlapped);
}
catch
{
_singleBufferHandleState = SingleBufferHandleState.None;
FreeNativeOverlapped(overlapped);
throw;
}
}
}
internal unsafe SocketError DoOperationReceiveFromMultiBuffer(SafeSocketHandle handle)
{
NativeOverlapped* overlapped = AllocateNativeOverlapped();
try
{
SocketFlags flags = _socketFlags;
SocketError socketError = Interop.Winsock.WSARecvFrom(
handle,
_wsaBufferArray,
_bufferListInternal.Count,
out int bytesTransferred,
ref flags,
PtrSocketAddressBuffer,
PtrSocketAddressBufferSize,
overlapped,
IntPtr.Zero);
return ProcessIOCPResult(socketError == SocketError.Success, bytesTransferred, overlapped);
}
catch
{
FreeNativeOverlapped(overlapped);
throw;
}
}
internal unsafe SocketError DoOperationReceiveMessageFrom(Socket socket, SafeSocketHandle handle)
{
// WSARecvMsg uses a WSAMsg descriptor.
// The WSAMsg buffer is pinned with a GCHandle to avoid complicating the use of Overlapped.
// WSAMsg contains a pointer to a sockaddr.
// The sockaddr is pinned with a GCHandle to avoid complicating the use of Overlapped.
// WSAMsg contains a pointer to a WSABuffer array describing data buffers.
// WSAMsg also contains a single WSABuffer describing a control buffer.
PinSocketAddressBuffer();
// Create a WSAMessageBuffer if none exists yet.
if (_wsaMessageBuffer == null)
{
Debug.Assert(!_wsaMessageBufferGCHandle.IsAllocated);
_wsaMessageBuffer = new byte[sizeof(Interop.Winsock.WSAMsg)];
}
// And ensure the WSAMessageBuffer is appropriately pinned.
Debug.Assert(!_wsaMessageBufferGCHandle.IsAllocated || _wsaMessageBufferGCHandle.Target == _wsaMessageBuffer);
if (!_wsaMessageBufferGCHandle.IsAllocated)
{
_wsaMessageBufferGCHandle = GCHandle.Alloc(_wsaMessageBuffer, GCHandleType.Pinned);
}
// Create and pin an appropriately sized control buffer if none already
IPAddress ipAddress = (_socketAddress.Family == AddressFamily.InterNetworkV6 ? _socketAddress.GetIPAddress() : null);
bool ipv4 = (_currentSocket.AddressFamily == AddressFamily.InterNetwork || (ipAddress != null && ipAddress.IsIPv4MappedToIPv6)); // DualMode
bool ipv6 = _currentSocket.AddressFamily == AddressFamily.InterNetworkV6;
if (ipv4 && (_controlBuffer == null || _controlBuffer.Length != sizeof(Interop.Winsock.ControlData)))
{
if (_controlBufferGCHandle.IsAllocated)
{
_controlBufferGCHandle.Free();
}
_controlBuffer = new byte[sizeof(Interop.Winsock.ControlData)];
}
else if (ipv6 && (_controlBuffer == null || _controlBuffer.Length != sizeof(Interop.Winsock.ControlDataIPv6)))
{
if (_controlBufferGCHandle.IsAllocated)
{
_controlBufferGCHandle.Free();
}
_controlBuffer = new byte[sizeof(Interop.Winsock.ControlDataIPv6)];
}
// If single buffer we need a single element WSABuffer.
WSABuffer[] wsaRecvMsgWSABufferArray;
uint wsaRecvMsgWSABufferCount;
if (_bufferList == null)
{
if (_wsaRecvMsgWSABufferArray == null)
{
_wsaRecvMsgWSABufferArray = new WSABuffer[1];
}
Debug.Assert(_singleBufferHandleState == SingleBufferHandleState.None);
_singleBufferHandle = _buffer.Pin();
_singleBufferHandleState = SingleBufferHandleState.Set;
_wsaRecvMsgWSABufferArray[0].Pointer = (IntPtr)_singleBufferHandle.Pointer;
_wsaRecvMsgWSABufferArray[0].Length = _count;
wsaRecvMsgWSABufferArray = _wsaRecvMsgWSABufferArray;
wsaRecvMsgWSABufferCount = 1;
}
else
{
// Use the multi-buffer WSABuffer.
wsaRecvMsgWSABufferArray = _wsaBufferArray;
wsaRecvMsgWSABufferCount = (uint)_bufferListInternal.Count;
}
// Ensure the array is pinned.
Debug.Assert(!_wsaRecvMsgWSABufferArrayGCHandle.IsAllocated || _wsaRecvMsgWSABufferArrayGCHandle.Target == wsaRecvMsgWSABufferArray);
if (!_wsaRecvMsgWSABufferArrayGCHandle.IsAllocated)
{
_wsaRecvMsgWSABufferArrayGCHandle = GCHandle.Alloc(wsaRecvMsgWSABufferArray, GCHandleType.Pinned);
}
// Fill in WSAMessageBuffer.
unsafe
{
Interop.Winsock.WSAMsg* pMessage = (Interop.Winsock.WSAMsg*)Marshal.UnsafeAddrOfPinnedArrayElement(_wsaMessageBuffer, 0);
pMessage->socketAddress = PtrSocketAddressBuffer;
pMessage->addressLength = (uint)_socketAddress.Size;
fixed (void* ptrWSARecvMsgWSABufferArray = &wsaRecvMsgWSABufferArray[0])
{
pMessage->buffers = (IntPtr)ptrWSARecvMsgWSABufferArray;
}
pMessage->count = wsaRecvMsgWSABufferCount;
if (_controlBuffer != null)
{
Debug.Assert(_controlBuffer.Length > 0);
Debug.Assert(!_controlBufferGCHandle.IsAllocated || _controlBufferGCHandle.Target == _controlBuffer);
if (!_controlBufferGCHandle.IsAllocated)
{
_controlBufferGCHandle = GCHandle.Alloc(_controlBuffer, GCHandleType.Pinned);
}
fixed (void* ptrControlBuffer = &_controlBuffer[0])
{
pMessage->controlBuffer.Pointer = (IntPtr)ptrControlBuffer;
}
pMessage->controlBuffer.Length = _controlBuffer.Length;
}
pMessage->flags = _socketFlags;
}
NativeOverlapped* overlapped = AllocateNativeOverlapped();
try
{
SocketError socketError = socket.WSARecvMsg(
handle,
Marshal.UnsafeAddrOfPinnedArrayElement(_wsaMessageBuffer, 0),
out int bytesTransferred,
overlapped,
IntPtr.Zero);
return ProcessIOCPResultWithSingleBufferHandle(socketError, bytesTransferred, overlapped);
}
catch
{
_singleBufferHandleState = SingleBufferHandleState.None;
FreeNativeOverlapped(overlapped);
_singleBufferHandle.Dispose();
throw;
}
}
internal unsafe SocketError DoOperationSend(SafeSocketHandle handle, CancellationToken cancellationToken) => _bufferList == null ?
DoOperationSendSingleBuffer(handle, cancellationToken) :
DoOperationSendMultiBuffer(handle);
internal unsafe SocketError DoOperationSendSingleBuffer(SafeSocketHandle handle, CancellationToken cancellationToken)
{
fixed (byte* bufferPtr = &MemoryMarshal.GetReference(_buffer.Span))
{
NativeOverlapped* overlapped = AllocateNativeOverlapped();
try
{
Debug.Assert(_singleBufferHandleState == SingleBufferHandleState.None);
_singleBufferHandleState = SingleBufferHandleState.InProcess;
var wsaBuffer = new WSABuffer { Length = _count, Pointer = (IntPtr)(bufferPtr + _offset) };
SocketError socketError = Interop.Winsock.WSASend(
handle,
ref wsaBuffer,
1,
out int bytesTransferred,
_socketFlags,
overlapped,
IntPtr.Zero);
return ProcessIOCPResultWithSingleBufferHandle(socketError, bytesTransferred, overlapped, cancellationToken);
}
catch
{
_singleBufferHandleState = SingleBufferHandleState.None;
FreeNativeOverlapped(overlapped);
throw;
}
}
}
internal unsafe SocketError DoOperationSendMultiBuffer(SafeSocketHandle handle)
{
NativeOverlapped* overlapped = AllocateNativeOverlapped();
try
{
SocketError socketError = Interop.Winsock.WSASend(
handle,
_wsaBufferArray,
_bufferListInternal.Count,
out int bytesTransferred,
_socketFlags,
overlapped,
IntPtr.Zero);
return ProcessIOCPResult(socketError == SocketError.Success, bytesTransferred, overlapped);
}
catch
{
FreeNativeOverlapped(overlapped);
throw;
}
}
internal unsafe SocketError DoOperationSendPackets(Socket socket, SafeSocketHandle handle)
{
// Cache copy to avoid problems with concurrent manipulation during the async operation.
Debug.Assert(_sendPacketsElements != null);
SendPacketsElement[] sendPacketsElementsCopy = (SendPacketsElement[])_sendPacketsElements.Clone();
// TransmitPackets uses an array of TRANSMIT_PACKET_ELEMENT structs as
// descriptors for buffers and files to be sent. It also takes a send size
// and some flags. The TRANSMIT_PACKET_ELEMENT for a file contains a native file handle.
// Opens the files to get the file handles, pin down any buffers specified and builds the
// native TRANSMIT_PACKET_ELEMENT array that will be passed to TransmitPackets.
// Scan the elements to count files and buffers.
int sendPacketsElementsFileCount = 0, sendPacketsElementsFileStreamCount = 0, sendPacketsElementsBufferCount = 0;
foreach (SendPacketsElement spe in sendPacketsElementsCopy)
{
if (spe != null)
{
if (spe.FilePath != null)
{
sendPacketsElementsFileCount++;
}
else if (spe.FileStream != null)
{
sendPacketsElementsFileStreamCount++;
}
else if (spe.Buffer != null && spe.Count > 0)
{
sendPacketsElementsBufferCount++;
}
}
}
if (sendPacketsElementsFileCount + sendPacketsElementsFileStreamCount + sendPacketsElementsBufferCount == 0)
{
FinishOperationSyncSuccess(0, SocketFlags.None);
return SocketError.Success;
}
// Attempt to open the files if any were given.
if (sendPacketsElementsFileCount > 0)
{
// Loop through the elements attempting to open each files and get its handle.
int index = 0;
_sendPacketsFileStreams = new FileStream[sendPacketsElementsFileCount];
try
{
foreach (SendPacketsElement spe in sendPacketsElementsCopy)
{
if (spe?.FilePath != null)
{
// Create a FileStream to open the file.
_sendPacketsFileStreams[index] =
new FileStream(spe.FilePath, FileMode.Open, FileAccess.Read, FileShare.Read);
// Get the file handle from the stream.
index++;
}
}
}
catch
{
// Got an exception opening a file - close any open streams, then throw.
for (int i = index - 1; i >= 0; i--)
_sendPacketsFileStreams[i].Dispose();
_sendPacketsFileStreams = null;
throw;
}
}
Interop.Winsock.TransmitPacketsElement[] sendPacketsDescriptor =
SetupPinHandlesSendPackets(sendPacketsElementsCopy, sendPacketsElementsFileCount,
sendPacketsElementsFileStreamCount, sendPacketsElementsBufferCount);
Debug.Assert(sendPacketsDescriptor != null);
Debug.Assert(sendPacketsDescriptor.Length > 0);
Debug.Assert(_multipleBufferGCHandles != null);
Debug.Assert(_multipleBufferGCHandles[0].IsAllocated);
Debug.Assert(_multipleBufferGCHandles[0].Target == sendPacketsDescriptor);
NativeOverlapped* overlapped = AllocateNativeOverlapped();
try
{
bool result = socket.TransmitPackets(
handle,
_multipleBufferGCHandles[0].AddrOfPinnedObject(),
sendPacketsDescriptor.Length,
_sendPacketsSendSize,
overlapped,
_sendPacketsFlags);
return ProcessIOCPResult(result, 0, overlapped);
}
catch
{
FreeNativeOverlapped(overlapped);
throw;
}
}
internal unsafe SocketError DoOperationSendTo(SafeSocketHandle handle)
{
// WSASendTo uses a WSABuffer array describing buffers in which to
// receive data and from which to send data respectively. Single and multiple buffers
// are handled differently so as to optimize performance for the more common single buffer case.
//
// WSARecvFrom and WSASendTo also uses a sockaddr buffer in which to store the address from which the data was received.
// The sockaddr is pinned with a GCHandle to avoid having to use the object array form of UnsafePack.
PinSocketAddressBuffer();
return _bufferList == null ?
DoOperationSendToSingleBuffer(handle) :
DoOperationSendToMultiBuffer(handle);
}
internal unsafe SocketError DoOperationSendToSingleBuffer(SafeSocketHandle handle)
{
fixed (byte* bufferPtr = &MemoryMarshal.GetReference(_buffer.Span))
{
NativeOverlapped* overlapped = AllocateNativeOverlapped();
try
{
Debug.Assert(_singleBufferHandleState == SingleBufferHandleState.None);
_singleBufferHandleState = SingleBufferHandleState.InProcess;
var wsaBuffer = new WSABuffer { Length = _count, Pointer = (IntPtr)(bufferPtr + _offset) };
SocketError socketError = Interop.Winsock.WSASendTo(
handle,
ref wsaBuffer,
1,
out int bytesTransferred,
_socketFlags,
PtrSocketAddressBuffer,
_socketAddress.Size,
overlapped,
IntPtr.Zero);
return ProcessIOCPResultWithSingleBufferHandle(socketError, bytesTransferred, overlapped);
}
catch
{
_singleBufferHandleState = SingleBufferHandleState.None;
FreeNativeOverlapped(overlapped);
throw;
}
}
}
internal unsafe SocketError DoOperationSendToMultiBuffer(SafeSocketHandle handle)
{
NativeOverlapped* overlapped = AllocateNativeOverlapped();
try
{
SocketError socketError = Interop.Winsock.WSASendTo(
handle,
_wsaBufferArray,
_bufferListInternal.Count,
out int bytesTransferred,
_socketFlags,
PtrSocketAddressBuffer,
_socketAddress.Size,
overlapped,
IntPtr.Zero);
return ProcessIOCPResult(socketError == SocketError.Success, bytesTransferred, overlapped);
}
catch
{
FreeNativeOverlapped(overlapped);
throw;
}
}
// Ensures Overlapped object exists with appropriate multiple buffers pinned.
private void SetupMultipleBuffers()
{
if (_bufferListInternal == null || _bufferListInternal.Count == 0)
{
// No buffer list is set so unpin any existing multiple buffer pinning.
if (_pinState == PinState.MultipleBuffer)
{
FreePinHandles();
}
}
else
{
// Need to setup a new Overlapped.
FreePinHandles();
try
{
int bufferCount = _bufferListInternal.Count;
#if DEBUG
if (_multipleBufferGCHandles != null)
{
foreach (GCHandle gcHandle in _multipleBufferGCHandles)
{
Debug.Assert(!gcHandle.IsAllocated);
}
}
#endif
// Number of things to pin is number of buffers.
// Ensure we have properly sized object array.
if (_multipleBufferGCHandles == null || (_multipleBufferGCHandles.Length < bufferCount))
{
_multipleBufferGCHandles = new GCHandle[bufferCount];
}
// Pin the buffers.
for (int i = 0; i < bufferCount; i++)
{
Debug.Assert(!_multipleBufferGCHandles[i].IsAllocated);
_multipleBufferGCHandles[i] = GCHandle.Alloc(_bufferListInternal[i].Array, GCHandleType.Pinned);
}
if (_wsaBufferArray == null || _wsaBufferArray.Length < bufferCount)
{
_wsaBufferArray = new WSABuffer[bufferCount];
}
for (int i = 0; i < bufferCount; i++)
{
ArraySegment<byte> localCopy = _bufferListInternal[i];
_wsaBufferArray[i].Pointer = Marshal.UnsafeAddrOfPinnedArrayElement(localCopy.Array, localCopy.Offset);
_wsaBufferArray[i].Length = localCopy.Count;
}
_pinState = PinState.MultipleBuffer;
}
catch (Exception)
{
FreePinHandles();
throw;
}
}
}
// Ensures appropriate SocketAddress buffer is pinned.
private void PinSocketAddressBuffer()
{
// Check if already pinned.
if (_pinnedSocketAddress == _socketAddress)
{
return;
}
// Unpin any existing.
if (_socketAddressGCHandle.IsAllocated)
{
_socketAddressGCHandle.Free();
}
// Pin down the new one.
_socketAddressGCHandle = GCHandle.Alloc(_socketAddress.Buffer, GCHandleType.Pinned);
_socketAddress.CopyAddressSizeIntoBuffer();
_pinnedSocketAddress = _socketAddress;
}
private unsafe IntPtr PtrSocketAddressBuffer
{
get
{
Debug.Assert(_pinnedSocketAddress != null);
Debug.Assert(_pinnedSocketAddress.Buffer != null);
Debug.Assert(_pinnedSocketAddress.Buffer.Length > 0);
Debug.Assert(_socketAddressGCHandle.IsAllocated);
Debug.Assert(_socketAddressGCHandle.Target == _pinnedSocketAddress.Buffer);
fixed (void* ptrSocketAddressBuffer = &_pinnedSocketAddress.Buffer[0])
{
return (IntPtr)ptrSocketAddressBuffer;
}
}
}
private IntPtr PtrSocketAddressBufferSize => PtrSocketAddressBuffer + _socketAddress.GetAddressSizeOffset();
// Cleans up any existing Overlapped object and related state variables.
private void FreeOverlapped()
{
// Free the preallocated overlapped object. This in turn will unpin
// any pinned buffers.
if (_preAllocatedOverlapped != null)
{
_preAllocatedOverlapped.Dispose();
_preAllocatedOverlapped = null;
}
}
private void FreePinHandles()
{
_pinState = PinState.None;
if (_singleBufferHandleState != SingleBufferHandleState.None)
{
_singleBufferHandleState = SingleBufferHandleState.None;
_singleBufferHandle.Dispose();
}
if (_multipleBufferGCHandles != null)
{
for (int i = 0; i < _multipleBufferGCHandles.Length; i++)
{
if (_multipleBufferGCHandles[i].IsAllocated)
{
_multipleBufferGCHandles[i].Free();
}
}
}
if (_socketAddressGCHandle.IsAllocated)
{
_socketAddressGCHandle.Free();
_pinnedSocketAddress = null;
}
if (_wsaMessageBufferGCHandle.IsAllocated)
{
_wsaMessageBufferGCHandle.Free();
}
if (_wsaRecvMsgWSABufferArrayGCHandle.IsAllocated)
{
_wsaRecvMsgWSABufferArrayGCHandle.Free();
}
if (_controlBufferGCHandle.IsAllocated)
{
_controlBufferGCHandle.Free();
}
}
// Sets up an Overlapped object for SendPacketsAsync.
private unsafe Interop.Winsock.TransmitPacketsElement[] SetupPinHandlesSendPackets(
SendPacketsElement[] sendPacketsElementsCopy, int sendPacketsElementsFileCount, int sendPacketsElementsFileStreamCount, int sendPacketsElementsBufferCount)
{
if (_pinState != PinState.None)
{
FreePinHandles();
}
// Alloc native descriptor.
var sendPacketsDescriptor = new Interop.Winsock.TransmitPacketsElement[sendPacketsElementsFileCount + sendPacketsElementsFileStreamCount + sendPacketsElementsBufferCount];
// Number of things to pin is number of buffers + 1 (native descriptor).
// Ensure we have properly sized object array.
#if DEBUG
if (_multipleBufferGCHandles != null)
{
foreach (GCHandle gcHandle in _multipleBufferGCHandles)
{
Debug.Assert(!gcHandle.IsAllocated);
}
}
#endif
if (_multipleBufferGCHandles == null || (_multipleBufferGCHandles.Length < sendPacketsElementsBufferCount + 1))
{
_multipleBufferGCHandles = new GCHandle[sendPacketsElementsBufferCount + 1];
}
// Pin objects. Native descriptor buffer first and then user specified buffers.
Debug.Assert(!_multipleBufferGCHandles[0].IsAllocated);
_multipleBufferGCHandles[0] = GCHandle.Alloc(sendPacketsDescriptor, GCHandleType.Pinned);
int index = 1;
foreach (SendPacketsElement spe in sendPacketsElementsCopy)
{
if (spe?.Buffer != null && spe.Count > 0)
{
Debug.Assert(!_multipleBufferGCHandles[index].IsAllocated);
_multipleBufferGCHandles[index] = GCHandle.Alloc(spe.Buffer, GCHandleType.Pinned);
index++;
}
}
// Fill in native descriptor.
int descriptorIndex = 0;
int fileIndex = 0;
foreach (SendPacketsElement spe in sendPacketsElementsCopy)
{
if (spe != null)
{
if (spe.Buffer != null && spe.Count > 0)
{
// This element is a buffer.
sendPacketsDescriptor[descriptorIndex].buffer = Marshal.UnsafeAddrOfPinnedArrayElement(spe.Buffer, spe.Offset);
sendPacketsDescriptor[descriptorIndex].length = (uint)spe.Count;
sendPacketsDescriptor[descriptorIndex].flags =
Interop.Winsock.TransmitPacketsElementFlags.Memory | (spe.EndOfPacket
? Interop.Winsock.TransmitPacketsElementFlags.EndOfPacket
: 0);
descriptorIndex++;
}
else if (spe.FilePath != null)
{
// This element is a file.
sendPacketsDescriptor[descriptorIndex].fileHandle = _sendPacketsFileStreams[fileIndex].SafeFileHandle.DangerousGetHandle();
sendPacketsDescriptor[descriptorIndex].fileOffset = spe.OffsetLong;
sendPacketsDescriptor[descriptorIndex].length = (uint)spe.Count;
sendPacketsDescriptor[descriptorIndex].flags =
Interop.Winsock.TransmitPacketsElementFlags.File | (spe.EndOfPacket
? Interop.Winsock.TransmitPacketsElementFlags.EndOfPacket
: 0);
fileIndex++;
descriptorIndex++;
}
else if (spe.FileStream != null)
{
// This element is a file stream. SendPacketsElement throws if the FileStream is not opened asynchronously;
// Synchronously opened FileStream can't be used concurrently (e.g. multiple SendPacketsElements with the same
// FileStream).
sendPacketsDescriptor[descriptorIndex].fileHandle = spe.FileStream.SafeFileHandle.DangerousGetHandle();
sendPacketsDescriptor[descriptorIndex].fileOffset = spe.OffsetLong;
sendPacketsDescriptor[descriptorIndex].length = (uint)spe.Count;
sendPacketsDescriptor[descriptorIndex].flags =
Interop.Winsock.TransmitPacketsElementFlags.File | (spe.EndOfPacket
? Interop.Winsock.TransmitPacketsElementFlags.EndOfPacket
: 0);
descriptorIndex++;
}
}
}
_pinState = PinState.SendPackets;
return sendPacketsDescriptor;
}
internal void LogBuffer(int size)
{
// This should only be called if tracing is enabled. However, there is the potential for a race
// condition where tracing is disabled between a calling check and here, in which case the assert
// may fire erroneously.
Debug.Assert(NetEventSource.IsEnabled);
if (_bufferList != null)
{
for (int i = 0; i < _bufferListInternal.Count; i++)
{
WSABuffer wsaBuffer = _wsaBufferArray[i];
NetEventSource.DumpBuffer(this, wsaBuffer.Pointer, Math.Min(wsaBuffer.Length, size));
if ((size -= wsaBuffer.Length) <= 0)
{
break;
}
}
}
else if (_buffer.Length != 0)
{
NetEventSource.DumpBuffer(this, _buffer, _offset, size);
}
}
private unsafe SocketError FinishOperationAccept(Internals.SocketAddress remoteSocketAddress)
{
SocketError socketError;
IntPtr localAddr;
int localAddrLength;
IntPtr remoteAddr;
bool refAdded = false;
SafeHandle safeHandle = _currentSocket.SafeHandle;
try
{
safeHandle.DangerousAddRef(ref refAdded);
IntPtr handle = safeHandle.DangerousGetHandle();
Debug.Assert(_singleBufferHandleState == SingleBufferHandleState.Set);
bool userBuffer = _count >= _acceptAddressBufferCount;
_currentSocket.GetAcceptExSockaddrs(
userBuffer ? (IntPtr)((byte*)_singleBufferHandle.Pointer + _offset) : (IntPtr)_singleBufferHandle.Pointer,
_count != 0 ? _count - _acceptAddressBufferCount : 0,
_acceptAddressBufferCount / 2,
_acceptAddressBufferCount / 2,
out localAddr,
out localAddrLength,
out remoteAddr,
out remoteSocketAddress.InternalSize
);
Marshal.Copy(remoteAddr, remoteSocketAddress.Buffer, 0, remoteSocketAddress.Size);
socketError = Interop.Winsock.setsockopt(
_acceptSocket.SafeHandle,
SocketOptionLevel.Socket,
SocketOptionName.UpdateAcceptContext,
ref handle,
IntPtr.Size);
if (socketError == SocketError.SocketError)
{
socketError = SocketPal.GetLastSocketError();
}
}
catch (ObjectDisposedException)
{
socketError = SocketError.OperationAborted;
}
finally
{
if (refAdded)
{
safeHandle.DangerousRelease();
}
}
return socketError;
}
private SocketError FinishOperationConnect()
{
try
{
// Update the socket context.
SocketError socketError = Interop.Winsock.setsockopt(
_currentSocket.SafeHandle,
SocketOptionLevel.Socket,
SocketOptionName.UpdateConnectContext,
null,
0);
return socketError == SocketError.SocketError ?
SocketPal.GetLastSocketError() :
socketError;
}
catch (ObjectDisposedException)
{
return SocketError.OperationAborted;
}
}
private unsafe int GetSocketAddressSize() => *(int*)PtrSocketAddressBufferSize;
private void CompleteCore()
{
_strongThisRef.Value = null; // null out this reference from the overlapped so this isn't kept alive artificially
if (_singleBufferHandleState != SingleBufferHandleState.None)
{
CompleteCoreSpin();
}
void CompleteCoreSpin() // separate out to help inline the fast path
{
// The operation could complete so quickly that it races with the code
// initiating it. Wait until that initiation code has completed before
// we try to undo the state it configures.
var sw = new SpinWait();
while (_singleBufferHandleState == SingleBufferHandleState.InProcess)
{
sw.SpinOnce();
}
// Remove any cancellation registration. First dispose the registration
// to ensure that cancellation will either never fine or will have completed
// firing before we continue. Only then can we safely null out the overlapped.
_registrationToCancelPendingIO.Dispose();
unsafe
{
_pendingOverlappedForCancellation = null;
}
// Release any GC handles.
if (_singleBufferHandleState == SingleBufferHandleState.Set)
{
_singleBufferHandleState = SingleBufferHandleState.None;
_singleBufferHandle.Dispose();
}
}
}
private unsafe void FinishOperationReceiveMessageFrom()
{
Interop.Winsock.WSAMsg* PtrMessage = (Interop.Winsock.WSAMsg*)Marshal.UnsafeAddrOfPinnedArrayElement(_wsaMessageBuffer, 0);
if (_controlBuffer.Length == sizeof(Interop.Winsock.ControlData))
{
// IPv4.
_receiveMessageFromPacketInfo = SocketPal.GetIPPacketInformation((Interop.Winsock.ControlData*)PtrMessage->controlBuffer.Pointer);
}
else if (_controlBuffer.Length == sizeof(Interop.Winsock.ControlDataIPv6))
{
// IPv6.
_receiveMessageFromPacketInfo = SocketPal.GetIPPacketInformation((Interop.Winsock.ControlDataIPv6*)PtrMessage->controlBuffer.Pointer);
}
else
{
// Other.
_receiveMessageFromPacketInfo = new IPPacketInformation();
}
}
private void FinishOperationSendPackets()
{
// Close the files if open.
if (_sendPacketsFileStreams != null)
{
for (int i = 0; i < _sendPacketsFileStreams.Length; i++)
{
_sendPacketsFileStreams[i]?.Dispose();
}
_sendPacketsFileStreams = null;
}
}
private static readonly unsafe IOCompletionCallback s_completionPortCallback = delegate (uint errorCode, uint numBytes, NativeOverlapped* nativeOverlapped)
{
var saeaBox = (StrongBox<SocketAsyncEventArgs>)ThreadPoolBoundHandle.GetNativeOverlappedState(nativeOverlapped);
SocketAsyncEventArgs saea = saeaBox.Value;
Debug.Assert(saea != null);
if ((SocketError)errorCode == SocketError.Success)
{
saea.FreeNativeOverlapped(nativeOverlapped);
saea.FinishOperationAsyncSuccess((int)numBytes, SocketFlags.None);
}
else
{
saea.HandleCompletionPortCallbackError(errorCode, numBytes, nativeOverlapped);
}
};
private unsafe void HandleCompletionPortCallbackError(uint errorCode, uint numBytes, NativeOverlapped* nativeOverlapped)
{
SocketError socketError = (SocketError)errorCode;
SocketFlags socketFlags = SocketFlags.None;
if (socketError != SocketError.OperationAborted)
{
if (_currentSocket.Disposed)
{
socketError = SocketError.OperationAborted;
}
else
{
try
{
// The Async IO completed with a failure.
// here we need to call WSAGetOverlappedResult() just so GetLastSocketError() will return the correct error.
Interop.Winsock.WSAGetOverlappedResult(
_currentSocket.SafeHandle,
nativeOverlapped,
out numBytes,
false,
out socketFlags);
socketError = SocketPal.GetLastSocketError();
}
catch
{
// _currentSocket.Disposed check above does not always work since this code is subject to race conditions.
socketError = SocketError.OperationAborted;
}
}
}
FreeNativeOverlapped(nativeOverlapped);
FinishOperationAsyncFailure(socketError, (int)numBytes, socketFlags);
}
}
}
| |
/* ====================================================================
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.XWPF.UserModel
{
using System;
using NUnit.Framework;
using NPOI.OpenXml4Net.OPC;
using System.IO;
using System.Collections.Generic;
using NPOI.Util;
using System.Xml.Serialization;
using NPOI.OpenXmlFormats.Wordprocessing;
using NPOI.XWPF.Util;
[TestFixture]
public class TestXWPFDocument
{
[Test]
public void TestContainsMainContentType()
{
XWPFDocument doc = XWPFTestDataSamples.OpenSampleDocument("sample.docx");
OPCPackage pack = doc.Package;
bool found = false;
foreach (PackagePart part in pack.GetParts())
{
if (part.ContentType.Equals(XWPFRelation.DOCUMENT.ContentType))
{
found = true;
}
if (false == found)
{
// successful tests should be silent
System.Console.WriteLine(part);
}
}
Assert.IsTrue(found);
}
[Test]
public void TestOpen()
{
XWPFDocument xml;
// Simple file
xml = XWPFTestDataSamples.OpenSampleDocument("sample.docx");
// Check it has key parts
Assert.IsNotNull(xml.Document);
Assert.IsNotNull(xml.Document.body);
Assert.IsNotNull(xml.GetStyles());
// Complex file
xml = XWPFTestDataSamples.OpenSampleDocument("IllustrativeCases.docx");
Assert.IsNotNull(xml.Document);
Assert.IsNotNull(xml.Document.body);
Assert.IsNotNull(xml.GetStyles());
}
[Test]
public void TestMetadataBasics()
{
XWPFDocument xml = XWPFTestDataSamples.OpenSampleDocument("sample.docx");
Assert.IsNotNull(xml.GetProperties().CoreProperties);
Assert.IsNotNull(xml.GetProperties().ExtendedProperties);
Assert.AreEqual("Microsoft Office Word", xml.GetProperties().ExtendedProperties.GetUnderlyingProperties().Application);
Assert.AreEqual(1315, xml.GetProperties().ExtendedProperties.GetUnderlyingProperties().Characters);
Assert.AreEqual(10, xml.GetProperties().ExtendedProperties.GetUnderlyingProperties().Lines);
Assert.AreEqual(null, xml.GetProperties().CoreProperties.Title);
Assert.AreEqual(null, xml.GetProperties().CoreProperties.GetUnderlyingProperties().GetSubjectProperty());
}
[Test]
public void TestMetadataComplex()
{
XWPFDocument xml = XWPFTestDataSamples.OpenSampleDocument("IllustrativeCases.docx");
Assert.IsNotNull(xml.GetProperties().CoreProperties);
Assert.IsNotNull(xml.GetProperties().ExtendedProperties);
Assert.AreEqual("Microsoft Office Outlook", xml.GetProperties().ExtendedProperties.GetUnderlyingProperties().Application);
Assert.AreEqual(5184, xml.GetProperties().ExtendedProperties.GetUnderlyingProperties().Characters);
Assert.AreEqual(0, xml.GetProperties().ExtendedProperties.GetUnderlyingProperties().Lines);
Assert.AreEqual(" ", xml.GetProperties().CoreProperties.Title);
Assert.AreEqual(" ", xml.GetProperties().CoreProperties.GetUnderlyingProperties().GetSubjectProperty());
}
[Test]
public void TestWorkbookProperties()
{
XWPFDocument doc = new XWPFDocument();
POIXMLProperties props = doc.GetProperties();
Assert.IsNotNull(props);
Assert.AreEqual("NPOI", props.ExtendedProperties.GetUnderlyingProperties().Application);
}
[Test]
public void TestAddParagraph()
{
XWPFDocument doc = XWPFTestDataSamples.OpenSampleDocument("sample.docx");
Assert.AreEqual(3, doc.Paragraphs.Count);
XWPFParagraph p = doc.CreateParagraph();
Assert.AreEqual(p, doc.Paragraphs[(3)]);
Assert.AreEqual(4, doc.Paragraphs.Count);
Assert.AreEqual(3, doc.GetParagraphPos(3));
Assert.AreEqual(3, doc.GetPosOfParagraph(p));
//CTP ctp = p.CTP;
//XWPFParagraph newP = doc.GetParagraph(ctp);
//Assert.AreSame(p, newP);
//XmlCursor cursor = doc.Document.Body.GetPArray(0).newCursor();
//XWPFParagraph cP = doc.InsertNewParagraph(cursor);
//Assert.AreSame(cP, doc.Paragraphs[(0)]);
//Assert.AreEqual(5, doc.Paragraphs.Count);
}
[Test]
public void TestAddPicture()
{
XWPFDocument doc = XWPFTestDataSamples.OpenSampleDocument("sample.docx");
byte[] jpeg = XWPFTestDataSamples.GetImage("nature1.jpg");
String relationId = doc.AddPictureData(jpeg, (int)PictureType.JPEG);
byte[] newJpeg = ((XWPFPictureData)doc.GetRelationById(relationId)).Data;
Assert.AreEqual(newJpeg.Length, jpeg.Length);
for (int i = 0; i < jpeg.Length; i++)
{
Assert.AreEqual(newJpeg[i], jpeg[i]);
}
}
[Test]
public void TestAllPictureFormats()
{
XWPFDocument doc = new XWPFDocument();
doc.AddPictureData(new byte[10], (int)PictureType.EMF);
doc.AddPictureData(new byte[11], (int)PictureType.WMF);
doc.AddPictureData(new byte[12], (int)PictureType.PICT);
doc.AddPictureData(new byte[13], (int)PictureType.JPEG);
doc.AddPictureData(new byte[14], (int)PictureType.PNG);
doc.AddPictureData(new byte[15], (int)PictureType.DIB);
doc.AddPictureData(new byte[16], (int)PictureType.GIF);
doc.AddPictureData(new byte[17], (int)PictureType.TIFF);
doc.AddPictureData(new byte[18], (int)PictureType.EPS);
doc.AddPictureData(new byte[19], (int)PictureType.BMP);
doc.AddPictureData(new byte[20], (int)PictureType.WPG);
Assert.AreEqual(11, doc.AllPictures.Count);
doc = XWPFTestDataSamples.WriteOutAndReadBack(doc);
Assert.AreEqual(11, doc.AllPictures.Count);
}
[Test]
public void TestRemoveBodyElement()
{
XWPFDocument doc = XWPFTestDataSamples.OpenSampleDocument("sample.docx");
Assert.AreEqual(3, doc.Paragraphs.Count);
Assert.AreEqual(3, doc.BodyElements.Count);
XWPFParagraph p1 = doc.Paragraphs[(0)];
XWPFParagraph p2 = doc.Paragraphs[(1)];
XWPFParagraph p3 = doc.Paragraphs[(2)];
Assert.AreEqual(p1, doc.BodyElements[(0)]);
Assert.AreEqual(p1, doc.Paragraphs[(0)]);
Assert.AreEqual(p2, doc.BodyElements[(1)]);
Assert.AreEqual(p2, doc.Paragraphs[(1)]);
Assert.AreEqual(p3, doc.BodyElements[(2)]);
Assert.AreEqual(p3, doc.Paragraphs[(2)]);
// Add another
XWPFParagraph p4 = doc.CreateParagraph();
Assert.AreEqual(4, doc.Paragraphs.Count);
Assert.AreEqual(4, doc.BodyElements.Count);
Assert.AreEqual(p1, doc.BodyElements[(0)]);
Assert.AreEqual(p1, doc.Paragraphs[(0)]);
Assert.AreEqual(p2, doc.BodyElements[(1)]);
Assert.AreEqual(p2, doc.Paragraphs[(1)]);
Assert.AreEqual(p3, doc.BodyElements[(2)]);
Assert.AreEqual(p3, doc.Paragraphs[(2)]);
Assert.AreEqual(p4, doc.BodyElements[(3)]);
Assert.AreEqual(p4, doc.Paragraphs[(3)]);
// Remove the 2nd
Assert.AreEqual(true, doc.RemoveBodyElement(1));
Assert.AreEqual(3, doc.Paragraphs.Count);
Assert.AreEqual(3, doc.BodyElements.Count);
Assert.AreEqual(p1, doc.BodyElements[(0)]);
Assert.AreEqual(p1, doc.Paragraphs[(0)]);
Assert.AreEqual(p3, doc.BodyElements[(1)]);
Assert.AreEqual(p3, doc.Paragraphs[(1)]);
Assert.AreEqual(p4, doc.BodyElements[(2)]);
Assert.AreEqual(p4, doc.Paragraphs[(2)]);
// Remove the 1st
Assert.AreEqual(true, doc.RemoveBodyElement(0));
Assert.AreEqual(2, doc.Paragraphs.Count);
Assert.AreEqual(2, doc.BodyElements.Count);
Assert.AreEqual(p3, doc.BodyElements[(0)]);
Assert.AreEqual(p3, doc.Paragraphs[(0)]);
Assert.AreEqual(p4, doc.BodyElements[(1)]);
Assert.AreEqual(p4, doc.Paragraphs[(1)]);
// Remove the last
Assert.AreEqual(true, doc.RemoveBodyElement(1));
Assert.AreEqual(1, doc.Paragraphs.Count);
Assert.AreEqual(1, doc.BodyElements.Count);
Assert.AreEqual(p3, doc.BodyElements[(0)]);
Assert.AreEqual(p3, doc.Paragraphs[(0)]);
}
[Test]
public void TestRegisterPackagePictureData()
{
XWPFDocument doc = XWPFTestDataSamples.OpenSampleDocument("issue_51265_1.docx");
/* manually assemble a new image package part*/
OPCPackage opcPckg = doc.Package;
XWPFRelation jpgRelation = XWPFRelation.IMAGE_JPEG;
PackagePartName partName = PackagingUriHelper.CreatePartName(jpgRelation.DefaultFileName.Replace('#', '2'));
PackagePart newImagePart = opcPckg.CreatePart(partName, jpgRelation.ContentType);
byte[] nature1 = XWPFTestDataSamples.GetImage("abstract4.jpg");
Stream os = newImagePart.GetOutputStream();
os.Write(nature1, 0, nature1.Length);
os.Close();
XWPFHeader xwpfHeader = doc.HeaderList[(0)];
PackageRelationship relationship = xwpfHeader.GetPackagePart().AddRelationship(partName, TargetMode.Internal, jpgRelation.Relation);
XWPFPictureData newPicData = new XWPFPictureData(newImagePart, relationship);
/* new part is now Ready to rumble */
Assert.IsFalse(xwpfHeader.AllPictures.Contains(newPicData));
Assert.IsFalse(doc.AllPictures.Contains(newPicData));
Assert.IsFalse(doc.AllPackagePictures.Contains(newPicData));
doc.RegisterPackagePictureData(newPicData);
Assert.IsFalse(xwpfHeader.AllPictures.Contains(newPicData));
Assert.IsFalse(doc.AllPictures.Contains(newPicData));
Assert.IsTrue(doc.AllPackagePictures.Contains(newPicData));
doc.Package.Revert();
}
[Test]
public void TestFindPackagePictureData()
{
XWPFDocument doc = XWPFTestDataSamples.OpenSampleDocument("issue_51265_1.docx");
byte[] nature1 = XWPFTestDataSamples.GetImage("nature1.gif");
XWPFPictureData part = doc.FindPackagePictureData(nature1, (int)PictureType.GIF);
Assert.IsNotNull(part);
Assert.IsTrue(doc.AllPictures.Contains(part));
Assert.IsTrue(doc.AllPackagePictures.Contains(part));
doc.Package.Revert();
}
[Test]
public void TestGetAllPictures()
{
XWPFDocument doc = XWPFTestDataSamples.OpenSampleDocument("issue_51265_3.docx");
IList<XWPFPictureData> allPictures = doc.AllPictures;
IList<XWPFPictureData> allPackagePictures = doc.AllPackagePictures;
Assert.IsNotNull(allPictures);
Assert.AreEqual(3, allPictures.Count);
foreach (XWPFPictureData xwpfPictureData in allPictures)
{
Assert.IsTrue(allPackagePictures.Contains(xwpfPictureData));
}
try
{
allPictures.Add(allPictures[0]);
Assert.Fail("This list must be unmodifiable!");
}
catch (NotSupportedException)
{
// all ok
}
doc.Package.Revert();
}
[Test]
public void TestGetAllPackagePictures()
{
XWPFDocument doc = XWPFTestDataSamples.OpenSampleDocument("issue_51265_3.docx");
IList<XWPFPictureData> allPackagePictures = doc.AllPackagePictures;
Assert.IsNotNull(allPackagePictures);
Assert.AreEqual(5, allPackagePictures.Count);
try
{
allPackagePictures.Add(allPackagePictures[0]);
Assert.Fail("This list must be unmodifiable!");
}
catch (NotSupportedException)
{
// all ok
}
doc.Package.Revert();
}
[Test]
public void TestPictureHandlingSimpleFile()
{
XWPFDocument doc = XWPFTestDataSamples.OpenSampleDocument("issue_51265_1.docx");
Assert.AreEqual(1, doc.AllPackagePictures.Count);
byte[] newPic = XWPFTestDataSamples.GetImage("abstract4.jpg");
String id1 = doc.AddPictureData(newPic, (int)PictureType.JPEG);
Assert.AreEqual(2, doc.AllPackagePictures.Count);
/* copy data, to avoid instance-Equality */
byte[] newPicCopy = Arrays.CopyOf(newPic, newPic.Length);
String id2 = doc.AddPictureData(newPicCopy, (int)PictureType.JPEG);
Assert.AreEqual(id1, id2);
doc.Package.Revert();
}
[Test]
public void TestPictureHandlingHeaderDocumentImages()
{
XWPFDocument doc = XWPFTestDataSamples.OpenSampleDocument("issue_51265_2.docx");
Assert.AreEqual(1, doc.AllPictures.Count);
Assert.AreEqual(1, doc.AllPackagePictures.Count);
Assert.AreEqual(1, doc.HeaderList[(0)].AllPictures.Count);
doc.Package.Revert();
}
[Test]
public void TestPictureHandlingComplex()
{
XWPFDocument doc = XWPFTestDataSamples.OpenSampleDocument("issue_51265_3.docx");
XWPFHeader xwpfHeader = doc.HeaderList[(0)];
Assert.AreEqual(3, doc.AllPictures.Count);
Assert.AreEqual(3, xwpfHeader.AllPictures.Count);
Assert.AreEqual(5, doc.AllPackagePictures.Count);
byte[] nature1 = XWPFTestDataSamples.GetImage("nature1.jpg");
String id = doc.AddPictureData(nature1, (int)PictureType.JPEG);
POIXMLDocumentPart part1 = xwpfHeader.GetRelationById("rId1");
XWPFPictureData part2 = (XWPFPictureData)doc.GetRelationById(id);
Assert.AreSame(part1, part2);
doc.Package.Revert();
}
[Test]
public void TestSettings()
{
XWPFSettings settings = new XWPFSettings();
settings.SetZoomPercent(50);
Assert.AreEqual(50, settings.GetZoomPercent());
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Orchard.Logging;
namespace Orchard.ContentManagement.Handlers {
public abstract class ContentHandler : IContentHandler {
protected ContentHandler() {
Filters = new List<IContentFilter>();
Logger = NullLogger.Instance;
}
public List<IContentFilter> Filters { get; set; }
public ILogger Logger { get; set; }
protected void OnActivated<TPart>(Action<ActivatedContentContext, TPart> handler) where TPart : class, IContent {
Filters.Add(new InlineStorageFilter<TPart> { OnActivated = handler });
}
protected void OnInitializing<TPart>(Action<InitializingContentContext, TPart> handler) where TPart : class, IContent {
Filters.Add(new InlineStorageFilter<TPart> { OnInitializing = handler });
}
protected void OnInitialized<TPart>(Action<InitializingContentContext, TPart> handler) where TPart : class, IContent {
Filters.Add(new InlineStorageFilter<TPart> { OnInitialized = handler });
}
protected void OnCreating<TPart>(Action<CreateContentContext, TPart> handler) where TPart : class, IContent {
Filters.Add(new InlineStorageFilter<TPart> { OnCreating = handler });
}
protected void OnCreated<TPart>(Action<CreateContentContext, TPart> handler) where TPart : class, IContent {
Filters.Add(new InlineStorageFilter<TPart> { OnCreated = handler });
}
protected void OnLoading<TPart>(Action<LoadContentContext, TPart> handler) where TPart : class, IContent {
Filters.Add(new InlineStorageFilter<TPart> { OnLoading = handler });
}
protected void OnLoaded<TPart>(Action<LoadContentContext, TPart> handler) where TPart : class, IContent {
Filters.Add(new InlineStorageFilter<TPart> { OnLoaded = handler });
}
protected void OnUpdating<TPart>(Action<UpdateContentContext, TPart> handler) where TPart : class, IContent {
Filters.Add(new InlineStorageFilter<TPart> { OnUpdating = handler });
}
protected void OnUpdated<TPart>(Action<UpdateContentContext, TPart> handler) where TPart : class, IContent {
Filters.Add(new InlineStorageFilter<TPart> { OnUpdated = handler });
}
protected void OnVersioning<TPart>(Action<VersionContentContext, TPart, TPart> handler) where TPart : class, IContent {
Filters.Add(new InlineStorageFilter<TPart> { OnVersioning = handler });
}
protected void OnVersioned<TPart>(Action<VersionContentContext, TPart, TPart> handler) where TPart : class, IContent {
Filters.Add(new InlineStorageFilter<TPart> { OnVersioned = handler });
}
protected void OnPublishing<TPart>(Action<PublishContentContext, TPart> handler) where TPart : class, IContent {
Filters.Add(new InlineStorageFilter<TPart> { OnPublishing = handler });
}
protected void OnPublished<TPart>(Action<PublishContentContext, TPart> handler) where TPart : class, IContent {
Filters.Add(new InlineStorageFilter<TPart> { OnPublished = handler });
}
protected void OnUnpublishing<TPart>(Action<PublishContentContext, TPart> handler) where TPart : class, IContent {
Filters.Add(new InlineStorageFilter<TPart> { OnUnpublishing = handler });
}
protected void OnUnpublished<TPart>(Action<PublishContentContext, TPart> handler) where TPart : class, IContent {
Filters.Add(new InlineStorageFilter<TPart> { OnUnpublished = handler });
}
protected void OnRemoving<TPart>(Action<RemoveContentContext, TPart> handler) where TPart : class, IContent {
Filters.Add(new InlineStorageFilter<TPart> { OnRemoving = handler });
}
protected void OnRemoved<TPart>(Action<RemoveContentContext, TPart> handler) where TPart : class, IContent {
Filters.Add(new InlineStorageFilter<TPart> { OnRemoved = handler });
}
protected void OnDestroying<TPart>(Action<DestroyContentContext, TPart> handler) where TPart : class, IContent {
Filters.Add(new InlineStorageFilter<TPart> { OnDestroying = handler });
}
protected void OnDestroyed<TPart>(Action<DestroyContentContext, TPart> handler) where TPart : class, IContent {
Filters.Add(new InlineStorageFilter<TPart> { OnDestroyed = handler });
}
protected void OnIndexing<TPart>(Action<IndexContentContext, TPart> handler) where TPart : class, IContent {
Filters.Add(new InlineStorageFilter<TPart> { OnIndexing = handler });
}
protected void OnIndexed<TPart>(Action<IndexContentContext, TPart> handler) where TPart : class, IContent {
Filters.Add(new InlineStorageFilter<TPart> { OnIndexed = handler });
}
protected void OnImporting<TPart>(Action<ImportContentContext, TPart> handler) where TPart : class, IContent {
Filters.Add(new InlineStorageFilter<TPart> { OnImporting = handler });
}
protected void OnImported<TPart>(Action<ImportContentContext, TPart> handler) where TPart : class, IContent {
Filters.Add(new InlineStorageFilter<TPart> { OnImported = handler });
}
protected void OnImportCompleted<TPart>(Action<ImportContentContext, TPart> handler) where TPart : class, IContent {
Filters.Add(new InlineStorageFilter<TPart> { OnImportCompleted = handler });
}
protected void OnExporting<TPart>(Action<ExportContentContext, TPart> handler) where TPart : class, IContent {
Filters.Add(new InlineStorageFilter<TPart> { OnExporting = handler });
}
protected void OnExported<TPart>(Action<ExportContentContext, TPart> handler) where TPart : class, IContent {
Filters.Add(new InlineStorageFilter<TPart> { OnExported = handler });
}
protected void OnRestoring<TPart>(Action<RestoreContentContext, TPart> handler) where TPart : class, IContent {
Filters.Add(new InlineStorageFilter<TPart> { OnRestoring = handler });
}
protected void OnRestored<TPart>(Action<RestoreContentContext, TPart> handler) where TPart : class, IContent {
Filters.Add(new InlineStorageFilter<TPart> { OnRestored = handler });
}
protected void OnGetContentItemMetadata<TPart>(Action<GetContentItemMetadataContext, TPart> handler) where TPart : class, IContent {
Filters.Add(new InlineTemplateFilter<TPart> { OnGetItemMetadata = handler });
}
protected void OnGetDisplayShape<TPart>(Action<BuildDisplayContext, TPart> handler) where TPart : class, IContent {
Filters.Add(new InlineTemplateFilter<TPart> { OnGetDisplayShape = handler });
}
protected void OnGetEditorShape<TPart>(Action<BuildEditorContext, TPart> handler) where TPart : class, IContent {
Filters.Add(new InlineTemplateFilter<TPart> { OnGetEditorShape = handler });
}
protected void OnUpdateEditorShape<TPart>(Action<UpdateEditorContext, TPart> handler) where TPart : class, IContent {
Filters.Add(new InlineTemplateFilter<TPart> { OnUpdateEditorShape = handler });
}
class InlineStorageFilter<TPart> : StorageFilterBase<TPart> where TPart : class, IContent {
public Action<ActivatedContentContext, TPart> OnActivated { get; set; }
public Action<InitializingContentContext, TPart> OnInitializing { get; set; }
public Action<InitializingContentContext, TPart> OnInitialized { get; set; }
public Action<CreateContentContext, TPart> OnCreating { get; set; }
public Action<CreateContentContext, TPart> OnCreated { get; set; }
public Action<LoadContentContext, TPart> OnLoading { get; set; }
public Action<LoadContentContext, TPart> OnLoaded { get; set; }
public Action<UpdateContentContext, TPart> OnUpdating { get; set; }
public Action<UpdateContentContext, TPart> OnUpdated { get; set; }
public Action<VersionContentContext, TPart, TPart> OnVersioning { get; set; }
public Action<VersionContentContext, TPart, TPart> OnVersioned { get; set; }
public Action<PublishContentContext, TPart> OnPublishing { get; set; }
public Action<PublishContentContext, TPart> OnPublished { get; set; }
public Action<PublishContentContext, TPart> OnUnpublishing { get; set; }
public Action<PublishContentContext, TPart> OnUnpublished { get; set; }
public Action<RemoveContentContext, TPart> OnRemoving { get; set; }
public Action<RemoveContentContext, TPart> OnRemoved { get; set; }
public Action<IndexContentContext, TPart> OnIndexing { get; set; }
public Action<IndexContentContext, TPart> OnIndexed { get; set; }
public Action<ImportContentContext, TPart> OnImporting { get; set; }
public Action<ImportContentContext, TPart> OnImported { get; set; }
public Action<ImportContentContext, TPart> OnImportCompleted { get; set; }
public Action<ExportContentContext, TPart> OnExporting { get; set; }
public Action<ExportContentContext, TPart> OnExported { get; set; }
public Action<RestoreContentContext, TPart> OnRestoring { get; set; }
public Action<RestoreContentContext, TPart> OnRestored { get; set; }
public Action<DestroyContentContext, TPart> OnDestroying { get; set; }
public Action<DestroyContentContext, TPart> OnDestroyed { get; set; }
protected override void Activated(ActivatedContentContext context, TPart instance) {
if (OnActivated != null) OnActivated(context, instance);
}
protected override void Initializing(InitializingContentContext context, TPart instance) {
if (OnInitializing != null) OnInitializing(context, instance);
}
protected override void Initialized(InitializingContentContext context, TPart instance) {
if (OnInitialized != null) OnInitialized(context, instance);
}
protected override void Creating(CreateContentContext context, TPart instance) {
if (OnCreating != null) OnCreating(context, instance);
}
protected override void Created(CreateContentContext context, TPart instance) {
if (OnCreated != null) OnCreated(context, instance);
}
protected override void Loading(LoadContentContext context, TPart instance) {
if (OnLoading != null) OnLoading(context, instance);
}
protected override void Loaded(LoadContentContext context, TPart instance) {
if (OnLoaded != null) OnLoaded(context, instance);
}
protected override void Updating(UpdateContentContext context, TPart instance) {
if (OnUpdating != null) OnUpdating(context, instance);
}
protected override void Updated(UpdateContentContext context, TPart instance) {
if (OnUpdated != null) OnUpdated(context, instance);
}
protected override void Versioning(VersionContentContext context, TPart existing, TPart building) {
if (OnVersioning != null) OnVersioning(context, existing, building);
}
protected override void Versioned(VersionContentContext context, TPart existing, TPart building) {
if (OnVersioned != null) OnVersioned(context, existing, building);
}
protected override void Publishing(PublishContentContext context, TPart instance) {
if (OnPublishing != null) OnPublishing(context, instance);
}
protected override void Published(PublishContentContext context, TPart instance) {
if (OnPublished != null) OnPublished(context, instance);
}
protected override void Unpublishing(PublishContentContext context, TPart instance) {
if (OnUnpublishing != null) OnUnpublishing(context, instance);
}
protected override void Unpublished(PublishContentContext context, TPart instance) {
if (OnUnpublished != null) OnUnpublished(context, instance);
}
protected override void Removing(RemoveContentContext context, TPart instance) {
if (OnRemoving != null) OnRemoving(context, instance);
}
protected override void Removed(RemoveContentContext context, TPart instance) {
if (OnRemoved != null) OnRemoved(context, instance);
}
protected override void Indexing(IndexContentContext context, TPart instance) {
if (OnIndexing != null)
OnIndexing(context, instance);
}
protected override void Indexed(IndexContentContext context, TPart instance) {
if (OnIndexed != null)
OnIndexed(context, instance);
}
protected override void Importing(ImportContentContext context, TPart instance) {
if (OnImporting != null)
OnImporting(context, instance);
}
protected override void Imported(ImportContentContext context, TPart instance) {
if (OnImported != null)
OnImported(context, instance);
}
protected override void ImportCompleted(ImportContentContext context, TPart instance) {
if (OnImportCompleted != null)
OnImportCompleted(context, instance);
}
protected override void Exporting(ExportContentContext context, TPart instance) {
if (OnExporting != null)
OnExporting(context, instance);
}
protected override void Exported(ExportContentContext context, TPart instance) {
if (OnExported != null)
OnExported(context, instance);
}
protected override void Restoring(RestoreContentContext context, TPart instance) {
if (OnRestoring != null)
OnRestoring(context, instance);
}
protected override void Restored(RestoreContentContext context, TPart instance) {
if (OnRestored != null)
OnRestored(context, instance);
}
protected override void Destroying(DestroyContentContext context, TPart instance) {
if (OnDestroying != null)
OnDestroying(context, instance);
}
protected override void Destroyed(DestroyContentContext context, TPart instance) {
if (OnDestroyed != null)
OnDestroyed(context, instance);
}
}
class InlineTemplateFilter<TPart> : TemplateFilterBase<TPart> where TPart : class, IContent {
public Action<GetContentItemMetadataContext, TPart> OnGetItemMetadata { get; set; }
public Action<BuildDisplayContext, TPart> OnGetDisplayShape { get; set; }
public Action<BuildEditorContext, TPart> OnGetEditorShape { get; set; }
public Action<UpdateEditorContext, TPart> OnUpdateEditorShape { get; set; }
protected override void GetContentItemMetadata(GetContentItemMetadataContext context, TPart instance) {
if (OnGetItemMetadata != null) OnGetItemMetadata(context, instance);
}
protected override void BuildDisplayShape(BuildDisplayContext context, TPart instance) {
if (OnGetDisplayShape != null) OnGetDisplayShape(context, instance);
}
protected override void BuildEditorShape(BuildEditorContext context, TPart instance) {
if (OnGetEditorShape != null) OnGetEditorShape(context, instance);
}
protected override void UpdateEditorShape(UpdateEditorContext context, TPart instance) {
if (OnUpdateEditorShape != null) OnUpdateEditorShape(context, instance);
}
}
void IContentHandler.Activating(ActivatingContentContext context) {
foreach (var filter in Filters.OfType<IContentActivatingFilter>())
filter.Activating(context);
Activating(context);
}
void IContentHandler.Activated(ActivatedContentContext context) {
foreach (var filter in Filters.OfType<IContentStorageFilter>())
filter.Activated(context);
Activated(context);
}
void IContentHandler.Initializing(InitializingContentContext context) {
foreach (var filter in Filters.OfType<IContentStorageFilter>())
filter.Initializing(context);
Initializing(context);
}
void IContentHandler.Initialized(InitializingContentContext context) {
foreach (var filter in Filters.OfType<IContentStorageFilter>())
filter.Initialized(context);
Initialized(context);
}
void IContentHandler.Creating(CreateContentContext context) {
foreach (var filter in Filters.OfType<IContentStorageFilter>())
filter.Creating(context);
Creating(context);
}
void IContentHandler.Created(CreateContentContext context) {
foreach (var filter in Filters.OfType<IContentStorageFilter>())
filter.Created(context);
Created(context);
}
void IContentHandler.Loading(LoadContentContext context) {
foreach (var filter in Filters.OfType<IContentStorageFilter>())
filter.Loading(context);
Loading(context);
}
void IContentHandler.Loaded(LoadContentContext context) {
foreach (var filter in Filters.OfType<IContentStorageFilter>())
filter.Loaded(context);
Loaded(context);
}
void IContentHandler.Updating(UpdateContentContext context) {
foreach (var filter in Filters.OfType<IContentStorageFilter>())
filter.Updating(context);
Updating(context);
}
void IContentHandler.Updated(UpdateContentContext context) {
foreach (var filter in Filters.OfType<IContentStorageFilter>())
filter.Updated(context);
Updated(context);
}
void IContentHandler.Versioning(VersionContentContext context) {
foreach (var filter in Filters.OfType<IContentStorageFilter>())
filter.Versioning(context);
Versioning(context);
}
void IContentHandler.Versioned(VersionContentContext context) {
foreach (var filter in Filters.OfType<IContentStorageFilter>())
filter.Versioned(context);
Versioned(context);
}
void IContentHandler.Publishing(PublishContentContext context) {
foreach (var filter in Filters.OfType<IContentStorageFilter>())
filter.Publishing(context);
Publishing(context);
}
void IContentHandler.Published(PublishContentContext context) {
foreach (var filter in Filters.OfType<IContentStorageFilter>())
filter.Published(context);
Published(context);
}
void IContentHandler.Unpublishing(PublishContentContext context) {
foreach (var filter in Filters.OfType<IContentStorageFilter>())
filter.Unpublishing(context);
Unpublishing(context);
}
void IContentHandler.Unpublished(PublishContentContext context) {
foreach (var filter in Filters.OfType<IContentStorageFilter>())
filter.Unpublished(context);
Unpublished(context);
}
void IContentHandler.Removing(RemoveContentContext context) {
foreach (var filter in Filters.OfType<IContentStorageFilter>())
filter.Removing(context);
Removing(context);
}
void IContentHandler.Removed(RemoveContentContext context) {
foreach (var filter in Filters.OfType<IContentStorageFilter>())
filter.Removed(context);
Removed(context);
}
void IContentHandler.Indexing(IndexContentContext context) {
foreach ( var filter in Filters.OfType<IContentStorageFilter>() )
filter.Indexing(context);
Indexing(context);
}
void IContentHandler.Indexed(IndexContentContext context) {
foreach ( var filter in Filters.OfType<IContentStorageFilter>() )
filter.Indexed(context);
Indexed(context);
}
void IContentHandler.Importing(ImportContentContext context) {
foreach (var filter in Filters.OfType<IContentStorageFilter>())
filter.Importing(context);
Importing(context);
}
void IContentHandler.Imported(ImportContentContext context) {
foreach (var filter in Filters.OfType<IContentStorageFilter>())
filter.Imported(context);
Imported(context);
}
void IContentHandler.ImportCompleted(ImportContentContext importContentContext) {
foreach (var filter in Filters.OfType<IContentStorageFilter>())
filter.ImportCompleted(importContentContext);
ImportCompleted(importContentContext);
}
void IContentHandler.Exporting(ExportContentContext context) {
foreach (var filter in Filters.OfType<IContentStorageFilter>())
filter.Exporting(context);
Exporting(context);
}
void IContentHandler.Exported(ExportContentContext context) {
foreach (var filter in Filters.OfType<IContentStorageFilter>())
filter.Exported(context);
Exported(context);
}
void IContentHandler.Restoring(RestoreContentContext context) {
foreach (var filter in Filters.OfType<IContentStorageFilter>())
filter.Restoring(context);
Restoring(context);
}
void IContentHandler.Restored(RestoreContentContext context) {
foreach (var filter in Filters.OfType<IContentStorageFilter>())
filter.Restored(context);
Restored(context);
}
void IContentHandler.Destroying(DestroyContentContext context) {
foreach (var filter in Filters.OfType<IContentStorageFilter>())
filter.Destroying(context);
Destroying(context);
}
void IContentHandler.Destroyed(DestroyContentContext context) {
foreach (var filter in Filters.OfType<IContentStorageFilter>())
filter.Destroyed(context);
Destroyed(context);
}
void IContentHandler.GetContentItemMetadata(GetContentItemMetadataContext context) {
foreach (var filter in Filters.OfType<IContentTemplateFilter>())
filter.GetContentItemMetadata(context);
GetItemMetadata(context);
}
void IContentHandler.BuildDisplay(BuildDisplayContext context) {
foreach (var filter in Filters.OfType<IContentTemplateFilter>())
filter.BuildDisplayShape(context);
BuildDisplayShape(context);
}
void IContentHandler.BuildEditor(BuildEditorContext context) {
foreach (var filter in Filters.OfType<IContentTemplateFilter>())
filter.BuildEditorShape(context);
BuildEditorShape(context);
}
void IContentHandler.UpdateEditor(UpdateEditorContext context) {
foreach (var filter in Filters.OfType<IContentTemplateFilter>())
filter.UpdateEditorShape(context);
UpdateEditorShape(context);
}
protected virtual void Activating(ActivatingContentContext context) { }
protected virtual void Activated(ActivatedContentContext context) { }
protected virtual void Initializing(InitializingContentContext context) { }
protected virtual void Initialized(InitializingContentContext context) { }
protected virtual void Creating(CreateContentContext context) { }
protected virtual void Created(CreateContentContext context) { }
protected virtual void Loading(LoadContentContext context) { }
protected virtual void Loaded(LoadContentContext context) { }
protected virtual void Updating(UpdateContentContext context) { }
protected virtual void Updated(UpdateContentContext context) { }
protected virtual void Versioning(VersionContentContext context) { }
protected virtual void Versioned(VersionContentContext context) { }
protected virtual void Publishing(PublishContentContext context) { }
protected virtual void Published(PublishContentContext context) { }
protected virtual void Unpublishing(PublishContentContext context) { }
protected virtual void Unpublished(PublishContentContext context) { }
protected virtual void Removing(RemoveContentContext context) { }
protected virtual void Removed(RemoveContentContext context) { }
protected virtual void Indexing(IndexContentContext context) { }
protected virtual void Indexed(IndexContentContext context) { }
protected virtual void Importing(ImportContentContext context) { }
protected virtual void Imported(ImportContentContext context) { }
protected virtual void ImportCompleted(ImportContentContext context) { }
protected virtual void Exporting(ExportContentContext context) { }
protected virtual void Exported(ExportContentContext context) { }
protected virtual void Restoring(RestoreContentContext context) { }
protected virtual void Restored(RestoreContentContext context) { }
protected virtual void Destroying(DestroyContentContext context) { }
protected virtual void Destroyed(DestroyContentContext context) { }
protected virtual void GetItemMetadata(GetContentItemMetadataContext context) { }
protected virtual void BuildDisplayShape(BuildDisplayContext context) { }
protected virtual void BuildEditorShape(BuildEditorContext context) { }
protected virtual void UpdateEditorShape(UpdateEditorContext context) { }
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
// <auto-generated />
namespace NorthwindAccess{
/// <summary>
/// Strongly-typed collection for the AlphabeticalListOfProduct class.
/// </summary>
[Serializable]
public partial class AlphabeticalListOfProductCollection : ReadOnlyList<AlphabeticalListOfProduct, AlphabeticalListOfProductCollection>
{
public AlphabeticalListOfProductCollection() {}
}
/// <summary>
/// This is Read-only wrapper class for the Alphabetical List of Products view.
/// </summary>
[Serializable]
public partial class AlphabeticalListOfProduct : ReadOnlyRecord<AlphabeticalListOfProduct>, IReadOnlyRecord
{
#region Default Settings
protected static void SetSQLProps()
{
GetTableSchema();
}
#endregion
#region Schema Accessor
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
{
SetSQLProps();
}
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("Alphabetical List of Products", TableType.View, DataService.GetInstance("NorthwindAccess"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"";
//columns
TableSchema.TableColumn colvarProductID = new TableSchema.TableColumn(schema);
colvarProductID.ColumnName = "ProductID";
colvarProductID.DataType = DbType.Int32;
colvarProductID.MaxLength = 0;
colvarProductID.AutoIncrement = false;
colvarProductID.IsNullable = false;
colvarProductID.IsPrimaryKey = false;
colvarProductID.IsForeignKey = false;
colvarProductID.IsReadOnly = false;
schema.Columns.Add(colvarProductID);
TableSchema.TableColumn colvarProductName = new TableSchema.TableColumn(schema);
colvarProductName.ColumnName = "ProductName";
colvarProductName.DataType = DbType.String;
colvarProductName.MaxLength = 40;
colvarProductName.AutoIncrement = false;
colvarProductName.IsNullable = true;
colvarProductName.IsPrimaryKey = false;
colvarProductName.IsForeignKey = false;
colvarProductName.IsReadOnly = false;
schema.Columns.Add(colvarProductName);
TableSchema.TableColumn colvarSupplierID = new TableSchema.TableColumn(schema);
colvarSupplierID.ColumnName = "SupplierID";
colvarSupplierID.DataType = DbType.Int32;
colvarSupplierID.MaxLength = 0;
colvarSupplierID.AutoIncrement = false;
colvarSupplierID.IsNullable = true;
colvarSupplierID.IsPrimaryKey = false;
colvarSupplierID.IsForeignKey = false;
colvarSupplierID.IsReadOnly = false;
schema.Columns.Add(colvarSupplierID);
TableSchema.TableColumn colvarCategoryID = new TableSchema.TableColumn(schema);
colvarCategoryID.ColumnName = "CategoryID";
colvarCategoryID.DataType = DbType.Int32;
colvarCategoryID.MaxLength = 0;
colvarCategoryID.AutoIncrement = false;
colvarCategoryID.IsNullable = true;
colvarCategoryID.IsPrimaryKey = false;
colvarCategoryID.IsForeignKey = false;
colvarCategoryID.IsReadOnly = false;
schema.Columns.Add(colvarCategoryID);
TableSchema.TableColumn colvarQuantityPerUnit = new TableSchema.TableColumn(schema);
colvarQuantityPerUnit.ColumnName = "QuantityPerUnit";
colvarQuantityPerUnit.DataType = DbType.String;
colvarQuantityPerUnit.MaxLength = 20;
colvarQuantityPerUnit.AutoIncrement = false;
colvarQuantityPerUnit.IsNullable = true;
colvarQuantityPerUnit.IsPrimaryKey = false;
colvarQuantityPerUnit.IsForeignKey = false;
colvarQuantityPerUnit.IsReadOnly = false;
schema.Columns.Add(colvarQuantityPerUnit);
TableSchema.TableColumn colvarUnitPrice = new TableSchema.TableColumn(schema);
colvarUnitPrice.ColumnName = "UnitPrice";
colvarUnitPrice.DataType = DbType.Currency;
colvarUnitPrice.MaxLength = 0;
colvarUnitPrice.AutoIncrement = false;
colvarUnitPrice.IsNullable = true;
colvarUnitPrice.IsPrimaryKey = false;
colvarUnitPrice.IsForeignKey = false;
colvarUnitPrice.IsReadOnly = false;
schema.Columns.Add(colvarUnitPrice);
TableSchema.TableColumn colvarUnitsInStock = new TableSchema.TableColumn(schema);
colvarUnitsInStock.ColumnName = "UnitsInStock";
colvarUnitsInStock.DataType = DbType.Int16;
colvarUnitsInStock.MaxLength = 0;
colvarUnitsInStock.AutoIncrement = false;
colvarUnitsInStock.IsNullable = true;
colvarUnitsInStock.IsPrimaryKey = false;
colvarUnitsInStock.IsForeignKey = false;
colvarUnitsInStock.IsReadOnly = false;
schema.Columns.Add(colvarUnitsInStock);
TableSchema.TableColumn colvarUnitsOnOrder = new TableSchema.TableColumn(schema);
colvarUnitsOnOrder.ColumnName = "UnitsOnOrder";
colvarUnitsOnOrder.DataType = DbType.Int16;
colvarUnitsOnOrder.MaxLength = 0;
colvarUnitsOnOrder.AutoIncrement = false;
colvarUnitsOnOrder.IsNullable = true;
colvarUnitsOnOrder.IsPrimaryKey = false;
colvarUnitsOnOrder.IsForeignKey = false;
colvarUnitsOnOrder.IsReadOnly = false;
schema.Columns.Add(colvarUnitsOnOrder);
TableSchema.TableColumn colvarReorderLevel = new TableSchema.TableColumn(schema);
colvarReorderLevel.ColumnName = "ReorderLevel";
colvarReorderLevel.DataType = DbType.Int16;
colvarReorderLevel.MaxLength = 0;
colvarReorderLevel.AutoIncrement = false;
colvarReorderLevel.IsNullable = true;
colvarReorderLevel.IsPrimaryKey = false;
colvarReorderLevel.IsForeignKey = false;
colvarReorderLevel.IsReadOnly = false;
schema.Columns.Add(colvarReorderLevel);
TableSchema.TableColumn colvarDiscontinued = new TableSchema.TableColumn(schema);
colvarDiscontinued.ColumnName = "Discontinued";
colvarDiscontinued.DataType = DbType.Boolean;
colvarDiscontinued.MaxLength = 2;
colvarDiscontinued.AutoIncrement = false;
colvarDiscontinued.IsNullable = false;
colvarDiscontinued.IsPrimaryKey = false;
colvarDiscontinued.IsForeignKey = false;
colvarDiscontinued.IsReadOnly = false;
schema.Columns.Add(colvarDiscontinued);
TableSchema.TableColumn colvarAttributeXML = new TableSchema.TableColumn(schema);
colvarAttributeXML.ColumnName = "AttributeXML";
colvarAttributeXML.DataType = DbType.String;
colvarAttributeXML.MaxLength = 0;
colvarAttributeXML.AutoIncrement = false;
colvarAttributeXML.IsNullable = true;
colvarAttributeXML.IsPrimaryKey = false;
colvarAttributeXML.IsForeignKey = false;
colvarAttributeXML.IsReadOnly = false;
schema.Columns.Add(colvarAttributeXML);
TableSchema.TableColumn colvarDateCreated = new TableSchema.TableColumn(schema);
colvarDateCreated.ColumnName = "DateCreated";
colvarDateCreated.DataType = DbType.DateTime;
colvarDateCreated.MaxLength = 0;
colvarDateCreated.AutoIncrement = false;
colvarDateCreated.IsNullable = true;
colvarDateCreated.IsPrimaryKey = false;
colvarDateCreated.IsForeignKey = false;
colvarDateCreated.IsReadOnly = false;
schema.Columns.Add(colvarDateCreated);
TableSchema.TableColumn colvarProductGUID = new TableSchema.TableColumn(schema);
colvarProductGUID.ColumnName = "ProductGUID";
colvarProductGUID.DataType = DbType.Guid;
colvarProductGUID.MaxLength = 0;
colvarProductGUID.AutoIncrement = false;
colvarProductGUID.IsNullable = true;
colvarProductGUID.IsPrimaryKey = false;
colvarProductGUID.IsForeignKey = false;
colvarProductGUID.IsReadOnly = false;
schema.Columns.Add(colvarProductGUID);
TableSchema.TableColumn colvarCreatedOn = new TableSchema.TableColumn(schema);
colvarCreatedOn.ColumnName = "CreatedOn";
colvarCreatedOn.DataType = DbType.DateTime;
colvarCreatedOn.MaxLength = 0;
colvarCreatedOn.AutoIncrement = false;
colvarCreatedOn.IsNullable = true;
colvarCreatedOn.IsPrimaryKey = false;
colvarCreatedOn.IsForeignKey = false;
colvarCreatedOn.IsReadOnly = false;
schema.Columns.Add(colvarCreatedOn);
TableSchema.TableColumn colvarCreatedBy = new TableSchema.TableColumn(schema);
colvarCreatedBy.ColumnName = "CreatedBy";
colvarCreatedBy.DataType = DbType.String;
colvarCreatedBy.MaxLength = 50;
colvarCreatedBy.AutoIncrement = false;
colvarCreatedBy.IsNullable = true;
colvarCreatedBy.IsPrimaryKey = false;
colvarCreatedBy.IsForeignKey = false;
colvarCreatedBy.IsReadOnly = false;
schema.Columns.Add(colvarCreatedBy);
TableSchema.TableColumn colvarModifiedOn = new TableSchema.TableColumn(schema);
colvarModifiedOn.ColumnName = "ModifiedOn";
colvarModifiedOn.DataType = DbType.DateTime;
colvarModifiedOn.MaxLength = 0;
colvarModifiedOn.AutoIncrement = false;
colvarModifiedOn.IsNullable = true;
colvarModifiedOn.IsPrimaryKey = false;
colvarModifiedOn.IsForeignKey = false;
colvarModifiedOn.IsReadOnly = false;
schema.Columns.Add(colvarModifiedOn);
TableSchema.TableColumn colvarModifiedBy = new TableSchema.TableColumn(schema);
colvarModifiedBy.ColumnName = "ModifiedBy";
colvarModifiedBy.DataType = DbType.String;
colvarModifiedBy.MaxLength = 50;
colvarModifiedBy.AutoIncrement = false;
colvarModifiedBy.IsNullable = true;
colvarModifiedBy.IsPrimaryKey = false;
colvarModifiedBy.IsForeignKey = false;
colvarModifiedBy.IsReadOnly = false;
schema.Columns.Add(colvarModifiedBy);
TableSchema.TableColumn colvarDeleted = new TableSchema.TableColumn(schema);
colvarDeleted.ColumnName = "Deleted";
colvarDeleted.DataType = DbType.Boolean;
colvarDeleted.MaxLength = 2;
colvarDeleted.AutoIncrement = false;
colvarDeleted.IsNullable = false;
colvarDeleted.IsPrimaryKey = false;
colvarDeleted.IsForeignKey = false;
colvarDeleted.IsReadOnly = false;
schema.Columns.Add(colvarDeleted);
TableSchema.TableColumn colvarCategoryName = new TableSchema.TableColumn(schema);
colvarCategoryName.ColumnName = "CategoryName";
colvarCategoryName.DataType = DbType.String;
colvarCategoryName.MaxLength = 15;
colvarCategoryName.AutoIncrement = false;
colvarCategoryName.IsNullable = true;
colvarCategoryName.IsPrimaryKey = false;
colvarCategoryName.IsForeignKey = false;
colvarCategoryName.IsReadOnly = false;
schema.Columns.Add(colvarCategoryName);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["NorthwindAccess"].AddSchema("Alphabetical List of Products",schema);
}
}
#endregion
#region Query Accessor
public static Query CreateQuery()
{
return new Query(Schema);
}
#endregion
#region .ctors
public AlphabeticalListOfProduct()
{
SetSQLProps();
SetDefaults();
MarkNew();
}
public AlphabeticalListOfProduct(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
{
ForceDefaults();
}
MarkNew();
}
public AlphabeticalListOfProduct(object keyID)
{
SetSQLProps();
LoadByKey(keyID);
}
public AlphabeticalListOfProduct(string columnName, object columnValue)
{
SetSQLProps();
LoadByParam(columnName,columnValue);
}
#endregion
#region Props
[XmlAttribute("ProductID")]
[Bindable(true)]
public int ProductID
{
get
{
return GetColumnValue<int>("ProductID");
}
set
{
SetColumnValue("ProductID", value);
}
}
[XmlAttribute("ProductName")]
[Bindable(true)]
public string ProductName
{
get
{
return GetColumnValue<string>("ProductName");
}
set
{
SetColumnValue("ProductName", value);
}
}
[XmlAttribute("SupplierID")]
[Bindable(true)]
public int? SupplierID
{
get
{
return GetColumnValue<int?>("SupplierID");
}
set
{
SetColumnValue("SupplierID", value);
}
}
[XmlAttribute("CategoryID")]
[Bindable(true)]
public int? CategoryID
{
get
{
return GetColumnValue<int?>("CategoryID");
}
set
{
SetColumnValue("CategoryID", value);
}
}
[XmlAttribute("QuantityPerUnit")]
[Bindable(true)]
public string QuantityPerUnit
{
get
{
return GetColumnValue<string>("QuantityPerUnit");
}
set
{
SetColumnValue("QuantityPerUnit", value);
}
}
[XmlAttribute("UnitPrice")]
[Bindable(true)]
public decimal? UnitPrice
{
get
{
return GetColumnValue<decimal?>("UnitPrice");
}
set
{
SetColumnValue("UnitPrice", value);
}
}
[XmlAttribute("UnitsInStock")]
[Bindable(true)]
public short? UnitsInStock
{
get
{
return GetColumnValue<short?>("UnitsInStock");
}
set
{
SetColumnValue("UnitsInStock", value);
}
}
[XmlAttribute("UnitsOnOrder")]
[Bindable(true)]
public short? UnitsOnOrder
{
get
{
return GetColumnValue<short?>("UnitsOnOrder");
}
set
{
SetColumnValue("UnitsOnOrder", value);
}
}
[XmlAttribute("ReorderLevel")]
[Bindable(true)]
public short? ReorderLevel
{
get
{
return GetColumnValue<short?>("ReorderLevel");
}
set
{
SetColumnValue("ReorderLevel", value);
}
}
[XmlAttribute("Discontinued")]
[Bindable(true)]
public bool Discontinued
{
get
{
return GetColumnValue<bool>("Discontinued");
}
set
{
SetColumnValue("Discontinued", value);
}
}
[XmlAttribute("AttributeXML")]
[Bindable(true)]
public string AttributeXML
{
get
{
return GetColumnValue<string>("AttributeXML");
}
set
{
SetColumnValue("AttributeXML", value);
}
}
[XmlAttribute("DateCreated")]
[Bindable(true)]
public DateTime? DateCreated
{
get
{
return GetColumnValue<DateTime?>("DateCreated");
}
set
{
SetColumnValue("DateCreated", value);
}
}
[XmlAttribute("ProductGUID")]
[Bindable(true)]
public Guid? ProductGUID
{
get
{
return GetColumnValue<Guid?>("ProductGUID");
}
set
{
SetColumnValue("ProductGUID", value);
}
}
[XmlAttribute("CreatedOn")]
[Bindable(true)]
public DateTime? CreatedOn
{
get
{
return GetColumnValue<DateTime?>("CreatedOn");
}
set
{
SetColumnValue("CreatedOn", value);
}
}
[XmlAttribute("CreatedBy")]
[Bindable(true)]
public string CreatedBy
{
get
{
return GetColumnValue<string>("CreatedBy");
}
set
{
SetColumnValue("CreatedBy", value);
}
}
[XmlAttribute("ModifiedOn")]
[Bindable(true)]
public DateTime? ModifiedOn
{
get
{
return GetColumnValue<DateTime?>("ModifiedOn");
}
set
{
SetColumnValue("ModifiedOn", value);
}
}
[XmlAttribute("ModifiedBy")]
[Bindable(true)]
public string ModifiedBy
{
get
{
return GetColumnValue<string>("ModifiedBy");
}
set
{
SetColumnValue("ModifiedBy", value);
}
}
[XmlAttribute("Deleted")]
[Bindable(true)]
public bool Deleted
{
get
{
return GetColumnValue<bool>("Deleted");
}
set
{
SetColumnValue("Deleted", value);
}
}
[XmlAttribute("CategoryName")]
[Bindable(true)]
public string CategoryName
{
get
{
return GetColumnValue<string>("CategoryName");
}
set
{
SetColumnValue("CategoryName", value);
}
}
#endregion
#region Columns Struct
public struct Columns
{
public static string ProductID = @"ProductID";
public static string ProductName = @"ProductName";
public static string SupplierID = @"SupplierID";
public static string CategoryID = @"CategoryID";
public static string QuantityPerUnit = @"QuantityPerUnit";
public static string UnitPrice = @"UnitPrice";
public static string UnitsInStock = @"UnitsInStock";
public static string UnitsOnOrder = @"UnitsOnOrder";
public static string ReorderLevel = @"ReorderLevel";
public static string Discontinued = @"Discontinued";
public static string AttributeXML = @"AttributeXML";
public static string DateCreated = @"DateCreated";
public static string ProductGUID = @"ProductGUID";
public static string CreatedOn = @"CreatedOn";
public static string CreatedBy = @"CreatedBy";
public static string ModifiedOn = @"ModifiedOn";
public static string ModifiedBy = @"ModifiedBy";
public static string Deleted = @"Deleted";
public static string CategoryName = @"CategoryName";
}
#endregion
#region IAbstractRecord Members
public new CT GetColumnValue<CT>(string columnName) {
return base.GetColumnValue<CT>(columnName);
}
public object GetColumnValue(string columnName) {
return base.GetColumnValue<object>(columnName);
}
#endregion
}
}
| |
namespace LoreSoft.Calculator
{
partial class CalculatorForm
{
/// <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.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(CalculatorForm));
this.mainMenuStrip = new System.Windows.Forms.MenuStrip();
this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.saveToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.editToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.undoToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator3 = new System.Windows.Forms.ToolStripSeparator();
this.cutToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.copyToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.pasteToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator4 = new System.Windows.Forms.ToolStripSeparator();
this.selectAllToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.optionsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.clearHistoryToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator6 = new System.Windows.Forms.ToolStripSeparator();
this.historyFontToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.inputFontToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator10 = new System.Windows.Forms.ToolStripSeparator();
this.replaceCalculatorToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.functionsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.basicOperationsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.addToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.subtractToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.multiplyToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.divideToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.modulusToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.powerToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator11 = new System.Windows.Forms.ToolStripSeparator();
this.sqrtToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.absToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.trigFunctionsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.cosToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.coshToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.acosToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.sinToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.sinhToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.asinToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.tanToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.tanhToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.atanToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.logFunctionsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.expToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.logToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.log10ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.conversionsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.lengthToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.lengthDummyToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.massToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.massDummyToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.speedToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.speedDummyToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.temperatureToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.temperatureDummyToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.timeToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.timeDummyToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.volumeToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.volumeDummyToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.helpToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.aboutToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.mainToolStrip = new System.Windows.Forms.ToolStrip();
this.saveToolStripButton = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator = new System.Windows.Forms.ToolStripSeparator();
this.cutToolStripButton = new System.Windows.Forms.ToolStripButton();
this.copyToolStripButton = new System.Windows.Forms.ToolStripButton();
this.pasteToolStripButton = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator5 = new System.Windows.Forms.ToolStripSeparator();
this.undoToolStripButton = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator7 = new System.Windows.Forms.ToolStripSeparator();
this.clearHistoryToolStripButton = new System.Windows.Forms.ToolStripButton();
this.historyPanel = new System.Windows.Forms.Panel();
this.historyRichTextBox = new System.Windows.Forms.RichTextBox();
this.historyContextMenuStrip = new System.Windows.Forms.ContextMenuStrip(this.components);
this.clearHistoryContextStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator9 = new System.Windows.Forms.ToolStripSeparator();
this.copyHistoryContextStripMenuItem2 = new System.Windows.Forms.ToolStripMenuItem();
this.historyLabel = new System.Windows.Forms.Label();
this.inputLabel = new System.Windows.Forms.Label();
this.inputTextBox = new System.Windows.Forms.TextBox();
this.inputContextMenuStrip = new System.Windows.Forms.ContextMenuStrip(this.components);
this.undoContextStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator();
this.cutContextStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.copyContextStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.pasteContextStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator8 = new System.Windows.Forms.ToolStripSeparator();
this.selectAllContextStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.statusStrip = new System.Windows.Forms.StatusStrip();
this.answerToolStripStatusLabel = new System.Windows.Forms.ToolStripStatusLabel();
this.timerToolStripStatusLabel = new System.Windows.Forms.ToolStripStatusLabel();
this.numLockToolStripStatusLabel = new System.Windows.Forms.ToolStripStatusLabel();
this.fontDialog = new System.Windows.Forms.FontDialog();
this.saveFileDialog = new System.Windows.Forms.SaveFileDialog();
this.allowOnlyOneInstanceToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.mainMenuStrip.SuspendLayout();
this.mainToolStrip.SuspendLayout();
this.historyPanel.SuspendLayout();
this.historyContextMenuStrip.SuspendLayout();
this.inputContextMenuStrip.SuspendLayout();
this.statusStrip.SuspendLayout();
this.SuspendLayout();
//
// mainMenuStrip
//
this.mainMenuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.fileToolStripMenuItem,
this.editToolStripMenuItem,
this.optionsToolStripMenuItem,
this.functionsToolStripMenuItem,
this.conversionsToolStripMenuItem,
this.helpToolStripMenuItem});
this.mainMenuStrip.Location = new System.Drawing.Point(0, 0);
this.mainMenuStrip.Name = "mainMenuStrip";
this.mainMenuStrip.Size = new System.Drawing.Size(384, 24);
this.mainMenuStrip.TabIndex = 0;
this.mainMenuStrip.Text = "menuStrip1";
//
// fileToolStripMenuItem
//
this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.saveToolStripMenuItem,
this.toolStripSeparator1,
this.exitToolStripMenuItem});
this.fileToolStripMenuItem.Name = "fileToolStripMenuItem";
this.fileToolStripMenuItem.Size = new System.Drawing.Size(37, 20);
this.fileToolStripMenuItem.Text = "&File";
//
// saveToolStripMenuItem
//
this.saveToolStripMenuItem.Image = global::LoreSoft.Calculator.Properties.Resources.Save;
this.saveToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta;
this.saveToolStripMenuItem.Name = "saveToolStripMenuItem";
this.saveToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.S)));
this.saveToolStripMenuItem.Size = new System.Drawing.Size(179, 22);
this.saveToolStripMenuItem.Text = "&Save History";
this.saveToolStripMenuItem.Click += new System.EventHandler(this.saveToolStripMenuItem_Click);
//
// toolStripSeparator1
//
this.toolStripSeparator1.Name = "toolStripSeparator1";
this.toolStripSeparator1.Size = new System.Drawing.Size(176, 6);
//
// exitToolStripMenuItem
//
this.exitToolStripMenuItem.Name = "exitToolStripMenuItem";
this.exitToolStripMenuItem.Size = new System.Drawing.Size(179, 22);
this.exitToolStripMenuItem.Text = "E&xit";
this.exitToolStripMenuItem.Click += new System.EventHandler(this.exitToolStripMenuItem_Click);
//
// editToolStripMenuItem
//
this.editToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.undoToolStripMenuItem,
this.toolStripSeparator3,
this.cutToolStripMenuItem,
this.copyToolStripMenuItem,
this.pasteToolStripMenuItem,
this.toolStripSeparator4,
this.selectAllToolStripMenuItem});
this.editToolStripMenuItem.Name = "editToolStripMenuItem";
this.editToolStripMenuItem.Size = new System.Drawing.Size(39, 20);
this.editToolStripMenuItem.Text = "&Edit";
//
// undoToolStripMenuItem
//
this.undoToolStripMenuItem.Image = global::LoreSoft.Calculator.Properties.Resources.Undo;
this.undoToolStripMenuItem.Name = "undoToolStripMenuItem";
this.undoToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Z)));
this.undoToolStripMenuItem.Size = new System.Drawing.Size(164, 22);
this.undoToolStripMenuItem.Text = "&Undo";
this.undoToolStripMenuItem.Click += new System.EventHandler(this.undoToolStripMenuItem_Click);
//
// toolStripSeparator3
//
this.toolStripSeparator3.Name = "toolStripSeparator3";
this.toolStripSeparator3.Size = new System.Drawing.Size(161, 6);
//
// cutToolStripMenuItem
//
this.cutToolStripMenuItem.Image = global::LoreSoft.Calculator.Properties.Resources.Cut;
this.cutToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta;
this.cutToolStripMenuItem.Name = "cutToolStripMenuItem";
this.cutToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.X)));
this.cutToolStripMenuItem.Size = new System.Drawing.Size(164, 22);
this.cutToolStripMenuItem.Text = "Cu&t";
this.cutToolStripMenuItem.Click += new System.EventHandler(this.cutToolStripMenuItem_Click);
//
// copyToolStripMenuItem
//
this.copyToolStripMenuItem.Image = global::LoreSoft.Calculator.Properties.Resources.Copy;
this.copyToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta;
this.copyToolStripMenuItem.Name = "copyToolStripMenuItem";
this.copyToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.C)));
this.copyToolStripMenuItem.Size = new System.Drawing.Size(164, 22);
this.copyToolStripMenuItem.Text = "&Copy";
this.copyToolStripMenuItem.Click += new System.EventHandler(this.copyToolStripMenuItem_Click);
//
// pasteToolStripMenuItem
//
this.pasteToolStripMenuItem.Image = global::LoreSoft.Calculator.Properties.Resources.Paste;
this.pasteToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta;
this.pasteToolStripMenuItem.Name = "pasteToolStripMenuItem";
this.pasteToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.V)));
this.pasteToolStripMenuItem.Size = new System.Drawing.Size(164, 22);
this.pasteToolStripMenuItem.Text = "&Paste";
this.pasteToolStripMenuItem.Click += new System.EventHandler(this.pasteToolStripMenuItem_Click);
//
// toolStripSeparator4
//
this.toolStripSeparator4.Name = "toolStripSeparator4";
this.toolStripSeparator4.Size = new System.Drawing.Size(161, 6);
//
// selectAllToolStripMenuItem
//
this.selectAllToolStripMenuItem.Name = "selectAllToolStripMenuItem";
this.selectAllToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.A)));
this.selectAllToolStripMenuItem.Size = new System.Drawing.Size(164, 22);
this.selectAllToolStripMenuItem.Text = "Select &All";
this.selectAllToolStripMenuItem.Click += new System.EventHandler(this.selectAllToolStripMenuItem_Click);
//
// optionsToolStripMenuItem
//
this.optionsToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.clearHistoryToolStripMenuItem,
this.toolStripSeparator6,
this.historyFontToolStripMenuItem,
this.inputFontToolStripMenuItem,
this.toolStripSeparator10,
this.replaceCalculatorToolStripMenuItem,
this.allowOnlyOneInstanceToolStripMenuItem});
this.optionsToolStripMenuItem.Name = "optionsToolStripMenuItem";
this.optionsToolStripMenuItem.Size = new System.Drawing.Size(61, 20);
this.optionsToolStripMenuItem.Text = "&Options";
//
// clearHistoryToolStripMenuItem
//
this.clearHistoryToolStripMenuItem.Image = global::LoreSoft.Calculator.Properties.Resources.Delete;
this.clearHistoryToolStripMenuItem.Name = "clearHistoryToolStripMenuItem";
this.clearHistoryToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.D)));
this.clearHistoryToolStripMenuItem.Size = new System.Drawing.Size(204, 22);
this.clearHistoryToolStripMenuItem.Text = "&Clear History";
this.clearHistoryToolStripMenuItem.Click += new System.EventHandler(this.clearHistoryToolStripMenuItem_Click);
//
// toolStripSeparator6
//
this.toolStripSeparator6.Name = "toolStripSeparator6";
this.toolStripSeparator6.Size = new System.Drawing.Size(201, 6);
//
// historyFontToolStripMenuItem
//
this.historyFontToolStripMenuItem.Image = global::LoreSoft.Calculator.Properties.Resources.Font;
this.historyFontToolStripMenuItem.Name = "historyFontToolStripMenuItem";
this.historyFontToolStripMenuItem.Size = new System.Drawing.Size(204, 22);
this.historyFontToolStripMenuItem.Text = "&History Font...";
this.historyFontToolStripMenuItem.Click += new System.EventHandler(this.historyFontToolStripMenuItem_Click);
//
// inputFontToolStripMenuItem
//
this.inputFontToolStripMenuItem.Image = global::LoreSoft.Calculator.Properties.Resources.Font;
this.inputFontToolStripMenuItem.Name = "inputFontToolStripMenuItem";
this.inputFontToolStripMenuItem.Size = new System.Drawing.Size(204, 22);
this.inputFontToolStripMenuItem.Text = "&Input Font...";
this.inputFontToolStripMenuItem.Click += new System.EventHandler(this.inputFontToolStripMenuItem_Click);
//
// toolStripSeparator10
//
this.toolStripSeparator10.Name = "toolStripSeparator10";
this.toolStripSeparator10.Size = new System.Drawing.Size(201, 6);
//
// replaceCalculatorToolStripMenuItem
//
this.replaceCalculatorToolStripMenuItem.CheckOnClick = true;
this.replaceCalculatorToolStripMenuItem.Name = "replaceCalculatorToolStripMenuItem";
this.replaceCalculatorToolStripMenuItem.Size = new System.Drawing.Size(204, 22);
this.replaceCalculatorToolStripMenuItem.Text = "&Replace Calculator";
this.replaceCalculatorToolStripMenuItem.Click += new System.EventHandler(this.replaceCalculatorToolStripMenuItem_Click);
//
// functionsToolStripMenuItem
//
this.functionsToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.basicOperationsToolStripMenuItem,
this.trigFunctionsToolStripMenuItem,
this.logFunctionsToolStripMenuItem});
this.functionsToolStripMenuItem.Name = "functionsToolStripMenuItem";
this.functionsToolStripMenuItem.Size = new System.Drawing.Size(71, 20);
this.functionsToolStripMenuItem.Text = "F&unctions";
//
// basicOperationsToolStripMenuItem
//
this.basicOperationsToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.addToolStripMenuItem,
this.subtractToolStripMenuItem,
this.multiplyToolStripMenuItem,
this.divideToolStripMenuItem,
this.modulusToolStripMenuItem,
this.powerToolStripMenuItem,
this.toolStripSeparator11,
this.sqrtToolStripMenuItem,
this.absToolStripMenuItem});
this.basicOperationsToolStripMenuItem.Name = "basicOperationsToolStripMenuItem";
this.basicOperationsToolStripMenuItem.Size = new System.Drawing.Size(162, 22);
this.basicOperationsToolStripMenuItem.Text = "Basic Operations";
//
// addToolStripMenuItem
//
this.addToolStripMenuItem.Name = "addToolStripMenuItem";
this.addToolStripMenuItem.Size = new System.Drawing.Size(121, 22);
this.addToolStripMenuItem.Tag = "+";
this.addToolStripMenuItem.Text = "add";
this.addToolStripMenuItem.ToolTipText = "Adds two numbers.";
this.addToolStripMenuItem.Click += new System.EventHandler(this.function_Click);
//
// subtractToolStripMenuItem
//
this.subtractToolStripMenuItem.Name = "subtractToolStripMenuItem";
this.subtractToolStripMenuItem.Size = new System.Drawing.Size(121, 22);
this.subtractToolStripMenuItem.Tag = "-";
this.subtractToolStripMenuItem.Text = "subtract";
this.subtractToolStripMenuItem.ToolTipText = "Subtracts two numbers ";
this.subtractToolStripMenuItem.Click += new System.EventHandler(this.function_Click);
//
// multiplyToolStripMenuItem
//
this.multiplyToolStripMenuItem.Name = "multiplyToolStripMenuItem";
this.multiplyToolStripMenuItem.Size = new System.Drawing.Size(121, 22);
this.multiplyToolStripMenuItem.Tag = "*";
this.multiplyToolStripMenuItem.Text = "multiply";
this.multiplyToolStripMenuItem.ToolTipText = "Multiplies two numbers.";
this.multiplyToolStripMenuItem.Click += new System.EventHandler(this.function_Click);
//
// divideToolStripMenuItem
//
this.divideToolStripMenuItem.Name = "divideToolStripMenuItem";
this.divideToolStripMenuItem.Size = new System.Drawing.Size(121, 22);
this.divideToolStripMenuItem.Tag = "/";
this.divideToolStripMenuItem.Text = "divide";
this.divideToolStripMenuItem.ToolTipText = "Divides two numbers.";
this.divideToolStripMenuItem.Click += new System.EventHandler(this.function_Click);
//
// modulusToolStripMenuItem
//
this.modulusToolStripMenuItem.Name = "modulusToolStripMenuItem";
this.modulusToolStripMenuItem.Size = new System.Drawing.Size(121, 22);
this.modulusToolStripMenuItem.Tag = "%";
this.modulusToolStripMenuItem.Text = "modulus";
this.modulusToolStripMenuItem.ToolTipText = "Divides two numbers and returns only the remainder.";
this.modulusToolStripMenuItem.Click += new System.EventHandler(this.function_Click);
//
// powerToolStripMenuItem
//
this.powerToolStripMenuItem.Name = "powerToolStripMenuItem";
this.powerToolStripMenuItem.Size = new System.Drawing.Size(121, 22);
this.powerToolStripMenuItem.Tag = "^";
this.powerToolStripMenuItem.Text = "power";
this.powerToolStripMenuItem.ToolTipText = "Raises a number to the power of another number.";
this.powerToolStripMenuItem.Click += new System.EventHandler(this.function_Click);
//
// toolStripSeparator11
//
this.toolStripSeparator11.Name = "toolStripSeparator11";
this.toolStripSeparator11.Size = new System.Drawing.Size(118, 6);
//
// sqrtToolStripMenuItem
//
this.sqrtToolStripMenuItem.Name = "sqrtToolStripMenuItem";
this.sqrtToolStripMenuItem.Size = new System.Drawing.Size(121, 22);
this.sqrtToolStripMenuItem.Tag = "sqrt(|)";
this.sqrtToolStripMenuItem.Text = "sqrt";
this.sqrtToolStripMenuItem.ToolTipText = "Returns the square root of a specified number.";
this.sqrtToolStripMenuItem.Click += new System.EventHandler(this.function_Click);
//
// absToolStripMenuItem
//
this.absToolStripMenuItem.Name = "absToolStripMenuItem";
this.absToolStripMenuItem.Size = new System.Drawing.Size(121, 22);
this.absToolStripMenuItem.Tag = "abs(|)";
this.absToolStripMenuItem.Text = "abs";
this.absToolStripMenuItem.ToolTipText = "Returns the absolute value of a specified number. ";
this.absToolStripMenuItem.Click += new System.EventHandler(this.function_Click);
//
// trigFunctionsToolStripMenuItem
//
this.trigFunctionsToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.cosToolStripMenuItem,
this.coshToolStripMenuItem,
this.acosToolStripMenuItem,
this.sinToolStripMenuItem,
this.sinhToolStripMenuItem,
this.asinToolStripMenuItem,
this.tanToolStripMenuItem,
this.tanhToolStripMenuItem,
this.atanToolStripMenuItem});
this.trigFunctionsToolStripMenuItem.Name = "trigFunctionsToolStripMenuItem";
this.trigFunctionsToolStripMenuItem.Size = new System.Drawing.Size(162, 22);
this.trigFunctionsToolStripMenuItem.Text = "Trig Functions";
//
// cosToolStripMenuItem
//
this.cosToolStripMenuItem.Name = "cosToolStripMenuItem";
this.cosToolStripMenuItem.Size = new System.Drawing.Size(99, 22);
this.cosToolStripMenuItem.Tag = "cos(|)";
this.cosToolStripMenuItem.Text = "cos";
this.cosToolStripMenuItem.ToolTipText = "Returns the cosine of the specified angle.";
this.cosToolStripMenuItem.Click += new System.EventHandler(this.function_Click);
//
// coshToolStripMenuItem
//
this.coshToolStripMenuItem.Name = "coshToolStripMenuItem";
this.coshToolStripMenuItem.Size = new System.Drawing.Size(99, 22);
this.coshToolStripMenuItem.Tag = "cosh(|)";
this.coshToolStripMenuItem.Text = "cosh";
this.coshToolStripMenuItem.ToolTipText = "Returns the hyperbolic cosine of the specified angle. ";
this.coshToolStripMenuItem.Click += new System.EventHandler(this.function_Click);
//
// acosToolStripMenuItem
//
this.acosToolStripMenuItem.Name = "acosToolStripMenuItem";
this.acosToolStripMenuItem.Size = new System.Drawing.Size(99, 22);
this.acosToolStripMenuItem.Tag = "acos(|)";
this.acosToolStripMenuItem.Text = "acos";
this.acosToolStripMenuItem.ToolTipText = "Returns the angle whose cosine is the specified number.";
this.acosToolStripMenuItem.Click += new System.EventHandler(this.function_Click);
//
// sinToolStripMenuItem
//
this.sinToolStripMenuItem.Name = "sinToolStripMenuItem";
this.sinToolStripMenuItem.Size = new System.Drawing.Size(99, 22);
this.sinToolStripMenuItem.Tag = "sin(|)";
this.sinToolStripMenuItem.Text = "sin";
this.sinToolStripMenuItem.ToolTipText = "Returns the sine of the specified angle. ";
this.sinToolStripMenuItem.Click += new System.EventHandler(this.function_Click);
//
// sinhToolStripMenuItem
//
this.sinhToolStripMenuItem.Name = "sinhToolStripMenuItem";
this.sinhToolStripMenuItem.Size = new System.Drawing.Size(99, 22);
this.sinhToolStripMenuItem.Tag = "sinh(|)";
this.sinhToolStripMenuItem.Text = "sinh";
this.sinhToolStripMenuItem.ToolTipText = "Returns the hyperbolic sine of the specified angle.";
this.sinhToolStripMenuItem.Click += new System.EventHandler(this.function_Click);
//
// asinToolStripMenuItem
//
this.asinToolStripMenuItem.Name = "asinToolStripMenuItem";
this.asinToolStripMenuItem.Size = new System.Drawing.Size(99, 22);
this.asinToolStripMenuItem.Tag = "asin(|)";
this.asinToolStripMenuItem.Text = "asin";
this.asinToolStripMenuItem.ToolTipText = "Returns the angle whose sine is the specified number.";
this.asinToolStripMenuItem.Click += new System.EventHandler(this.function_Click);
//
// tanToolStripMenuItem
//
this.tanToolStripMenuItem.Name = "tanToolStripMenuItem";
this.tanToolStripMenuItem.Size = new System.Drawing.Size(99, 22);
this.tanToolStripMenuItem.Tag = "tan(|)";
this.tanToolStripMenuItem.Text = "tan";
this.tanToolStripMenuItem.ToolTipText = "Returns the tangent of the specified angle.";
this.tanToolStripMenuItem.Click += new System.EventHandler(this.function_Click);
//
// tanhToolStripMenuItem
//
this.tanhToolStripMenuItem.Name = "tanhToolStripMenuItem";
this.tanhToolStripMenuItem.Size = new System.Drawing.Size(99, 22);
this.tanhToolStripMenuItem.Tag = "tanh(|)";
this.tanhToolStripMenuItem.Text = "tanh";
this.tanhToolStripMenuItem.ToolTipText = "Returns the hyperbolic tangent of the specified angle.";
this.tanhToolStripMenuItem.Click += new System.EventHandler(this.function_Click);
//
// atanToolStripMenuItem
//
this.atanToolStripMenuItem.Name = "atanToolStripMenuItem";
this.atanToolStripMenuItem.Size = new System.Drawing.Size(99, 22);
this.atanToolStripMenuItem.Tag = "atan(|)";
this.atanToolStripMenuItem.Text = "atan";
this.atanToolStripMenuItem.ToolTipText = "Returns the angle whose tangent is the specified number.";
this.atanToolStripMenuItem.Click += new System.EventHandler(this.function_Click);
//
// logFunctionsToolStripMenuItem
//
this.logFunctionsToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.expToolStripMenuItem,
this.logToolStripMenuItem,
this.log10ToolStripMenuItem});
this.logFunctionsToolStripMenuItem.Name = "logFunctionsToolStripMenuItem";
this.logFunctionsToolStripMenuItem.Size = new System.Drawing.Size(162, 22);
this.logFunctionsToolStripMenuItem.Text = "Log Functions";
//
// expToolStripMenuItem
//
this.expToolStripMenuItem.Name = "expToolStripMenuItem";
this.expToolStripMenuItem.Size = new System.Drawing.Size(103, 22);
this.expToolStripMenuItem.Tag = "exp(|)";
this.expToolStripMenuItem.Text = "exp";
this.expToolStripMenuItem.ToolTipText = "Returns e raised to the specified power.";
this.expToolStripMenuItem.Click += new System.EventHandler(this.function_Click);
//
// logToolStripMenuItem
//
this.logToolStripMenuItem.Name = "logToolStripMenuItem";
this.logToolStripMenuItem.Size = new System.Drawing.Size(103, 22);
this.logToolStripMenuItem.Tag = "log(|)";
this.logToolStripMenuItem.Text = "log";
this.logToolStripMenuItem.ToolTipText = "Returns the logarithm of a specified number.";
this.logToolStripMenuItem.Click += new System.EventHandler(this.function_Click);
//
// log10ToolStripMenuItem
//
this.log10ToolStripMenuItem.Name = "log10ToolStripMenuItem";
this.log10ToolStripMenuItem.Size = new System.Drawing.Size(103, 22);
this.log10ToolStripMenuItem.Tag = "log10(|)";
this.log10ToolStripMenuItem.Text = "log10";
this.log10ToolStripMenuItem.ToolTipText = "Returns the base 10 logarithm of a specified number.";
this.log10ToolStripMenuItem.Click += new System.EventHandler(this.function_Click);
//
// conversionsToolStripMenuItem
//
this.conversionsToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.lengthToolStripMenuItem,
this.massToolStripMenuItem,
this.speedToolStripMenuItem,
this.temperatureToolStripMenuItem,
this.timeToolStripMenuItem,
this.volumeToolStripMenuItem});
this.conversionsToolStripMenuItem.Name = "conversionsToolStripMenuItem";
this.conversionsToolStripMenuItem.Size = new System.Drawing.Size(84, 20);
this.conversionsToolStripMenuItem.Text = "&Conversions";
//
// lengthToolStripMenuItem
//
this.lengthToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.lengthDummyToolStripMenuItem});
this.lengthToolStripMenuItem.Name = "lengthToolStripMenuItem";
this.lengthToolStripMenuItem.Size = new System.Drawing.Size(142, 22);
this.lengthToolStripMenuItem.Text = "&Length";
this.lengthToolStripMenuItem.DropDownOpening += new System.EventHandler(this.lengthToolStripMenuItem_DropDownOpening);
//
// lengthDummyToolStripMenuItem
//
this.lengthDummyToolStripMenuItem.Name = "lengthDummyToolStripMenuItem";
this.lengthDummyToolStripMenuItem.Size = new System.Drawing.Size(157, 22);
this.lengthDummyToolStripMenuItem.Text = "Length Dummy";
//
// massToolStripMenuItem
//
this.massToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.massDummyToolStripMenuItem});
this.massToolStripMenuItem.Name = "massToolStripMenuItem";
this.massToolStripMenuItem.Size = new System.Drawing.Size(142, 22);
this.massToolStripMenuItem.Text = "&Mass";
this.massToolStripMenuItem.DropDownOpening += new System.EventHandler(this.massToolStripMenuItem_DropDownOpening);
//
// massDummyToolStripMenuItem
//
this.massDummyToolStripMenuItem.Name = "massDummyToolStripMenuItem";
this.massDummyToolStripMenuItem.Size = new System.Drawing.Size(147, 22);
this.massDummyToolStripMenuItem.Text = "Mass Dummy";
//
// speedToolStripMenuItem
//
this.speedToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.speedDummyToolStripMenuItem});
this.speedToolStripMenuItem.Name = "speedToolStripMenuItem";
this.speedToolStripMenuItem.Size = new System.Drawing.Size(142, 22);
this.speedToolStripMenuItem.Text = "&Speed";
this.speedToolStripMenuItem.DropDownOpening += new System.EventHandler(this.speedToolStripMenuItem_DropDownOpening);
//
// speedDummyToolStripMenuItem
//
this.speedDummyToolStripMenuItem.Name = "speedDummyToolStripMenuItem";
this.speedDummyToolStripMenuItem.Size = new System.Drawing.Size(152, 22);
this.speedDummyToolStripMenuItem.Text = "Speed Dummy";
//
// temperatureToolStripMenuItem
//
this.temperatureToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.temperatureDummyToolStripMenuItem});
this.temperatureToolStripMenuItem.Name = "temperatureToolStripMenuItem";
this.temperatureToolStripMenuItem.Size = new System.Drawing.Size(142, 22);
this.temperatureToolStripMenuItem.Text = "Tem&perature";
this.temperatureToolStripMenuItem.DropDownOpening += new System.EventHandler(this.temperatureToolStripMenuItem_DropDownOpening);
//
// temperatureDummyToolStripMenuItem
//
this.temperatureDummyToolStripMenuItem.Name = "temperatureDummyToolStripMenuItem";
this.temperatureDummyToolStripMenuItem.Size = new System.Drawing.Size(188, 22);
this.temperatureDummyToolStripMenuItem.Text = "Temperature Dummy";
//
// timeToolStripMenuItem
//
this.timeToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.timeDummyToolStripMenuItem});
this.timeToolStripMenuItem.Name = "timeToolStripMenuItem";
this.timeToolStripMenuItem.Size = new System.Drawing.Size(142, 22);
this.timeToolStripMenuItem.Text = "&Time";
this.timeToolStripMenuItem.DropDownOpening += new System.EventHandler(this.timeToolStripMenuItem_DropDownOpening);
//
// timeDummyToolStripMenuItem
//
this.timeDummyToolStripMenuItem.Name = "timeDummyToolStripMenuItem";
this.timeDummyToolStripMenuItem.Size = new System.Drawing.Size(147, 22);
this.timeDummyToolStripMenuItem.Text = "Time Dummy";
//
// volumeToolStripMenuItem
//
this.volumeToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.volumeDummyToolStripMenuItem});
this.volumeToolStripMenuItem.Name = "volumeToolStripMenuItem";
this.volumeToolStripMenuItem.Size = new System.Drawing.Size(142, 22);
this.volumeToolStripMenuItem.Text = "&Volume";
this.volumeToolStripMenuItem.DropDownOpening += new System.EventHandler(this.volumeToolStripMenuItem_DropDownOpening);
//
// volumeDummyToolStripMenuItem
//
this.volumeDummyToolStripMenuItem.Name = "volumeDummyToolStripMenuItem";
this.volumeDummyToolStripMenuItem.Size = new System.Drawing.Size(161, 22);
this.volumeDummyToolStripMenuItem.Text = "Volume Dummy";
//
// helpToolStripMenuItem
//
this.helpToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.aboutToolStripMenuItem});
this.helpToolStripMenuItem.Name = "helpToolStripMenuItem";
this.helpToolStripMenuItem.Size = new System.Drawing.Size(44, 20);
this.helpToolStripMenuItem.Text = "&Help";
//
// aboutToolStripMenuItem
//
this.aboutToolStripMenuItem.Image = global::LoreSoft.Calculator.Properties.Resources.Help;
this.aboutToolStripMenuItem.Name = "aboutToolStripMenuItem";
this.aboutToolStripMenuItem.Size = new System.Drawing.Size(116, 22);
this.aboutToolStripMenuItem.Text = "&About...";
this.aboutToolStripMenuItem.Click += new System.EventHandler(this.aboutToolStripMenuItem_Click);
//
// mainToolStrip
//
this.mainToolStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.saveToolStripButton,
this.toolStripSeparator,
this.cutToolStripButton,
this.copyToolStripButton,
this.pasteToolStripButton,
this.toolStripSeparator5,
this.undoToolStripButton,
this.toolStripSeparator7,
this.clearHistoryToolStripButton});
this.mainToolStrip.Location = new System.Drawing.Point(0, 24);
this.mainToolStrip.Name = "mainToolStrip";
this.mainToolStrip.Size = new System.Drawing.Size(384, 25);
this.mainToolStrip.TabIndex = 1;
this.mainToolStrip.Text = "toolStrip1";
//
// saveToolStripButton
//
this.saveToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.saveToolStripButton.Image = global::LoreSoft.Calculator.Properties.Resources.Save;
this.saveToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.saveToolStripButton.Name = "saveToolStripButton";
this.saveToolStripButton.Size = new System.Drawing.Size(23, 22);
this.saveToolStripButton.Text = "&Save History";
this.saveToolStripButton.Click += new System.EventHandler(this.saveToolStripMenuItem_Click);
//
// toolStripSeparator
//
this.toolStripSeparator.Name = "toolStripSeparator";
this.toolStripSeparator.Size = new System.Drawing.Size(6, 25);
//
// cutToolStripButton
//
this.cutToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.cutToolStripButton.Image = global::LoreSoft.Calculator.Properties.Resources.Cut;
this.cutToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.cutToolStripButton.Name = "cutToolStripButton";
this.cutToolStripButton.Size = new System.Drawing.Size(23, 22);
this.cutToolStripButton.Text = "C&ut";
this.cutToolStripButton.Click += new System.EventHandler(this.cutToolStripMenuItem_Click);
//
// copyToolStripButton
//
this.copyToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.copyToolStripButton.Image = global::LoreSoft.Calculator.Properties.Resources.Copy;
this.copyToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.copyToolStripButton.Name = "copyToolStripButton";
this.copyToolStripButton.Size = new System.Drawing.Size(23, 22);
this.copyToolStripButton.Text = "&Copy";
this.copyToolStripButton.Click += new System.EventHandler(this.copyToolStripMenuItem_Click);
//
// pasteToolStripButton
//
this.pasteToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.pasteToolStripButton.Image = global::LoreSoft.Calculator.Properties.Resources.Paste;
this.pasteToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.pasteToolStripButton.Name = "pasteToolStripButton";
this.pasteToolStripButton.Size = new System.Drawing.Size(23, 22);
this.pasteToolStripButton.Text = "&Paste";
this.pasteToolStripButton.Click += new System.EventHandler(this.pasteToolStripMenuItem_Click);
//
// toolStripSeparator5
//
this.toolStripSeparator5.Name = "toolStripSeparator5";
this.toolStripSeparator5.Size = new System.Drawing.Size(6, 25);
//
// undoToolStripButton
//
this.undoToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.undoToolStripButton.Image = global::LoreSoft.Calculator.Properties.Resources.Undo;
this.undoToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.undoToolStripButton.Name = "undoToolStripButton";
this.undoToolStripButton.Size = new System.Drawing.Size(23, 22);
this.undoToolStripButton.Text = "&Undo";
this.undoToolStripButton.Click += new System.EventHandler(this.undoToolStripMenuItem_Click);
//
// toolStripSeparator7
//
this.toolStripSeparator7.Name = "toolStripSeparator7";
this.toolStripSeparator7.Size = new System.Drawing.Size(6, 25);
//
// clearHistoryToolStripButton
//
this.clearHistoryToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.clearHistoryToolStripButton.Image = global::LoreSoft.Calculator.Properties.Resources.Delete;
this.clearHistoryToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.clearHistoryToolStripButton.Name = "clearHistoryToolStripButton";
this.clearHistoryToolStripButton.Size = new System.Drawing.Size(23, 22);
this.clearHistoryToolStripButton.Text = "&Clear History";
this.clearHistoryToolStripButton.Click += new System.EventHandler(this.clearHistoryToolStripMenuItem_Click);
//
// historyPanel
//
this.historyPanel.Controls.Add(this.historyRichTextBox);
this.historyPanel.Controls.Add(this.historyLabel);
this.historyPanel.Dock = System.Windows.Forms.DockStyle.Fill;
this.historyPanel.Location = new System.Drawing.Point(0, 49);
this.historyPanel.Name = "historyPanel";
this.historyPanel.Size = new System.Drawing.Size(384, 200);
this.historyPanel.TabIndex = 5;
//
// historyRichTextBox
//
this.historyRichTextBox.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.historyRichTextBox.ContextMenuStrip = this.historyContextMenuStrip;
this.historyRichTextBox.DetectUrls = false;
this.historyRichTextBox.Dock = System.Windows.Forms.DockStyle.Fill;
this.historyRichTextBox.Font = new System.Drawing.Font("Consolas", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.historyRichTextBox.Location = new System.Drawing.Point(0, 23);
this.historyRichTextBox.Margin = new System.Windows.Forms.Padding(5);
this.historyRichTextBox.Name = "historyRichTextBox";
this.historyRichTextBox.ReadOnly = true;
this.historyRichTextBox.Size = new System.Drawing.Size(384, 177);
this.historyRichTextBox.TabIndex = 1;
this.historyRichTextBox.Text = "";
//
// historyContextMenuStrip
//
this.historyContextMenuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.clearHistoryContextStripMenuItem,
this.toolStripSeparator9,
this.copyHistoryContextStripMenuItem2});
this.historyContextMenuStrip.Name = "historyContextMenuStrip";
this.historyContextMenuStrip.Size = new System.Drawing.Size(185, 54);
//
// clearHistoryContextStripMenuItem
//
this.clearHistoryContextStripMenuItem.Image = global::LoreSoft.Calculator.Properties.Resources.Delete;
this.clearHistoryContextStripMenuItem.Name = "clearHistoryContextStripMenuItem";
this.clearHistoryContextStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.D)));
this.clearHistoryContextStripMenuItem.Size = new System.Drawing.Size(184, 22);
this.clearHistoryContextStripMenuItem.Text = "&Clear History";
this.clearHistoryContextStripMenuItem.Click += new System.EventHandler(this.clearHistoryToolStripMenuItem_Click);
//
// toolStripSeparator9
//
this.toolStripSeparator9.Name = "toolStripSeparator9";
this.toolStripSeparator9.Size = new System.Drawing.Size(181, 6);
//
// copyHistoryContextStripMenuItem2
//
this.copyHistoryContextStripMenuItem2.Image = global::LoreSoft.Calculator.Properties.Resources.Copy;
this.copyHistoryContextStripMenuItem2.ImageTransparentColor = System.Drawing.Color.Magenta;
this.copyHistoryContextStripMenuItem2.Name = "copyHistoryContextStripMenuItem2";
this.copyHistoryContextStripMenuItem2.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.C)));
this.copyHistoryContextStripMenuItem2.Size = new System.Drawing.Size(184, 22);
this.copyHistoryContextStripMenuItem2.Text = "&Copy";
this.copyHistoryContextStripMenuItem2.Click += new System.EventHandler(this.copyToolStripMenuItem_Click);
//
// historyLabel
//
this.historyLabel.BackColor = System.Drawing.Color.LightSlateGray;
this.historyLabel.Dock = System.Windows.Forms.DockStyle.Top;
this.historyLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.historyLabel.ForeColor = System.Drawing.SystemColors.HighlightText;
this.historyLabel.Location = new System.Drawing.Point(0, 0);
this.historyLabel.Name = "historyLabel";
this.historyLabel.Padding = new System.Windows.Forms.Padding(10, 0, 0, 0);
this.historyLabel.Size = new System.Drawing.Size(384, 23);
this.historyLabel.TabIndex = 0;
this.historyLabel.Text = "History";
this.historyLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// inputLabel
//
this.inputLabel.BackColor = System.Drawing.Color.LightSlateGray;
this.inputLabel.Dock = System.Windows.Forms.DockStyle.Bottom;
this.inputLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.inputLabel.ForeColor = System.Drawing.SystemColors.HighlightText;
this.inputLabel.Location = new System.Drawing.Point(0, 249);
this.inputLabel.Name = "inputLabel";
this.inputLabel.Padding = new System.Windows.Forms.Padding(10, 0, 0, 0);
this.inputLabel.Size = new System.Drawing.Size(384, 23);
this.inputLabel.TabIndex = 2;
this.inputLabel.Text = "Input";
this.inputLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// inputTextBox
//
this.inputTextBox.ContextMenuStrip = this.inputContextMenuStrip;
this.inputTextBox.Dock = System.Windows.Forms.DockStyle.Bottom;
this.inputTextBox.Font = new System.Drawing.Font("Consolas", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.inputTextBox.Location = new System.Drawing.Point(0, 272);
this.inputTextBox.Name = "inputTextBox";
this.inputTextBox.Size = new System.Drawing.Size(384, 30);
this.inputTextBox.TabIndex = 3;
this.inputTextBox.KeyDown += new System.Windows.Forms.KeyEventHandler(this.inputTextBox_KeyDown);
this.inputTextBox.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.inputTextBox_KeyPress);
//
// inputContextMenuStrip
//
this.inputContextMenuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.undoContextStripMenuItem,
this.toolStripSeparator2,
this.cutContextStripMenuItem,
this.copyContextStripMenuItem,
this.pasteContextStripMenuItem,
this.toolStripSeparator8,
this.selectAllContextStripMenuItem});
this.inputContextMenuStrip.Name = "inputContextMenuStrip";
this.inputContextMenuStrip.Size = new System.Drawing.Size(165, 126);
//
// undoContextStripMenuItem
//
this.undoContextStripMenuItem.Image = global::LoreSoft.Calculator.Properties.Resources.Undo;
this.undoContextStripMenuItem.Name = "undoContextStripMenuItem";
this.undoContextStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Z)));
this.undoContextStripMenuItem.Size = new System.Drawing.Size(164, 22);
this.undoContextStripMenuItem.Text = "&Undo";
this.undoContextStripMenuItem.Click += new System.EventHandler(this.undoToolStripMenuItem_Click);
//
// toolStripSeparator2
//
this.toolStripSeparator2.Name = "toolStripSeparator2";
this.toolStripSeparator2.Size = new System.Drawing.Size(161, 6);
//
// cutContextStripMenuItem
//
this.cutContextStripMenuItem.Image = global::LoreSoft.Calculator.Properties.Resources.Cut;
this.cutContextStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta;
this.cutContextStripMenuItem.Name = "cutContextStripMenuItem";
this.cutContextStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.X)));
this.cutContextStripMenuItem.Size = new System.Drawing.Size(164, 22);
this.cutContextStripMenuItem.Text = "Cu&t";
this.cutContextStripMenuItem.Click += new System.EventHandler(this.cutToolStripMenuItem_Click);
//
// copyContextStripMenuItem
//
this.copyContextStripMenuItem.Image = global::LoreSoft.Calculator.Properties.Resources.Copy;
this.copyContextStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta;
this.copyContextStripMenuItem.Name = "copyContextStripMenuItem";
this.copyContextStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.C)));
this.copyContextStripMenuItem.Size = new System.Drawing.Size(164, 22);
this.copyContextStripMenuItem.Text = "&Copy";
this.copyContextStripMenuItem.Click += new System.EventHandler(this.copyToolStripMenuItem_Click);
//
// pasteContextStripMenuItem
//
this.pasteContextStripMenuItem.Image = global::LoreSoft.Calculator.Properties.Resources.Paste;
this.pasteContextStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta;
this.pasteContextStripMenuItem.Name = "pasteContextStripMenuItem";
this.pasteContextStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.V)));
this.pasteContextStripMenuItem.Size = new System.Drawing.Size(164, 22);
this.pasteContextStripMenuItem.Text = "&Paste";
this.pasteContextStripMenuItem.Click += new System.EventHandler(this.pasteToolStripMenuItem_Click);
//
// toolStripSeparator8
//
this.toolStripSeparator8.Name = "toolStripSeparator8";
this.toolStripSeparator8.Size = new System.Drawing.Size(161, 6);
//
// selectAllContextStripMenuItem
//
this.selectAllContextStripMenuItem.Name = "selectAllContextStripMenuItem";
this.selectAllContextStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.A)));
this.selectAllContextStripMenuItem.Size = new System.Drawing.Size(164, 22);
this.selectAllContextStripMenuItem.Text = "Select &All";
this.selectAllContextStripMenuItem.Click += new System.EventHandler(this.selectAllToolStripMenuItem_Click);
//
// statusStrip
//
this.statusStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.answerToolStripStatusLabel,
this.timerToolStripStatusLabel,
this.numLockToolStripStatusLabel});
this.statusStrip.Location = new System.Drawing.Point(0, 302);
this.statusStrip.Name = "statusStrip";
this.statusStrip.Size = new System.Drawing.Size(384, 22);
this.statusStrip.TabIndex = 4;
this.statusStrip.Text = "statusStrip1";
//
// answerToolStripStatusLabel
//
this.answerToolStripStatusLabel.Name = "answerToolStripStatusLabel";
this.answerToolStripStatusLabel.Size = new System.Drawing.Size(219, 17);
this.answerToolStripStatusLabel.Spring = true;
this.answerToolStripStatusLabel.Text = "Ready";
this.answerToolStripStatusLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.answerToolStripStatusLabel.ToolTipText = "The last answer value.";
//
// timerToolStripStatusLabel
//
this.timerToolStripStatusLabel.AutoSize = false;
this.timerToolStripStatusLabel.Name = "timerToolStripStatusLabel";
this.timerToolStripStatusLabel.Size = new System.Drawing.Size(100, 17);
this.timerToolStripStatusLabel.Text = "0.000 ms";
this.timerToolStripStatusLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.timerToolStripStatusLabel.ToolTipText = "The number of miliseconds the last calculation took.";
//
// numLockToolStripStatusLabel
//
this.numLockToolStripStatusLabel.AutoSize = false;
this.numLockToolStripStatusLabel.Name = "numLockToolStripStatusLabel";
this.numLockToolStripStatusLabel.Size = new System.Drawing.Size(50, 17);
this.numLockToolStripStatusLabel.Text = "NUM";
this.numLockToolStripStatusLabel.ToolTipText = "The state of the Num Locks key.";
//
// saveFileDialog
//
this.saveFileDialog.DefaultExt = "txt";
this.saveFileDialog.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*";
this.saveFileDialog.SupportMultiDottedExtensions = true;
this.saveFileDialog.Title = "Save History";
//
// allowOnlyOneInstanceToolStripMenuItem
//
this.allowOnlyOneInstanceToolStripMenuItem.CheckOnClick = true;
this.allowOnlyOneInstanceToolStripMenuItem.Name = "allowOnlyOneInstanceToolStripMenuItem";
this.allowOnlyOneInstanceToolStripMenuItem.Size = new System.Drawing.Size(204, 22);
this.allowOnlyOneInstanceToolStripMenuItem.Text = "Allow Only One &Instance";
this.allowOnlyOneInstanceToolStripMenuItem.Click += new System.EventHandler(this.allowOnlyOneInstanceToolStripMenuItem_Click);
//
// CalculatorForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(384, 324);
this.Controls.Add(this.historyPanel);
this.Controls.Add(this.inputLabel);
this.Controls.Add(this.inputTextBox);
this.Controls.Add(this.mainToolStrip);
this.Controls.Add(this.mainMenuStrip);
this.Controls.Add(this.statusStrip);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MinimumSize = new System.Drawing.Size(400, 360);
this.Name = "CalculatorForm";
this.Text = "Calculator.NET";
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.CalculatorForm_FormClosing);
this.Load += new System.EventHandler(this.CalculatorForm_Load);
this.mainMenuStrip.ResumeLayout(false);
this.mainMenuStrip.PerformLayout();
this.mainToolStrip.ResumeLayout(false);
this.mainToolStrip.PerformLayout();
this.historyPanel.ResumeLayout(false);
this.historyContextMenuStrip.ResumeLayout(false);
this.inputContextMenuStrip.ResumeLayout(false);
this.statusStrip.ResumeLayout(false);
this.statusStrip.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.MenuStrip mainMenuStrip;
private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem saveToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator1;
private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem editToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem undoToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator3;
private System.Windows.Forms.ToolStripMenuItem cutToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem copyToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem pasteToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator4;
private System.Windows.Forms.ToolStripMenuItem selectAllToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem optionsToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem functionsToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem conversionsToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem helpToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem aboutToolStripMenuItem;
private System.Windows.Forms.ToolStrip mainToolStrip;
private System.Windows.Forms.ToolStripButton saveToolStripButton;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator;
private System.Windows.Forms.ToolStripButton cutToolStripButton;
private System.Windows.Forms.ToolStripButton copyToolStripButton;
private System.Windows.Forms.ToolStripButton pasteToolStripButton;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator5;
private System.Windows.Forms.Panel historyPanel;
private System.Windows.Forms.RichTextBox historyRichTextBox;
private System.Windows.Forms.Label historyLabel;
private System.Windows.Forms.Label inputLabel;
private System.Windows.Forms.TextBox inputTextBox;
private System.Windows.Forms.StatusStrip statusStrip;
private System.Windows.Forms.ToolStripStatusLabel answerToolStripStatusLabel;
private System.Windows.Forms.ToolStripStatusLabel numLockToolStripStatusLabel;
private System.Windows.Forms.ToolStripStatusLabel timerToolStripStatusLabel;
private System.Windows.Forms.ToolStripMenuItem clearHistoryToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator6;
private System.Windows.Forms.ToolStripMenuItem historyFontToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem inputFontToolStripMenuItem;
private System.Windows.Forms.ToolStripButton undoToolStripButton;
private System.Windows.Forms.FontDialog fontDialog;
private System.Windows.Forms.SaveFileDialog saveFileDialog;
private System.Windows.Forms.ContextMenuStrip inputContextMenuStrip;
private System.Windows.Forms.ToolStripMenuItem undoContextStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator2;
private System.Windows.Forms.ToolStripMenuItem cutContextStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem copyContextStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem pasteContextStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator8;
private System.Windows.Forms.ToolStripMenuItem selectAllContextStripMenuItem;
private System.Windows.Forms.ContextMenuStrip historyContextMenuStrip;
private System.Windows.Forms.ToolStripMenuItem clearHistoryContextStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator9;
private System.Windows.Forms.ToolStripMenuItem copyHistoryContextStripMenuItem2;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator10;
private System.Windows.Forms.ToolStripMenuItem replaceCalculatorToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem basicOperationsToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem trigFunctionsToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem addToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem subtractToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem multiplyToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem divideToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem modulusToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem powerToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem sqrtToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem absToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem cosToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem acosToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem sinToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem asinToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem tanToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem atanToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem logFunctionsToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem coshToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem sinhToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem tanhToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem expToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem logToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem log10ToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator11;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator7;
private System.Windows.Forms.ToolStripButton clearHistoryToolStripButton;
private System.Windows.Forms.ToolStripMenuItem temperatureToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem timeToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem volumeToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem speedToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem lengthToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem massToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem lengthDummyToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem massDummyToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem speedDummyToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem temperatureDummyToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem timeDummyToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem volumeDummyToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem allowOnlyOneInstanceToolStripMenuItem;
}
}
| |
/*
* Copyright (c) 2007-2008, Second Life Reverse Engineering Team
* All rights reserved.
*
* - Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* - Neither the name of the Second Life Reverse Engineering Team nor the names
* of its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using libsecondlife;
using libsecondlife.Packets;
using libsecondlife.StructuredData;
using NUnit.Framework;
namespace libsecondlife.Tests
{
[TestFixture]
public class TypeTests : Assert
{
[Test]
public void LLUUIDs()
{
// Creation
LLUUID a = new LLUUID();
byte[] bytes = a.GetBytes();
for (int i = 0; i < 16; i++)
Assert.IsTrue(bytes[i] == 0x00);
// Comparison
a = new LLUUID(new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A,
0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0xFF, 0xFF }, 0);
LLUUID b = new LLUUID(new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A,
0x0B, 0x0C, 0x0D, 0x0E, 0x0F }, 0);
Assert.IsTrue(a == b, "LLUUID comparison operator failed, " + a.ToString() + " should equal " +
b.ToString());
// From string
a = new LLUUID(new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A,
0x0B, 0x0C, 0x0D, 0x0E, 0x0F }, 0);
string zeroonetwo = "00010203-0405-0607-0809-0a0b0c0d0e0f";
b = new LLUUID(zeroonetwo);
Assert.IsTrue(a == b, "LLUUID hyphenated string constructor failed, should have " + a.ToString() +
" but we got " + b.ToString());
// ToString()
string one = a.ToString();
string two = b.ToString();
Assert.IsTrue(a == b);
one = a.ToString();
two = b.ToString();
Assert.IsTrue(a == b);
Assert.IsTrue(a == zeroonetwo);
// TODO: CRC test
}
[Test]
public void Quaternions()
{
LLQuaternion a = new LLQuaternion(1, 0, 0, 0);
LLQuaternion b = new LLQuaternion(1, 0, 0, 0);
Assert.IsTrue(a == b, "LLQuaternion comparison operator failed");
LLQuaternion expected = new LLQuaternion(0, 0, 0, -1);
LLQuaternion result = a * b;
Assert.IsTrue(result == expected, a.ToString() + " * " + b.ToString() + " produced " + result.ToString() +
" instead of " + expected.ToString());
a = new LLQuaternion(1, 0, 0, 0);
b = new LLQuaternion(0, 1, 0, 0);
expected = new LLQuaternion(0, 0, 1, 0);
result = a * b;
Assert.IsTrue(result == expected, a.ToString() + " * " + b.ToString() + " produced " + result.ToString() +
" instead of " + expected.ToString());
a = new LLQuaternion(0, 0, 1, 0);
b = new LLQuaternion(0, 1, 0, 0);
expected = new LLQuaternion(-1, 0, 0, 0);
result = a * b;
Assert.IsTrue(result == expected, a.ToString() + " * " + b.ToString() + " produced " + result.ToString() +
" instead of " + expected.ToString());
}
//[Test]
//public void VectorQuaternionMath()
//{
// // Convert a vector to a quaternion and back
// LLVector3 a = new LLVector3(1f, 0.5f, 0.75f);
// LLQuaternion b = a.ToQuaternion();
// LLVector3 c;
// b.GetEulerAngles(out c.X, out c.Y, out c.Z);
// Assert.IsTrue(a == c, c.ToString() + " does not equal " + a.ToString());
//}
[Test]
public void FloatsToTerseStrings()
{
float f = 1.20f;
string a = String.Empty;
string b = "1.2";
a = Helpers.FloatToTerseString(f);
Assert.IsTrue(a == b, f.ToString() + " converted to " + a + ", expecting " + b);
f = 24.00f;
b = "24";
a = Helpers.FloatToTerseString(f);
Assert.IsTrue(a == b, f.ToString() + " converted to " + a + ", expecting " + b);
f = -0.59f;
b = "-.59";
a = Helpers.FloatToTerseString(f);
Assert.IsTrue(a == b, f.ToString() + " converted to " + a + ", expecting " + b);
f = 0.59f;
b = ".59";
a = Helpers.FloatToTerseString(f);
Assert.IsTrue(a == b, f.ToString() + " converted to " + a + ", expecting " + b);
}
[Test]
public void BitUnpacking()
{
byte[] data = new byte[] { 0x80, 0x00, 0x0F, 0x50, 0x83, 0x7D };
BitPack bitpacker = new BitPack(data, 0);
int b = bitpacker.UnpackBits(1);
Assert.IsTrue(b == 1, "Unpacked " + b + " instead of 1");
b = bitpacker.UnpackBits(1);
Assert.IsTrue(b == 0, "Unpacked " + b + " instead of 0");
bitpacker = new BitPack(data, 2);
b = bitpacker.UnpackBits(4);
Assert.IsTrue(b == 0, "Unpacked " + b + " instead of 0");
b = bitpacker.UnpackBits(8);
Assert.IsTrue(b == 0xF5, "Unpacked " + b + " instead of 0xF5");
b = bitpacker.UnpackBits(4);
Assert.IsTrue(b == 0, "Unpacked " + b + " instead of 0");
b = bitpacker.UnpackBits(10);
Assert.IsTrue(b == 0x0183, "Unpacked " + b + " instead of 0x0183");
}
[Test]
public void BitPacking()
{
byte[] packedBytes = new byte[12];
BitPack bitpacker = new BitPack(packedBytes, 0);
bitpacker.PackBits(0x0ABBCCDD, 32);
bitpacker.PackBits(25, 5);
bitpacker.PackFloat(123.321f);
bitpacker.PackBits(1000, 16);
bitpacker = new BitPack(packedBytes, 0);
int b = bitpacker.UnpackBits(32);
Assert.IsTrue(b == 0x0ABBCCDD, "Unpacked " + b + " instead of 2864434397");
b = bitpacker.UnpackBits(5);
Assert.IsTrue(b == 25, "Unpacked " + b + " instead of 25");
float f = bitpacker.UnpackFloat();
Assert.IsTrue(f == 123.321f, "Unpacked " + f + " instead of 123.321");
b = bitpacker.UnpackBits(16);
Assert.IsTrue(b == 1000, "Unpacked " + b + " instead of 1000");
}
[Test]
public void LLSDTerseParsing()
{
string testOne = "[r0.99967899999999998428,r-0.025334599999999998787,r0]";
string testTwo = "[[r1,r1,r1],r0]";
string testThree = "{'region_handle':[r255232, r256512], 'position':[r33.6, r33.71, r43.13], 'look_at':[r34.6, r33.71, r43.13]}";
LLSD obj = LLSDParser.DeserializeNotation(testOne);
Assert.IsInstanceOfType(typeof(LLSDArray), obj, "Expected LLSDArray, got " + obj.GetType().ToString());
LLSDArray array = (LLSDArray)obj;
Assert.IsTrue(array.Count == 3, "Expected three contained objects, got " + array.Count);
Assert.IsTrue(array[0].AsReal() > 0.9d && array[0].AsReal() < 1.0d, "Unexpected value for first real " + array[0].AsReal());
Assert.IsTrue(array[1].AsReal() < 0.0d && array[1].AsReal() > -0.03d, "Unexpected value for second real " + array[1].AsReal());
Assert.IsTrue(array[2].AsReal() == 0.0d, "Unexpected value for third real " + array[2].AsReal());
obj = LLSDParser.DeserializeNotation(testTwo);
Assert.IsInstanceOfType(typeof(LLSDArray), obj, "Expected LLSDArray, got " + obj.GetType().ToString());
array = (LLSDArray)obj;
Assert.IsTrue(array.Count == 2, "Expected two contained objects, got " + array.Count);
Assert.IsTrue(array[1].AsReal() == 0.0d, "Unexpected value for real " + array[1].AsReal());
obj = array[0];
Assert.IsInstanceOfType(typeof(LLSDArray), obj, "Expected ArrayList, got " + obj.GetType().ToString());
array = (LLSDArray)obj;
Assert.IsTrue(array[0].AsReal() == 1.0d && array[1].AsReal() == 1.0d && array[2].AsReal() == 1.0d,
"Unexpected value(s) for nested array: " + array[0].AsReal() + ", " + array[1].AsReal() + ", " +
array[2].AsReal());
obj = LLSDParser.DeserializeNotation(testThree);
Assert.IsInstanceOfType(typeof(LLSDMap), obj, "Expected LLSDMap, got " + obj.GetType().ToString());
LLSDMap hashtable = (LLSDMap)obj;
Assert.IsTrue(hashtable.Count == 3, "Expected three contained objects, got " + hashtable.Count);
Assert.IsInstanceOfType(typeof(LLSDArray), hashtable["region_handle"]);
Assert.IsTrue(((LLSDArray)hashtable["region_handle"]).Count == 2);
Assert.IsInstanceOfType(typeof(LLSDArray), hashtable["position"]);
Assert.IsTrue(((LLSDArray)hashtable["position"]).Count == 3);
Assert.IsInstanceOfType(typeof(LLSDArray), hashtable["look_at"]);
Assert.IsTrue(((LLSDArray)hashtable["look_at"]).Count == 3);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.Threading.Tasks;
using Xunit;
namespace System.Threading.Tests
{
public class SemaphoreTests : RemoteExecutorTestBase
{
private const int FailedWaitTimeout = 30000;
[Theory]
[InlineData(0, 1)]
[InlineData(1, 1)]
[InlineData(1, 2)]
[InlineData(0, int.MaxValue)]
[InlineData(int.MaxValue, int.MaxValue)]
public void Ctor_InitialAndMax(int initialCount, int maximumCount)
{
new Semaphore(initialCount, maximumCount).Dispose();
new Semaphore(initialCount, maximumCount, null).Dispose();
}
[PlatformSpecific(TestPlatforms.Windows)] // named semaphores aren't supported on Unix
[Fact]
public void Ctor_ValidName_Windows()
{
string name = Guid.NewGuid().ToString("N");
new Semaphore(0, 1, name).Dispose();
bool createdNew;
new Semaphore(0, 1, name, out createdNew).Dispose();
Assert.True(createdNew);
}
[PlatformSpecific(TestPlatforms.AnyUnix)] // named semaphores aren't supported on Unix
[Fact]
public void Ctor_NamesArentSupported_Unix()
{
string name = Guid.NewGuid().ToString("N");
Assert.Throws<PlatformNotSupportedException>(() => new Semaphore(0, 1, name));
Assert.Throws<PlatformNotSupportedException>(() =>
{
bool createdNew;
new Semaphore(0, 1, name, out createdNew).Dispose();
});
}
[Fact]
public void Ctor_InvalidArguments()
{
bool createdNew;
AssertExtensions.Throws<ArgumentOutOfRangeException>("initialCount", () => new Semaphore(-1, 1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("initialCount", () => new Semaphore(-2, 1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("maximumCount", () => new Semaphore(0, 0));
AssertExtensions.Throws<ArgumentException>(null, () => new Semaphore(2, 1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("initialCount", () => new Semaphore(-1, 1, null));
AssertExtensions.Throws<ArgumentOutOfRangeException>("initialCount", () => new Semaphore(-2, 1, null));
AssertExtensions.Throws<ArgumentOutOfRangeException>("maximumCount", () => new Semaphore(0, 0, null));
AssertExtensions.Throws<ArgumentException>(null, () => new Semaphore(2, 1, null));
AssertExtensions.Throws<ArgumentOutOfRangeException>("initialCount", () => new Semaphore(-1, 1, "CtorSemaphoreTest", out createdNew));
AssertExtensions.Throws<ArgumentOutOfRangeException>("initialCount", () => new Semaphore(-2, 1, "CtorSemaphoreTest", out createdNew));
AssertExtensions.Throws<ArgumentOutOfRangeException>("maximumCount", () => new Semaphore(0, 0, "CtorSemaphoreTest", out createdNew));
AssertExtensions.Throws<ArgumentException>(null, () => new Semaphore(2, 1, "CtorSemaphoreTest", out createdNew));
}
[PlatformSpecific(TestPlatforms.Windows)] // named semaphores aren't supported on Unix
[Fact]
public void Ctor_InvalidNames()
{
AssertExtensions.Throws<ArgumentException>("name", null, () => new Semaphore(0, 1, new string('a', 10000)));
bool createdNew;
AssertExtensions.Throws<ArgumentException>("name", null, () => new Semaphore(0, 1, new string('a', 10000), out createdNew));
}
[Fact]
public void CanWaitWithoutBlockingUntilNoCount()
{
const int InitialCount = 5;
using (Semaphore s = new Semaphore(InitialCount, InitialCount))
{
for (int i = 0; i < InitialCount; i++)
Assert.True(s.WaitOne(0));
Assert.False(s.WaitOne(0));
}
}
[Fact]
public void CanWaitWithoutBlockingForReleasedCount()
{
using (Semaphore s = new Semaphore(0, Int32.MaxValue))
{
for (int counts = 1; counts < 5; counts++)
{
Assert.False(s.WaitOne(0));
if (counts % 2 == 0)
{
for (int i = 0; i < counts; i++)
s.Release();
}
else
{
s.Release(counts);
}
for (int i = 0; i < counts; i++)
{
Assert.True(s.WaitOne(0));
}
Assert.False(s.WaitOne(0));
}
}
}
[Fact]
public void Release()
{
using (Semaphore s = new Semaphore(1, 1))
{
Assert.Throws<SemaphoreFullException>(() => s.Release());
}
using (Semaphore s = new Semaphore(0, 10))
{
Assert.Throws<SemaphoreFullException>(() => s.Release(11));
AssertExtensions.Throws<ArgumentOutOfRangeException>("releaseCount", () => s.Release(-1));
}
using (Semaphore s = new Semaphore(0, 10))
{
for (int i = 0; i < 10; i++)
{
Assert.Equal(i, s.Release());
}
}
}
[Fact]
public void AnonymousProducerConsumer()
{
using (Semaphore s = new Semaphore(0, Int32.MaxValue))
{
const int NumItems = 5;
Task.WaitAll(
Task.Factory.StartNew(() =>
{
for (int i = 0; i < NumItems; i++)
Assert.True(s.WaitOne(FailedWaitTimeout));
Assert.False(s.WaitOne(0));
}, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default),
Task.Factory.StartNew(() =>
{
for (int i = 0; i < NumItems; i++)
s.Release();
}, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default));
}
}
[PlatformSpecific(TestPlatforms.Windows)] // named semaphores aren't supported on Unix
[Fact]
public void NamedProducerConsumer()
{
string name = Guid.NewGuid().ToString("N");
const int NumItems = 5;
var b = new Barrier(2);
Task.WaitAll(
Task.Factory.StartNew(() =>
{
using (var s = new Semaphore(0, int.MaxValue, name))
{
Assert.True(b.SignalAndWait(FailedWaitTimeout));
for (int i = 0; i < NumItems; i++)
Assert.True(s.WaitOne(FailedWaitTimeout));
Assert.False(s.WaitOne(0));
}
}, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default),
Task.Factory.StartNew(() =>
{
using (var s = new Semaphore(0, int.MaxValue, name))
{
Assert.True(b.SignalAndWait(FailedWaitTimeout));
for (int i = 0; i < NumItems; i++)
s.Release();
}
}, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default));
}
[PlatformSpecific(TestPlatforms.AnyUnix)] // named semaphores aren't supported on Unix
[Fact]
public void OpenExisting_NotSupported_Unix()
{
Assert.Throws<PlatformNotSupportedException>(() => Semaphore.OpenExisting(null));
Assert.Throws<PlatformNotSupportedException>(() => Semaphore.OpenExisting(string.Empty));
Assert.Throws<PlatformNotSupportedException>(() => Semaphore.OpenExisting("anything"));
Semaphore semaphore;
Assert.Throws<PlatformNotSupportedException>(() => Semaphore.TryOpenExisting("anything", out semaphore));
}
[PlatformSpecific(TestPlatforms.Windows)] // named semaphores aren't supported on Unix
[Fact]
public void OpenExisting_InvalidNames_Windows()
{
AssertExtensions.Throws<ArgumentNullException>("name", () => Semaphore.OpenExisting(null));
AssertExtensions.Throws<ArgumentException>("name", null, () => Semaphore.OpenExisting(string.Empty));
AssertExtensions.Throws<ArgumentException>("name", null, () => Semaphore.OpenExisting(new string('a', 10000)));
}
[PlatformSpecific(TestPlatforms.Windows)] // named semaphores aren't supported on Unix
[Fact]
public void OpenExisting_UnavailableName_Windows()
{
string name = Guid.NewGuid().ToString("N");
Assert.Throws<WaitHandleCannotBeOpenedException>(() => Semaphore.OpenExisting(name));
Semaphore ignored;
Assert.False(Semaphore.TryOpenExisting(name, out ignored));
}
[PlatformSpecific(TestPlatforms.Windows)] // named semaphores aren't supported on Unix
[Fact]
public void OpenExisting_NameUsedByOtherSynchronizationPrimitive_Windows()
{
string name = Guid.NewGuid().ToString("N");
using (Mutex mtx = new Mutex(true, name))
{
Assert.Throws<WaitHandleCannotBeOpenedException>(() => Semaphore.OpenExisting(name));
Semaphore ignored;
Assert.False(Semaphore.TryOpenExisting(name, out ignored));
}
}
[PlatformSpecific(TestPlatforms.Windows)] // named semaphores aren't supported on Unix
[Fact]
public void OpenExisting_SameAsOriginal_Windows()
{
string name = Guid.NewGuid().ToString("N");
bool createdNew;
using (Semaphore s1 = new Semaphore(0, Int32.MaxValue, name, out createdNew))
{
Assert.True(createdNew);
using (Semaphore s2 = Semaphore.OpenExisting(name))
{
Assert.False(s1.WaitOne(0));
Assert.False(s2.WaitOne(0));
s1.Release();
Assert.True(s2.WaitOne(0));
Assert.False(s2.WaitOne(0));
s2.Release();
Assert.True(s1.WaitOne(0));
Assert.False(s1.WaitOne(0));
}
Semaphore s3;
Assert.True(Semaphore.TryOpenExisting(name, out s3));
using (s3)
{
Assert.False(s1.WaitOne(0));
Assert.False(s3.WaitOne(0));
s1.Release();
Assert.True(s3.WaitOne(0));
Assert.False(s3.WaitOne(0));
s3.Release();
Assert.True(s1.WaitOne(0));
Assert.False(s1.WaitOne(0));
}
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // names aren't supported on Unix
[ActiveIssue(21275, TargetFrameworkMonikers.Uap)]
public void PingPong()
{
// Create names for the two semaphores
string outboundName = Guid.NewGuid().ToString("N");
string inboundName = Guid.NewGuid().ToString("N");
// Create the two semaphores and the other process with which to synchronize
using (var inbound = new Semaphore(1, 1, inboundName))
using (var outbound = new Semaphore(0, 1, outboundName))
using (var remote = RemoteInvoke(new Func<string, string, int>(PingPong_OtherProcess), outboundName, inboundName))
{
// Repeatedly wait for count in one semaphore and then release count into the other
for (int i = 0; i < 10; i++)
{
Assert.True(inbound.WaitOne(FailWaitTimeoutMilliseconds));
outbound.Release();
}
}
}
private static int PingPong_OtherProcess(string inboundName, string outboundName)
{
// Open the two semaphores
using (var inbound = Semaphore.OpenExisting(inboundName))
using (var outbound = Semaphore.OpenExisting(outboundName))
{
// Repeatedly wait for count in one semaphore and then release count into the other
for (int i = 0; i < 10; i++)
{
Assert.True(inbound.WaitOne(FailWaitTimeoutMilliseconds));
outbound.Release();
}
}
return SuccessExitCode;
}
}
}
| |
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
namespace ParentLoadSoftDelete.Business.ERCLevel
{
/// <summary>
/// F07_RegionColl (editable child list).<br/>
/// This is a generated base class of <see cref="F07_RegionColl"/> business object.
/// </summary>
/// <remarks>
/// This class is child of <see cref="F06_Country"/> editable child object.<br/>
/// The items of the collection are <see cref="F08_Region"/> objects.
/// </remarks>
[Serializable]
public partial class F07_RegionColl : BusinessListBase<F07_RegionColl, F08_Region>
{
#region Collection Business Methods
/// <summary>
/// Removes a <see cref="F08_Region"/> item from the collection.
/// </summary>
/// <param name="region_ID">The Region_ID of the item to be removed.</param>
public void Remove(int region_ID)
{
foreach (var f08_Region in this)
{
if (f08_Region.Region_ID == region_ID)
{
Remove(f08_Region);
break;
}
}
}
/// <summary>
/// Determines whether a <see cref="F08_Region"/> item is in the collection.
/// </summary>
/// <param name="region_ID">The Region_ID of the item to search for.</param>
/// <returns><c>true</c> if the F08_Region is a collection item; otherwise, <c>false</c>.</returns>
public bool Contains(int region_ID)
{
foreach (var f08_Region in this)
{
if (f08_Region.Region_ID == region_ID)
{
return true;
}
}
return false;
}
/// <summary>
/// Determines whether a <see cref="F08_Region"/> item is in the collection's DeletedList.
/// </summary>
/// <param name="region_ID">The Region_ID of the item to search for.</param>
/// <returns><c>true</c> if the F08_Region is a deleted collection item; otherwise, <c>false</c>.</returns>
public bool ContainsDeleted(int region_ID)
{
foreach (var f08_Region in DeletedList)
{
if (f08_Region.Region_ID == region_ID)
{
return true;
}
}
return false;
}
#endregion
#region Find Methods
/// <summary>
/// Finds a <see cref="F08_Region"/> item of the <see cref="F07_RegionColl"/> collection, based on item key properties.
/// </summary>
/// <param name="region_ID">The Region_ID.</param>
/// <returns>A <see cref="F08_Region"/> object.</returns>
public F08_Region FindF08_RegionByParentProperties(int region_ID)
{
for (var i = 0; i < this.Count; i++)
{
if (this[i].Region_ID.Equals(region_ID))
{
return this[i];
}
}
return null;
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="F07_RegionColl"/> collection.
/// </summary>
/// <returns>A reference to the created <see cref="F07_RegionColl"/> collection.</returns>
internal static F07_RegionColl NewF07_RegionColl()
{
return DataPortal.CreateChild<F07_RegionColl>();
}
/// <summary>
/// Factory method. Loads a <see cref="F07_RegionColl"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
/// <returns>A reference to the fetched <see cref="F07_RegionColl"/> object.</returns>
internal static F07_RegionColl GetF07_RegionColl(SafeDataReader dr)
{
F07_RegionColl obj = new F07_RegionColl();
// show the framework that this is a child object
obj.MarkAsChild();
obj.Fetch(dr);
return obj;
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="F07_RegionColl"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public F07_RegionColl()
{
// Use factory methods and do not use direct creation.
// show the framework that this is a child object
MarkAsChild();
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = false;
AllowNew = true;
AllowEdit = true;
AllowRemove = true;
RaiseListChangedEvents = rlce;
}
#endregion
#region Data Access
/// <summary>
/// Loads all <see cref="F07_RegionColl"/> collection items from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = false;
var args = new DataPortalHookArgs(dr);
OnFetchPre(args);
while (dr.Read())
{
Add(F08_Region.GetF08_Region(dr));
}
OnFetchPost(args);
RaiseListChangedEvents = rlce;
}
/// <summary>
/// Loads <see cref="F08_Region"/> items on the F07_RegionObjects collection.
/// </summary>
/// <param name="collection">The grand parent <see cref="F05_CountryColl"/> collection.</param>
internal void LoadItems(F05_CountryColl collection)
{
foreach (var item in this)
{
var obj = collection.FindF06_CountryByParentProperties(item.parent_Country_ID);
var rlce = obj.F07_RegionObjects.RaiseListChangedEvents;
obj.F07_RegionObjects.RaiseListChangedEvents = false;
obj.F07_RegionObjects.Add(item);
obj.F07_RegionObjects.RaiseListChangedEvents = rlce;
}
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
#endregion
}
}
| |
//
// ImageView.cs
//
// Author:
// Stephane Delcroix <stephane@delcroix.org>
// Ruben Vermeersch <ruben@savanne.be>
//
// Copyright (C) 2009-2010 Novell, Inc.
// Copyright (C) 2009 Stephane Delcroix
// Copyright (C) 2010 Ruben Vermeersch
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using Gtk;
using Gdk;
using FSpot.Utils;
using TagLib.Image;
using Hyena;
namespace FSpot.Widgets
{
public partial class ImageView : Container
{
#region public API
protected ImageView (IntPtr raw) : base (raw) { }
public ImageView (Adjustment hadjustment, Adjustment vadjustment, bool canSelect)
{
OnSetScrollAdjustments (hadjustment, vadjustment);
AdjustmentsChanged += ScrollToAdjustments;
WidgetFlags &= ~WidgetFlags.NoWindow;
SetFlag (WidgetFlags.CanFocus);
can_select = canSelect;
}
public ImageView (bool canSelect) : this (null, null, canSelect)
{
}
public ImageView () : this (true)
{
}
Pixbuf pixbuf;
public Pixbuf Pixbuf {
get { return pixbuf; }
set {
if (pixbuf == value)
return;
pixbuf = value;
min_zoom = ComputeMinZoom (upscale);
ComputeScaledSize ();
AdjustmentsChanged -= ScrollToAdjustments;
Hadjustment.Value = Vadjustment.Value = 0;
XOffset = YOffset = 0;
AdjustmentsChanged += ScrollToAdjustments;
QueueDraw ();
}
}
ImageOrientation pixbuf_orientation;
public ImageOrientation PixbufOrientation {
get { return pixbuf_orientation; }
set {
if (value == pixbuf_orientation)
return;
pixbuf_orientation = value;
min_zoom = ComputeMinZoom (upscale);
ComputeScaledSize ();
QueueDraw ();
}
}
CheckPattern check_pattern = CheckPattern.Dark;
public CheckPattern CheckPattern {
get { return check_pattern; }
set {
if (check_pattern == value)
return;
check_pattern = value;
if (Pixbuf != null && Pixbuf.HasAlpha)
QueueDraw ();
}
}
PointerMode pointer_mode = PointerMode.Select;
public PointerMode PointerMode {
get { return pointer_mode; }
set { pointer_mode = value; }
}
public Adjustment Hadjustment { get; private set; }
public Adjustment Vadjustment { get; private set; }
bool can_select = false;
public bool CanSelect {
get { return can_select; }
set {
if (can_select == value)
return;
if (!value)
Selection = Rectangle.Zero;
can_select = value;
}
}
Gdk.Rectangle selection = Rectangle.Zero;
public Gdk.Rectangle Selection {
get {
if (!can_select)
return Rectangle.Zero;
return selection;
}
set {
if (!can_select)
return;
if (value == selection)
return;
selection = value;
SelectionChanged?.Invoke (this, EventArgs.Empty);
QueueDraw ();
}
}
double selection_xy_ratio = 0;
public double SelectionXyRatio {
get { return selection_xy_ratio; }
set {
if (selection_xy_ratio == value)
return;
selection_xy_ratio = value;
if (selection_xy_ratio == 0)
return;
if (Selection == Rectangle.Zero)
return;
Selection = ConstrainSelection (Selection, false, false);
}
}
InterpType interpolation = InterpType.Bilinear;
public Gdk.InterpType Interpolation {
get { return interpolation; }
set {
if (interpolation == value)
return;
interpolation = value;
QueueDraw ();
}
}
double zoom = 1.0;
public double Zoom {
get { return zoom; }
set {
// Zoom around the center of the image.
DoZoom (value, Allocation.Width / 2, Allocation.Height / 2);
}
}
public void ZoomIn ()
{
Zoom *= ZOOM_FACTOR;
}
public void ZoomOut ()
{
Zoom *= 1.0 / ZOOM_FACTOR;
}
public void ZoomAboutPoint (double zoomIncrement, int x, int y)
{
DoZoom (zoom * zoomIncrement, x, y);
}
public bool Fit { get; private set; }
public void ZoomFit (bool upscale)
{
Gtk.ScrolledWindow scrolled = Parent as Gtk.ScrolledWindow;
if (scrolled != null)
scrolled.SetPolicy (Gtk.PolicyType.Never, Gtk.PolicyType.Never);
min_zoom = ComputeMinZoom (upscale);
this.upscale = upscale;
Fit = true;
DoZoom (MIN_ZOOM, Allocation.Width / 2, Allocation.Height / 2);
if (scrolled != null) {
ThreadAssist.ProxyToMain (() => {
scrolled.SetPolicy (Gtk.PolicyType.Automatic, Gtk.PolicyType.Automatic);
});
}
}
public Point WindowCoordsToImage (Point win)
{
if (Pixbuf == null)
return Point.Zero;
int x_offset = scaled_width < Allocation.Width ? (int)(Allocation.Width - scaled_width) / 2 : -XOffset;
int y_offset = scaled_height < Allocation.Height ? (int)(Allocation.Height - scaled_height) / 2 : -YOffset;
win.X = Clamp (win.X - x_offset, 0, (int)scaled_width - 1);
win.Y = Clamp (win.Y - y_offset, 0, (int)scaled_height - 1);
win = PixbufUtils.TransformOrientation ((int)scaled_width, (int)scaled_height, win, PixbufUtils.ReverseTransformation (pixbuf_orientation));
return new Point ((int) Math.Floor (win.X * (double)(((int)PixbufOrientation <= 4 ? Pixbuf.Width : Pixbuf.Height) - 1) / (double)(scaled_width - 1) + .5),
(int) Math.Floor (win.Y * (double)(((int)PixbufOrientation <= 4 ? Pixbuf.Height : Pixbuf.Width) - 1) / (double)(scaled_height - 1) + .5));
}
public Point ImageCoordsToWindow (Point image)
{
if (Pixbuf == null)
return Point.Zero;
image = PixbufUtils.TransformOrientation (Pixbuf.Width, Pixbuf.Height, image, pixbuf_orientation);
int x_offset = scaled_width < Allocation.Width ? (int)(Allocation.Width - scaled_width) / 2 : -XOffset;
int y_offset = scaled_height < Allocation.Height ? (int)(Allocation.Height - scaled_height) / 2 : -YOffset;
return new Point ((int) Math.Floor (image.X * (double) (scaled_width - 1) / (((int)pixbuf_orientation <= 4 ? Pixbuf.Width : Pixbuf.Height) - 1) + 0.5) + x_offset,
(int) Math.Floor (image.Y * (double) (scaled_height - 1) / (((int)pixbuf_orientation <= 4 ? Pixbuf.Height : Pixbuf.Width) - 1) + 0.5) + y_offset);
}
public Rectangle ImageCoordsToWindow (Rectangle image)
{
if (Pixbuf == null)
return Gdk.Rectangle.Zero;
image = PixbufUtils.TransformOrientation (Pixbuf.Width, Pixbuf.Height, image, pixbuf_orientation);
int x_offset = scaled_width < Allocation.Width ? (int)(Allocation.Width - scaled_width) / 2 : -XOffset;
int y_offset = scaled_height < Allocation.Height ? (int)(Allocation.Height - scaled_height) / 2 : -YOffset;
Gdk.Rectangle win = Gdk.Rectangle.Zero;
win.X = (int) Math.Floor (image.X * (double) (scaled_width - 1) / (((int)pixbuf_orientation <= 4 ? Pixbuf.Width : Pixbuf.Height) - 1) + 0.5) + x_offset;
win.Y = (int) Math.Floor (image.Y * (double) (scaled_height - 1) / (((int)pixbuf_orientation <= 4 ? Pixbuf.Height : Pixbuf.Width) - 1) + 0.5) + y_offset;
win.Width = (int) Math.Floor ((image.X + image.Width) * (double) (scaled_width - 1) / (((int)pixbuf_orientation <= 4 ? Pixbuf.Width : Pixbuf.Height) - 1) + 0.5) - win.X + x_offset;
win.Height = (int) Math.Floor ((image.Y + image.Height) * (double) (scaled_height - 1) / (((int)pixbuf_orientation <= 4 ? Pixbuf.Height : Pixbuf.Width) - 1) + 0.5) - win.Y + y_offset;
return win;
}
public event EventHandler ZoomChanged;
public event EventHandler SelectionChanged;
#endregion
#region protected API
protected static double ZOOM_FACTOR = 1.1;
protected double max_zoom = 10.0;
protected double MAX_ZOOM {
get { return max_zoom; }
}
protected double min_zoom = 0.1;
protected double MIN_ZOOM {
get { return min_zoom; }
}
bool upscale;
protected void ZoomFit ()
{
ZoomFit (upscale);
}
protected virtual void ApplyColorTransform (Pixbuf pixbuf)
{
}
#endregion
#region GtkWidgetry
protected override void OnRealized ()
{
SetFlag (Gtk.WidgetFlags.Realized);
GdkWindow = new Gdk.Window (ParentWindow,
new Gdk.WindowAttr {
WindowType = Gdk.WindowType.Child,
X = Allocation.X,
Y = Allocation.Y,
Width = Allocation.Width,
Height = Allocation.Height,
Wclass = Gdk.WindowClass.InputOutput,
Visual = ParentWindow.Visual,
Colormap = ParentWindow.Colormap,
Mask = this.Events
| EventMask.ExposureMask
| EventMask.ButtonPressMask
| EventMask.ButtonReleaseMask
| EventMask.PointerMotionMask
| EventMask.PointerMotionHintMask
| EventMask.ScrollMask
| EventMask.KeyPressMask
| EventMask.LeaveNotifyMask
},
Gdk.WindowAttributesType.X | Gdk.WindowAttributesType.Y |
Gdk.WindowAttributesType.Visual | Gdk.WindowAttributesType.Colormap);
GdkWindow.SetBackPixmap (null, false);
GdkWindow.UserData = Handle;
Style.Attach (GdkWindow);
Style.SetBackground (GdkWindow, Gtk.StateType.Normal);
OnRealizedChildren ();
}
protected override void OnMapped ()
{
SetFlag (Gtk.WidgetFlags.Mapped);
OnMappedChildren ();
GdkWindow.Show ();
}
protected override void OnSizeRequested (ref Gtk.Requisition requisition)
{
requisition.Width = requisition.Height = 0;
OnSizeRequestedChildren ();
}
protected override void OnSizeAllocated (Gdk.Rectangle allocation)
{
min_zoom = ComputeMinZoom (upscale);
if (Fit || zoom < MIN_ZOOM)
zoom = MIN_ZOOM;
// Since this affects the zoom_scale we should alert it
ZoomChanged?.Invoke (this, EventArgs.Empty);
ComputeScaledSize ();
OnSizeAllocatedChildren ();
if (IsRealized) {
GdkWindow.MoveResize (allocation.X, allocation.Y, allocation.Width, allocation.Height);
}
if (XOffset > Hadjustment.Upper - Hadjustment.PageSize)
ScrollTo ((int)(Hadjustment.Upper - Hadjustment.PageSize), YOffset, false);
if (YOffset > Vadjustment.Upper - Vadjustment.PageSize)
ScrollTo (XOffset, (int)(Vadjustment.Upper - Vadjustment.PageSize), false);
base.OnSizeAllocated (allocation);
if (Fit)
ZoomFit (upscale);
}
protected override bool OnExposeEvent (Gdk.EventExpose evnt)
{
if (evnt.Window != GdkWindow)
return false;
foreach (Rectangle area in evnt.Region.GetRectangles ())
{
var p_area = new Rectangle (Math.Max (0, area.X), Math.Max (0, area.Y),
Math.Min (Allocation.Width, area.Width), Math.Min (Allocation.Height, area.Height));
if (p_area == Rectangle.Zero)
continue;
//draw synchronously if InterpType.Nearest or zoom 1:1
if (Interpolation == InterpType.Nearest || zoom == 1.0) {
PaintRectangle (p_area, InterpType.Nearest);
continue;
}
//Do this on idle ???
PaintRectangle (p_area, Interpolation);
}
if (can_select)
OnSelectionExposeEvent (evnt);
return true;
}
protected override void OnSetScrollAdjustments (Gtk.Adjustment hadjustment, Gtk.Adjustment vadjustment)
{
if (hadjustment == null)
hadjustment = new Gtk.Adjustment (0, 0, 0, 0, 0, 0);
if (vadjustment == null)
vadjustment = new Gtk.Adjustment (0, 0, 0, 0, 0, 0);
bool need_change = false;
if (Hadjustment != hadjustment) {
Hadjustment = hadjustment;
Hadjustment.Upper = scaled_width;
Hadjustment.ValueChanged += HandleAdjustmentsValueChanged;
need_change = true;
}
if (Vadjustment != vadjustment) {
Vadjustment = vadjustment;
Vadjustment.Upper = scaled_height;
Vadjustment.ValueChanged += HandleAdjustmentsValueChanged;
need_change = true;
}
if (need_change)
HandleAdjustmentsValueChanged (this, EventArgs.Empty);
}
protected override bool OnButtonPressEvent (EventButton evnt)
{
bool handled = false;
if (!HasFocus)
GrabFocus ();
if (PointerMode == PointerMode.None)
return false;
handled = handled || OnPanButtonPressEvent (evnt);
if (can_select)
handled = handled || OnSelectionButtonPressEvent (evnt);
return handled || base.OnButtonPressEvent (evnt);
}
protected override bool OnButtonReleaseEvent (EventButton evnt)
{
bool handled = false;
handled = handled || OnPanButtonReleaseEvent (evnt);
if (can_select)
handled = handled || OnSelectionButtonReleaseEvent (evnt);
return handled || base.OnButtonReleaseEvent (evnt);
}
protected override bool OnMotionNotifyEvent (EventMotion evnt)
{
bool handled = false;
handled = handled || OnPanMotionNotifyEvent (evnt);
if (can_select)
handled = handled || OnSelectionMotionNotifyEvent (evnt);
return handled || base.OnMotionNotifyEvent (evnt);
}
protected override bool OnScrollEvent (EventScroll evnt)
{
if ((evnt.State & ModifierType.ShiftMask) == 0) {//no shift, let's zoom
ZoomAboutPoint ((evnt.Direction == ScrollDirection.Up || evnt.Direction == ScrollDirection.Right) ? ZOOM_FACTOR : 1.0 / ZOOM_FACTOR,
(int)evnt.X, (int)evnt.Y);
return true;
}
int x_incr = (int)Hadjustment.PageIncrement / 4;
int y_incr = (int)Vadjustment.PageIncrement / 4;
if ((evnt.State & ModifierType.ControlMask) == 0) {//no control scroll
ScrollBy ((evnt.Direction == ScrollDirection.Left) ? -x_incr : (evnt.Direction == ScrollDirection.Right) ? x_incr : 0,
(evnt.Direction == ScrollDirection.Up) ? -y_incr : (evnt.Direction == ScrollDirection.Down) ? y_incr : 0);
return true;
}
//invert x and y for scrolling
ScrollBy ((evnt.Direction == ScrollDirection.Up) ? -y_incr : (evnt.Direction == ScrollDirection.Down) ? y_incr : 0,
(evnt.Direction == ScrollDirection.Left) ? -x_incr : (evnt.Direction == ScrollDirection.Right) ? x_incr : 0);
return true;
}
protected override bool OnKeyPressEvent (EventKey evnt)
{
if ((evnt.State & (ModifierType.Mod1Mask | ModifierType.ControlMask)) != 0)
return base.OnKeyPressEvent (evnt);
bool handled = true;
int x, y;
Gdk.ModifierType type;
switch(evnt.Key) {
case Gdk.Key.Up:
case Gdk.Key.KP_Up:
case Gdk.Key.k:
case Gdk.Key.K:
ScrollBy (0, -Vadjustment.StepIncrement);
break;
case Gdk.Key.Down:
case Gdk.Key.KP_Down:
case Gdk.Key.j:
case Gdk.Key.J:
ScrollBy (0, Vadjustment.StepIncrement);
break;
case Gdk.Key.Left:
case Gdk.Key.KP_Left:
case Gdk.Key.h:
case Gdk.Key.H:
ScrollBy (-Hadjustment.StepIncrement, 0);
break;
case Gdk.Key.Right:
case Gdk.Key.KP_Right:
case Gdk.Key.l:
case Gdk.Key.L:
ScrollBy (Hadjustment.StepIncrement, 0);
break;
case Gdk.Key.equal:
case Gdk.Key.plus:
case Gdk.Key.KP_Add:
ZoomIn ();
break;
case Gdk.Key.minus:
case Gdk.Key.KP_Subtract:
ZoomOut ();
break;
case Gdk.Key.Key_0:
case Gdk.Key.KP_0:
ZoomFit ();
break;
case Gdk.Key.KP_1:
case Gdk.Key.Key_1:
GdkWindow.GetPointer (out x, out y, out type);
DoZoom (1.0, x, y);
break;
case Gdk.Key.Key_2:
case Gdk.Key.KP_2:
GdkWindow.GetPointer (out x, out y, out type);
DoZoom (2.0, x, y);
break;
default:
handled = false;
break;
}
return handled || base.OnKeyPressEvent (evnt);
}
#endregion
#region private painting, zooming and misc
int XOffset { get; set;}
int YOffset { get; set;}
/// <summary>
/// Zoom to the given factor.
/// </summary>
/// <param name='zoom'>
/// A zoom factor, expressed as a double.
/// </param>
/// <param name='x'>
/// The point of the viewport around which to zoom.
/// </param>
/// <param name='y'>
/// The point of the viewport around which to zoom.
/// </param>
void DoZoom (double zoom, int x, int y)
{
Fit = zoom == MIN_ZOOM;
if (zoom == this.zoom || Math.Abs (this.zoom - zoom) < Double.Epsilon) {
// Don't recalculate if the zoom factor stays the same.
return;
}
// Clamp the zoom factor within the [ MIN_ZOOM , MAX_ZOOM ] interval.
zoom = Math.Max (Math.Min (zoom, MAX_ZOOM), MIN_ZOOM);
this.zoom = zoom;
int x_offset = scaled_width < Allocation.Width ? (int)(Allocation.Width - scaled_width) / 2 : -XOffset;
int y_offset = scaled_height < Allocation.Height ? (int)(Allocation.Height - scaled_height) / 2 : -YOffset;
double x_anchor = (double)(x - x_offset) / (double)scaled_width;
double y_anchor = (double)(y - y_offset) / (double)scaled_height;
ComputeScaledSize ();
AdjustmentsChanged -= ScrollToAdjustments;
if (scaled_width < Allocation.Width)
Hadjustment.Value = XOffset = 0;
else
Hadjustment.Value = XOffset = Clamp ((int)(x_anchor * scaled_width - x), 0, (int)(Hadjustment.Upper - Hadjustment.PageSize));
if (scaled_height < Allocation.Height)
Vadjustment.Value = YOffset = 0;
else
Vadjustment.Value = YOffset = Clamp ((int)(y_anchor * scaled_height - y), 0, (int)(Vadjustment.Upper - Vadjustment.PageSize));
AdjustmentsChanged += ScrollToAdjustments;
ZoomChanged?.Invoke (this, EventArgs.Empty);
QueueDraw ();
}
void PaintBackground (Rectangle backgound, Rectangle area)
{
GdkWindow.DrawRectangle (Style.BackgroundGCs [(int)StateType.Normal], true, area);
}
void PaintRectangle (Rectangle area, InterpType interpolation)
{
int x_offset = scaled_width < Allocation.Width ? (int)(Allocation.Width - scaled_width) / 2 : -XOffset;
int y_offset = scaled_height < Allocation.Height ? (int)(Allocation.Height - scaled_height) / 2 : -YOffset;
//Draw background
if (y_offset > 0) //Top
PaintBackground (new Rectangle (0, 0, Allocation.Width, y_offset), area);
if (x_offset > 0) //Left
PaintBackground (new Rectangle (0, y_offset, x_offset, (int)scaled_height), area);
if (x_offset >= 0) //Right
PaintBackground (new Rectangle (x_offset + (int)scaled_width, y_offset, Allocation.Width - x_offset - (int)scaled_width, (int)scaled_height), area);
if (y_offset >= 0) //Bottom
PaintBackground (new Rectangle (0, y_offset + (int)scaled_height, Allocation.Width, Allocation.Height - y_offset - (int)scaled_height), area);
if (Pixbuf == null)
return;
area.Intersect (new Rectangle (x_offset, y_offset, (int)scaled_width, (int)scaled_height));
if (area.Width <= 0 || area.Height <= 0)
return;
//Short circuit for 1:1 zoom
if (zoom == 1.0 &&
!Pixbuf.HasAlpha &&
Pixbuf.BitsPerSample == 8 &&
pixbuf_orientation == ImageOrientation.TopLeft) {
GdkWindow.DrawPixbuf (Style.BlackGC,
Pixbuf,
area.X - x_offset, area.Y - y_offset,
area.X, area.Y,
area.Width, area.Height,
RgbDither.Max,
area.X - x_offset, area.Y - y_offset);
return;
}
Rectangle pixbuf_area = PixbufUtils.TransformOrientation ((int)scaled_width,
(int)scaled_height,
new Rectangle ((area.X - x_offset),
(area.Y - y_offset),
area.Width,
area.Height),
PixbufUtils.ReverseTransformation (pixbuf_orientation));
using (Pixbuf temp_pixbuf = new Pixbuf (Colorspace.Rgb, false, 8, pixbuf_area.Width, pixbuf_area.Height)) {
if (Pixbuf.HasAlpha)
temp_pixbuf.Fill (0x00000000);
Pixbuf.CompositeColor (temp_pixbuf,
0, 0,
pixbuf_area.Width, pixbuf_area.Height,
-pixbuf_area.X, -pixbuf_area.Y,
zoom, zoom,
zoom == 1.0 ? InterpType.Nearest : interpolation, 255,
pixbuf_area.X, pixbuf_area.Y,
CheckPattern.CheckSize, CheckPattern.Color1, CheckPattern.Color2);
ApplyColorTransform (temp_pixbuf);
using (var dest_pixbuf = PixbufUtils.TransformOrientation (temp_pixbuf, pixbuf_orientation)) {
GdkWindow.DrawPixbuf (Style.BlackGC,
dest_pixbuf,
0, 0,
area.X, area.Y,
area.Width, area.Height,
RgbDither.Max,
area.X - x_offset, area.Y - y_offset);
}
}
}
uint scaled_width, scaled_height;
void ComputeScaledSize ()
{
if (Pixbuf == null)
scaled_width = scaled_height = 0;
else {
double width;
double height;
if ((int)pixbuf_orientation <= 4 ) { //TopLeft, TopRight, BottomRight, BottomLeft
width = Pixbuf.Width;
height = Pixbuf.Height;
} else { //LeftTop, RightTop, RightBottom, LeftBottom
width = Pixbuf.Height;
height = Pixbuf.Width;
}
scaled_width = (uint)Math.Floor (width * Zoom + .5);
scaled_height = (uint)Math.Floor (height * Zoom + .5);
}
Hadjustment.PageSize = Math.Min (scaled_width, Allocation.Width);
Hadjustment.PageIncrement = scaled_width * .9;
Hadjustment.StepIncrement = 32;
Hadjustment.Upper = scaled_width;
Hadjustment.Lower = 0;
Vadjustment.PageSize = Math.Min (scaled_height, Allocation.Height);
Vadjustment.PageIncrement = scaled_height * .9;
Vadjustment.StepIncrement = 32;
Vadjustment.Upper = scaled_height;
Vadjustment.Lower = 0;
}
event EventHandler AdjustmentsChanged;
void HandleAdjustmentsValueChanged (object sender, EventArgs e)
{
AdjustmentsChanged?.Invoke (this, EventArgs.Empty);
}
void ScrollToAdjustments (object sender, EventArgs e)
{
ScrollTo ((int)Hadjustment.Value, (int)Vadjustment.Value, false);
}
void ScrollTo (int x, int y, bool change_adjustments)
{
x = Clamp (x, 0, (int)(Hadjustment.Upper - Hadjustment.PageSize));
y = Clamp (y, 0, (int)(Vadjustment.Upper - Vadjustment.PageSize));
int xof = x - XOffset;
int yof = y - YOffset;
XOffset = x;
YOffset = y;
if (IsRealized) {
GdkWindow.Scroll (-xof, -yof);
GdkWindow.ProcessUpdates (true);
}
if (change_adjustments) {
AdjustmentsChanged -= ScrollToAdjustments;
Hadjustment.Value = XOffset;
Vadjustment.Value = YOffset;
AdjustmentsChanged += ScrollToAdjustments;
}
}
void ScrollBy (double x, double y)
{
ScrollTo ((int)(XOffset + x), (int)(YOffset + y), true);
}
static int Clamp (int value, int min, int max)
{
return Math.Min (Math.Max (value, min), max);
}
double ComputeMinZoom (bool upscale)
{
if (Pixbuf == null)
return 0.1;
double width;
double height;
if ((int)pixbuf_orientation <= 4 ) { //TopLeft, TopRight, BottomRight, BottomLeft
width = Pixbuf.Width;
height = Pixbuf.Height;
} else { //LeftTop, RightTop, RightBottom, LeftBottom
width = Pixbuf.Height;
height = Pixbuf.Width;
}
if (upscale)
return Math.Min ((double)Allocation.Width / width,
(double)Allocation.Height / height);
return Math.Min (1.0,
Math.Min ((double)Allocation.Width / width,
(double)Allocation.Height / height));
}
#endregion
#region selection
bool OnSelectionExposeEvent (EventExpose evnt)
{
if (selection == Rectangle.Zero)
return false;
Rectangle win_selection = ImageCoordsToWindow (selection);
using (var evnt_region = evnt.Region.Copy ()) {
using (Region r = new Region ()) {
r.UnionWithRect (win_selection);
evnt_region.Subtract (r);
}
using (Cairo.Context ctx = CairoHelper.Create (GdkWindow)) {
ctx.SetSourceRGBA (.5, .5, .5, .7);
CairoHelper.Region (ctx, evnt_region);
ctx.Fill ();
}
}
return true;
}
enum DragMode {
None,
Move,
Extend,
}
const int SELECTION_SNAP_DISTANCE = 8;
DragMode GetDragMode (int x, int y)
{
Rectangle win_selection = ImageCoordsToWindow (selection);
if (Rectangle.Inflate (win_selection, -SELECTION_SNAP_DISTANCE, -SELECTION_SNAP_DISTANCE).Contains (x, y))
return DragMode.Move;
if (Rectangle.Inflate (win_selection, SELECTION_SNAP_DISTANCE, SELECTION_SNAP_DISTANCE).Contains (x, y))
return DragMode.Extend;
return DragMode.None;
}
bool is_dragging_selection = false;
bool fixed_height = false;
bool fixed_width = false;
bool is_moving_selection = false;
Point selection_anchor = Point.Zero;
bool OnSelectionButtonPressEvent (EventButton evnt)
{
if (evnt.Button != 1)
return false;
if (evnt.Type == EventType.TwoButtonPress) {
is_dragging_selection = false;
is_moving_selection = false;
return false;
}
Point img = WindowCoordsToImage (new Point ((int)evnt.X, (int)evnt.Y));
switch (GetDragMode ((int)evnt.X, (int)evnt.Y)) {
case DragMode.None:
is_dragging_selection = true;
PointerMode = PointerMode.Select;
Selection = Rectangle.Zero;
selection_anchor = img;
break;
case DragMode.Extend:
Rectangle win_sel = ImageCoordsToWindow (Selection);
is_dragging_selection = true;
if (Math.Abs (win_sel.X - evnt.X) < SELECTION_SNAP_DISTANCE &&
Math.Abs (win_sel.Y - evnt.Y) < SELECTION_SNAP_DISTANCE) { //TopLeft
selection_anchor = new Point (Selection.X + Selection.Width, Selection.Y + Selection.Height);
} else if (Math.Abs (win_sel.X + win_sel.Width - evnt.X) < SELECTION_SNAP_DISTANCE &&
Math.Abs (win_sel.Y - evnt.Y) < SELECTION_SNAP_DISTANCE) { //TopRight
selection_anchor = new Point (Selection.X, Selection.Y + Selection.Height);
} else if (Math.Abs (win_sel.X - evnt.X) < SELECTION_SNAP_DISTANCE &&
Math.Abs (win_sel.Y + win_sel.Height - evnt.Y) < SELECTION_SNAP_DISTANCE) { //BottomLeft
selection_anchor = new Point (Selection.X + Selection.Width, Selection.Y);
} else if (Math.Abs (win_sel.X + win_sel.Width - evnt.X) < SELECTION_SNAP_DISTANCE &&
Math.Abs (win_sel.Y + win_sel.Height - evnt.Y) < SELECTION_SNAP_DISTANCE) { //BottomRight
selection_anchor = new Point (Selection.X, Selection.Y);
} else if (Math.Abs (win_sel.X - evnt.X) < SELECTION_SNAP_DISTANCE) { //Left
selection_anchor = new Point (Selection.X + Selection.Width, Selection.Y);
fixed_height = true;
} else if (Math.Abs (win_sel.X + win_sel.Width - evnt.X) < SELECTION_SNAP_DISTANCE) { //Right
selection_anchor = new Point (Selection.X, Selection.Y);
fixed_height = true;
} else if (Math.Abs (win_sel.Y - evnt.Y) < SELECTION_SNAP_DISTANCE) { //Top
selection_anchor = new Point (Selection.X, Selection.Y + Selection.Height);
fixed_width = true;
} else if (Math.Abs (win_sel.Y + win_sel.Height - evnt.Y) < SELECTION_SNAP_DISTANCE) { //Bottom
selection_anchor = new Point (Selection.X, Selection.Y);
fixed_width = true;
} else {
fixed_width = fixed_height = false;
is_dragging_selection = false;
}
break;
case DragMode.Move:
is_moving_selection = true;
selection_anchor = img;
SelectionSetPointer ((int)evnt.X, (int)evnt.Y);
break;
}
return true;
}
bool OnSelectionButtonReleaseEvent (EventButton evnt)
{
if (evnt.Button != 1)
return false;
is_dragging_selection = false;
is_moving_selection = false;
fixed_width = fixed_height = false;
SelectionSetPointer ((int)evnt.X, (int)evnt.Y);
return true;
}
void SelectionSetPointer (int x, int y)
{
if (is_moving_selection)
GdkWindow.Cursor = new Cursor (CursorType.Crosshair);
else {
switch (GetDragMode (x, y)) {
case DragMode.Move:
GdkWindow.Cursor = new Cursor (CursorType.Hand1);
break;
default:
GdkWindow.Cursor = null;
break;
case DragMode.Extend:
Rectangle win_sel = ImageCoordsToWindow (Selection);
if (Math.Abs (win_sel.X - x) < SELECTION_SNAP_DISTANCE &&
Math.Abs (win_sel.Y - y) < SELECTION_SNAP_DISTANCE) { //TopLeft
GdkWindow.Cursor = new Cursor (CursorType.TopLeftCorner);
} else if (Math.Abs (win_sel.X + win_sel.Width - x) < SELECTION_SNAP_DISTANCE &&
Math.Abs (win_sel.Y - y) < SELECTION_SNAP_DISTANCE) { //TopRight
GdkWindow.Cursor = new Cursor (CursorType.TopRightCorner);
} else if (Math.Abs (win_sel.X - x) < SELECTION_SNAP_DISTANCE &&
Math.Abs (win_sel.Y + win_sel.Height - y) < SELECTION_SNAP_DISTANCE) { //BottomLeft
GdkWindow.Cursor = new Cursor (CursorType.BottomLeftCorner);
} else if (Math.Abs (win_sel.X + win_sel.Width - x) < SELECTION_SNAP_DISTANCE &&
Math.Abs (win_sel.Y + win_sel.Height - y) < SELECTION_SNAP_DISTANCE) { //BottomRight
GdkWindow.Cursor = new Cursor (CursorType.BottomRightCorner);
} else if (Math.Abs (win_sel.X - x) < SELECTION_SNAP_DISTANCE) { //Left
GdkWindow.Cursor = new Cursor (CursorType.LeftSide);
} else if (Math.Abs (win_sel.X + win_sel.Width - x) < SELECTION_SNAP_DISTANCE) { //Right
GdkWindow.Cursor = new Cursor (CursorType.RightSide);
} else if (Math.Abs (win_sel.Y - y) < SELECTION_SNAP_DISTANCE) { //Top
GdkWindow.Cursor = new Cursor (CursorType.TopSide);
} else if (Math.Abs (win_sel.Y + win_sel.Height - y) < SELECTION_SNAP_DISTANCE) { //Bottom
GdkWindow.Cursor = new Cursor (CursorType.BottomSide);
}
break;
}
}
}
const int SELECTION_THRESHOLD = 5;
bool OnSelectionMotionNotifyEvent (EventMotion evnt)
{
int x, y;
ModifierType mod;
if (evnt.IsHint)
GdkWindow.GetPointer (out x, out y, out mod);
else {
x = (int)evnt.X;
y = (int)evnt.Y;
}
Point img = WindowCoordsToImage (new Point (x, y));
if (is_dragging_selection) {
Point win_anchor = ImageCoordsToWindow (selection_anchor);
if (Selection == Rectangle.Zero &&
Math.Abs (evnt.X - win_anchor.X) < SELECTION_THRESHOLD &&
Math.Abs (evnt.Y - win_anchor.Y) < SELECTION_THRESHOLD) {
SelectionSetPointer (x, y);
return true;
}
if (selection_xy_ratio == 0)
Selection = new Rectangle (fixed_width ? Selection.X : Math.Min (selection_anchor.X, img.X),
fixed_height ? Selection.Y : Math.Min (selection_anchor.Y, img.Y),
fixed_width ? Selection.Width : Math.Abs (selection_anchor.X - img.X),
fixed_height ? Selection.Height : Math.Abs (selection_anchor.Y - img.Y));
else
Selection = ConstrainSelection (new Rectangle (Math.Min (selection_anchor.X, img.X),
Math.Min (selection_anchor.Y, img.Y),
Math.Abs (selection_anchor.X - img.X),
Math.Abs (selection_anchor.Y - img.Y)),
fixed_width, fixed_height);
SelectionSetPointer (x, y);
return true;
}
if (is_moving_selection) {
Selection = new Rectangle (Clamp (Selection.X + img.X - selection_anchor.X, 0, Pixbuf.Width - Selection.Width),
Clamp (Selection.Y + img.Y - selection_anchor.Y, 0, Pixbuf.Height - Selection.Height),
Selection.Width, Selection.Height);
selection_anchor = img;
SelectionSetPointer (x, y);
return true;
}
SelectionSetPointer (x, y);
return true;
}
Rectangle ConstrainSelection (Rectangle sel, bool fixed_width, bool fixed_height)
{
double constrain = selection_xy_ratio;
if ((double)sel.Width > (double)sel.Height && selection_xy_ratio < 1 ||
(double)sel.Width < (double)sel.Height && selection_xy_ratio > 1)
constrain = 1.0 / constrain;
double ratio = (double)sel.Width / (double)sel.Height;
int height = sel.Height;
int width = sel.Width;
if (ratio > constrain) {
height = (int)((double)sel.Width / constrain);
if (height > Pixbuf.Height) {
height = sel.Height;
width = (int)(height * constrain);
}
} else {
width = (int)(height * constrain);
if (width > Pixbuf.Width) {
width = sel.Width;
height = (int)((double)width / constrain);
}
}
return new Rectangle (sel.X + width < Pixbuf.Width ? sel.X : Pixbuf.Width - width,
sel.Y + height < Pixbuf.Height ? sel.Y : Pixbuf.Height - height,
width, height);
}
#endregion
}
}
| |
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 WebTextEditor.Areas.HelpPage.ModelDescriptions;
using WebTextEditor.Areas.HelpPage.Models;
namespace WebTextEditor.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 company="Simply Code Ltd.">
// Copyright (c) Simply Code Ltd. All rights reserved.
// Licensed under the MIT License.
// See LICENSE file in the project root for full license information.
// </copyright>
namespace PackIt.Plan
{
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using PackIt.Helpers.Enums;
/// <summary> A stage. </summary>
[ExcludeFromCodeCoverage]
public class Stage
{
/// <summary>
/// Initialises a new instance of the <see cref="Stage" /> class.
/// </summary>
public Stage()
{
this.Shape = ShapeType.Rectangle;
this.Form = FormType.Box;
this.Limits = new List<Limit>();
}
/// <summary> Gets or sets the Stage level. </summary>
///
/// <value> The Stage level. </value>
public StageLevel StageLevel { get; set; }
/// <summary> Gets or sets the collation. </summary>
///
/// <value> The collation. </value>
public long Collation { get; set; }
/// <summary> Gets or sets the draw offset. </summary>
///
/// <value> The draw offset. </value>
public long DrawOffset { get; set; }
/// <summary> Gets or sets the shape. </summary>
///
/// <value> The shape. </value>
public ShapeType Shape { get; set; }
/// <summary> Gets or sets the form. </summary>
///
/// <value> The form. </value>
public FormType Form { get; set; }
/// <summary> Gets or sets the shape parameter 0. </summary>
///
/// <value> The shape parameter 0. </value>
public double ShapeParameter0 { get; set; }
/// <summary> Gets or sets the shape parameter 1. </summary>
///
/// <value> The shape parameter 1. </value>
public double ShapeParameter1 { get; set; }
/// <summary> Gets or sets the shape parameter 2. </summary>
///
/// <value> The shape parameter 2. </value>
public double ShapeParameter2 { get; set; }
/// <summary> Gets or sets the shape parameter 3. </summary>
///
/// <value> The shape parameter 3. </value>
public double ShapeParameter3 { get; set; }
/// <summary> Gets or sets the shape parameter 4. </summary>
///
/// <value> The shape parameter 4. </value>
public double ShapeParameter4 { get; set; }
/// <summary> Gets or sets the shape parameter 5. </summary>
///
/// <value> The shape parameter 5. </value>
public double ShapeParameter5 { get; set; }
/// <summary> Gets or sets the shape parameter 6. </summary>
///
/// <value> The shape parameter 6. </value>
public double ShapeParameter6 { get; set; }
/// <summary> Gets or sets the shape parameter 7. </summary>
///
/// <value> The shape parameter 7. </value>
public double ShapeParameter7 { get; set; }
/// <summary> Gets or sets the form parameter 0. </summary>
///
/// <value> The form parameter 0. </value>
public double FormParameter0 { get; set; }
/// <summary> Gets or sets the form parameter 1. </summary>
///
/// <value> The form parameter 1. </value>
public double FormParameter1 { get; set; }
/// <summary> Gets or sets the form parameter 2. </summary>
///
/// <value> The form parameter 2. </value>
public double FormParameter2 { get; set; }
/// <summary> Gets or sets the form parameter 3. </summary>
///
/// <value> The form parameter 3. </value>
public double FormParameter3 { get; set; }
/// <summary> Gets or sets the form parameter 4. </summary>
///
/// <value> The form parameter 4. </value>
public double FormParameter4 { get; set; }
/// <summary> Gets or sets the form parameter 5. </summary>
///
/// <value> The form parameter 5. </value>
public double FormParameter5 { get; set; }
/// <summary> Gets or sets the form parameter 6. </summary>
///
/// <value> The form parameter 6. </value>
public double FormParameter6 { get; set; }
/// <summary> Gets or sets the form parameter 7. </summary>
///
/// <value> The form parameter 7. </value>
public double FormParameter7 { get; set; }
/// <summary> Gets or sets the density. </summary>
///
/// <value> The density. </value>
public double Density { get; set; }
/// <summary> Gets or sets the generator. </summary>
///
/// <value> The generator. </value>
public long Generator { get; set; }
/// <summary> Gets or sets the rotation. </summary>
///
/// <value> The rotation. </value>
public long Rotation { get; set; }
/// <summary> Gets or sets a value indicating whether the materials should be computed. </summary>
///
/// <value> True if compute materials, false if not. </value>
public bool ComputeMaterials { get; set; }
/// <summary> Gets or sets the sort. </summary>
///
/// <value> The sort. </value>
public long Sort { get; set; }
/// <summary> Gets or sets the breathing space x coordinate. </summary>
///
/// <value> The breathing space x coordinate. </value>
public double BreathingSpaceX { get; set; }
/// <summary> Gets or sets the breathing space y coordinate. </summary>
///
/// <value> The breathing space y coordinate. </value>
public double BreathingSpaceY { get; set; }
/// <summary> Gets or sets the breathing space z coordinate. </summary>
///
/// <value> The breathing space z coordinate. </value>
public double BreathingSpaceZ { get; set; }
/// <summary> Gets or sets the bulging x coordinate. </summary>
///
/// <value> The bulging x coordinate. </value>
public double BulgingX { get; set; }
/// <summary> Gets or sets the bulging y coordinate. </summary>
///
/// <value> The bulging y coordinate. </value>
public double BulgingY { get; set; }
/// <summary> Gets or sets the bulging z coordinate. </summary>
///
/// <value> The bulging z coordinate. </value>
public double BulgingZ { get; set; }
/// <summary> Gets or sets the percent minimum. </summary>
///
/// <value> The percent minimum. </value>
public double PercentMin { get; set; }
/// <summary> Gets or sets the percent maximum. </summary>
///
/// <value> The percent maximum. </value>
public double PercentMax { get; set; }
/// <summary> Gets or sets the load minimum. </summary>
///
/// <value> The load minimum. </value>
public long LoadMin { get; set; }
/// <summary> Gets or sets the load maximum. </summary>
///
/// <value> The load maximum. </value>
public long LoadMax { get; set; }
/// <summary> Gets or sets the load step. </summary>
///
/// <value> The load step. </value>
public long LoadStep { get; set; }
/// <summary> Gets or sets the tiers minimum. </summary>
///
/// <value> The tiers minimum. </value>
public long TiersMin { get; set; }
/// <summary> Gets or sets the tiers maximum. </summary>
///
/// <value> The tiers maximum. </value>
public long TiersMax { get; set; }
/// <summary> Gets or sets the tiers step. </summary>
///
/// <value> The tiers step. </value>
public long TiersStep { get; set; }
/// <summary> Gets or sets the per tier minimum. </summary>
///
/// <value> The per tier minimum. </value>
public long PerTierMin { get; set; }
/// <summary> Gets or sets the per tier maximum. </summary>
///
/// <value> The per tier maximum. </value>
public long PerTierMax { get; set; }
/// <summary> Gets or sets the per tier step. </summary>
///
/// <value> The per tier step. </value>
public long PerTierStep { get; set; }
/// <summary> Gets or sets the along side minimum. </summary>
///
/// <value> The along side minimum. </value>
public long AlongSideMin { get; set; }
/// <summary> Gets or sets the along side maximum. </summary>
///
/// <value> The along side maximum. </value>
public long AlongSideMax { get; set; }
/// <summary> Gets or sets the along side step. </summary>
///
/// <value> The along side step. </value>
public long AlongSideStep { get; set; }
/// <summary> Gets or sets the product minimum. </summary>
///
/// <value> The product minimum. </value>
public long ProductMin { get; set; }
/// <summary> Gets or sets the product maximum. </summary>
///
/// <value> The product maximum. </value>
public long ProductMax { get; set; }
/// <summary> Gets or sets the product step. </summary>
///
/// <value> The product step. </value>
public long ProductStep { get; set; }
/// <summary> Gets or sets the length of the external. </summary>
///
/// <value> The length of the external. </value>
public double ExternalLength { get; set; }
/// <summary> Gets or sets the external length minimum. </summary>
///
/// <value> The external length minimum. </value>
public double ExternalLengthMin { get; set; }
/// <summary> Gets or sets the external length maximum. </summary>
///
/// <value> The external length maximum. </value>
public double ExternalLengthMax { get; set; }
/// <summary> Gets or sets the external length step. </summary>
///
/// <value> The external length step. </value>
public double ExternalLengthStep { get; set; }
/// <summary> Gets or sets the external breadth. </summary>
///
/// <value> The external breadth. </value>
public double ExternalBreadth { get; set; }
/// <summary> Gets or sets the external breadth minimum. </summary>
///
/// <value> The external breadth minimum. </value>
public double ExternalBreadthMin { get; set; }
/// <summary> Gets or sets the external breadth maximum. </summary>
///
/// <value> The external breadth maximum. </value>
public double ExternalBreadthMax { get; set; }
/// <summary> Gets or sets the external breadth step. </summary>
///
/// <value> The external breadth step. </value>
public double ExternalBreadthStep { get; set; }
/// <summary> Gets or sets the height of the external. </summary>
///
/// <value> The height of the external. </value>
public double ExternalHeight { get; set; }
/// <summary> Gets or sets the external height minimum. </summary>
///
/// <value> The external height minimum. </value>
public double ExternalHeightMin { get; set; }
/// <summary> Gets or sets the external height maximum. </summary>
///
/// <value> The external height maximum. </value>
public double ExternalHeightMax { get; set; }
/// <summary> Gets or sets the external height step. </summary>
///
/// <value> The external height step. </value>
public double ExternalHeightStep { get; set; }
/// <summary> Gets or sets the external volume. </summary>
///
/// <value> The external volume. </value>
public double ExternalVolume { get; set; }
/// <summary> Gets or sets the external volume minimum. </summary>
///
/// <value> The external volume minimum. </value>
public double ExternalVolumeMin { get; set; }
/// <summary> Gets or sets the external volume maximum. </summary>
///
/// <value> The external volume maximum. </value>
public double ExternalVolumeMax { get; set; }
/// <summary> Gets or sets the external volume step. </summary>
///
/// <value> The external volume step. </value>
public double ExternalVolumeStep { get; set; }
/// <summary> Gets or sets the external length to breadth ratio. </summary>
///
/// <value> The external length to breadth ratio. </value>
public double ExternalLengthToBreadthRatio { get; set; }
/// <summary> Gets or sets the external length to breadth ratio minimum. </summary>
///
/// <value> The external length to breadth ratio minimum. </value>
public double ExternalLengthToBreadthRatioMin { get; set; }
/// <summary> Gets or sets the external length to breadth ratio maximum. </summary>
///
/// <value> The external length to breadth ratio maximum. </value>
public double ExternalLengthToBreadthRatioMax { get; set; }
/// <summary> Gets or sets the external length to breadth ratio step. </summary>
///
/// <value> The external length to breadth ratio step. </value>
public double ExternalLengthToBreadthRatioStep { get; set; }
/// <summary> Gets or sets the external length to height ratio. </summary>
///
/// <value> The external length to height ratio. </value>
public double ExternalLengthToHeightRatio { get; set; }
/// <summary> Gets or sets the external length to height ratio minimum. </summary>
///
/// <value> The external length to height ratio minimum. </value>
public double ExternalLengthToHeightRatioMin { get; set; }
/// <summary> Gets or sets the external length to height ratio maximum. </summary>
///
/// <value> The external length to height ratio maximum. </value>
public double ExternalLengthToHeightRatioMax { get; set; }
/// <summary> Gets or sets the external length to height ratio step. </summary>
///
/// <value> The external length to height ratio step. </value>
public double ExternalLengthToHeightRatioStep { get; set; }
/// <summary> Gets or sets the external angle. </summary>
///
/// <value> The external angle. </value>
public double ExternalAngle { get; set; }
/// <summary> Gets or sets the external angle minimum. </summary>
///
/// <value> The external angle minimum. </value>
public double ExternalAngleMin { get; set; }
/// <summary> Gets or sets the external angle maximum. </summary>
///
/// <value> The external angle maximum. </value>
public double ExternalAngleMax { get; set; }
/// <summary> Gets or sets the external angle step. </summary>
///
/// <value> The external angle step. </value>
public double ExternalAngleStep { get; set; }
/// <summary> Gets or sets the gross weight. </summary>
///
/// <value> The gross weight. </value>
public double GrossWeight { get; set; }
/// <summary> Gets or sets the gross weight minimum. </summary>
///
/// <value> The gross weight minimum. </value>
public double GrossWeightMin { get; set; }
/// <summary> Gets or sets the gross weight maximum. </summary>
///
/// <value> The gross weight maximum. </value>
public double GrossWeightMax { get; set; }
/// <summary> Gets or sets the gross weight step. </summary>
///
/// <value> The gross weight step. </value>
public double GrossWeightStep { get; set; }
/// <summary> Gets or sets the length of the internal. </summary>
///
/// <value> The length of the internal. </value>
public double InternalLength { get; set; }
/// <summary> Gets or sets the internal length minimum. </summary>
///
/// <value> The internal length minimum. </value>
public double InternalLengthMin { get; set; }
/// <summary> Gets or sets the internal length maximum. </summary>
///
/// <value> The internal length maximum. </value>
public double InternalLengthMax { get; set; }
/// <summary> Gets or sets the internal length step. </summary>
///
/// <value> The internal length step. </value>
public double InternalLengthStep { get; set; }
/// <summary> Gets or sets the internal breadth. </summary>
///
/// <value> The internal breadth. </value>
public double InternalBreadth { get; set; }
/// <summary> Gets or sets the internal breadth minimum. </summary>
///
/// <value> The internal breadth minimum. </value>
public double InternalBreadthMin { get; set; }
/// <summary> Gets or sets the internal breadth maximum. </summary>
///
/// <value> The internal breadth maximum. </value>
public double InternalBreadthMax { get; set; }
/// <summary> Gets or sets the internal breadth step. </summary>
///
/// <value> The internal breadth step. </value>
public double InternalBreadthStep { get; set; }
/// <summary> Gets or sets the height of the internal. </summary>
///
/// <value> The height of the internal. </value>
public double InternalHeight { get; set; }
/// <summary> Gets or sets the internal height minimum. </summary>
///
/// <value> The internal height minimum. </value>
public double InternalHeightMin { get; set; }
/// <summary> Gets or sets the internal height maximum. </summary>
///
/// <value> The internal height maximum. </value>
public double InternalHeightMax { get; set; }
/// <summary> Gets or sets the internal height step. </summary>
///
/// <value> The internal height step. </value>
public double InternalHeightStep { get; set; }
/// <summary> Gets or sets the internal volume. </summary>
///
/// <value> The internal volume. </value>
public double InternalVolume { get; set; }
/// <summary> Gets or sets the internal volume minimum. </summary>
///
/// <value> The internal volume minimum. </value>
public double InternalVolumeMin { get; set; }
/// <summary> Gets or sets the internal volume maximum. </summary>
///
/// <value> The internal volume maximum. </value>
public double InternalVolumeMax { get; set; }
/// <summary> Gets or sets the internal volume step. </summary>
///
/// <value> The internal volume step. </value>
public double InternalVolumeStep { get; set; }
/// <summary> Gets or sets the internal length to breadth ratio. </summary>
///
/// <value> The internal length to breadth ratio. </value>
public double InternalLengthToBreadthRatio { get; set; }
/// <summary> Gets or sets the internal length to breadth ratio minimum. </summary>
///
/// <value> The internal length to breadth ratio minimum. </value>
public double InternalLengthToBreadthRatioMin { get; set; }
/// <summary> Gets or sets the internal length to breadth ratio maximum. </summary>
///
/// <value> The internal length to breadth ratio maximum. </value>
public double InternalLengthToBreadthRatioMax { get; set; }
/// <summary> Gets or sets the internal length to breadth ratio step. </summary>
///
/// <value> The internal length to breadth ratio step. </value>
public double InternalLengthToBreadthRatioStep { get; set; }
/// <summary> Gets or sets the internal length to height ratio. </summary>
///
/// <value> The internal length to height ratio. </value>
public double InternalLengthToHeightRatio { get; set; }
/// <summary> Gets or sets the internal length to height ratio minimum. </summary>
///
/// <value> The internal length to height ratio minimum. </value>
public double InternalLengthToHeightRatioMin { get; set; }
/// <summary> Gets or sets the internal length to height ratio maximum. </summary>
///
/// <value> The internal length to height ratio maximum. </value>
public double InternalLengthToHeightRatioMax { get; set; }
/// <summary> Gets or sets the internal length to height ratio step. </summary>
///
/// <value> The internal length to height ratio step. </value>
public double InternalLengthToHeightRatioStep { get; set; }
/// <summary> Gets or sets the internal angle. </summary>
///
/// <value> The internal angle. </value>
public double InternalAngle { get; set; }
/// <summary> Gets or sets the internal angle minimum. </summary>
///
/// <value> The internal angle minimum. </value>
public double InternalAngleMin { get; set; }
/// <summary> Gets or sets the internal angle maximum. </summary>
///
/// <value> The internal angle maximum. </value>
public double InternalAngleMax { get; set; }
/// <summary> Gets or sets the internal angle step. </summary>
///
/// <value> The internal angle step. </value>
public double InternalAngleStep { get; set; }
/// <summary> Gets or sets the nett weight. </summary>
///
/// <value> The nett weight. </value>
public double NettWeight { get; set; }
/// <summary> Gets or sets the nett weight minimum. </summary>
///
/// <value> The nett weight minimum. </value>
public double NettWeightMin { get; set; }
/// <summary> Gets or sets the nett weight maximum. </summary>
///
/// <value> The nett weight maximum. </value>
public double NettWeightMax { get; set; }
/// <summary> Gets or sets the nett weight step. </summary>
///
/// <value> The nett weight step. </value>
public double NettWeightStep { get; set; }
/// <summary> Gets or sets the area utilisation minimum. </summary>
///
/// <value> The area utilisation minimum. </value>
public double AreaUtilisationMin { get; set; }
/// <summary> Gets or sets the area utilisation maximum. </summary>
///
/// <value> The area utilisation maximum. </value>
public double AreaUtilisationMax { get; set; }
/// <summary> Gets or sets the volume utilisation minimum. </summary>
///
/// <value> The volume utilisation minimum. </value>
public double VolumeUtilisationMin { get; set; }
/// <summary> Gets or sets the volume utilisation maximum. </summary>
///
/// <value> The volume utilisation maximum. </value>
public double VolumeUtilisationMax { get; set; }
/// <summary> Gets or sets the outer. </summary>
///
/// <value> The outer. </value>
public long Outer { get; set; }
/// <summary> Gets or sets the draw detail. </summary>
///
/// <value> The draw detail. </value>
public Detail DrawDetail { get; set; }
/// <summary> Gets or sets the length of the minimum block. </summary>
///
/// <value> The length of the minimum block. </value>
public long MinBlockLength { get; set; }
/// <summary> Gets or sets the minimum block breadth. </summary>
///
/// <value> The minimum block breadth. </value>
public long MinBlockBreadth { get; set; }
/// <summary> Gets or sets a value indicating whether the hands should be drawn. </summary>
///
/// <value> True if draw hands, false if not. </value>
public bool DrawHands { get; set; }
/// <summary> Gets or sets the collection of limits. </summary>
///
/// <value> Collection of limits. </value>
public IList<Limit> Limits { get; set; }
}
}
| |
using System.Diagnostics;
using DWORD = System.Int32;
using System.Threading;
using System;
namespace Community.CsharpSqlite
{
public partial class Sqlite3
{
/*
** 2007 August 14
**
** 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 the C functions that implement mutexes for win32
*************************************************************************
** 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-03-09 19:31:43 4ae453ea7be69018d8c16eb8dabe05617397dc4d
**
*************************************************************************
*/
//#include "sqliteInt.h"
/*
** The code in this file is only used if we are compiling multithreaded
** on a win32 system.
*/
#if SQLITE_MUTEX_W32
/*
** Each recursive mutex is an instance of the following structure.
*/
public partial class sqlite3_mutex
{
public Object mutex; /* Mutex controlling the lock */
public int id; /* Mutex type */
public int nRef; /* Number of enterances */
public DWORD owner; /* Thread holding this mutex */
#if SQLITE_DEBUG
public int trace; /* True to trace changes */
#endif
public sqlite3_mutex()
{
mutex = new Object();
}
public sqlite3_mutex( Mutex mutex, int id, int nRef, DWORD owner
#if SQLITE_DEBUG
, int trace
#endif
)
{
this.mutex = mutex;
this.id = id;
this.nRef = nRef;
this.owner = owner;
#if SQLITE_DEBUG
this.trace = 0;
#endif
}
};
//#define SQLITE_W32_MUTEX_INITIALIZER { 0 }
static Mutex SQLITE_W32_MUTEX_INITIALIZER = null;
#if SQLITE_DEBUG
//#define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0, 0L, (DWORD)0, 0 }
#else
//#define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0, 0L, (DWORD)0 }
#endif
/*
** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
** or WinCE. Return false (zero) for Win95, Win98, or WinME.
**
** Here is an interesting observation: Win95, Win98, and WinME lack
** the LockFileEx() API. But we can still statically link against that
** API as long as we don't call it win running Win95/98/ME. A call to
** this routine is used to determine if the host is Win95/98/ME or
** WinNT/2K/XP so that we will know whether or not we can safely call
** the LockFileEx() API.
**
** mutexIsNT() is only used for the TryEnterCriticalSection() API call,
** which is only available if your application was compiled with
** _WIN32_WINNT defined to a value >= 0x0400. Currently, the only
** call to TryEnterCriticalSection() is #ifdef'ed out, so #if
** this out as well.
*/
#if FALSE
#if SQLITE_OS_WINCE
//# define mutexIsNT() (1)
#else
static int mutexIsNT(void){
static int osType = 0;
if( osType==0 ){
OSVERSIONINFO sInfo;
sInfo.dwOSVersionInfoSize = sizeof(sInfo);
GetVersionEx(&sInfo);
osType = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
}
return osType==2;
}
#endif //* SQLITE_OS_WINCE */
#endif
#if SQLITE_DEBUG
/*
** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
** intended for use only inside Debug.Assert() statements.
*/
static bool winMutexHeld( sqlite3_mutex p )
{
return p.nRef != 0 && p.owner == GetCurrentThreadId();
}
static bool winMutexNotheld2( sqlite3_mutex p, DWORD tid )
{
return p.nRef == 0 || p.owner != tid;
}
static bool winMutexNotheld( sqlite3_mutex p )
{
DWORD tid = GetCurrentThreadId();
return winMutexNotheld2( p, tid );
}
#endif
/*
** Initialize and deinitialize the mutex subsystem.
*/
//No MACROS under C#; Cannot use SQLITE3_MUTEX_INITIALIZER,
static sqlite3_mutex[] winMutex_staticMutexes = new sqlite3_mutex[]{
new sqlite3_mutex( SQLITE_W32_MUTEX_INITIALIZER, 0, 0, (DWORD)0
#if SQLITE_DEBUG
, 0
#endif
),// SQLITE3_MUTEX_INITIALIZER,
new sqlite3_mutex( SQLITE_W32_MUTEX_INITIALIZER, 0, 0, (DWORD)0
#if SQLITE_DEBUG
, 0
#endif
),// SQLITE3_MUTEX_INITIALIZER,
new sqlite3_mutex( SQLITE_W32_MUTEX_INITIALIZER, 0, 0, (DWORD)0
#if SQLITE_DEBUG
, 0
#endif
),// SQLITE3_MUTEX_INITIALIZER,
new sqlite3_mutex( SQLITE_W32_MUTEX_INITIALIZER, 0, 0, (DWORD)0
#if SQLITE_DEBUG
, 0
#endif
),// SQLITE3_MUTEX_INITIALIZER,
new sqlite3_mutex( SQLITE_W32_MUTEX_INITIALIZER, 0, 0, (DWORD)0
#if SQLITE_DEBUG
, 0
#endif
),// SQLITE3_MUTEX_INITIALIZER,
new sqlite3_mutex( SQLITE_W32_MUTEX_INITIALIZER, 0, 0, (DWORD)0
#if SQLITE_DEBUG
, 0
#endif
),// SQLITE3_MUTEX_INITIALIZER,
};
static int winMutex_isInit = 0;
/* As winMutexInit() and winMutexEnd() are called as part
** of the sqlite3_initialize and sqlite3_shutdown()
** processing, the "interlocked" magic is probably not
** strictly necessary.
*/
static long winMutex_lock = 0;
private static System.Object lockThis = new System.Object();
static int winMutexInit()
{
/* The first to increment to 1 does actual initialization */
lock ( lockThis )
//if ( Interlocked.CompareExchange(ref winMutex_lock, 1, 0 ) == 0 )
{
int i;
for ( i = 0; i < ArraySize( winMutex_staticMutexes ); i++ )
{
if (winMutex_staticMutexes[i].mutex== null) winMutex_staticMutexes[i].mutex = new Mutex();
//InitializeCriticalSection( winMutex_staticMutexes[i].mutex );
}
winMutex_isInit = 1;
}
//else
//{
// /* Someone else is in the process of initing the static mutexes */
// while ( 0 == winMutex_isInit )
// {
// Thread.Sleep( 1 );
// }
//}
return SQLITE_OK;
}
static int winMutexEnd()
{
/* The first to decrement to 0 does actual shutdown
** (which should be the last to shutdown.) */
if ( Interlocked.CompareExchange( ref winMutex_lock, 0, 1 ) == 1 )
{
if ( winMutex_isInit == 1 )
{
int i;
for ( i = 0; i < ArraySize( winMutex_staticMutexes ); i++ )
{
DeleteCriticalSection( winMutex_staticMutexes[i].mutex );
}
winMutex_isInit = 0;
}
}
return SQLITE_OK;
}
/*
** The sqlite3_mutex_alloc() routine allocates a new
** mutex and returns a pointer to it. If it returns NULL
** that means that a mutex could not be allocated. SQLite
** will unwind its stack and return an error. The argument
** to sqlite3_mutex_alloc() is one of these integer constants:
**
** <ul>
** <li> SQLITE_MUTEX_FAST
** <li> SQLITE_MUTEX_RECURSIVE
** <li> SQLITE_MUTEX_STATIC_MASTER
** <li> SQLITE_MUTEX_STATIC_MEM
** <li> SQLITE_MUTEX_STATIC_MEM2
** <li> SQLITE_MUTEX_STATIC_PRNG
** <li> SQLITE_MUTEX_STATIC_LRU
** <li> SQLITE_MUTEX_STATIC_LRU2
** </ul>
**
** The first two constants cause sqlite3_mutex_alloc() to create
** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
** The mutex implementation does not need to make a distinction
** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
** not want to. But SQLite will only request a recursive mutex in
** cases where it really needs one. If a faster non-recursive mutex
** implementation is available on the host platform, the mutex subsystem
** might return such a mutex in response to SQLITE_MUTEX_FAST.
**
** The other allowed parameters to sqlite3_mutex_alloc() each return
** a pointer to a static preexisting mutex. Six static mutexes are
** used by the current version of SQLite. Future versions of SQLite
** may add additional static mutexes. Static mutexes are for internal
** use by SQLite only. Applications that use SQLite mutexes should
** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
** SQLITE_MUTEX_RECURSIVE.
**
** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
** returns a different mutex on every call. But for the static
** mutex types, the same mutex is returned on every call that has
** the same type number.
*/
static sqlite3_mutex winMutexAlloc( int iType )
{
sqlite3_mutex p;
switch ( iType )
{
case SQLITE_MUTEX_FAST:
case SQLITE_MUTEX_RECURSIVE:
{
p = new sqlite3_mutex();//sqlite3MallocZero( sizeof(*p) );
if ( p != null )
{
p.id = iType;
InitializeCriticalSection( p.mutex );
}
break;
}
default:
{
Debug.Assert( winMutex_isInit == 1 );
Debug.Assert( iType - 2 >= 0 );
Debug.Assert( iType - 2 < ArraySize( winMutex_staticMutexes ) );
p = winMutex_staticMutexes[iType - 2];
p.id = iType;
break;
}
}
return p;
}
/*
** This routine deallocates a previously
** allocated mutex. SQLite is careful to deallocate every
** mutex that it allocates.
*/
static void winMutexFree( sqlite3_mutex p )
{
Debug.Assert( p != null );
Debug.Assert( p.nRef == 0 );
Debug.Assert( p.id == SQLITE_MUTEX_FAST || p.id == SQLITE_MUTEX_RECURSIVE );
DeleteCriticalSection( p.mutex );
p.owner = 0;
//sqlite3_free( p );
}
/*
** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
** to enter a mutex. If another thread is already within the mutex,
** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
** be entered multiple times by the same thread. In such cases the,
** mutex must be exited an equal number of times before another thread
** can enter. If the same thread tries to enter any other kind of mutex
** more than once, the behavior is undefined.
*/
static void winMutexEnter( sqlite3_mutex p )
{
DWORD tid = GetCurrentThreadId();
Debug.Assert( p.id == SQLITE_MUTEX_RECURSIVE || winMutexNotheld2( p, tid ) );
EnterCriticalSection( p.mutex );
p.owner = tid;
p.nRef++;
#if SQLITE_DEBUG
if ( p.trace != 0 )
{
printf( "enter mutex {0} ({1}) with nRef={2}\n", p.GetHashCode(), p.owner, p.nRef );
}
#endif
}
static int winMutexTry( sqlite3_mutex p )
{
DWORD tid = GetCurrentThreadId();
int rc = SQLITE_BUSY;
Debug.Assert( p.id == SQLITE_MUTEX_RECURSIVE || winMutexNotheld2( p, tid ) );
/*
** The sqlite3_mutex_try() routine is very rarely used, and when it
** is used it is merely an optimization. So it is OK for it to always
** fail.
**
** The TryEnterCriticalSection() interface is only available on WinNT.
** And some windows compilers complain if you try to use it without
** first doing some #defines that prevent SQLite from building on Win98.
** For that reason, we will omit this optimization for now. See
** ticket #2685.
*/
#if FALSE
if( mutexIsNT() && TryEnterCriticalSection(p.mutex) ){
p.owner = tid;
p.nRef++;
rc = SQLITE_OK;
}
#else
UNUSED_PARAMETER( p );
#endif
#if SQLITE_DEBUG
if ( rc == SQLITE_OK && p.trace != 0 )
{
printf( "try mutex {0} ({1}) with nRef={2}\n", p.GetHashCode(), p.owner, p.nRef );
}
#endif
return rc;
}
/*
** The sqlite3_mutex_leave() routine exits a mutex that was
** previously entered by the same thread. The behavior
** is undefined if the mutex is not currently entered or
** is not currently allocated. SQLite will never do either.
*/
static void winMutexLeave( sqlite3_mutex p )
{
DWORD tid = GetCurrentThreadId();
Debug.Assert( p.nRef > 0 );
Debug.Assert( p.owner == tid );
p.nRef--;
Debug.Assert( p.nRef == 0 || p.id == SQLITE_MUTEX_RECURSIVE );
if ( p.nRef == 0 ) p.owner = 0;
LeaveCriticalSection( p.mutex );
#if SQLITE_DEBUG
if ( p.trace != 0 )
{
printf( "leave mutex {0} ({1}) with nRef={2}\n", p.GetHashCode(), p.owner, p.nRef );
}
#endif
}
static sqlite3_mutex_methods sqlite3DefaultMutex()
{
sqlite3_mutex_methods sMutex = new sqlite3_mutex_methods (
(dxMutexInit)winMutexInit,
(dxMutexEnd)winMutexEnd,
(dxMutexAlloc)winMutexAlloc,
(dxMutexFree)winMutexFree,
(dxMutexEnter)winMutexEnter,
(dxMutexTry)winMutexTry,
(dxMutexLeave)winMutexLeave,
#if SQLITE_DEBUG
(dxMutexHeld)winMutexHeld,
(dxMutexNotheld)winMutexNotheld
#else
null,
null
#endif
);
return sMutex;
}
#endif // * SQLITE_MUTEX_W32 */
}
}
| |
/*
* Copyright 2021 Google LLC All Rights Reserved.
* Use of this source code is governed by a BSD-style
* license that can be found in the LICENSE file or at
* https://developers.google.com/open-source/licenses/bsd
*/
// <auto-generated>
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/type/fraction.proto
// </auto-generated>
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Google.Type {
/// <summary>Holder for reflection information generated from google/type/fraction.proto</summary>
public static partial class FractionReflection {
#region Descriptor
/// <summary>File descriptor for google/type/fraction.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static FractionReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Chpnb29nbGUvdHlwZS9mcmFjdGlvbi5wcm90bxILZ29vZ2xlLnR5cGUiMgoI",
"RnJhY3Rpb24SEQoJbnVtZXJhdG9yGAEgASgDEhMKC2Rlbm9taW5hdG9yGAIg",
"ASgDQmYKD2NvbS5nb29nbGUudHlwZUINRnJhY3Rpb25Qcm90b1ABWjxnb29n",
"bGUuZ29sYW5nLm9yZy9nZW5wcm90by9nb29nbGVhcGlzL3R5cGUvZnJhY3Rp",
"b247ZnJhY3Rpb26iAgNHVFBiBnByb3RvMw=="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Type.Fraction), global::Google.Type.Fraction.Parser, new[]{ "Numerator", "Denominator" }, null, null, null, null)
}));
}
#endregion
}
#region Messages
/// <summary>
/// Represents a fraction in terms of a numerator divided by a denominator.
/// </summary>
public sealed partial class Fraction : pb::IMessage<Fraction>
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
, pb::IBufferMessage
#endif
{
private static readonly pb::MessageParser<Fraction> _parser = new pb::MessageParser<Fraction>(() => new Fraction());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<Fraction> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Type.FractionReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Fraction() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Fraction(Fraction other) : this() {
numerator_ = other.numerator_;
denominator_ = other.denominator_;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Fraction Clone() {
return new Fraction(this);
}
/// <summary>Field number for the "numerator" field.</summary>
public const int NumeratorFieldNumber = 1;
private long numerator_;
/// <summary>
/// The numerator in the fraction, e.g. 2 in 2/3.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public long Numerator {
get { return numerator_; }
set {
numerator_ = value;
}
}
/// <summary>Field number for the "denominator" field.</summary>
public const int DenominatorFieldNumber = 2;
private long denominator_;
/// <summary>
/// The value by which the numerator is divided, e.g. 3 in 2/3. Must be
/// positive.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public long Denominator {
get { return denominator_; }
set {
denominator_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as Fraction);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(Fraction other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Numerator != other.Numerator) return false;
if (Denominator != other.Denominator) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Numerator != 0L) hash ^= Numerator.GetHashCode();
if (Denominator != 0L) hash ^= Denominator.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
output.WriteRawMessage(this);
#else
if (Numerator != 0L) {
output.WriteRawTag(8);
output.WriteInt64(Numerator);
}
if (Denominator != 0L) {
output.WriteRawTag(16);
output.WriteInt64(Denominator);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) {
if (Numerator != 0L) {
output.WriteRawTag(8);
output.WriteInt64(Numerator);
}
if (Denominator != 0L) {
output.WriteRawTag(16);
output.WriteInt64(Denominator);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(ref output);
}
}
#endif
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Numerator != 0L) {
size += 1 + pb::CodedOutputStream.ComputeInt64Size(Numerator);
}
if (Denominator != 0L) {
size += 1 + pb::CodedOutputStream.ComputeInt64Size(Denominator);
}
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(Fraction other) {
if (other == null) {
return;
}
if (other.Numerator != 0L) {
Numerator = other.Numerator;
}
if (other.Denominator != 0L) {
Denominator = other.Denominator;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
input.ReadRawMessage(this);
#else
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 8: {
Numerator = input.ReadInt64();
break;
}
case 16: {
Denominator = input.ReadInt64();
break;
}
}
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 8: {
Numerator = input.ReadInt64();
break;
}
case 16: {
Denominator = input.ReadInt64();
break;
}
}
}
}
#endif
}
#endregion
}
#endregion Designer generated code
| |
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Collections;
using System.Text;
using LumiSoft.Net;
using LumiSoft.Net.SMTP;
using LumiSoft.Net.AUTH;
namespace LumiSoft.Net.SMTP.Server
{
/// <summary>
/// SMTP Session.
/// </summary>
public class SMTP_Session : SocketServerSession
{
private SMTP_Server m_pServer = null;
private Stream m_pMsgStream = null;
private SMTP_Cmd_Validator m_CmdValidator = null;
private long m_BDAT_ReadedCount = 0;
private string m_EhloName = "";
private string m_Reverse_path = ""; // Holds sender's reverse path.
private Hashtable m_Forward_path = null; // Holds Mail to.
private int m_BadCmdCount = 0; // Holds number of bad commands.
private BodyType m_BodyType;
private bool m_BDat = false;
/// <summary>
/// Default constructor.
/// </summary>
/// <param name="sessionID">Session ID.</param>
/// <param name="socket">Server connected socket.</param>
/// <param name="bindInfo">BindInfo what accepted socket.</param>
/// <param name="server">Reference to server.</param>
internal SMTP_Session(string sessionID,SocketEx socket,IPBindInfo bindInfo,SMTP_Server server) : base(sessionID,socket,bindInfo,server)
{
m_pServer = server;
m_BodyType = BodyType.x7_bit;
m_Forward_path = new Hashtable();
m_CmdValidator = new SMTP_Cmd_Validator();
// Start session proccessing
StartSession();
}
#region method StartSession
/// <summary>
/// Starts session.
/// </summary>
private void StartSession()
{
// Add session to session list
m_pServer.AddSession(this);
try{
// Check if ip is allowed to connect this computer
ValidateIP_EventArgs oArg = m_pServer.OnValidate_IpAddress(this);
if(oArg.Validated){
//--- Dedicated SSL connection, switch to SSL -----------------------------------//
if(this.BindInfo.SslMode == SslMode.SSL){
try{
this.Socket.SwitchToSSL(this.BindInfo.Certificate);
if(this.Socket.Logger != null){
this.Socket.Logger.AddTextEntry("SSL negotiation completed successfully.");
}
}
catch(Exception x){
if(this.Socket.Logger != null){
this.Socket.Logger.AddTextEntry("SSL handshake failed ! " + x.Message);
EndSession();
return;
}
}
}
//-------------------------------------------------------------------------------//
if(!string.IsNullOrEmpty(m_pServer.GreetingText)){
this.Socket.WriteLine("220 " + m_pServer.GreetingText);
}
else{
this.Socket.WriteLine("220 " + Net_Utils.GetLocalHostName(this.BindInfo.HostName) + " SMTP Server ready");
}
BeginRecieveCmd();
}
else{
// There is user specified error text, send it to connected socket
if(oArg.ErrorText.Length > 0){
this.Socket.WriteLine(oArg.ErrorText);
}
EndSession();
}
}
catch(Exception x){
OnError(x);
}
}
#endregion
#region method EndSession
/// <summary>
/// Ends session, closes socket.
/// </summary>
private void EndSession()
{
try{
try{
// Message storing not completed successfully, otherwise it must be null here.
// This can happen if BDAT -> QUIT and LAST BDAT block wasn't sent or
// when session times out on DATA or BDAT command.
if(m_pMsgStream != null){
// We must call that method to notify Message stream owner to close/dispose that stream.
m_pServer.OnMessageStoringCompleted(this,"Message storing not completed successfully",m_pMsgStream);
m_pMsgStream = null;
}
}
catch{
}
if(this.Socket != null){
// Write logs to log file, if needed
if(m_pServer.LogCommands){
this.Socket.Logger.Flush();
}
this.Socket.Shutdown(SocketShutdown.Both);
this.Socket.Disconnect();
//this.Socket = null;
}
}
catch{ // We don't need to check errors here, because they only may be Socket closing errors.
}
finally{
m_pServer.RemoveSession(this);
}
}
#endregion
#region method Kill
/// <summary>
/// Kill this session.
/// </summary>
public override void Kill()
{
EndSession();
}
#endregion
#region method OnSessionTimeout
/// <summary>
/// Is called by server when session has timed out.
/// </summary>
internal protected override void OnSessionTimeout()
{
try{
this.Socket.WriteLine("421 Session timeout, closing transmission channel");
}
catch{
}
EndSession();
}
#endregion
#region method OnError
/// <summary>
/// Is called when error occures.
/// </summary>
/// <param name="x"></param>
private void OnError(Exception x)
{
try{
// We must see InnerException too, SocketException may be as inner exception.
SocketException socketException = null;
if(x is SocketException){
socketException = (SocketException)x;
}
else if(x.InnerException != null && x.InnerException is SocketException){
socketException = (SocketException)x.InnerException;
}
if(socketException != null){
// Client disconnected without shutting down.
if(socketException.ErrorCode == 10054 || socketException.ErrorCode == 10053){
if(m_pServer.LogCommands){
this.Socket.Logger.AddTextEntry("Client aborted/disconnected");
}
EndSession();
// Exception handled, return
return;
}
// Connection timed out.
else if(socketException.ErrorCode == 10060){
if(m_pServer.LogCommands){
this.Socket.Logger.AddTextEntry("Connection timeout.");
}
EndSession();
// Exception handled, return
return;
}
}
m_pServer.OnSysError("",x);
}
catch(Exception ex){
m_pServer.OnSysError("",ex);
}
}
#endregion
#region method BeginRecieveCmd
/// <summary>
/// Starts recieveing command.
/// </summary>
private void BeginRecieveCmd()
{
MemoryStream strm = new MemoryStream();
this.Socket.BeginReadLine(strm,1024,strm,new SocketCallBack(this.EndRecieveCmd));
}
#endregion
#region method EndRecieveCmd
/// <summary>
/// Is called if command is recieved.
/// </summary>
/// <param name="result"></param>
/// <param name="count"></param>
/// <param name="exception"></param>
/// <param name="tag"></param>
private void EndRecieveCmd(SocketCallBackResult result,long count,Exception exception,object tag)
{
try{
switch(result)
{
case SocketCallBackResult.Ok:
MemoryStream strm = (MemoryStream)tag;
string cmdLine = System.Text.Encoding.Default.GetString(strm.ToArray());
// Exceute command
if(SwitchCommand(cmdLine)){
// Session end, close session
EndSession();
}
break;
case SocketCallBackResult.LengthExceeded:
this.Socket.WriteLine("500 Line too long.");
BeginRecieveCmd();
break;
case SocketCallBackResult.SocketClosed:
EndSession();
break;
case SocketCallBackResult.Exception:
OnError(exception);
break;
}
}
catch(ReadException x){
if(x.ReadReplyCode == ReadReplyCode.LengthExceeded){
this.Socket.WriteLine("500 Line too long.");
BeginRecieveCmd();
}
else if(x.ReadReplyCode == ReadReplyCode.SocketClosed){
EndSession();
}
else if(x.ReadReplyCode == ReadReplyCode.UnKnownError){
OnError(x);
}
}
catch(Exception x){
OnError(x);
}
}
#endregion
#region method SwitchCommand
/// <summary>
/// Executes SMTP command.
/// </summary>
/// <param name="SMTP_commandTxt">Original command text.</param>
/// <returns>Returns true if must end session(command loop).</returns>
private bool SwitchCommand(string SMTP_commandTxt)
{
//---- Parse command --------------------------------------------------//
string[] cmdParts = SMTP_commandTxt.TrimStart().Split(new char[]{' '});
string SMTP_command = cmdParts[0].ToUpper().Trim();
string argsText = Core.GetArgsText(SMTP_commandTxt,SMTP_command);
//---------------------------------------------------------------------//
bool getNextCmd = true;
switch(SMTP_command)
{
case "HELO":
HELO(argsText);
getNextCmd = false;
break;
case "EHLO":
EHLO(argsText);
getNextCmd = false;
break;
case "STARTTLS":
STARTTLS(argsText);
getNextCmd = false;
break;
case "AUTH":
AUTH(argsText);
break;
case "MAIL":
MAIL(argsText);
getNextCmd = false;
break;
case "RCPT":
RCPT(argsText);
getNextCmd = false;
break;
case "DATA":
BeginDataCmd(argsText);
getNextCmd = false;
break;
case "BDAT":
BeginBDATCmd(argsText);
getNextCmd = false;
break;
case "RSET":
RSET(argsText);
getNextCmd = false;
break;
// case "VRFY":
// VRFY();
// break;
// case "EXPN":
// EXPN();
// break;
case "HELP":
HELP();
break;
case "NOOP":
NOOP();
getNextCmd = false;
break;
case "QUIT":
QUIT(argsText);
getNextCmd = false;
return true;
default:
this.Socket.WriteLine("500 command unrecognized");
//---- Check that maximum bad commands count isn't exceeded ---------------//
if(m_BadCmdCount > m_pServer.MaxBadCommands-1){
this.Socket.WriteLine("421 Too many bad commands, closing transmission channel");
return true;
}
m_BadCmdCount++;
//-------------------------------------------------------------------------//
break;
}
if(getNextCmd){
BeginRecieveCmd();
}
return false;
}
#endregion
#region method HELO
private void HELO(string argsText)
{
/* Rfc 2821 4.1.1.1
These commands, and a "250 OK" reply to one of them, confirm that
both the SMTP client and the SMTP server are in the initial state,
that is, there is no transaction in progress and all state tables and
buffers are cleared.
Arguments:
Host name.
Syntax:
"HELO" SP Domain CRLF
*/
m_EhloName = argsText;
ResetState();
this.Socket.BeginWriteLine("250 " + Net_Utils.GetLocalHostName(this.BindInfo.HostName) + " Hello [" + this.RemoteEndPoint.Address.ToString() + "]",new SocketCallBack(this.EndSend));
m_CmdValidator.Helo_ok = true;
}
#endregion
#region method EHLO
private void EHLO(string argsText)
{
/* Rfc 2821 4.1.1.1
These commands, and a "250 OK" reply to one of them, confirm that
both the SMTP client and the SMTP server are in the initial state,
that is, there is no transaction in progress and all state tables and
buffers are cleared.
*/
m_EhloName = argsText;
ResetState();
//--- Construct supported AUTH types value ----------------------------//
string authTypesString = "";
if((m_pServer.SupportedAuthentications & SaslAuthTypes.Login) != 0){
authTypesString += "LOGIN ";
}
if((m_pServer.SupportedAuthentications & SaslAuthTypes.Cram_md5) != 0){
authTypesString += "CRAM-MD5 ";
}
if((m_pServer.SupportedAuthentications & SaslAuthTypes.Digest_md5) != 0){
authTypesString += "DIGEST-MD5 ";
}
authTypesString = authTypesString.Trim();
//-----------------------------------------------------------------------//
string reply = "";
reply += "250-" + Net_Utils.GetLocalHostName(this.BindInfo.HostName) + " Hello [" + this.RemoteEndPoint.Address.ToString() + "]\r\n";
reply += "250-PIPELINING\r\n";
reply += "250-SIZE " + m_pServer.MaxMessageSize + "\r\n";
// reply += "250-DSN\r\n";
// reply += "250-HELP\r\n";
reply += "250-8BITMIME\r\n";
reply += "250-BINARYMIME\r\n";
reply += "250-CHUNKING\r\n";
if(authTypesString.Length > 0){
reply += "250-AUTH " + authTypesString + "\r\n";
}
if(!this.Socket.SSL && this.BindInfo.Certificate != null){
reply += "250-STARTTLS\r\n";
}
reply += "250 Ok\r\n";
this.Socket.BeginWriteLine(reply,null,new SocketCallBack(this.EndSend));
m_CmdValidator.Helo_ok = true;
}
#endregion
#region method STARTTLS
private void STARTTLS(string argsText)
{
/* RFC 2487 STARTTLS 5. STARTTLS Command.
The format for the STARTTLS command is:
STARTTLS
with no parameters.
After the client gives the STARTTLS command, the server responds with
one of the following reply codes:
220 Ready to start TLS
501 Syntax error (no parameters allowed)
454 TLS not available due to temporary reason
5.2 Result of the STARTTLS Command
Upon completion of the TLS handshake, the SMTP protocol is reset to
the initial state (the state in SMTP after a server issues a 220
service ready greeting).
*/
if(this.Socket.SSL){
this.Socket.WriteLine("500 TLS already started !");
return;
}
if(this.BindInfo.Certificate == null){
this.Socket.WriteLine("454 TLS not available, SSL certificate isn't specified !");
return;
}
this.Socket.WriteLine("220 Ready to start TLS");
try{
this.Socket.SwitchToSSL(this.BindInfo.Certificate);
if(m_pServer.LogCommands){
this.Socket.Logger.AddTextEntry("TLS negotiation completed successfully.");
}
}
catch(Exception x){
this.Socket.WriteLine("500 TLS handshake failed ! " + x.Message);
}
ResetState();
BeginRecieveCmd();
}
#endregion
#region method AUTH
private void AUTH(string argsText)
{
/* Rfc 2554 AUTH --------------------------------------------------//
Restrictions:
After an AUTH command has successfully completed, no more AUTH
commands may be issued in the same session. After a successful
AUTH command completes, a server MUST reject any further AUTH
commands with a 503 reply.
Remarks:
If an AUTH command fails, the server MUST behave the same as if
the client had not issued the AUTH command.
*/
if(this.Authenticated){
this.Socket.WriteLine("503 already authenticated");
return;
}
try{
//------ Parse parameters -------------------------------------//
string userName = "";
string password = "";
AuthUser_EventArgs aArgs = null;
string[] param = argsText.Split(new char[]{' '});
switch(param[0].ToUpper())
{
case "PLAIN":
this.Socket.WriteLine("504 Unrecognized authentication type.");
break;
case "LOGIN":
#region LOGIN authentication
//---- AUTH = LOGIN ------------------------------
/* Login
C: AUTH LOGIN
S: 334 VXNlcm5hbWU6
C: username_in_base64
S: 334 UGFzc3dvcmQ6
C: password_in_base64
or (initial-response argument included to avoid one 334 server response)
C: AUTH LOGIN username_in_base64
S: 334 UGFzc3dvcmQ6
C: password_in_base64
VXNlcm5hbWU6 base64_decoded= USERNAME
UGFzc3dvcmQ6 base64_decoded= PASSWORD
*/
// Note: all strings are base64 strings eg. VXNlcm5hbWU6 = UserName.
// No user name included (initial-response argument)
if(param.Length == 1){
// Query UserName
this.Socket.WriteLine("334 VXNlcm5hbWU6");
string userNameLine = this.Socket.ReadLine();
// Encode username from base64
if(userNameLine.Length > 0){
userName = System.Text.Encoding.Default.GetString(Convert.FromBase64String(userNameLine));
}
}
// User name included, use it
else{
userName = System.Text.Encoding.Default.GetString(Convert.FromBase64String(param[1]));
}
// Query Password
this.Socket.WriteLine("334 UGFzc3dvcmQ6");
string passwordLine = this.Socket.ReadLine();
// Encode password from base64
if(passwordLine.Length > 0){
password = System.Text.Encoding.Default.GetString(Convert.FromBase64String(passwordLine));
}
aArgs = m_pServer.OnAuthUser(this,userName,password,"",AuthType.Plain);
if(aArgs.Validated){
this.Socket.WriteLine("235 Authentication successful.");
this.SetUserName(userName);
}
else{
this.Socket.WriteLine("535 Authentication failed");
}
#endregion
break;
case "CRAM-MD5":
#region CRAM-MD5 authentication
/* Cram-M5
C: AUTH CRAM-MD5
S: 334 <md5_calculation_hash_in_base64>
C: base64(username password_hash)
*/
string md5Hash = "<" + Guid.NewGuid().ToString().ToLower() + ">";
this.Socket.WriteLine("334 " + Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes(md5Hash)));
string reply = this.Socket.ReadLine();
reply = System.Text.Encoding.Default.GetString(Convert.FromBase64String(reply));
string[] replyArgs = reply.Split(' ');
userName = replyArgs[0];
aArgs = m_pServer.OnAuthUser(this,userName,replyArgs[1],md5Hash,AuthType.CRAM_MD5);
if(aArgs.Validated){
this.Socket.WriteLine("235 Authentication successful.");
this.SetUserName(userName);
}
else{
this.Socket.WriteLine("535 Authentication failed");
}
#endregion
break;
case "DIGEST-MD5":
#region DIGEST-MD5 authentication
/* RFC 2831 AUTH DIGEST-MD5
*
* Example:
*
* C: AUTH DIGEST-MD5
* S: 334 base64(realm="elwood.innosoft.com",nonce="OA6MG9tEQGm2hh",qop="auth",algorithm=md5-sess)
* C: base64(username="chris",realm="elwood.innosoft.com",nonce="OA6MG9tEQGm2hh",
* nc=00000001,cnonce="OA6MHXh6VqTrRk",digest-uri="smtp/elwood.innosoft.com",
* response=d388dad90d4bbd760a152321f2143af7,qop=auth)
* S: 334 base64(rspauth=ea40f60335c427b5527b84dbabcdfffd)
* C:
* S: 235 Authentication successful.
*/
string nonce = Auth_HttpDigest.CreateNonce();
string opaque = Auth_HttpDigest.CreateOpaque();
Auth_HttpDigest digest = new Auth_HttpDigest(this.BindInfo.HostName,nonce,opaque);
digest.Algorithm = "md5-sess";
this.Socket.WriteLine("334 " + AuthHelper.Base64en(digest.ToChallange(false)));
string clientResponse = AuthHelper.Base64de(this.Socket.ReadLine());
digest = new Auth_HttpDigest(clientResponse,"AUTHENTICATE");
// Check that realm,nonce and opaque in client response are same as we specified.
if(this.BindInfo.HostName != digest.Realm){
this.Socket.WriteLine("535 Authentication failed, 'realm' won't match.");
return;
}
if(nonce != digest.Nonce){
this.Socket.WriteLine("535 Authentication failed, 'nonce' won't match.");
return;
}
if(opaque != digest.Opaque){
this.Socket.WriteLine("535 Authentication failed, 'opaque' won't match.");
return;
}
userName = digest.UserName;
aArgs = m_pServer.OnAuthUser(this,userName,digest.Response,clientResponse,AuthType.DIGEST_MD5);
if(aArgs.Validated){
// Send server computed password hash
this.Socket.WriteLine("334 " + AuthHelper.Base64en("rspauth=" + aArgs.ReturnData));
// We must got empty line here
clientResponse = this.Socket.ReadLine();
if(clientResponse == ""){
this.Socket.WriteLine("235 Authentication successful.");
this.SetUserName(userName);
}
else{
this.Socket.WriteLine("535 Authentication failed, unexpected client response.");
}
}
else{
this.Socket.WriteLine("535 Authentication failed.");
}
#endregion
break;
default:
this.Socket.WriteLine("504 Unrecognized authentication type.");
break;
}
//-----------------------------------------------------------------//
}
catch{
this.Socket.WriteLine("535 Authentication failed.");
}
}
#endregion
#region method MAIL
private void MAIL(string argsText)
{
/* RFC 2821 3.3
NOTE:
This command tells the SMTP-receiver that a new mail transaction is
starting and to reset all its state tables and buffers, including any
recipients or mail data. The <reverse-path> portion of the first or
only argument contains the source mailbox (between "<" and ">"
brackets), which can be used to report errors (see section 4.2 for a
discussion of error reporting). If accepted, the SMTP server returns
a 250 OK reply.
MAIL FROM:<reverse-path> [SP <mail-parameters> ] <CRLF>
reverse-path = "<" [ A-d-l ":" ] Mailbox ">"
Mailbox = Local-part "@" Domain
body-value ::= "7BIT" / "8BITMIME" / "BINARYMIME"
Examples:
C: MAIL FROM:<ned@thor.innosoft.com>
C: MAIL FROM:<ned@thor.innosoft.com> SIZE=500000 BODY=8BITMIME AUTH=xxxx
*/
if(!m_CmdValidator.MayHandle_MAIL){
if(m_CmdValidator.MailFrom_ok){
this.Socket.BeginWriteLine("503 Sender already specified",new SocketCallBack(this.EndSend));
}
else{
this.Socket.BeginWriteLine("503 Bad sequence of commands",new SocketCallBack(this.EndSend));
}
return;
}
//------ Parse parameters -------------------------------------------------------------------//
string senderEmail = "";
long messageSize = 0;
BodyType bodyType = BodyType.x7_bit;
bool isFromParam = false;
// Parse while all params parsed or while is breaked
while(argsText.Length > 0){
if(argsText.ToLower().StartsWith("from:")){
// Remove from:
argsText = argsText.Substring(5).Trim();
// If there is more parameters
if(argsText.IndexOf(" ") > -1){
senderEmail = argsText.Substring(0,argsText.IndexOf(" "));
argsText = argsText.Substring(argsText.IndexOf(" ")).Trim();
}
else{
senderEmail = argsText;
argsText = "";
}
// If address between <>, remove <>
if(senderEmail.StartsWith("<") && senderEmail.EndsWith(">")){
senderEmail = senderEmail.Substring(1,senderEmail.Length - 2);
}
isFromParam = true;
}
else if(argsText.ToLower().StartsWith("size=")){
// Remove size=
argsText = argsText.Substring(5).Trim();
string sizeS = "";
// If there is more parameters
if(argsText.IndexOf(" ") > -1){
sizeS = argsText.Substring(0,argsText.IndexOf(" "));
argsText = argsText.Substring(argsText.IndexOf(" ")).Trim();
}
else{
sizeS = argsText;
argsText = "";
}
// See if value ok
if(Core.IsNumber(sizeS)){
messageSize = Convert.ToInt64(sizeS);
}
else{
this.Socket.BeginWriteLine("501 SIZE parameter value is invalid. Syntax:{MAIL FROM:<address> [SIZE=msgSize] [BODY=8BITMIME]}",new SocketCallBack(this.EndSend));
return;
}
}
else if(argsText.ToLower().StartsWith("body=")){
// Remove body=
argsText = argsText.Substring(5).Trim();
string bodyTypeS = "";
// If there is more parameters
if(argsText.IndexOf(" ") > -1){
bodyTypeS = argsText.Substring(0,argsText.IndexOf(" "));
argsText = argsText.Substring(argsText.IndexOf(" ")).Trim();
}
else{
bodyTypeS = argsText;
argsText = "";
}
// See if value ok
switch(bodyTypeS.ToUpper())
{
case "7BIT":
bodyType = BodyType.x7_bit;
break;
case "8BITMIME":
bodyType = BodyType.x8_bit;
break;
case "BINARYMIME":
bodyType = BodyType.binary;
break;
default:
this.Socket.BeginWriteLine("501 BODY parameter value is invalid. Syntax:{MAIL FROM:<address> [BODY=(7BIT/8BITMIME)]}",new SocketCallBack(this.EndSend));
return;
}
}
else if(argsText.ToLower().StartsWith("auth=")){
// Currently just eat AUTH keyword
// Remove auth=
argsText = argsText.Substring(5).Trim();
string authS = "";
// If there is more parameters
if(argsText.IndexOf(" ") > -1){
authS = argsText.Substring(0,argsText.IndexOf(" "));
argsText = argsText.Substring(argsText.IndexOf(" ")).Trim();
}
else{
authS = argsText;
argsText = "";
}
}
else{
this.Socket.BeginWriteLine("501 Error in parameters. Syntax:{MAIL FROM:<address> [SIZE=msgSize] [BODY=8BITMIME]}",new SocketCallBack(this.EndSend));
return;
}
}
// If required parameter 'FROM:' is missing
if(!isFromParam){
this.Socket.BeginWriteLine("501 Required param FROM: is missing. Syntax:{MAIL FROM:<address> [SIZE=msgSize] [BODY=8BITMIME]}",new SocketCallBack(this.EndSend));
return;
}
//---------------------------------------------------------------------------------------------//
//--- Check message size
if(m_pServer.MaxMessageSize > messageSize){
// Check if sender is ok
ValidateSender_EventArgs eArgs = m_pServer.OnValidate_MailFrom(this,senderEmail,senderEmail);
if(eArgs.Validated){
// See note above
ResetState();
// Store reverse path
m_Reverse_path = senderEmail;
m_CmdValidator.MailFrom_ok = true;
//-- Store params
m_BodyType = bodyType;
this.Socket.BeginWriteLine("250 OK <" + senderEmail + "> Sender ok",new SocketCallBack(this.EndSend));
}
else{
if(eArgs.ErrorText != null && eArgs.ErrorText.Length > 0){
this.Socket.BeginWriteLine("550 " + eArgs.ErrorText,new SocketCallBack(this.EndSend));
}
else{
this.Socket.BeginWriteLine("550 You are refused to send mail here",new SocketCallBack(this.EndSend));
}
}
}
else{
this.Socket.BeginWriteLine("552 Message exceeds allowed size",new SocketCallBack(this.EndSend));
}
}
#endregion
#region method RCPT
private void RCPT(string argsText)
{
/* RFC 2821 4.1.1.3 RCPT
NOTE:
This command is used to identify an individual recipient of the mail
data; multiple recipients are specified by multiple use of this
command. The argument field contains a forward-path and may contain
optional parameters.
Relay hosts SHOULD strip or ignore source routes, and
names MUST NOT be copied into the reverse-path.
Example:
RCPT TO:<@hosta.int,@jkl.org:userc@d.bar.org>
will normally be sent directly on to host d.bar.org with envelope
commands
RCPT TO:<userc@d.bar.org>
RCPT TO:<userc@d.bar.org> SIZE=40000
RCPT TO:<forward-path> [ SP <rcpt-parameters> ] <CRLF>
*/
/* RFC 2821 3.3
If a RCPT command appears without a previous MAIL command,
the server MUST return a 503 "Bad sequence of commands" response.
*/
if(!m_CmdValidator.MayHandle_RCPT || m_BDat){
this.Socket.BeginWriteLine("503 Bad sequence of commands",new SocketCallBack(this.EndSend));
return;
}
// Check that recipient count isn't exceeded
if(m_Forward_path.Count > m_pServer.MaxRecipients){
this.Socket.BeginWriteLine("452 Too many recipients",new SocketCallBack(this.EndSend));
return;
}
//------ Parse parameters -------------------------------------------------------------------//
string recipientEmail = "";
long messageSize = 0;
bool isToParam = false;
// Parse while all params parsed or while is breaked
while(argsText.Length > 0){
if(argsText.ToLower().StartsWith("to:")){
// Remove to:
argsText = argsText.Substring(3).Trim();
// If there is more parameters
if(argsText.IndexOf(" ") > -1){
recipientEmail = argsText.Substring(0,argsText.IndexOf(" "));
argsText = argsText.Substring(argsText.IndexOf(" ")).Trim();
}
else{
recipientEmail = argsText;
argsText = "";
}
// If address between <>, remove <>
if(recipientEmail.StartsWith("<") && recipientEmail.EndsWith(">")){
recipientEmail = recipientEmail.Substring(1,recipientEmail.Length - 2);
}
// See if value ok
if(recipientEmail.Length == 0){
this.Socket.BeginWriteLine("501 Recipient address isn't specified. Syntax:{RCPT TO:<address> [SIZE=msgSize]}",new SocketCallBack(this.EndSend));
return;
}
isToParam = true;
}
else if(argsText.ToLower().StartsWith("size=")){
// Remove size=
argsText = argsText.Substring(5).Trim();
string sizeS = "";
// If there is more parameters
if(argsText.IndexOf(" ") > -1){
sizeS = argsText.Substring(0,argsText.IndexOf(" "));
argsText = argsText.Substring(argsText.IndexOf(" ")).Trim();
}
else{
sizeS = argsText;
argsText = "";
}
// See if value ok
if(Core.IsNumber(sizeS)){
messageSize = Convert.ToInt64(sizeS);
}
else{
this.Socket.BeginWriteLine("501 SIZE parameter value is invalid. Syntax:{RCPT TO:<address> [SIZE=msgSize]}",new SocketCallBack(this.EndSend));
return;
}
}
else{
this.Socket.BeginWriteLine("501 Error in parameters. Syntax:{RCPT TO:<address> [SIZE=msgSize]}",new SocketCallBack(this.EndSend));
return;
}
}
// If required parameter 'TO:' is missing
if(!isToParam){
this.Socket.BeginWriteLine("501 Required param TO: is missing. Syntax:<RCPT TO:{address> [SIZE=msgSize]}",new SocketCallBack(this.EndSend));
return;
}
//---------------------------------------------------------------------------------------------//
// Check message size
if(m_pServer.MaxMessageSize > messageSize){
// Check if email address is ok
ValidateRecipient_EventArgs rcpt_args = m_pServer.OnValidate_MailTo(this,recipientEmail,recipientEmail,this.Authenticated);
if(rcpt_args.Validated){
// Check if mailbox size isn't exceeded
if(m_pServer.Validate_MailBoxSize(this,recipientEmail,messageSize)){
// Store reciptient
if(!m_Forward_path.Contains(recipientEmail)){
m_Forward_path.Add(recipientEmail,recipientEmail);
}
m_CmdValidator.RcptTo_ok = true;
this.Socket.BeginWriteLine("250 OK <" + recipientEmail + "> Recipient ok",new SocketCallBack(this.EndSend));
}
else{
this.Socket.BeginWriteLine("552 Mailbox size limit exceeded",new SocketCallBack(this.EndSend));
}
}
// Recipient rejected
else{
if(rcpt_args.LocalRecipient){
this.Socket.BeginWriteLine("550 <" + recipientEmail + "> No such user here",new SocketCallBack(this.EndSend));
}
else{
this.Socket.BeginWriteLine("550 <" + recipientEmail + "> Relay not allowed",new SocketCallBack(this.EndSend));
}
}
}
else{
this.Socket.BeginWriteLine("552 Message exceeds allowed size",new SocketCallBack(this.EndSend));
}
}
#endregion
#region method DATA
#region method BeginDataCmd
private void BeginDataCmd(string argsText)
{
/* RFC 2821 4.1.1
NOTE:
Several commands (RSET, DATA, QUIT) are specified as not permitting
parameters. In the absence of specific extensions offered by the
server and accepted by the client, clients MUST NOT send such
parameters and servers SHOULD reject commands containing them as
having invalid syntax.
*/
if(argsText.Length > 0){
this.Socket.BeginWriteLine("500 Syntax error. Syntax:{DATA}",new SocketCallBack(this.EndSend));
return;
}
/* RFC 2821 4.1.1.4 DATA
NOTE:
If accepted, the SMTP server returns a 354 Intermediate reply and
considers all succeeding lines up to but not including the end of
mail data indicator to be the message text. When the end of text is
successfully received and stored the SMTP-receiver sends a 250 OK
reply.
The mail data is terminated by a line containing only a period, that
is, the character sequence "<CRLF>.<CRLF>" (see section 4.5.2). This
is the end of mail data indication.
When the SMTP server accepts a message either for relaying or for
final delivery, it inserts a trace record (also referred to
interchangeably as a "time stamp line" or "Received" line) at the top
of the mail data. This trace record indicates the identity of the
host that sent the message, the identity of the host that received
the message (and is inserting this time stamp), and the date and time
the message was received. Relayed messages will have multiple time
stamp lines. Details for formation of these lines, including their
syntax, is specified in section 4.4.
*/
/* RFC 2821 DATA
NOTE:
If there was no MAIL, or no RCPT, command, or all such commands
were rejected, the server MAY return a "command out of sequence"
(503) or "no valid recipients" (554) reply in response to the DATA
command.
*/
if(!m_CmdValidator.MayHandle_DATA || m_BDat){
this.Socket.BeginWriteLine("503 Bad sequence of commands",new SocketCallBack(this.EndSend));
return;
}
if(m_Forward_path.Count == 0){
this.Socket.BeginWriteLine("554 no valid recipients given",new SocketCallBack(this.EndSend));
return;
}
// Get message store stream
GetMessageStoreStream_eArgs eArgs = m_pServer.OnGetMessageStoreStream(this);
m_pMsgStream = eArgs.StoreStream;
// reply: 354 Start mail input
this.Socket.WriteLine("354 Start mail input; end with <CRLF>.<CRLF>");
//---- Construct server headers for message----------------------------------------------------------------//
string header = "Received: from " + Core.GetHostName(this.RemoteEndPoint.Address) + " (" + this.RemoteEndPoint.Address.ToString() + ")\r\n";
header += "\tby " + this.BindInfo.HostName + " with SMTP; " + DateTime.Now.ToUniversalTime().ToString("r",System.Globalization.DateTimeFormatInfo.InvariantInfo) + "\r\n";
byte[] headers = System.Text.Encoding.ASCII.GetBytes(header);
m_pMsgStream.Write(headers,0,headers.Length);
//---------------------------------------------------------------------------------------------------------//
// Begin recieving data
this.Socket.BeginReadPeriodTerminated(m_pMsgStream,m_pServer.MaxMessageSize,null,new SocketCallBack(this.EndDataCmd));
}
#endregion
#region method EndDataCmd
/// <summary>
/// Is called when DATA command is finnished.
/// </summary>
/// <param name="result"></param>
/// <param name="count"></param>
/// <param name="exception"></param>
/// <param name="tag"></param>
private void EndDataCmd(SocketCallBackResult result,long count,Exception exception,object tag)
{
try{
switch(result)
{
case SocketCallBackResult.Ok:
// Notify Message stream owner that message storing completed ok.
MessageStoringCompleted_eArgs oArg = m_pServer.OnMessageStoringCompleted(this,null,m_pMsgStream);
if(oArg.ServerReply.ErrorReply){
this.Socket.BeginWriteLine(oArg.ServerReply.ToSmtpReply("500","Error storing message"),new SocketCallBack(this.EndSend));
}
else{
this.Socket.BeginWriteLine(oArg.ServerReply.ToSmtpReply("250","OK"),new SocketCallBack(this.EndSend));
}
break;
case SocketCallBackResult.LengthExceeded:
// We must call that method to notify Message stream owner to close/dispose that stream.
m_pServer.OnMessageStoringCompleted(this,"Requested mail action aborted: exceeded storage allocation",m_pMsgStream);
this.Socket.BeginWriteLine("552 Requested mail action aborted: exceeded storage allocation",new SocketCallBack(this.EndSend));
break;
case SocketCallBackResult.SocketClosed:
if(m_pMsgStream != null){
// We must call that method to notify Message stream owner to close/dispose that stream.
m_pServer.OnMessageStoringCompleted(this,"SocketClosed",m_pMsgStream);
m_pMsgStream = null;
}
// Stream is already closed, probably by the EndSession method, do nothing.
//else{
//}
EndSession();
break;
case SocketCallBackResult.Exception:
if(m_pMsgStream != null){
// We must call that method to notify Message stream owner to close/dispose that stream.
m_pServer.OnMessageStoringCompleted(this,"Exception: " + exception.Message,m_pMsgStream);
m_pMsgStream = null;
}
// Stream is already closed, probably by the EndSession method, do nothing.
//else{
//}
OnError(exception);
break;
}
/* RFC 2821 4.1.1.4 DATA
NOTE:
Receipt of the end of mail data indication requires the server to
process the stored mail transaction information. This processing
consumes the information in the reverse-path buffer, the forward-path
buffer, and the mail data buffer, and on the completion of this
command these buffers are cleared.
*/
ResetState();
}
catch(Exception x){
OnError(x);
}
}
#endregion
#endregion
#region function BDAT
#region method BeginBDATCmd
private void BeginBDATCmd(string argsText)
{
/*RFC 3030 2
The BDAT verb takes two arguments.The first argument indicates the length,
in octets, of the binary data chunk. The second optional argument indicates
that the data chunk is the last.
The message data is sent immediately after the trailing <CR>
<LF> of the BDAT command line. Once the receiver-SMTP receives the
specified number of octets, it will return a 250 reply code.
The optional LAST parameter on the BDAT command indicates that this
is the last chunk of message data to be sent. The last BDAT command
MAY have a byte-count of zero indicating there is no additional data
to be sent. Any BDAT command sent after the BDAT LAST is illegal and
MUST be replied to with a 503 "Bad sequence of commands" reply code.
The state resulting from this error is indeterminate. A RSET command
MUST be sent to clear the transaction before continuing.
A 250 response MUST be sent to each successful BDAT data block within
a mail transaction.
bdat-cmd ::= "BDAT" SP chunk-size [ SP end-marker ] CR LF
chunk-size ::= 1*DIGIT
end-marker ::= "LAST"
*/
if(!m_CmdValidator.MayHandle_BDAT){
this.Socket.BeginWriteLine("503 Bad sequence of commands",new SocketCallBack(this.EndSend));
return;
}
string[] param = argsText.Split(new char[]{' '});
if(param.Length > 0 && param.Length < 3){
if(Core.IsNumber(param[0])){
int countToRead = Convert.ToInt32(param[0]);
// LAST specified
bool lastChunk = false;
if(param.Length == 2){
lastChunk = true;
}
// First BDAT command call.
if(!m_BDat){
// Get message store stream
GetMessageStoreStream_eArgs eArgs = m_pServer.OnGetMessageStoreStream(this);
m_pMsgStream = eArgs.StoreStream;
// Add header to first bdat block only
//---- Construct server headers for message----------------------------------------------------------------//
string header = "Received: from " + Core.GetHostName(this.RemoteEndPoint.Address) + " (" + this.RemoteEndPoint.Address.ToString() + ")\r\n";
header += "\tby " + this.BindInfo.HostName + " with SMTP; " + DateTime.Now.ToUniversalTime().ToString("r",System.Globalization.DateTimeFormatInfo.InvariantInfo) + "\r\n";
byte[] headers = System.Text.Encoding.ASCII.GetBytes(header);
m_pMsgStream.Write(headers,0,headers.Length);
//---------------------------------------------------------------------------------------------------------//
}
// Begin junking data, maximum allowed message size exceeded.
// BDAT comman is dummy, after commandline binary data is at once follwed,
// so server server must junk all data and then report error.
if((m_BDAT_ReadedCount + countToRead) > m_pServer.MaxMessageSize){
this.Socket.BeginReadSpecifiedLength(new JunkingStream(),countToRead,lastChunk,new SocketCallBack(this.EndBDatCmd));
}
// Begin reading data
else{
this.Socket.BeginReadSpecifiedLength(m_pMsgStream,countToRead,lastChunk,new SocketCallBack(this.EndBDatCmd));
}
m_BDat = true;
}
else{
this.Socket.BeginWriteLine("500 Syntax error. Syntax:{BDAT chunk-size [LAST]}",new SocketCallBack(this.EndSend));
}
}
else{
this.Socket.BeginWriteLine("500 Syntax error. Syntax:{BDAT chunk-size [LAST]}",new SocketCallBack(this.EndSend));
}
}
#endregion
#region method EndBDatCmd
private void EndBDatCmd(SocketCallBackResult result,long count,Exception exception,object tag)
{
try{
switch(result)
{
case SocketCallBackResult.Ok:
m_BDAT_ReadedCount += count;
// BDAT command completed, got all data junks
if((bool)tag){
// Maximum allowed message size exceeded.
if((m_BDAT_ReadedCount) > m_pServer.MaxMessageSize){
m_pServer.OnMessageStoringCompleted(this,"Requested mail action aborted: exceeded storage allocation",m_pMsgStream);
this.Socket.BeginWriteLine("552 Requested mail action aborted: exceeded storage allocation",new SocketCallBack(this.EndSend));
}
else{
// Notify Message stream owner that message storing completed ok.
MessageStoringCompleted_eArgs oArg = m_pServer.OnMessageStoringCompleted(this,null,m_pMsgStream);
if(oArg.ServerReply.ErrorReply){
this.Socket.BeginWriteLine(oArg.ServerReply.ToSmtpReply("500","Error storing message"),new SocketCallBack(this.EndSend));
}
else{
this.Socket.BeginWriteLine(oArg.ServerReply.ToSmtpReply("250","Message(" + m_BDAT_ReadedCount + " bytes) stored ok."),new SocketCallBack(this.EndSend));
}
}
/* RFC 2821 4.1.1.4 DATA
NOTE:
Receipt of the end of mail data indication requires the server to
process the stored mail transaction information. This processing
consumes the information in the reverse-path buffer, the forward-path
buffer, and the mail data buffer, and on the completion of this
command these buffers are cleared.
*/
ResetState();
}
// Got BDAT data block, BDAT must continue, that wasn't last data block.
else{
// Maximum allowed message size exceeded.
if((m_BDAT_ReadedCount) > m_pServer.MaxMessageSize){
this.Socket.BeginWriteLine("552 Requested mail action aborted: exceeded storage allocation",new SocketCallBack(this.EndSend));
}
else{
this.Socket.BeginWriteLine("250 Data block of " + count + " bytes recieved OK.",new SocketCallBack(this.EndSend));
}
}
break;
case SocketCallBackResult.SocketClosed:
if(m_pMsgStream != null){
// We must call that method to notify Message stream owner to close/dispose that stream.
m_pServer.OnMessageStoringCompleted(this,"SocketClosed",m_pMsgStream);
m_pMsgStream = null;
}
// Stream is already closed, probably by the EndSession method, do nothing.
//else{
//}
EndSession();
return;
case SocketCallBackResult.Exception:
if(m_pMsgStream != null){
// We must call that method to notify Message stream owner to close/dispose that stream.
m_pServer.OnMessageStoringCompleted(this,"Exception: " + exception.Message,m_pMsgStream);
m_pMsgStream = null;
}
// Stream is already closed, probably by the EndSession method, do nothing.
//else{
//}
OnError(exception);
return;
}
}
catch(Exception x){
OnError(x);
}
}
#endregion
#endregion
#region method RSET
private void RSET(string argsText)
{
/* RFC 2821 4.1.1
NOTE:
Several commands (RSET, DATA, QUIT) are specified as not permitting
parameters. In the absence of specific extensions offered by the
server and accepted by the client, clients MUST NOT send such
parameters and servers SHOULD reject commands containing them as
having invalid syntax.
*/
if(argsText.Length > 0){
this.Socket.BeginWriteLine("500 Syntax error. Syntax:{RSET}",new SocketCallBack(this.EndSend));
return;
}
/* RFC 2821 4.1.1.5 RESET (RSET)
NOTE:
This command specifies that the current mail transaction will be
aborted. Any stored sender, recipients, and mail data MUST be
discarded, and all buffers and state tables cleared. The receiver
MUST send a "250 OK" reply to a RSET command with no arguments.
*/
try{
// Message storing aborted by RSET.
// This can happen if BDAT -> RSET and LAST BDAT block wasn't sent.
if(m_pMsgStream != null){
// We must call that method to notify Message stream owner to close/dispose that stream.
m_pServer.OnMessageStoringCompleted(this,"Message storing aborted by RSET",m_pMsgStream);
m_pMsgStream = null;
}
}
catch{
}
ResetState();
this.Socket.BeginWriteLine("250 OK",new SocketCallBack(this.EndSend));
}
#endregion
#region method VRFY
private void VRFY()
{
/* RFC 821 VRFY
Example:
S: VRFY Lumi
R: 250 Ivar Lumi <ivx@lumisoft.ee>
S: VRFY lum
R: 550 String does not match anything.
*/
// ToDo: Parse user, add new event for cheking user
this.Socket.BeginWriteLine("502 Command not implemented",new SocketCallBack(this.EndSend));
}
#endregion
#region mehtod NOOP
private void NOOP()
{
/* RFC 2821 4.1.1.9 NOOP (NOOP)
NOTE:
This command does not affect any parameters or previously entered
commands. It specifies no action other than that the receiver send
an OK reply.
*/
this.Socket.BeginWriteLine("250 OK",new SocketCallBack(this.EndSend));
}
#endregion
#region method QUIT
private void QUIT(string argsText)
{
/* RFC 2821 4.1.1
NOTE:
Several commands (RSET, DATA, QUIT) are specified as not permitting
parameters. In the absence of specific extensions offered by the
server and accepted by the client, clients MUST NOT send such
parameters and servers SHOULD reject commands containing them as
having invalid syntax.
*/
if(argsText.Length > 0){
this.Socket.BeginWriteLine("500 Syntax error. Syntax:<QUIT>",new SocketCallBack(this.EndSend));
return;
}
/* RFC 2821 4.1.1.10 QUIT (QUIT)
NOTE:
This command specifies that the receiver MUST send an OK reply, and
then close the transmission channel.
*/
// reply: 221 - Close transmission cannel
this.Socket.WriteLine("221 Service closing transmission channel");
// this.Socket.BeginSendLine("221 Service closing transmission channel",null);
}
#endregion
//---- Optional commands
#region function EXPN
private void EXPN()
{
/* RFC 821 EXPN
NOTE:
This command asks the receiver to confirm that the argument
identifies a mailing list, and if so, to return the
membership of that list. The full name of the users (if
known) and the fully specified mailboxes are returned in a
multiline reply.
Example:
S: EXPN lsAll
R: 250-ivar lumi <ivx@lumisoft.ee>
R: 250-<willy@lumisoft.ee>
R: 250 <kaido@lumisoft.ee>
*/
this.Socket.WriteLine("502 Command not implemented");
}
#endregion
#region function HELP
private void HELP()
{
/* RFC 821 HELP
NOTE:
This command causes the receiver to send helpful information
to the sender of the HELP command. The command may take an
argument (e.g., any command name) and return more specific
information as a response.
*/
this.Socket.WriteLine("502 Command not implemented");
}
#endregion
#region method ResetState
private void ResetState()
{
//--- Reset variables
m_BodyType = BodyType.x7_bit;
m_Forward_path.Clear();
m_Reverse_path = "";
// m_Authenticated = false; // Keep AUTH
m_CmdValidator.Reset();
m_CmdValidator.Helo_ok = true;
m_pMsgStream = null;
m_BDat = false;
m_BDAT_ReadedCount = 0;
}
#endregion
#region function EndSend
/// <summary>
/// Is called when asynchronous send completes.
/// </summary>
/// <param name="result">If true, then send was successfull.</param>
/// <param name="count">Count sended.</param>
/// <param name="exception">Exception happend on send. NOTE: available only is result=false.</param>
/// <param name="tag">User data.</param>
private void EndSend(SocketCallBackResult result,long count,Exception exception,object tag)
{
try{
switch(result)
{
case SocketCallBackResult.Ok:
BeginRecieveCmd();
break;
case SocketCallBackResult.SocketClosed:
EndSession();
break;
case SocketCallBackResult.Exception:
OnError(exception);
break;
}
}
catch(Exception x){
OnError(x);
}
}
#endregion
#region Properties Implementation
/// <summary>
/// Gets client reported EHLO/HELO name.
/// </summary>
public string EhloName
{
get{ return m_EhloName; }
}
/// <summary>
/// Gets body type.
/// </summary>
public BodyType BodyType
{
get{ return m_BodyType; }
}
/// <summary>
/// Gets sender.
/// </summary>
public string MailFrom
{
get{ return m_Reverse_path; }
}
/// <summary>
/// Gets recipients.
/// </summary>
public string[] MailTo
{
get{
string[] to = new string[m_Forward_path.Count];
m_Forward_path.Values.CopyTo(to,0);
return to;
}
}
#endregion
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Web.Script.Serialization;
using Microsoft.PythonTools.Analysis;
using Microsoft.PythonTools.Interpreter;
using Microsoft.PythonTools.Parsing.Ast;
using Microsoft.PythonTools.Projects;
namespace Microsoft.PythonTools.Django.Analysis {
[Export(typeof(IAnalysisExtension))]
[AnalysisExtensionName(Name)]
partial class DjangoAnalyzer : IDisposable, IAnalysisExtension {
internal const string Name = "django";
internal readonly Dictionary<string, TagInfo> _tags = new Dictionary<string, TagInfo>();
internal readonly Dictionary<string, TagInfo> _filters = new Dictionary<string, TagInfo>();
private readonly HashSet<IPythonProjectEntry> _hookedEntries = new HashSet<IPythonProjectEntry>();
internal readonly Dictionary<string, TemplateVariables> _templateFiles = new Dictionary<string, TemplateVariables>(StringComparer.OrdinalIgnoreCase);
private ConditionalWeakTable<Node, ContextMarker> _contextTable = new ConditionalWeakTable<Node, ContextMarker>();
private ConditionalWeakTable<Node, DeferredDecorator> _decoratorTable = new ConditionalWeakTable<Node, DeferredDecorator>();
private readonly Dictionary<string, GetTemplateAnalysisValue> _templateAnalysis = new Dictionary<string, GetTemplateAnalysisValue>();
private PythonAnalyzer _analyzer;
internal static readonly Dictionary<string, string> _knownTags = MakeKnownTagsTable();
internal static readonly Dictionary<string, string> _knownFilters = MakeKnownFiltersTable();
public DjangoAnalyzer() {
foreach (var tagName in _nestedEndTags) {
_tags[tagName] = new TagInfo("", null);
}
}
internal static readonly Dictionary<string, string> _nestedTags = new Dictionary<string, string>() {
{ "for", "endfor" },
{ "if", "endif" },
{ "ifequal", "endifequal" },
{ "ifnotequal", "endifnotequal" },
{ "ifchanged", "endifchanged" },
{ "autoescape", "endautoescape" },
{ "comment", "endcomment" },
{ "filter", "endfilter" },
{ "spaceless", "endspaceless" },
{ "with", "endwith" },
{ "empty", "endfor" },
{ "else", "endif" },
};
internal static readonly HashSet<string> _nestedEndTags = MakeNestedEndTags();
internal static readonly HashSet<string> _nestedStartTags = MakeNestedStartTags();
internal static class Commands {
public const string GetTags = "getTags";
public const string GetVariables = "getVariables";
public const string GetFilters = "getFilters";
public const string GetMembers = "getMembers";
}
public string HandleCommand(string commandId, string body) {
var serializer = new JavaScriptSerializer();
Dictionary<string, HashSet<AnalysisValue>> variables;
switch (commandId) {
case Commands.GetTags:
return serializer.Serialize(_tags.Keys.ToArray());
case Commands.GetVariables:
variables = GetVariablesForTemplateFile(body);
if (variables != null) {
return serializer.Serialize(variables.Keys.ToArray());
}
return "[]";
case Commands.GetFilters:
Dictionary<string, string> res = new Dictionary<string, string>();
foreach (var filter in _filters) {
res[filter.Key] = filter.Value.Documentation;
}
return serializer.Serialize(res);
case Commands.GetMembers:
string[] args = serializer.Deserialize<string[]>(body);
var file = args[0];
var varName = args[1];
variables = GetVariablesForTemplateFile(file);
HashSet<AnalysisValue> values;
IProjectEntry projEntry;
if (_analyzer.TryGetProjectEntryByPath(file, out projEntry)) {
var context = projEntry.AnalysisContext;
if (variables != null && variables.TryGetValue(varName, out values)) {
var newTags = new Dictionary<string, PythonMemberType>();
foreach (var member in values.SelectMany(item => item.GetAllMembers(context))) {
string name = member.Key;
PythonMemberType type, newType = GetMemberType(member.Value);
if (!newTags.TryGetValue(name, out type)) {
newTags[name] = newType;
} else if (type != newType && type != PythonMemberType.Unknown && newType != PythonMemberType.Unknown) {
newTags[name] = PythonMemberType.Multiple;
}
}
var dict = newTags.ToDictionary(x => x.Key, x => x.Value.ToString().ToLower());
return serializer.Serialize(dict);
}
}
return "{}";
default:
return String.Empty;
}
}
private static PythonMemberType GetMemberType(IAnalysisSet values) {
PythonMemberType newType = PythonMemberType.Unknown;
foreach (var value in values) {
if (value.MemberType == newType) {
continue;
} else if (newType == PythonMemberType.Unknown) {
newType = value.MemberType;
} else {
newType = PythonMemberType.Multiple;
break;
}
}
return newType;
}
public void Register(PythonAnalyzer analyzer) {
if (analyzer == null) {
throw new ArgumentNullException("analyzer");
}
_tags.Clear();
_filters.Clear();
foreach (var entry in _hookedEntries) {
entry.OnNewParseTree -= OnNewParseTree;
}
_hookedEntries.Clear();
_templateAnalysis.Clear();
_templateFiles.Clear();
_contextTable = new ConditionalWeakTable<Node, ContextMarker>();
_decoratorTable = new ConditionalWeakTable<Node, DeferredDecorator>();
foreach (var keyValue in _knownTags) {
_tags[keyValue.Key] = new TagInfo(keyValue.Value, null);
}
foreach (var keyValue in _knownFilters) {
_filters[keyValue.Key] = new TagInfo(keyValue.Value, null);
}
HookAnalysis(analyzer);
_analyzer = analyzer;
}
private void OnNewParseTree(object sender, EventArgs e) {
var entry = sender as IPythonProjectEntry;
if (entry != null && _hookedEntries.Remove(entry)) {
var removeTags = _tags.Where(kv => kv.Value.Entry == entry).Select(kv => kv.Key).ToList();
var removeFilters = _filters.Where(kv => kv.Value.Entry == entry).Select(kv => kv.Key).ToList();
foreach (var key in removeTags) {
_tags.Remove(key);
}
foreach (var key in removeFilters) {
_filters.Remove(key);
}
}
}
private void HookAnalysis(PythonAnalyzer analyzer) {
analyzer.SpecializeFunction("django.template.loader", "render_to_string", RenderToStringProcessor, true);
analyzer.SpecializeFunction("django.shortcuts", "render_to_response", RenderToStringProcessor, true);
analyzer.SpecializeFunction("django.shortcuts", "render", RenderProcessor, true);
analyzer.SpecializeFunction("django.contrib.gis.shortcuts", "render_to_kml", RenderToStringProcessor, true);
analyzer.SpecializeFunction("django.contrib.gis.shortcuts", "render_to_kmz", RenderToStringProcessor, true);
analyzer.SpecializeFunction("django.contrib.gis.shortcuts", "render_to_text", RenderToStringProcessor, true);
analyzer.SpecializeFunction("django.template.base.Library", "filter", FilterProcessor, true);
analyzer.SpecializeFunction("django.template.base.Library", "filter_function", FilterProcessor, true);
analyzer.SpecializeFunction("django.template.base.Library", "tag", TagProcessor, true);
analyzer.SpecializeFunction("django.template.base.Library", "tag_function", TagProcessor, true);
analyzer.SpecializeFunction("django.template.base.Library", "assignment_tag", TagProcessor, true);
analyzer.SpecializeFunction("django.template.base.Library", "simple_tag", TagProcessor, true);
analyzer.SpecializeFunction("django.template.base.Parser", "parse", ParseProcessor, true);
analyzer.SpecializeFunction("django.template.base", "import_library", "django.template.base.Library", true);
analyzer.SpecializeFunction("django.template.loader", "get_template", GetTemplateProcessor, true);
analyzer.SpecializeFunction("django.template.context", "Context", ContextClassProcessor, true);
analyzer.SpecializeFunction("django.template", "RequestContext", RequestContextClassProcessor, true);
analyzer.SpecializeFunction("django.template.context", "RequestContext", RequestContextClassProcessor, true);
analyzer.SpecializeFunction("django.template.base.Template", "render", TemplateRenderProcessor, true);
// View specializers
analyzer.SpecializeFunction("django.views.generic.detail.DetailView", "as_view", DetailViewProcessor, true);
analyzer.SpecializeFunction("django.views.generic.DetailView", "as_view", DetailViewProcessor, true);
analyzer.SpecializeFunction("django.views.generic.list.ListView", "as_view", ListViewProcessor, true);
analyzer.SpecializeFunction("django.views.generic.ListView", "as_view", ListViewProcessor, true);
}
private IAnalysisSet ParseProcessor(Node node, AnalysisUnit unit, IAnalysisSet[] args, NameExpression[] keywordArgNames) {
// def parse(self, parse_until=None):
// We want to find closing tags here passed to parse_until...
if (args.Length >= 2) {
foreach (var tuple in args[1]) {
foreach (var indexValue in tuple.GetItems()) {
var values = indexValue.Value;
foreach (var value in values) {
var str = value.GetConstantValueAsString();
if (str != null) {
RegisterTag(unit.Project, _tags, str);
}
}
}
}
}
return AnalysisSet.Empty;
}
#region IDisposable Members
public void Dispose() {
_filters.Clear();
_tags.Clear();
foreach (var entry in _hookedEntries) {
entry.OnNewParseTree -= OnNewParseTree;
}
_hookedEntries.Clear();
_templateAnalysis.Clear();
_templateFiles.Clear();
}
#endregion
/// <summary>
/// Specializes "DetailView.as_view"
/// </summary>
private IAnalysisSet DetailViewProcessor(Node node, AnalysisUnit unit, IAnalysisSet[] args, NameExpression[] keywordArgNames) {
return ViewProcessor(node, unit, args, keywordArgNames, "_details.html");
}
/// <summary>
/// Specializes "ListView.as_view"
/// </summary>
private IAnalysisSet ListViewProcessor(Node node, AnalysisUnit unit, IAnalysisSet[] args, NameExpression[] keywordArgNames) {
return ViewProcessor(node, unit, args, keywordArgNames, "_list.html");
}
private IAnalysisSet ViewProcessor(Node node, AnalysisUnit unit, IAnalysisSet[] args, NameExpression[] keywordArgNames, string defaultTemplateNameSuffix) {
var templateNames = GetArg(args, keywordArgNames, "template_name", -1, AnalysisSet.Empty)
.Select(v => v.GetConstantValueAsString())
.Where(s => !string.IsNullOrEmpty(s))
.ToList();
var templateNameSuffix = GetArg(args, keywordArgNames, "template_name_suffix", -1, AnalysisSet.Empty)
.Select(v => v.GetConstantValueAsString())
.Where(s => !string.IsNullOrEmpty(s))
.ToList();
var contextObjName = GetArg(args, keywordArgNames, "context_object_name", -1, AnalysisSet.Empty)
.Select(v => v.GetConstantValueAsString())
.Where(s => !string.IsNullOrEmpty(s))
.ToList();
var model = GetArg(args, keywordArgNames, "model", -1);
// TODO: Support this (this requires some analyis improvements as currently we
// typically don't get useful values for queryset
// Right now, queryset only flows into the template if template_name
// is also specified.
var querySet = GetArg(args, keywordArgNames, "queryset", -1);
if (templateNames.Any()) {
foreach (var templateName in templateNames) {
AddViewTemplate(unit, model, querySet, contextObjName, templateName);
}
} else if (model != null) {
// template name is [app]/[modelname]_[template_name_suffix]
string appName;
int firstDot = unit.Project.ModuleName.IndexOf('.');
if (firstDot != -1) {
appName = unit.Project.ModuleName.Substring(0, firstDot);
} else {
appName = unit.Project.ModuleName;
}
foreach (var modelInst in model) {
string baseName = appName + "/" + modelInst.Name.ToLower();
foreach (var suffix in templateNameSuffix.DefaultIfEmpty(defaultTemplateNameSuffix)) {
AddViewTemplate(unit, model, querySet, contextObjName, baseName + suffix);
}
}
}
return AnalysisSet.Empty;
}
private void AddViewTemplate(
AnalysisUnit unit,
IAnalysisSet model,
IAnalysisSet querySet,
IEnumerable<string> contextObjName,
string templateName
) {
TemplateVariables tags;
if (!_templateFiles.TryGetValue(templateName, out tags)) {
_templateFiles[templateName] = tags = new TemplateVariables();
}
if (querySet != null) {
foreach (var name in contextObjName) {
tags.UpdateVariable(name, unit, AnalysisSet.Empty);
}
} else if (model != null) {
foreach (var modelInst in model) {
foreach (var name in contextObjName.DefaultIfEmpty(modelInst.Name.ToLower())) {
tags.UpdateVariable(name, unit, modelInst.GetInstanceType());
}
}
}
}
private static void GetStringArguments(HashSet<string> arguments, IAnalysisSet arg) {
foreach (var value in arg) {
string templateName = value.GetConstantValueAsString();
if (templateName != null) {
arguments.Add(templateName);
}
}
}
private IAnalysisSet FilterProcessor(Node node, AnalysisUnit unit, IAnalysisSet[] args, NameExpression[] keywordArgNames) {
return ProcessTags(node, unit, args, keywordArgNames, _filters);
}
private IAnalysisSet TagProcessor(Node node, AnalysisUnit unit, IAnalysisSet[] args, NameExpression[] keywordArgNames) {
return ProcessTags(node, unit, args, keywordArgNames, _tags);
}
class DeferredDecorator : AnalysisValue {
private readonly DjangoAnalyzer _analyzer;
private readonly IAnalysisSet _name;
private readonly Dictionary<string, TagInfo> _tags;
public DeferredDecorator(DjangoAnalyzer analyzer, IAnalysisSet name, Dictionary<string, TagInfo> tags) {
_analyzer = analyzer;
_name = name;
_tags = tags;
}
public override IAnalysisSet Call(Node node, AnalysisUnit unit, IAnalysisSet[] args, NameExpression[] keywordArgNames) {
_analyzer.ProcessTags(node, unit, new[] { AnalysisSet.Empty, _name, args[0] }, NameExpression.EmptyArray, _tags);
return AnalysisSet.Empty;
}
}
private IAnalysisSet ProcessTags(Node node, AnalysisUnit unit, IAnalysisSet[] args, NameExpression[] keywordArgNames, Dictionary<string, TagInfo> tags) {
if (args.Length >= 3) {
// library.filter(name, value)
foreach (var name in args[1]) {
var constName = name.GetConstantValue();
if (constName == Type.Missing) {
if (name.Name != null) {
RegisterTag(unit.Project, tags, name.Name, name.Documentation);
}
} else {
var strName = name.GetConstantValueAsString();
if (strName != null) {
RegisterTag(unit.Project, tags, strName);
}
}
}
foreach (var func in args[2]) {
// TODO: Find a better node
var parser = unit.FindAnalysisValueByName(node, "django.template.base.Parser");
if (parser != null) {
func.Call(node, unit, new[] { parser, AnalysisSet.Empty }, NameExpression.EmptyArray);
}
}
} else if (args.Length >= 2) {
// library.filter(value)
foreach (var name in args[1]) {
string tagName = name.Name ?? name.GetConstantValueAsString();
if (tagName != null) {
RegisterTag(unit.Project, tags, tagName, name.Documentation);
}
if (name.MemberType != PythonMemberType.Constant) {
var parser = unit.FindAnalysisValueByName(node, "django.template.base.Parser");
if (parser != null) {
name.Call(node, unit, new[] { parser, AnalysisSet.Empty }, NameExpression.EmptyArray);
}
}
}
} else if (args.Length == 1) {
foreach (var name in args[0]) {
if (name.MemberType == PythonMemberType.Constant) {
// library.filter('name')
DeferredDecorator dec;
if (!_decoratorTable.TryGetValue(node, out dec)) {
dec = new DeferredDecorator(this, name, tags);
_decoratorTable.Add(node, dec);
}
return dec;
} else if (name.Name != null) {
// library.filter
RegisterTag(unit.Project, tags, name.Name, name.Documentation);
}
}
}
return AnalysisSet.Empty;
}
private void RegisterTag(IPythonProjectEntry entry, Dictionary<string, TagInfo> tags, string name, string documentation = null) {
TagInfo tag;
if (!tags.TryGetValue(name, out tag) || (String.IsNullOrWhiteSpace(tag.Documentation) && !String.IsNullOrEmpty(documentation))) {
tags[name] = tag = new TagInfo(documentation, entry);
if (entry != null && _hookedEntries.Add(entry)) {
entry.OnNewParseTree += OnNewParseTree;
}
}
}
private IAnalysisSet RenderToStringProcessor(Node node, AnalysisUnit unit, IAnalysisSet[] args, NameExpression[] keywordArgNames) {
var names = GetArg(args, keywordArgNames, "template_name", 0);
var context = GetArg(args, keywordArgNames, "context_instance", 2);
var dictArgs = context == null ? GetArg(args, keywordArgNames, "dictionary", 1) : null;
if (dictArgs != null || context != null) {
foreach (var name in names.Select(n => n.GetConstantValueAsString()).Where(n => !string.IsNullOrEmpty(n))) {
AddTemplateMapping(unit, name, dictArgs, context);
}
}
return AnalysisSet.Empty;
}
private IAnalysisSet RenderProcessor(Node node, AnalysisUnit unit, IAnalysisSet[] args, NameExpression[] keywordArgNames) {
var names = GetArg(args, keywordArgNames, "template_name", 1);
var context = GetArg(args, keywordArgNames, "context_instance", 3);
var dictArgs = context == null ? GetArg(args, keywordArgNames, "dictionary", 2) : null;
if (dictArgs != null || context != null) {
foreach (var name in names.Select(n => n.GetConstantValueAsString()).Where(n => !string.IsNullOrEmpty(n))) {
AddTemplateMapping(unit, name, dictArgs, context);
}
}
return AnalysisSet.Empty;
}
private void AddTemplateMapping(
AnalysisUnit unit,
string filename,
IEnumerable<AnalysisValue> dictArgs,
IEnumerable<AnalysisValue> context
) {
TemplateVariables tags;
if (!_templateFiles.TryGetValue(filename, out tags)) {
_templateFiles[filename] = tags = new TemplateVariables();
}
IEnumerable<KeyValuePair<IAnalysisSet, IAnalysisSet>> items = null;
if (context != null) {
items = context.OfType<ContextMarker>()
.SelectMany(ctxt => ctxt.Arguments.SelectMany(v => v.GetItems()));
} else if (dictArgs != null) {
items = dictArgs.SelectMany(v => v.GetItems());
}
if (items != null) {
foreach (var keyValue in items) {
foreach (var key in keyValue.Key) {
var keyName = key.GetConstantValueAsString();
if (keyName != null) {
tags.UpdateVariable(keyName, unit, keyValue.Value);
}
}
}
}
}
class GetTemplateAnalysisValue : AnalysisValue {
public readonly string Filename;
public readonly TemplateRenderMethod RenderMethod;
public readonly DjangoAnalyzer Analyzer;
public GetTemplateAnalysisValue(DjangoAnalyzer analyzer, string name) {
Analyzer = analyzer;
Filename = name;
RenderMethod = new TemplateRenderMethod(this);
}
public override IAnalysisSet GetMember(Node node, AnalysisUnit unit, string name) {
if (name == "render") {
return RenderMethod;
}
return base.GetMember(node, unit, name);
}
}
class TemplateRenderMethod : AnalysisValue {
public readonly GetTemplateAnalysisValue GetTemplateValue;
public TemplateRenderMethod(GetTemplateAnalysisValue getTemplateAnalysisValue) {
this.GetTemplateValue = getTemplateAnalysisValue;
}
public override IAnalysisSet Call(Node node, AnalysisUnit unit, IAnalysisSet[] args, NameExpression[] keywordArgNames) {
if (args.Length == 1) {
string filename = GetTemplateValue.Filename;
GetTemplateValue.Analyzer.AddTemplateMapping(unit, filename, null, args[0]);
}
return base.Call(node, unit, args, keywordArgNames);
}
}
private IAnalysisSet GetTemplateProcessor(Node node, AnalysisUnit unit, IAnalysisSet[] args, NameExpression[] keywordArgNames) {
var res = AnalysisSet.Empty;
if (args.Length >= 1) {
foreach (var filename in args[0]) {
var file = filename.GetConstantValueAsString();
if (file != null) {
GetTemplateAnalysisValue value;
if (!_templateAnalysis.TryGetValue(file, out value)) {
_templateAnalysis[file] = value = new GetTemplateAnalysisValue(this, file);
}
res = res.Add(value);
}
}
}
return res;
}
class ContextMarker : AnalysisValue {
public readonly HashSet<AnalysisValue> Arguments;
public ContextMarker() {
Arguments = new HashSet<AnalysisValue>();
}
public override IEnumerable<KeyValuePair<IAnalysisSet, IAnalysisSet>> GetItems() {
return Arguments.SelectMany(av => av.GetItems());
}
}
private IAnalysisSet ContextClassProcessor(Node node, AnalysisUnit unit, IAnalysisSet[] args, NameExpression[] keywordArgNames) {
var dict = GetArg(args, keywordArgNames, "dict_", 0);
if (dict != null && dict.Any()) {
ContextMarker contextValue;
if (!_contextTable.TryGetValue(node, out contextValue)) {
contextValue = new ContextMarker();
_contextTable.Add(node, contextValue);
}
contextValue.Arguments.UnionWith(dict);
return contextValue;
}
return AnalysisSet.Empty;
}
private IAnalysisSet RequestContextClassProcessor(Node node, AnalysisUnit unit, IAnalysisSet[] args, NameExpression[] keywordArgNames) {
var dict = GetArg(args, keywordArgNames, "dict_", 1);
if (dict != null) {
return ContextClassProcessor(node, unit, new[] { dict }, NameExpression.EmptyArray);
}
return AnalysisSet.Empty;
}
private IAnalysisSet TemplateRenderProcessor(Node node, AnalysisUnit unit, IAnalysisSet[] args, NameExpression[] keywordArgNames) {
if (args.Length == 2) {
foreach (var templateValue in args[0].OfType<GetTemplateAnalysisValue>()) {
AddTemplateMapping(unit, templateValue.Filename, null, args[1]);
}
}
return AnalysisSet.Empty;
}
private static IAnalysisSet GetArg(
IAnalysisSet[] args,
NameExpression[] keywordArgNames,
string name,
int index,
IAnalysisSet defaultValue = null
) {
for (int i = 0, j = args.Length - keywordArgNames.Length;
i < keywordArgNames.Length && j < args.Length;
++i, ++j) {
var kwArg = keywordArgNames[i];
if (kwArg == null) {
Debug.Fail("Null keyword argument");
} else if (kwArg.Name == name) {
return args[j];
}
}
if (0 <= index && index < args.Length) {
return args[index];
}
return defaultValue;
}
public Dictionary<string, HashSet<AnalysisValue>> GetVariablesForTemplateFile(string filename) {
string curLevel = filename; // is C:\Fob\Oar\Baz\fob.html
string curPath = filename = Path.GetFileName(filename); // is fob.html
for (; ; ) {
string curFilename = filename.Replace('\\', '/');
TemplateVariables res;
if (_templateFiles.TryGetValue(curFilename, out res)) {
return res.GetAllValues();
}
curLevel = Path.GetDirectoryName(curLevel); // C:\Fob\Oar\Baz\fob.html gets us C:\Fob\Oar\Baz
var fn2 = Path.GetFileName(curLevel); // Gets us Baz
if (String.IsNullOrEmpty(fn2)) {
break;
}
curPath = Path.Combine(fn2, curPath); // Get us Baz\fob.html
filename = curPath;
}
return null;
}
private static HashSet<string> MakeNestedEndTags() {
HashSet<string> res = new HashSet<string>();
foreach (var value in _nestedTags.Values) {
res.Add(value);
}
return res;
}
private static HashSet<string> MakeNestedStartTags() {
HashSet<string> res = new HashSet<string>();
foreach (var key in _nestedTags.Keys) {
res.Add(key);
}
return res;
}
}
}
| |
// 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 Internal.Runtime.Augments;
using Microsoft.Win32;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
namespace System
{
public static partial class Environment
{
public static int ExitCode { get { return EnvironmentAugments.ExitCode; } set { EnvironmentAugments.ExitCode = value; } }
private static string ExpandEnvironmentVariablesCore(string name)
{
int currentSize = 100;
StringBuilder result = StringBuilderCache.Acquire(currentSize); // A somewhat reasonable default size
result.Length = 0;
int size = Interop.Kernel32.ExpandEnvironmentStringsW(name, result, currentSize);
if (size == 0)
{
StringBuilderCache.Release(result);
Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
}
while (size > currentSize)
{
currentSize = size;
result.Capacity = currentSize;
result.Length = 0;
size = Interop.Kernel32.ExpandEnvironmentStringsW(name, result, currentSize);
if (size == 0)
{
StringBuilderCache.Release(result);
Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
}
}
return StringBuilderCache.GetStringAndRelease(result);
}
private static string GetFolderPathCore(SpecialFolder folder, SpecialFolderOption option)
{
// We're using SHGetKnownFolderPath instead of SHGetFolderPath as SHGetFolderPath is
// capped at MAX_PATH.
//
// Because we validate both of the input enums we shouldn't have to care about CSIDL and flag
// definitions we haven't mapped. If we remove or loosen the checks we'd have to account
// for mapping here (this includes tweaking as SHGetFolderPath would do).
//
// The only SpecialFolderOption defines we have are equivalent to KnownFolderFlags.
string folderGuid;
switch (folder)
{
case SpecialFolder.ApplicationData:
folderGuid = Interop.Shell32.KnownFolders.RoamingAppData;
break;
case SpecialFolder.CommonApplicationData:
folderGuid = Interop.Shell32.KnownFolders.ProgramData;
break;
case SpecialFolder.LocalApplicationData:
folderGuid = Interop.Shell32.KnownFolders.LocalAppData;
break;
case SpecialFolder.Cookies:
folderGuid = Interop.Shell32.KnownFolders.Cookies;
break;
case SpecialFolder.Desktop:
folderGuid = Interop.Shell32.KnownFolders.Desktop;
break;
case SpecialFolder.Favorites:
folderGuid = Interop.Shell32.KnownFolders.Favorites;
break;
case SpecialFolder.History:
folderGuid = Interop.Shell32.KnownFolders.History;
break;
case SpecialFolder.InternetCache:
folderGuid = Interop.Shell32.KnownFolders.InternetCache;
break;
case SpecialFolder.Programs:
folderGuid = Interop.Shell32.KnownFolders.Programs;
break;
case SpecialFolder.MyComputer:
folderGuid = Interop.Shell32.KnownFolders.ComputerFolder;
break;
case SpecialFolder.MyMusic:
folderGuid = Interop.Shell32.KnownFolders.Music;
break;
case SpecialFolder.MyPictures:
folderGuid = Interop.Shell32.KnownFolders.Pictures;
break;
case SpecialFolder.MyVideos:
folderGuid = Interop.Shell32.KnownFolders.Videos;
break;
case SpecialFolder.Recent:
folderGuid = Interop.Shell32.KnownFolders.Recent;
break;
case SpecialFolder.SendTo:
folderGuid = Interop.Shell32.KnownFolders.SendTo;
break;
case SpecialFolder.StartMenu:
folderGuid = Interop.Shell32.KnownFolders.StartMenu;
break;
case SpecialFolder.Startup:
folderGuid = Interop.Shell32.KnownFolders.Startup;
break;
case SpecialFolder.System:
folderGuid = Interop.Shell32.KnownFolders.System;
break;
case SpecialFolder.Templates:
folderGuid = Interop.Shell32.KnownFolders.Templates;
break;
case SpecialFolder.DesktopDirectory:
folderGuid = Interop.Shell32.KnownFolders.Desktop;
break;
case SpecialFolder.Personal:
// Same as Personal
// case SpecialFolder.MyDocuments:
folderGuid = Interop.Shell32.KnownFolders.Documents;
break;
case SpecialFolder.ProgramFiles:
folderGuid = Interop.Shell32.KnownFolders.ProgramFiles;
break;
case SpecialFolder.CommonProgramFiles:
folderGuid = Interop.Shell32.KnownFolders.ProgramFilesCommon;
break;
case SpecialFolder.AdminTools:
folderGuid = Interop.Shell32.KnownFolders.AdminTools;
break;
case SpecialFolder.CDBurning:
folderGuid = Interop.Shell32.KnownFolders.CDBurning;
break;
case SpecialFolder.CommonAdminTools:
folderGuid = Interop.Shell32.KnownFolders.CommonAdminTools;
break;
case SpecialFolder.CommonDocuments:
folderGuid = Interop.Shell32.KnownFolders.PublicDocuments;
break;
case SpecialFolder.CommonMusic:
folderGuid = Interop.Shell32.KnownFolders.PublicMusic;
break;
case SpecialFolder.CommonOemLinks:
folderGuid = Interop.Shell32.KnownFolders.CommonOEMLinks;
break;
case SpecialFolder.CommonPictures:
folderGuid = Interop.Shell32.KnownFolders.PublicPictures;
break;
case SpecialFolder.CommonStartMenu:
folderGuid = Interop.Shell32.KnownFolders.CommonStartMenu;
break;
case SpecialFolder.CommonPrograms:
folderGuid = Interop.Shell32.KnownFolders.CommonPrograms;
break;
case SpecialFolder.CommonStartup:
folderGuid = Interop.Shell32.KnownFolders.CommonStartup;
break;
case SpecialFolder.CommonDesktopDirectory:
folderGuid = Interop.Shell32.KnownFolders.PublicDesktop;
break;
case SpecialFolder.CommonTemplates:
folderGuid = Interop.Shell32.KnownFolders.CommonTemplates;
break;
case SpecialFolder.CommonVideos:
folderGuid = Interop.Shell32.KnownFolders.PublicVideos;
break;
case SpecialFolder.Fonts:
folderGuid = Interop.Shell32.KnownFolders.Fonts;
break;
case SpecialFolder.NetworkShortcuts:
folderGuid = Interop.Shell32.KnownFolders.NetHood;
break;
case SpecialFolder.PrinterShortcuts:
folderGuid = Interop.Shell32.KnownFolders.PrintersFolder;
break;
case SpecialFolder.UserProfile:
folderGuid = Interop.Shell32.KnownFolders.Profile;
break;
case SpecialFolder.CommonProgramFilesX86:
folderGuid = Interop.Shell32.KnownFolders.ProgramFilesCommonX86;
break;
case SpecialFolder.ProgramFilesX86:
folderGuid = Interop.Shell32.KnownFolders.ProgramFilesX86;
break;
case SpecialFolder.Resources:
folderGuid = Interop.Shell32.KnownFolders.ResourceDir;
break;
case SpecialFolder.LocalizedResources:
folderGuid = Interop.Shell32.KnownFolders.LocalizedResourcesDir;
break;
case SpecialFolder.SystemX86:
folderGuid = Interop.Shell32.KnownFolders.SystemX86;
break;
case SpecialFolder.Windows:
folderGuid = Interop.Shell32.KnownFolders.Windows;
break;
default:
return string.Empty;
}
return GetKnownFolderPath(folderGuid, option);
}
private static string GetKnownFolderPath(string folderGuid, SpecialFolderOption option)
{
Guid folderId = new Guid(folderGuid);
string path;
int hr = Interop.Shell32.SHGetKnownFolderPath(folderId, (uint)option, IntPtr.Zero, out path);
if (hr != 0) // Not S_OK
{
if (hr == Interop.Shell32.COR_E_PLATFORMNOTSUPPORTED)
{
throw new PlatformNotSupportedException();
}
else
{
return string.Empty;
}
}
return path;
}
private static bool Is64BitOperatingSystemWhen32BitProcess
{
get
{
bool isWow64;
return Interop.Kernel32.IsWow64Process(Interop.Kernel32.GetCurrentProcess(), out isWow64) && isWow64;
}
}
public static string MachineName
{
get
{
string name = Interop.Kernel32.GetComputerName();
if (name == null)
{
throw new InvalidOperationException(SR.InvalidOperation_ComputerName);
}
return name;
}
}
private static unsafe Lazy<OperatingSystem> s_osVersion = new Lazy<OperatingSystem>(() =>
{
var version = new Interop.Kernel32.OSVERSIONINFOEX { dwOSVersionInfoSize = sizeof(Interop.Kernel32.OSVERSIONINFOEX) };
if (!Interop.Kernel32.GetVersionExW(ref version))
{
throw new InvalidOperationException(SR.InvalidOperation_GetVersion);
}
return new OperatingSystem(
PlatformID.Win32NT,
new Version(version.dwMajorVersion, version.dwMinorVersion, version.dwBuildNumber, (version.wServicePackMajor << 16) | version.wServicePackMinor),
Marshal.PtrToStringUni((IntPtr)version.szCSDVersion));
});
public static int ProcessorCount
{
get
{
// First try GetLogicalProcessorInformationEx, caching the result as desktop/coreclr does.
// If that fails for some reason, fall back to a non-cached result from GetSystemInfo.
// (See SystemNative::GetProcessorCount in coreclr for a comparison.)
int pc = s_processorCountFromGetLogicalProcessorInformationEx.Value;
return pc != 0 ? pc : ProcessorCountFromSystemInfo;
}
}
private static readonly unsafe Lazy<int> s_processorCountFromGetLogicalProcessorInformationEx = new Lazy<int>(() =>
{
// Determine how much size we need for a call to GetLogicalProcessorInformationEx
uint len = 0;
if (!Interop.Kernel32.GetLogicalProcessorInformationEx(Interop.Kernel32.LOGICAL_PROCESSOR_RELATIONSHIP.RelationGroup, IntPtr.Zero, ref len) &&
Marshal.GetLastWin32Error() == Interop.Errors.ERROR_INSUFFICIENT_BUFFER)
{
// Allocate that much space
Debug.Assert(len > 0);
var buffer = new byte[len];
fixed (byte* bufferPtr = buffer)
{
// Call GetLogicalProcessorInformationEx with the allocated buffer
if (Interop.Kernel32.GetLogicalProcessorInformationEx(Interop.Kernel32.LOGICAL_PROCESSOR_RELATIONSHIP.RelationGroup, (IntPtr)bufferPtr, ref len))
{
// Walk each SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX in the buffer, where the Size of each dictates how
// much space it's consuming. For each group relation, count the number of active processors in each of its group infos.
int processorCount = 0;
byte* ptr = bufferPtr, endPtr = bufferPtr + len;
while (ptr < endPtr)
{
var current = (Interop.Kernel32.SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX*)ptr;
if (current->Relationship == Interop.Kernel32.LOGICAL_PROCESSOR_RELATIONSHIP.RelationGroup)
{
Interop.Kernel32.PROCESSOR_GROUP_INFO* groupInfo = ¤t->Group.GroupInfo;
int groupCount = current->Group.ActiveGroupCount;
for (int i = 0; i < groupCount; i++)
{
processorCount += (groupInfo + i)->ActiveProcessorCount;
}
}
ptr += current->Size;
}
return processorCount;
}
}
}
return 0;
});
public static string SystemDirectory
{
get
{
StringBuilder sb = StringBuilderCache.Acquire(PathInternal.MaxShortPath);
if (Interop.Kernel32.GetSystemDirectoryW(sb, PathInternal.MaxShortPath) == 0)
{
StringBuilderCache.Release(sb);
throw Win32Marshal.GetExceptionForLastWin32Error();
}
return StringBuilderCache.GetStringAndRelease(sb);
}
}
public static string UserName
{
get
{
// Use GetUserNameExW, as GetUserNameW isn't available on all platforms, e.g. Win7
var domainName = new StringBuilder(1024);
uint domainNameLen = (uint)domainName.Capacity;
if (Interop.Secur32.GetUserNameExW(Interop.Secur32.NameSamCompatible, domainName, ref domainNameLen) == 1)
{
string samName = domainName.ToString();
int index = samName.IndexOf('\\');
if (index != -1)
{
return samName.Substring(index + 1);
}
}
return string.Empty;
}
}
public static string UserDomainName
{
get
{
var domainName = new StringBuilder(1024);
uint domainNameLen = (uint)domainName.Capacity;
if (Interop.Secur32.GetUserNameExW(Interop.Secur32.NameSamCompatible, domainName, ref domainNameLen) == 1)
{
string samName = domainName.ToString();
int index = samName.IndexOf('\\');
if (index != -1)
{
return samName.Substring(0, index);
}
}
domainNameLen = (uint)domainName.Capacity;
byte[] sid = new byte[1024];
int sidLen = sid.Length;
int peUse;
if (!Interop.Advapi32.LookupAccountNameW(null, UserName, sid, ref sidLen, domainName, ref domainNameLen, out peUse))
{
throw new InvalidOperationException(Win32Marshal.GetExceptionForLastWin32Error().Message);
}
return domainName.ToString();
}
}
}
}
| |
using System;
using System.Linq;
using System.Collections.Generic;
using Blueprint41;
using Blueprint41.Core;
using Blueprint41.Query;
using Blueprint41.DatastoreTemplates;
using q = Domain.Data.Query;
namespace Domain.Data.Manipulation
{
public interface IEmailAddressOriginalData : INeo4jBaseOriginalData
{
string EmailAddr { get; }
IEnumerable<Person> EmailAddresses { get; }
}
public partial class EmailAddress : OGM<EmailAddress, EmailAddress.EmailAddressData, System.String>, INeo4jBase, IEmailAddressOriginalData
{
#region Initialize
static EmailAddress()
{
Register.Types();
}
protected override void RegisterGeneratedStoredQueries()
{
#region LoadByKeys
RegisterQuery(nameof(LoadByKeys), (query, alias) => query.
Where(alias.Uid.In(Parameter.New<System.String>(Param0))));
#endregion
AdditionalGeneratedStoredQueries();
}
partial void AdditionalGeneratedStoredQueries();
public static Dictionary<System.String, EmailAddress> LoadByKeys(IEnumerable<System.String> uids)
{
return FromQuery(nameof(LoadByKeys), new Parameter(Param0, uids.ToArray(), typeof(System.String))).ToDictionary(item=> item.Uid, item => item);
}
protected static void RegisterQuery(string name, Func<IMatchQuery, q.EmailAddressAlias, IWhereQuery> query)
{
q.EmailAddressAlias alias;
IMatchQuery matchQuery = Blueprint41.Transaction.CompiledQuery.Match(q.Node.EmailAddress.Alias(out alias));
IWhereQuery partial = query.Invoke(matchQuery, alias);
ICompiled compiled = partial.Return(alias).Compile();
RegisterQuery(name, compiled);
}
public override string ToString()
{
return $"EmailAddress => EmailAddr : {this.EmailAddr?.ToString() ?? "null"}, Uid : {this.Uid}";
}
public override int GetHashCode()
{
return base.GetHashCode();
}
protected override void LazySet()
{
base.LazySet();
if (PersistenceState == PersistenceState.NewAndChanged || PersistenceState == PersistenceState.LoadedAndChanged)
{
if ((object)InnerData == (object)OriginalData)
OriginalData = new EmailAddressData(InnerData);
}
}
#endregion
#region Validations
protected override void ValidateSave()
{
bool isUpdate = (PersistenceState != PersistenceState.New && PersistenceState != PersistenceState.NewAndChanged);
#pragma warning disable CS0472
#pragma warning restore CS0472
}
protected override void ValidateDelete()
{
}
#endregion
#region Inner Data
public class EmailAddressData : Data<System.String>
{
public EmailAddressData()
{
}
public EmailAddressData(EmailAddressData data)
{
EmailAddr = data.EmailAddr;
EmailAddresses = data.EmailAddresses;
Uid = data.Uid;
}
#region Initialize Collections
protected override void InitializeCollections()
{
NodeType = "EmailAddress";
EmailAddresses = new EntityCollection<Person>(Wrapper, Members.EmailAddresses, item => { if (Members.EmailAddresses.Events.HasRegisteredChangeHandlers) { object loadHack = item.EmailAddress; } });
}
public string NodeType { get; private set; }
sealed public override System.String GetKey() { return Entity.Parent.PersistenceProvider.ConvertFromStoredType<System.String>(Uid); }
sealed protected override void SetKey(System.String key) { Uid = (string)Entity.Parent.PersistenceProvider.ConvertToStoredType<System.String>(key); base.SetKey(Uid); }
#endregion
#region Map Data
sealed public override IDictionary<string, object> MapTo()
{
IDictionary<string, object> dictionary = new Dictionary<string, object>();
dictionary.Add("EmailAddr", EmailAddr);
dictionary.Add("Uid", Uid);
return dictionary;
}
sealed public override void MapFrom(IReadOnlyDictionary<string, object> properties)
{
object value;
if (properties.TryGetValue("EmailAddr", out value))
EmailAddr = (string)value;
if (properties.TryGetValue("Uid", out value))
Uid = (string)value;
}
#endregion
#region Members for interface IEmailAddress
public string EmailAddr { get; set; }
public EntityCollection<Person> EmailAddresses { get; private set; }
#endregion
#region Members for interface INeo4jBase
public string Uid { get; set; }
#endregion
}
#endregion
#region Outer Data
#region Members for interface IEmailAddress
public string EmailAddr { get { LazyGet(); return InnerData.EmailAddr; } set { if (LazySet(Members.EmailAddr, InnerData.EmailAddr, value)) InnerData.EmailAddr = value; } }
public EntityCollection<Person> EmailAddresses { get { return InnerData.EmailAddresses; } }
private void ClearEmailAddresses(DateTime? moment)
{
((ILookupHelper<Person>)InnerData.EmailAddresses).ClearLookup(moment);
}
#endregion
#region Members for interface INeo4jBase
public string Uid { get { return InnerData.Uid; } set { KeySet(() => InnerData.Uid = value); } }
#endregion
#region Virtual Node Type
public string NodeType { get { return InnerData.NodeType; } }
#endregion
#endregion
#region Reflection
private static EmailAddressMembers members = null;
public static EmailAddressMembers Members
{
get
{
if (members == null)
{
lock (typeof(EmailAddress))
{
if (members == null)
members = new EmailAddressMembers();
}
}
return members;
}
}
public class EmailAddressMembers
{
internal EmailAddressMembers() { }
#region Members for interface IEmailAddress
public Property EmailAddr { get; } = Datastore.AdventureWorks.Model.Entities["EmailAddress"].Properties["EmailAddr"];
public Property EmailAddresses { get; } = Datastore.AdventureWorks.Model.Entities["EmailAddress"].Properties["EmailAddresses"];
#endregion
#region Members for interface INeo4jBase
public Property Uid { get; } = Datastore.AdventureWorks.Model.Entities["Neo4jBase"].Properties["Uid"];
#endregion
}
private static EmailAddressFullTextMembers fullTextMembers = null;
public static EmailAddressFullTextMembers FullTextMembers
{
get
{
if (fullTextMembers == null)
{
lock (typeof(EmailAddress))
{
if (fullTextMembers == null)
fullTextMembers = new EmailAddressFullTextMembers();
}
}
return fullTextMembers;
}
}
public class EmailAddressFullTextMembers
{
internal EmailAddressFullTextMembers() { }
}
sealed public override Entity GetEntity()
{
if (entity == null)
{
lock (typeof(EmailAddress))
{
if (entity == null)
entity = Datastore.AdventureWorks.Model.Entities["EmailAddress"];
}
}
return entity;
}
private static EmailAddressEvents events = null;
public static EmailAddressEvents Events
{
get
{
if (events == null)
{
lock (typeof(EmailAddress))
{
if (events == null)
events = new EmailAddressEvents();
}
}
return events;
}
}
public class EmailAddressEvents
{
#region OnNew
private bool onNewIsRegistered = false;
private EventHandler<EmailAddress, EntityEventArgs> onNew;
public event EventHandler<EmailAddress, EntityEventArgs> OnNew
{
add
{
lock (this)
{
if (!onNewIsRegistered)
{
Entity.Events.OnNew -= onNewProxy;
Entity.Events.OnNew += onNewProxy;
onNewIsRegistered = true;
}
onNew += value;
}
}
remove
{
lock (this)
{
onNew -= value;
if (onNew == null && onNewIsRegistered)
{
Entity.Events.OnNew -= onNewProxy;
onNewIsRegistered = false;
}
}
}
}
private void onNewProxy(object sender, EntityEventArgs args)
{
EventHandler<EmailAddress, EntityEventArgs> handler = onNew;
if ((object)handler != null)
handler.Invoke((EmailAddress)sender, args);
}
#endregion
#region OnDelete
private bool onDeleteIsRegistered = false;
private EventHandler<EmailAddress, EntityEventArgs> onDelete;
public event EventHandler<EmailAddress, EntityEventArgs> OnDelete
{
add
{
lock (this)
{
if (!onDeleteIsRegistered)
{
Entity.Events.OnDelete -= onDeleteProxy;
Entity.Events.OnDelete += onDeleteProxy;
onDeleteIsRegistered = true;
}
onDelete += value;
}
}
remove
{
lock (this)
{
onDelete -= value;
if (onDelete == null && onDeleteIsRegistered)
{
Entity.Events.OnDelete -= onDeleteProxy;
onDeleteIsRegistered = false;
}
}
}
}
private void onDeleteProxy(object sender, EntityEventArgs args)
{
EventHandler<EmailAddress, EntityEventArgs> handler = onDelete;
if ((object)handler != null)
handler.Invoke((EmailAddress)sender, args);
}
#endregion
#region OnSave
private bool onSaveIsRegistered = false;
private EventHandler<EmailAddress, EntityEventArgs> onSave;
public event EventHandler<EmailAddress, EntityEventArgs> OnSave
{
add
{
lock (this)
{
if (!onSaveIsRegistered)
{
Entity.Events.OnSave -= onSaveProxy;
Entity.Events.OnSave += onSaveProxy;
onSaveIsRegistered = true;
}
onSave += value;
}
}
remove
{
lock (this)
{
onSave -= value;
if (onSave == null && onSaveIsRegistered)
{
Entity.Events.OnSave -= onSaveProxy;
onSaveIsRegistered = false;
}
}
}
}
private void onSaveProxy(object sender, EntityEventArgs args)
{
EventHandler<EmailAddress, EntityEventArgs> handler = onSave;
if ((object)handler != null)
handler.Invoke((EmailAddress)sender, args);
}
#endregion
#region OnPropertyChange
public static class OnPropertyChange
{
#region OnEmailAddr
private static bool onEmailAddrIsRegistered = false;
private static EventHandler<EmailAddress, PropertyEventArgs> onEmailAddr;
public static event EventHandler<EmailAddress, PropertyEventArgs> OnEmailAddr
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onEmailAddrIsRegistered)
{
Members.EmailAddr.Events.OnChange -= onEmailAddrProxy;
Members.EmailAddr.Events.OnChange += onEmailAddrProxy;
onEmailAddrIsRegistered = true;
}
onEmailAddr += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onEmailAddr -= value;
if (onEmailAddr == null && onEmailAddrIsRegistered)
{
Members.EmailAddr.Events.OnChange -= onEmailAddrProxy;
onEmailAddrIsRegistered = false;
}
}
}
}
private static void onEmailAddrProxy(object sender, PropertyEventArgs args)
{
EventHandler<EmailAddress, PropertyEventArgs> handler = onEmailAddr;
if ((object)handler != null)
handler.Invoke((EmailAddress)sender, args);
}
#endregion
#region OnEmailAddresses
private static bool onEmailAddressesIsRegistered = false;
private static EventHandler<EmailAddress, PropertyEventArgs> onEmailAddresses;
public static event EventHandler<EmailAddress, PropertyEventArgs> OnEmailAddresses
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onEmailAddressesIsRegistered)
{
Members.EmailAddresses.Events.OnChange -= onEmailAddressesProxy;
Members.EmailAddresses.Events.OnChange += onEmailAddressesProxy;
onEmailAddressesIsRegistered = true;
}
onEmailAddresses += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onEmailAddresses -= value;
if (onEmailAddresses == null && onEmailAddressesIsRegistered)
{
Members.EmailAddresses.Events.OnChange -= onEmailAddressesProxy;
onEmailAddressesIsRegistered = false;
}
}
}
}
private static void onEmailAddressesProxy(object sender, PropertyEventArgs args)
{
EventHandler<EmailAddress, PropertyEventArgs> handler = onEmailAddresses;
if ((object)handler != null)
handler.Invoke((EmailAddress)sender, args);
}
#endregion
#region OnUid
private static bool onUidIsRegistered = false;
private static EventHandler<EmailAddress, PropertyEventArgs> onUid;
public static event EventHandler<EmailAddress, PropertyEventArgs> OnUid
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onUidIsRegistered)
{
Members.Uid.Events.OnChange -= onUidProxy;
Members.Uid.Events.OnChange += onUidProxy;
onUidIsRegistered = true;
}
onUid += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onUid -= value;
if (onUid == null && onUidIsRegistered)
{
Members.Uid.Events.OnChange -= onUidProxy;
onUidIsRegistered = false;
}
}
}
}
private static void onUidProxy(object sender, PropertyEventArgs args)
{
EventHandler<EmailAddress, PropertyEventArgs> handler = onUid;
if ((object)handler != null)
handler.Invoke((EmailAddress)sender, args);
}
#endregion
}
#endregion
}
#endregion
#region IEmailAddressOriginalData
public IEmailAddressOriginalData OriginalVersion { get { return this; } }
#region Members for interface IEmailAddress
string IEmailAddressOriginalData.EmailAddr { get { return OriginalData.EmailAddr; } }
IEnumerable<Person> IEmailAddressOriginalData.EmailAddresses { get { return OriginalData.EmailAddresses.OriginalData; } }
#endregion
#region Members for interface INeo4jBase
INeo4jBaseOriginalData INeo4jBase.OriginalVersion { get { return this; } }
string INeo4jBaseOriginalData.Uid { get { return OriginalData.Uid; } }
#endregion
#endregion
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
namespace OpenSim.Region.CoreModules.World.Terrain.PaintBrushes
{
/// <summary>
/// Hydraulic Erosion Brush
/// </summary>
public class ErodeSphere : ITerrainPaintableEffect
{
private const double rainHeight = 0.2;
private const int rounds = 10;
private const NeighbourSystem type = NeighbourSystem.Moore;
private const double waterSaturation = 0.30;
#region Supporting Functions
private static int[] Neighbours(NeighbourSystem neighbourType, int index)
{
int[] coord = new int[2];
index++;
switch (neighbourType)
{
case NeighbourSystem.Moore:
switch (index)
{
case 1:
coord[0] = -1;
coord[1] = -1;
break;
case 2:
coord[0] = -0;
coord[1] = -1;
break;
case 3:
coord[0] = +1;
coord[1] = -1;
break;
case 4:
coord[0] = -1;
coord[1] = -0;
break;
case 5:
coord[0] = -0;
coord[1] = -0;
break;
case 6:
coord[0] = +1;
coord[1] = -0;
break;
case 7:
coord[0] = -1;
coord[1] = +1;
break;
case 8:
coord[0] = -0;
coord[1] = +1;
break;
case 9:
coord[0] = +1;
coord[1] = +1;
break;
default:
break;
}
break;
case NeighbourSystem.VonNeumann:
switch (index)
{
case 1:
coord[0] = 0;
coord[1] = -1;
break;
case 2:
coord[0] = -1;
coord[1] = 0;
break;
case 3:
coord[0] = +1;
coord[1] = 0;
break;
case 4:
coord[0] = 0;
coord[1] = +1;
break;
case 5:
coord[0] = -0;
coord[1] = -0;
break;
default:
break;
}
break;
}
return coord;
}
private enum NeighbourSystem
{
Moore,
VonNeumann
} ;
#endregion
#region ITerrainPaintableEffect Members
public void PaintEffect(ITerrainChannel map, bool[,] mask, double rx, double ry, double rz, double strength, double duration)
{
strength = TerrainUtil.MetersToSphericalStrength(strength);
int x, y;
// Using one 'rain' round for this, so skipping a useless loop
// Will need to adapt back in for the Flood brush
ITerrainChannel water = new TerrainChannel(map.Width, map.Height);
ITerrainChannel sediment = new TerrainChannel(map.Width, map.Height);
// Fill with rain
for (x = 0; x < water.Width; x++)
for (y = 0; y < water.Height; y++)
water[x, y] = Math.Max(0.0, TerrainUtil.SphericalFactor(x, y, rx, ry, strength) * rainHeight * duration);
for (int i = 0; i < rounds; i++)
{
// Erode underlying terrain
for (x = 0; x < water.Width; x++)
{
for (y = 0; y < water.Height; y++)
{
if (mask[x,y])
{
const double solConst = (1.0 / rounds);
double sedDelta = water[x, y] * solConst;
map[x, y] -= sedDelta;
sediment[x, y] += sedDelta;
}
}
}
// Move water
for (x = 0; x < water.Width; x++)
{
for (y = 0; y < water.Height; y++)
{
if (water[x, y] <= 0)
continue;
// Step 1. Calculate average of neighbours
int neighbours = 0;
double altitudeTotal = 0.0;
double altitudeMe = map[x, y] + water[x, y];
const int NEIGHBOUR_ME = 4;
const int NEIGHBOUR_MAX = 9;
for (int j = 0; j < NEIGHBOUR_MAX; j++)
{
if (j != NEIGHBOUR_ME)
{
int[] coords = Neighbours(type, j);
coords[0] += x;
coords[1] += y;
if (coords[0] > map.Width - 1)
continue;
if (coords[1] > map.Height - 1)
continue;
if (coords[0] < 0)
continue;
if (coords[1] < 0)
continue;
// Calculate total height of this neighbour
double altitudeNeighbour = water[coords[0], coords[1]] + map[coords[0], coords[1]];
// If it's greater than me...
if (altitudeNeighbour - altitudeMe < 0)
{
// Add it to our calculations
neighbours++;
altitudeTotal += altitudeNeighbour;
}
}
}
if (neighbours == 0)
continue;
double altitudeAvg = altitudeTotal / neighbours;
// Step 2. Allocate water to neighbours.
for (int j = 0; j < NEIGHBOUR_MAX; j++)
{
if (j != NEIGHBOUR_ME)
{
int[] coords = Neighbours(type, j);
coords[0] += x;
coords[1] += y;
if (coords[0] > map.Width - 1)
continue;
if (coords[1] > map.Height - 1)
continue;
if (coords[0] < 0)
continue;
if (coords[1] < 0)
continue;
// Skip if we dont have water to begin with.
if (water[x, y] < 0)
continue;
// Calculate our delta average
double altitudeDelta = altitudeMe - altitudeAvg;
if (altitudeDelta < 0)
continue;
// Calculate how much water we can move
double waterMin = Math.Min(water[x, y], altitudeDelta);
double waterDelta = waterMin * ((water[coords[0], coords[1]] + map[coords[0], coords[1]])
/ altitudeTotal);
double sedimentDelta = sediment[x, y] * (waterDelta / water[x, y]);
if (sedimentDelta > 0)
{
sediment[x, y] -= sedimentDelta;
sediment[coords[0], coords[1]] += sedimentDelta;
}
}
}
}
}
// Evaporate
for (x = 0; x < water.Width; x++)
{
for (y = 0; y < water.Height; y++)
{
water[x, y] *= 1.0 - (rainHeight / rounds);
double waterCapacity = waterSaturation * water[x, y];
double sedimentDeposit = sediment[x, y] - waterCapacity;
if (sedimentDeposit > 0)
{
if (mask[x,y])
{
sediment[x, y] -= sedimentDeposit;
map[x, y] += sedimentDeposit;
}
}
}
}
}
// Deposit any remainder (should be minimal)
for (x = 0; x < water.Width; x++)
for (y = 0; y < water.Height; y++)
if (mask[x,y] && sediment[x, y] > 0)
map[x, y] += sediment[x, y];
}
#endregion
}
}
| |
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 SearchCTC.WebAPI.Areas.HelpPage.ModelDescriptions;
using SearchCTC.WebAPI.Areas.HelpPage.Models;
namespace SearchCTC.WebAPI.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 file="AssertHelpers.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
// Copyright (c) 2009-2010 Math.NET
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
using System.Collections.Generic;
using System.Numerics;
using NUnit.Framework;
namespace MathNet.Numerics.Data.UnitTests
{
/// <summary>
/// A class which includes some assertion helper methods particularly for numerical code.
/// </summary>
internal class AssertHelpers
{
/// <summary>
/// Asserts that the expected value and the actual value are equal.
/// </summary>
/// <param name="expected">The expected value.</param>
/// <param name="actual">The actual value.</param>
public static void AreEqual(Complex expected, Complex actual)
{
if (expected.IsNaN() && actual.IsNaN())
{
return;
}
if (expected.IsInfinity() && expected.IsInfinity())
{
return;
}
var pass = expected.Real.AlmostEqual(actual.Real);
if (!pass)
{
Assert.Fail("Real components are not equal. Expected:{0}; Actual:{1}", expected.Real, actual.Real);
}
pass = expected.Imaginary.AlmostEqual(actual.Imaginary);
if (!pass)
{
Assert.Fail("Imaginary components are not equal. Expected:{0}; Actual:{1}", expected.Imaginary, actual.Imaginary);
}
}
/// <summary>
/// Asserts that the expected value and the actual value are equal.
/// </summary>
/// <param name="expected">The expected value.</param>
/// <param name="actual">The actual value.</param>
public static void AreEqual(Complex32 expected, Complex32 actual)
{
if (expected.IsNaN() && actual.IsNaN())
{
return;
}
if (expected.IsInfinity() && expected.IsInfinity())
{
return;
}
var pass = expected.Real.AlmostEqual(actual.Real);
if (!pass)
{
Assert.Fail("Real components are not equal. Expected:{0}; Actual:{1}", expected.Real, actual.Real);
}
pass = expected.Imaginary.AlmostEqual(actual.Imaginary);
if (!pass)
{
Assert.Fail("Imaginary components are not equal. Expected:{0}; Actual:{1}", expected.Imaginary, actual.Imaginary);
}
}
/// <summary>
/// Asserts that the expected value and the actual value are equal up to a certain number of decimal places. If both
/// <paramref name="expected"/> and <paramref name="actual"/> are NaN then no assert is thrown.
/// </summary>
/// <param name="expected">The expected value.</param>
/// <param name="actual">The actual value.</param>
/// <param name="decimalPlaces">The number of decimal places to agree on.</param>
public static void AlmostEqual(double expected, double actual, int decimalPlaces)
{
if (double.IsNaN(expected) && double.IsNaN(actual))
{
return;
}
var pass = expected.AlmostEqualRelative(actual, decimalPlaces);
if (!pass)
{
// signals Gallio that the test failed.
Assert.Fail("Not equal within {0} places. Expected:{1}; Actual:{2}", decimalPlaces, expected, actual);
}
}
/// <summary>
/// Asserts that the expected value and the actual value are equal up to a certain number of decimal places. If both
/// <paramref name="expected"/> and <paramref name="actual"/> are NaN then no assert is thrown.
/// </summary>
/// <param name="expected">The expected value.</param>
/// <param name="actual">The actual value.</param>
/// <param name="decimalPlaces">The number of decimal places to agree on.</param>
public static void AlmostEqual(float expected, float actual, int decimalPlaces)
{
if (float.IsNaN(expected) && float.IsNaN(actual))
{
return;
}
var pass = expected.AlmostEqualRelative(actual, decimalPlaces);
if (!pass)
{
// signals Gallio that the test failed.
Assert.Fail("Not equal within {0} places. Expected:{1}; Actual:{2}", decimalPlaces, expected, actual);
}
}
/// <summary>
/// Asserts that the expected value and the actual value are equal up to a certain number of decimal places.
/// </summary>
/// <param name="expected">The expected value.</param>
/// <param name="actual">The actual value.</param>
/// <param name="decimalPlaces">The number of decimal places to agree on.</param>
public static void AlmostEqual(Complex expected, Complex actual, int decimalPlaces)
{
var pass = expected.Real.AlmostEqualRelative(actual.Real, decimalPlaces);
if (!pass)
{
Assert.Fail("Real components are not equal within {0} places. Expected:{1}; Actual:{2}", decimalPlaces, expected.Real, actual.Real);
}
pass = expected.Imaginary.AlmostEqualRelative(actual.Imaginary, decimalPlaces);
if (!pass)
{
Assert.Fail("Imaginary components are not equal within {0} places. Expected:{1}; Actual:{2}", decimalPlaces, expected.Imaginary, actual.Imaginary);
}
}
/// <summary>
/// Asserts that the expected value and the actual value are equal up to a certain number of decimal places.
/// </summary>
/// <param name="expected">The expected value.</param>
/// <param name="actual">The actual value.</param>
/// <param name="decimalPlaces">The number of decimal places to agree on.</param>
public static void AlmostEqual(Complex32 expected, Complex32 actual, int decimalPlaces)
{
var pass = expected.Real.AlmostEqualRelative(actual.Real, decimalPlaces);
if (!pass)
{
Assert.Fail("Real components are not equal within {0} places. Expected:{1}; Actual:{2}", decimalPlaces, expected.Real, actual.Real);
}
pass = expected.Imaginary.AlmostEqualRelative(actual.Imaginary, decimalPlaces);
if (!pass)
{
Assert.Fail("Imaginary components are not equal within {0} places. Expected:{1}; Actual:{2}", decimalPlaces, expected.Imaginary, actual.Imaginary);
}
}
/// <summary>
/// Asserts that the expected value and the actual value are equal up to a certain
/// maximum error.
/// </summary>
/// <typeparam name="T">The type of the structures. Must implement
/// <see cref="IPrecisionSupport{T}"/>.</typeparam>
/// <param name="expected">The expected value.</param>
/// <param name="actual">The actual value.</param>
/// <param name="maximumError">The accuracy required for being almost equal.</param>
public static void AlmostEqual<T>(T expected, T actual, double maximumError)
where T : IPrecisionSupport<T>
{
if (!actual.AlmostEqualNorm(expected, maximumError))
{
Assert.Fail("Not equal within a maximum error {0}. Expected:{1}; Actual:{2}", maximumError, expected, actual);
}
}
/// <summary>
/// Asserts that the expected value and the actual value are equal up to a certain
/// maximum error.
/// </summary>
/// <param name="expected">The expected value list.</param>
/// <param name="actual">The actual value list.</param>
/// <param name="maximumError">The accuracy required for being almost equal.</param>
public static void AlmostEqualList(IList<double> expected, IList<double> actual, double maximumError)
{
for (var i = 0; i < expected.Count; i++)
{
if (!actual[i].AlmostEqual(expected[i], maximumError))
{
Assert.Fail("Not equal within a maximum error {0}. Expected:{1}; Actual:{2}", maximumError, expected[i], actual[i]);
}
}
}
/// <summary>
/// Asserts that the expected value and the actual value are equal up to a certain
/// maximum error.
/// </summary>
/// <param name="expected">The expected value list.</param>
/// <param name="actual">The actual value list.</param>
/// <param name="maximumError">The accuracy required for being almost equal.</param>
public static void AlmostEqualList(IList<float> expected, IList<float> actual, double maximumError)
{
for (var i = 0; i < expected.Count; i++)
{
if (!actual[i].AlmostEqual(expected[i], maximumError))
{
Assert.Fail("Not equal within a maximum error {0}. Expected:{1}; Actual:{2}", maximumError, expected[i], actual[i]);
}
}
}
/// <summary>
/// Asserts that the expected value and the actual value are equal up to a certain
/// maximum error.
/// </summary>
/// <typeparam name="T">The type of the structures. Must implement
/// <see cref="IPrecisionSupport{T}"/>.</typeparam>
/// <param name="expected">The expected value list.</param>
/// <param name="actual">The actual value list.</param>
/// <param name="maximumError">The accuracy required for being almost equal.</param>
public static void AlmostEqualList<T>(IList<T> expected, IList<T> actual, double maximumError)
where T : IPrecisionSupport<T>
{
for (var i = 0; i < expected.Count; i++)
{
if (!actual[i].AlmostEqualNorm(expected[i], maximumError))
{
Assert.Fail("Not equal within a maximum error {0}. Expected:{1}; Actual:{2}", maximumError, expected[i], actual[i]);
}
}
}
/// <summary>
/// Asserts that the expected value and the actual value are equal up to a certain
/// maximum error.
/// </summary>
/// <param name="expected">The expected value list.</param>
/// <param name="actual">The actual value list.</param>
/// <param name="maximumError">The accuracy required for being almost equal.</param>
public static void AlmostEqualList(IList<Complex> expected, IList<Complex> actual, double maximumError)
{
for (var i = 0; i < expected.Count; i++)
{
if (!actual[i].AlmostEqual(expected[i], maximumError))
{
Assert.Fail("Not equal within a maximum error {0}. Expected:{1}; Actual:{2}", maximumError, expected[i], actual[i]);
}
}
}
}
}
| |
// 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.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// SortQueryOperator.cs
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
namespace System.Linq.Parallel
{
/// <summary>
/// The query operator for OrderBy and ThenBy.
/// </summary>
/// <typeparam name="TInputOutput"></typeparam>
/// <typeparam name="TSortKey"></typeparam>
internal sealed class SortQueryOperator<TInputOutput, TSortKey> :
UnaryQueryOperator<TInputOutput, TInputOutput>, IOrderedEnumerable<TInputOutput>
{
private readonly Func<TInputOutput, TSortKey> _keySelector; // Key selector used when sorting.
private readonly IComparer<TSortKey> _comparer; // Key comparison logic to use during sorting.
//---------------------------------------------------------------------------------------
// Instantiates a new sort operator.
//
internal SortQueryOperator(IEnumerable<TInputOutput> source, Func<TInputOutput, TSortKey> keySelector,
IComparer<TSortKey> comparer, bool descending)
: base(source, true)
{
Debug.Assert(keySelector != null, "key selector must not be null");
_keySelector = keySelector;
// If a comparer wasn't supplied, we use the default one for the key type.
if (comparer == null)
{
_comparer = Util.GetDefaultComparer<TSortKey>();
}
else
{
_comparer = comparer;
}
if (descending)
{
_comparer = new ReverseComparer<TSortKey>(_comparer);
}
SetOrdinalIndexState(OrdinalIndexState.Shuffled);
}
//---------------------------------------------------------------------------------------
// IOrderedEnumerable method for nesting an order by operator inside another.
//
IOrderedEnumerable<TInputOutput> IOrderedEnumerable<TInputOutput>.CreateOrderedEnumerable<TKey2>(
Func<TInputOutput, TKey2> key2Selector, IComparer<TKey2> key2Comparer, bool descending)
{
key2Comparer = key2Comparer ?? Util.GetDefaultComparer<TKey2>();
if (descending)
{
key2Comparer = new ReverseComparer<TKey2>(key2Comparer);
}
IComparer<Pair> pairComparer = new PairComparer<TSortKey, TKey2>(_comparer, key2Comparer);
Func<TInputOutput, Pair> pairKeySelector =
(TInputOutput elem) => new Pair(_keySelector(elem), key2Selector(elem));
return new SortQueryOperator<TInputOutput, Pair>(Child, pairKeySelector, pairComparer, false);
}
//---------------------------------------------------------------------------------------
// Accessor the the key selector.
//
internal Func<TInputOutput, TSortKey> KeySelector
{
get { return _keySelector; }
}
//---------------------------------------------------------------------------------------
// Accessor the the key comparer.
//
internal IComparer<TSortKey> KeyComparer
{
get { return _comparer; }
}
//---------------------------------------------------------------------------------------
// Opens the current operator. This involves opening the child operator tree, enumerating
// the results, sorting them, and then returning an enumerator that walks the result.
//
internal override QueryResults<TInputOutput> Open(QuerySettings settings, bool preferStriping)
{
QueryResults<TInputOutput> childQueryResults = Child.Open(settings, false);
return new SortQueryOperatorResults<TInputOutput, TSortKey>(childQueryResults, this, settings, preferStriping);
}
internal override void WrapPartitionedStream<TKey>(
PartitionedStream<TInputOutput, TKey> inputStream, IPartitionedStreamRecipient<TInputOutput> recipient, bool preferStriping, QuerySettings settings)
{
PartitionedStream<TInputOutput, TSortKey> outputStream =
new PartitionedStream<TInputOutput, TSortKey>(inputStream.PartitionCount, this._comparer, OrdinalIndexState);
for (int i = 0; i < outputStream.PartitionCount; i++)
{
outputStream[i] = new SortQueryOperatorEnumerator<TInputOutput, TKey, TSortKey>(
inputStream[i], _keySelector, _comparer);
}
recipient.Receive<TSortKey>(outputStream);
}
//---------------------------------------------------------------------------------------
// Returns an enumerable that represents the query executing sequentially.
//
internal override IEnumerable<TInputOutput> AsSequentialQuery(CancellationToken token)
{
IEnumerable<TInputOutput> wrappedChild = CancellableEnumerable.Wrap(Child.AsSequentialQuery(token), token);
return wrappedChild.OrderBy(_keySelector, _comparer);
}
//---------------------------------------------------------------------------------------
// Whether this operator performs a premature merge that would not be performed in
// a similar sequential operation (i.e., in LINQ to Objects).
//
internal override bool LimitsParallelism
{
get { return false; }
}
}
internal class SortQueryOperatorResults<TInputOutput, TSortKey> : QueryResults<TInputOutput>
{
protected QueryResults<TInputOutput> _childQueryResults; // Results of the child query
private SortQueryOperator<TInputOutput, TSortKey> _op; // Operator that generated these results
private QuerySettings _settings; // Settings collected from the query
private bool _preferStriping; // If the results are indexible, should we use striping when partitioning them
internal SortQueryOperatorResults(
QueryResults<TInputOutput> childQueryResults, SortQueryOperator<TInputOutput, TSortKey> op,
QuerySettings settings, bool preferStriping)
{
_childQueryResults = childQueryResults;
_op = op;
_settings = settings;
_preferStriping = preferStriping;
}
internal override bool IsIndexible
{
get { return false; }
}
internal override void GivePartitionedStream(IPartitionedStreamRecipient<TInputOutput> recipient)
{
_childQueryResults.GivePartitionedStream(new ChildResultsRecipient(recipient, _op, _settings));
}
private class ChildResultsRecipient : IPartitionedStreamRecipient<TInputOutput>
{
private IPartitionedStreamRecipient<TInputOutput> _outputRecipient;
private SortQueryOperator<TInputOutput, TSortKey> _op;
private QuerySettings _settings;
internal ChildResultsRecipient(IPartitionedStreamRecipient<TInputOutput> outputRecipient, SortQueryOperator<TInputOutput, TSortKey> op, QuerySettings settings)
{
_outputRecipient = outputRecipient;
_op = op;
_settings = settings;
}
public void Receive<TKey>(PartitionedStream<TInputOutput, TKey> childPartitionedStream)
{
_op.WrapPartitionedStream(childPartitionedStream, _outputRecipient, false, _settings);
}
}
}
//---------------------------------------------------------------------------------------
// This enumerator performs sorting based on a key selection and comparison routine.
//
internal class SortQueryOperatorEnumerator<TInputOutput, TKey, TSortKey> : QueryOperatorEnumerator<TInputOutput, TSortKey>
{
private readonly QueryOperatorEnumerator<TInputOutput, TKey> _source; // Data source to sort.
private readonly Func<TInputOutput, TSortKey> _keySelector; // Key selector used when sorting.
private readonly IComparer<TSortKey> _keyComparer; // Key comparison logic to use during sorting.
//---------------------------------------------------------------------------------------
// Instantiates a new sort operator enumerator.
//
internal SortQueryOperatorEnumerator(QueryOperatorEnumerator<TInputOutput, TKey> source,
Func<TInputOutput, TSortKey> keySelector, IComparer<TSortKey> keyComparer)
{
Debug.Assert(source != null);
Debug.Assert(keySelector != null, "need a key comparer");
Debug.Assert(keyComparer != null, "expected a compiled operator");
_source = source;
_keySelector = keySelector;
_keyComparer = keyComparer;
}
//---------------------------------------------------------------------------------------
// Accessor for the key comparison routine.
//
public IComparer<TSortKey> KeyComparer
{
get { return _keyComparer; }
}
//---------------------------------------------------------------------------------------
// Moves to the next element in the sorted output. When called for the first time, the
// descendents in the sort's child tree are executed entirely, the results accumulated
// in memory, and the data sorted.
//
internal override bool MoveNext(ref TInputOutput currentElement, ref TSortKey currentKey)
{
Debug.Assert(_source != null);
TKey keyUnused = default(TKey);
if (!_source.MoveNext(ref currentElement, ref keyUnused))
{
return false;
}
currentKey = _keySelector(currentElement);
return true;
}
protected override void Dispose(bool disposing)
{
Debug.Assert(_source != null);
_source.Dispose();
}
}
}
| |
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
namespace Invoices.Business
{
/// <summary>
/// ProductTypeEdit (editable root object).<br/>
/// This is a generated <see cref="ProductTypeEdit"/> business object.
/// </summary>
[Serializable]
public partial class ProductTypeEdit : BusinessBase<ProductTypeEdit>
{
#region Static Fields
private static int _lastId;
#endregion
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="ProductTypeId"/> property.
/// </summary>
[NotUndoable]
public static readonly PropertyInfo<int> ProductTypeIdProperty = RegisterProperty<int>(p => p.ProductTypeId, "Product Type Id");
/// <summary>
/// Gets the Product Type Id.
/// </summary>
/// <value>The Product Type Id.</value>
public int ProductTypeId
{
get { return GetProperty(ProductTypeIdProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> NameProperty = RegisterProperty<string>(p => p.Name, "Name");
/// <summary>
/// Gets or sets the Name.
/// </summary>
/// <value>The Name.</value>
public string Name
{
get { return GetProperty(NameProperty); }
set { SetProperty(NameProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="ProductTypeEdit"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="ProductTypeEdit"/> object.</returns>
public static ProductTypeEdit NewProductTypeEdit()
{
return DataPortal.Create<ProductTypeEdit>();
}
/// <summary>
/// Factory method. Loads a <see cref="ProductTypeEdit"/> object, based on given parameters.
/// </summary>
/// <param name="productTypeId">The ProductTypeId parameter of the ProductTypeEdit to fetch.</param>
/// <returns>A reference to the fetched <see cref="ProductTypeEdit"/> object.</returns>
public static ProductTypeEdit GetProductTypeEdit(int productTypeId)
{
return DataPortal.Fetch<ProductTypeEdit>(productTypeId);
}
/// <summary>
/// Factory method. Deletes a <see cref="ProductTypeEdit"/> object, based on given parameters.
/// </summary>
/// <param name="productTypeId">The ProductTypeId of the ProductTypeEdit to delete.</param>
public static void DeleteProductTypeEdit(int productTypeId)
{
DataPortal.Delete<ProductTypeEdit>(productTypeId);
}
/// <summary>
/// Factory method. Asynchronously creates a new <see cref="ProductTypeEdit"/> object.
/// </summary>
/// <param name="callback">The completion callback method.</param>
public static void NewProductTypeEdit(EventHandler<DataPortalResult<ProductTypeEdit>> callback)
{
DataPortal.BeginCreate<ProductTypeEdit>(callback);
}
/// <summary>
/// Factory method. Asynchronously loads a <see cref="ProductTypeEdit"/> object, based on given parameters.
/// </summary>
/// <param name="productTypeId">The ProductTypeId parameter of the ProductTypeEdit to fetch.</param>
/// <param name="callback">The completion callback method.</param>
public static void GetProductTypeEdit(int productTypeId, EventHandler<DataPortalResult<ProductTypeEdit>> callback)
{
DataPortal.BeginFetch<ProductTypeEdit>(productTypeId, callback);
}
/// <summary>
/// Factory method. Asynchronously deletes a <see cref="ProductTypeEdit"/> object, based on given parameters.
/// </summary>
/// <param name="productTypeId">The ProductTypeId of the ProductTypeEdit to delete.</param>
/// <param name="callback">The completion callback method.</param>
public static void DeleteProductTypeEdit(int productTypeId, EventHandler<DataPortalResult<ProductTypeEdit>> callback)
{
DataPortal.BeginDelete<ProductTypeEdit>(productTypeId, callback);
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="ProductTypeEdit"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public ProductTypeEdit()
{
// Use factory methods and do not use direct creation.
Saved += OnProductTypeEditSaved;
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="ProductTypeEdit"/> object properties.
/// </summary>
[RunLocal]
protected override void DataPortal_Create()
{
LoadProperty(ProductTypeIdProperty, System.Threading.Interlocked.Decrement(ref _lastId));
var args = new DataPortalHookArgs();
OnCreate(args);
base.DataPortal_Create();
}
/// <summary>
/// Loads a <see cref="ProductTypeEdit"/> object from the database, based on given criteria.
/// </summary>
/// <param name="productTypeId">The Product Type Id.</param>
protected void DataPortal_Fetch(int productTypeId)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("Invoices"))
{
using (var cmd = new SqlCommand("dbo.GetProductTypeEdit", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@ProductTypeId", productTypeId).DbType = DbType.Int32;
var args = new DataPortalHookArgs(cmd, productTypeId);
OnFetchPre(args);
Fetch(cmd);
OnFetchPost(args);
}
}
// check all object rules and property rules
BusinessRules.CheckRules();
}
private void Fetch(SqlCommand cmd)
{
using (var dr = new SafeDataReader(cmd.ExecuteReader()))
{
if (dr.Read())
{
Fetch(dr);
}
}
}
/// <summary>
/// Loads a <see cref="ProductTypeEdit"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
// Value properties
LoadProperty(ProductTypeIdProperty, dr.GetInt32("ProductTypeId"));
LoadProperty(NameProperty, dr.GetString("Name"));
var args = new DataPortalHookArgs(dr);
OnFetchRead(args);
}
/// <summary>
/// Inserts a new <see cref="ProductTypeEdit"/> object in the database.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_Insert()
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("Invoices"))
{
using (var cmd = new SqlCommand("dbo.AddProductTypeEdit", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@ProductTypeId", ReadProperty(ProductTypeIdProperty)).Direction = ParameterDirection.Output;
cmd.Parameters.AddWithValue("@Name", ReadProperty(NameProperty)).DbType = DbType.String;
var args = new DataPortalHookArgs(cmd);
OnInsertPre(args);
cmd.ExecuteNonQuery();
OnInsertPost(args);
LoadProperty(ProductTypeIdProperty, (int) cmd.Parameters["@ProductTypeId"].Value);
}
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="ProductTypeEdit"/> object.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_Update()
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("Invoices"))
{
using (var cmd = new SqlCommand("dbo.UpdateProductTypeEdit", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@ProductTypeId", ReadProperty(ProductTypeIdProperty)).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@Name", ReadProperty(NameProperty)).DbType = DbType.String;
var args = new DataPortalHookArgs(cmd);
OnUpdatePre(args);
cmd.ExecuteNonQuery();
OnUpdatePost(args);
}
}
}
/// <summary>
/// Self deletes the <see cref="ProductTypeEdit"/> object.
/// </summary>
protected override void DataPortal_DeleteSelf()
{
DataPortal_Delete(ProductTypeId);
}
/// <summary>
/// Deletes the <see cref="ProductTypeEdit"/> object from database.
/// </summary>
/// <param name="productTypeId">The delete criteria.</param>
[Transactional(TransactionalTypes.TransactionScope)]
protected void DataPortal_Delete(int productTypeId)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("Invoices"))
{
using (var cmd = new SqlCommand("dbo.DeleteProductTypeEdit", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@ProductTypeId", productTypeId).DbType = DbType.Int32;
var args = new DataPortalHookArgs(cmd, productTypeId);
OnDeletePre(args);
cmd.ExecuteNonQuery();
OnDeletePost(args);
}
}
}
#endregion
#region Saved Event
// TODO: edit "ProductTypeEdit.cs", uncomment the "OnDeserialized" method and add the following line:
// TODO: Saved += OnProductTypeEditSaved;
private void OnProductTypeEditSaved(object sender, Csla.Core.SavedEventArgs e)
{
if (ProductTypeEditSaved != null)
ProductTypeEditSaved(sender, e);
}
/// <summary> Use this event to signal a <see cref="ProductTypeEdit"/> object was saved.</summary>
public static event EventHandler<Csla.Core.SavedEventArgs> ProductTypeEditSaved;
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
//
// Copyright 2012, Xamarin Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Threading;
using Xamarin.Utilities;
#if PLATFORM_IOS
#if __UNIFIED__
using AuthenticateUIType = UIKit.UIViewController;
#else
using AuthenticateUIType = MonoTouch.UIKit.UIViewController;
#endif
#elif PLATFORM_ANDROID
using AuthenticateUIType = Android.Content.Intent;
using UIContext = Android.Content.Context;
#else
using AuthenticateUIType = System.Object;
#endif
namespace Xamarin.Auth
{
/// <summary>
/// A process and user interface to authenticate a user.
/// </summary>
#if XAMARIN_AUTH_INTERNAL
internal abstract class Authenticator
#else
public abstract class Authenticator
#endif
{
/// <summary>
/// Title of any UI elements that need to be presented for this authenticator.
/// </summary>
public string Title { get; set; }
/// <summary>
/// Occurs when authentication has been successfully or unsuccessfully completed.
/// Consult the <see cref="AuthenticatorCompletedEventArgs.IsAuthenticated"/> event argument to determine if
/// authentication was successful.
/// </summary>
public event EventHandler<AuthenticatorCompletedEventArgs> Completed;
/// <summary>
/// Occurs when there an error is encountered when authenticating.
/// </summary>
public event EventHandler<AuthenticatorErrorEventArgs> Error;
/// <summary>
/// Initializes a new instance of the <see cref="Xamarin.Auth.Authenticator"/> class.
/// </summary>
public Authenticator ()
{
Title = "Authenticate";
}
#if PLATFORM_ANDROID
UIContext context;
public AuthenticateUIType GetUI (UIContext context)
{
this.context = context;
return GetPlatformUI (context);
}
protected abstract AuthenticateUIType GetPlatformUI (UIContext context);
#else
/// <summary>
/// Gets the UI for this authenticator.
/// </summary>
/// <returns>
/// The UI that needs to be presented.
/// </returns>
public AuthenticateUIType GetUI ()
{
return GetPlatformUI ();
}
/// <summary>
/// Gets the UI for this authenticator.
/// </summary>
/// <returns>
/// The UI that needs to be presented.
/// </returns>
protected abstract AuthenticateUIType GetPlatformUI ();
#endif
/// <summary>
/// Implementations must call this function when they have successfully authenticated.
/// </summary>
/// <param name='account'>
/// The authenticated account.
/// </param>
public void OnSucceeded (SalesforceUser account)
{
BeginInvokeOnUIThread (delegate {
var ev = Completed;
if (ev != null) {
ev (this, new AuthenticatorCompletedEventArgs (account));
}
});
}
/// <summary>
/// Implementations must call this function when they have successfully authenticated.
/// </summary>
/// <param name='username'>
/// User name of the account.
/// </param>
/// <param name='accountProperties'>
/// Additional data, such as access tokens, that need to be stored with the account. This
/// information is secured.
/// </param>
public void OnSucceeded (string username, IDictionary<string, string> accountProperties)
{
OnSucceeded (new SalesforceUser (username, accountProperties));
}
/// <summary>
/// Implementations must call this function when they have cancelled the operation.
/// </summary>
public void OnCancelled ()
{
BeginInvokeOnUIThread (delegate {
var ev = Completed;
if (ev != null) {
ev (this, new AuthenticatorCompletedEventArgs (null));
}
});
}
/// <summary>
/// Implementations must call this function when they have failed to authenticate.
/// </summary>
/// <param name='message'>
/// The reason that this authentication has failed.
/// </param>
public void OnError (string message)
{
BeginInvokeOnUIThread (delegate {
var ev = Error;
if (ev != null) {
ev (this, new AuthenticatorErrorEventArgs (message));
}
});
}
/// <summary>
/// Implementations must call this function when they have failed to authenticate.
/// </summary>
/// <param name='exception'>
/// The reason that this authentication has failed.
/// </param>
public void OnError (Exception exception)
{
BeginInvokeOnUIThread (delegate {
var ev = Error;
if (ev != null) {
ev (this, new AuthenticatorErrorEventArgs (exception));
}
});
}
void BeginInvokeOnUIThread (Action action)
{
#if PLATFORM_IOS
#if __UNIFIED__
UIKit.UIApplication.SharedApplication.BeginInvokeOnMainThread (delegate {
action ();
#else
MonoTouch.UIKit.UIApplication.SharedApplication.BeginInvokeOnMainThread (delegate {
action ();
#endif
});
#elif PLATFORM_ANDROID
var a = context as Android.App.Activity;
if (a != null) {
a.RunOnUiThread (action);
}
else {
action ();
}
#else
action ();
#endif
}
}
/// <summary>
/// Authenticator completed event arguments.
/// </summary>
#if XAMARIN_AUTH_INTERNAL
internal class AuthenticatorCompletedEventArgs : EventArgs
#else
public class AuthenticatorCompletedEventArgs : EventArgs
#endif
{
/// <summary>
/// Whether the authentication succeeded and there is a valid <see cref="Account"/>.
/// </summary>
/// <value>
/// <see langword="true"/> if the user is authenticated; otherwise, <see langword="false"/>.
/// </value>
public bool IsAuthenticated { get { return Account != null; } }
/// <summary>
/// Gets the account created that represents this authentication.
/// </summary>
/// <value>
/// The account.
/// </value>
public ISalesforceUser Account { get; private set; }
/// <summary>
/// Initializes a new instance of the <see cref="Xamarin.Auth.AuthenticatorCompletedEventArgs"/> class.
/// </summary>
/// <param name='account'>
/// The account created or <see langword="null"/> if authentication failed or was canceled.
/// </param>
public AuthenticatorCompletedEventArgs (ISalesforceUser account)
{
Account = account;
}
}
/// <summary>
/// Authenticator error event arguments.
/// </summary>
#if XAMARIN_AUTH_INTERNAL
internal class AuthenticatorErrorEventArgs : EventArgs
#else
public class AuthenticatorErrorEventArgs : EventArgs
#endif
{
/// <summary>
/// Gets a message describing the error.
/// </summary>
/// <value>
/// The message.
/// </value>
public string Message { get; private set; }
/// <summary>
/// Gets the exception that signaled the error if there was one.
/// </summary>
/// <value>
/// The exception or <see langword="null"/>.
/// </value>
public Exception Exception { get; private set; }
/// <summary>
/// Initializes a new instance of the <see cref="Xamarin.Auth.AuthenticatorErrorEventArgs"/> class
/// with a message but no exception.
/// </summary>
/// <param name='message'>
/// A message describing the error.
/// </param>
public AuthenticatorErrorEventArgs (string message)
{
Message = message;
}
/// <summary>
/// Initializes a new instance of the <see cref="Xamarin.Auth.AuthenticatorErrorEventArgs"/> class with an exception.
/// </summary>
/// <param name='exception'>
/// The exception signaling the error. The message of this object is retrieved from this exception or
/// its inner exceptions.
/// </param>
public AuthenticatorErrorEventArgs (Exception exception)
{
Message = exception.GetUserMessage ();
Exception = exception;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
**
**
** Purpose: Capture execution context for a thread
**
**
===========================================================*/
namespace System.Threading
{
using System;
using System.Security;
using System.Runtime.Remoting;
#if FEATURE_IMPERSONATION
using System.Security.Principal;
#endif
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.ExceptionServices;
using System.Runtime.Serialization;
using System.Security.Permissions;
#if FEATURE_REMOTING
using System.Runtime.Remoting.Messaging;
#endif // FEATURE_REMOTING
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Diagnostics.Contracts;
using System.Diagnostics.CodeAnalysis;
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
[System.Runtime.InteropServices.ComVisible(true)]
public delegate void ContextCallback(Object state);
#if FEATURE_CORECLR
[SecurityCritical]
internal struct ExecutionContextSwitcher
{
internal ExecutionContext m_ec;
internal SynchronizationContext m_sc;
internal void Undo(Thread currentThread)
{
Contract.Assert(currentThread == Thread.CurrentThread);
// The common case is that these have not changed, so avoid the cost of a write if not needed.
if (currentThread.SynchronizationContext != m_sc)
{
currentThread.SynchronizationContext = m_sc;
}
if (currentThread.ExecutionContext != m_ec)
{
ExecutionContext.Restore(currentThread, m_ec);
}
}
}
public sealed class ExecutionContext : IDisposable
{
private static readonly ExecutionContext Default = new ExecutionContext();
private readonly Dictionary<IAsyncLocal, object> m_localValues;
private readonly IAsyncLocal[] m_localChangeNotifications;
private ExecutionContext()
{
m_localValues = new Dictionary<IAsyncLocal, object>();
m_localChangeNotifications = Array.Empty<IAsyncLocal>();
}
private ExecutionContext(Dictionary<IAsyncLocal, object> localValues, IAsyncLocal[] localChangeNotifications)
{
m_localValues = localValues;
m_localChangeNotifications = localChangeNotifications;
}
[SecuritySafeCritical]
public static ExecutionContext Capture()
{
return Thread.CurrentThread.ExecutionContext ?? ExecutionContext.Default;
}
[SecurityCritical]
[HandleProcessCorruptedStateExceptions]
public static void Run(ExecutionContext executionContext, ContextCallback callback, Object state)
{
if (executionContext == null)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NullContext"));
Thread currentThread = Thread.CurrentThread;
ExecutionContextSwitcher ecsw = default(ExecutionContextSwitcher);
try
{
EstablishCopyOnWriteScope(currentThread, ref ecsw);
ExecutionContext.Restore(currentThread, executionContext);
callback(state);
}
catch
{
// Note: we have a "catch" rather than a "finally" because we want
// to stop the first pass of EH here. That way we can restore the previous
// context before any of our callers' EH filters run. That means we need to
// end the scope separately in the non-exceptional case below.
ecsw.Undo(currentThread);
throw;
}
ecsw.Undo(currentThread);
}
[SecurityCritical]
internal static void Restore(Thread currentThread, ExecutionContext executionContext)
{
Contract.Assert(currentThread == Thread.CurrentThread);
ExecutionContext previous = currentThread.ExecutionContext ?? Default;
currentThread.ExecutionContext = executionContext;
// New EC could be null if that's what ECS.Undo saved off.
// For the purposes of dealing with context change, treat this as the default EC
executionContext = executionContext ?? Default;
if (previous != executionContext)
{
OnContextChanged(previous, executionContext);
}
}
[SecurityCritical]
static internal void EstablishCopyOnWriteScope(Thread currentThread, ref ExecutionContextSwitcher ecsw)
{
Contract.Assert(currentThread == Thread.CurrentThread);
ecsw.m_ec = currentThread.ExecutionContext;
ecsw.m_sc = currentThread.SynchronizationContext;
}
[SecurityCritical]
[HandleProcessCorruptedStateExceptions]
private static void OnContextChanged(ExecutionContext previous, ExecutionContext current)
{
Contract.Assert(previous != null);
Contract.Assert(current != null);
Contract.Assert(previous != current);
foreach (IAsyncLocal local in previous.m_localChangeNotifications)
{
object previousValue;
object currentValue;
previous.m_localValues.TryGetValue(local, out previousValue);
current.m_localValues.TryGetValue(local, out currentValue);
if (previousValue != currentValue)
local.OnValueChanged(previousValue, currentValue, true);
}
if (current.m_localChangeNotifications != previous.m_localChangeNotifications)
{
try
{
foreach (IAsyncLocal local in current.m_localChangeNotifications)
{
// If the local has a value in the previous context, we already fired the event for that local
// in the code above.
object previousValue;
if (!previous.m_localValues.TryGetValue(local, out previousValue))
{
object currentValue;
current.m_localValues.TryGetValue(local, out currentValue);
if (previousValue != currentValue)
local.OnValueChanged(previousValue, currentValue, true);
}
}
}
catch (Exception ex)
{
Environment.FailFast(
Environment.GetResourceString("ExecutionContext_ExceptionInAsyncLocalNotification"),
ex);
}
}
}
[SecurityCritical]
internal static object GetLocalValue(IAsyncLocal local)
{
ExecutionContext current = Thread.CurrentThread.ExecutionContext;
if (current == null)
return null;
object value;
current.m_localValues.TryGetValue(local, out value);
return value;
}
[SecurityCritical]
internal static void SetLocalValue(IAsyncLocal local, object newValue, bool needChangeNotifications)
{
ExecutionContext current = Thread.CurrentThread.ExecutionContext ?? ExecutionContext.Default;
object previousValue;
bool hadPreviousValue = current.m_localValues.TryGetValue(local, out previousValue);
if (previousValue == newValue)
return;
//
// Allocate a new Dictionary containing a copy of the old values, plus the new value. We have to do this manually to
// minimize allocations of IEnumerators, etc.
//
Dictionary<IAsyncLocal, object> newValues = new Dictionary<IAsyncLocal, object>(current.m_localValues.Count + (hadPreviousValue ? 0 : 1));
foreach (KeyValuePair<IAsyncLocal, object> pair in current.m_localValues)
newValues.Add(pair.Key, pair.Value);
newValues[local] = newValue;
//
// Either copy the change notification array, or create a new one, depending on whether we need to add a new item.
//
IAsyncLocal[] newChangeNotifications = current.m_localChangeNotifications;
if (needChangeNotifications)
{
if (hadPreviousValue)
{
Contract.Assert(Array.IndexOf(newChangeNotifications, local) >= 0);
}
else
{
int newNotificationIndex = newChangeNotifications.Length;
Array.Resize(ref newChangeNotifications, newNotificationIndex + 1);
newChangeNotifications[newNotificationIndex] = local;
}
}
Thread.CurrentThread.ExecutionContext = new ExecutionContext(newValues, newChangeNotifications);
if (needChangeNotifications)
{
local.OnValueChanged(previousValue, newValue, false);
}
}
#region Wrappers for CLR compat, to avoid ifdefs all over the BCL
[Flags]
internal enum CaptureOptions
{
None = 0x00,
IgnoreSyncCtx = 0x01,
OptimizeDefaultCase = 0x02,
}
[SecurityCritical]
internal static ExecutionContext Capture(ref StackCrawlMark stackMark, CaptureOptions captureOptions)
{
return Capture();
}
[SecuritySafeCritical]
[FriendAccessAllowed]
internal static ExecutionContext FastCapture()
{
return Capture();
}
[SecurityCritical]
[FriendAccessAllowed]
internal static void Run(ExecutionContext executionContext, ContextCallback callback, Object state, bool preserveSyncCtx)
{
Run(executionContext, callback, state);
}
[SecurityCritical]
internal bool IsDefaultFTContext(bool ignoreSyncCtx)
{
return this == Default;
}
[SecuritySafeCritical]
public ExecutionContext CreateCopy()
{
return this; // since CoreCLR's ExecutionContext is immutable, we don't need to create copies.
}
public void Dispose()
{
// For CLR compat only
}
public static bool IsFlowSuppressed()
{
return false;
}
internal static ExecutionContext PreAllocatedDefault
{
[SecuritySafeCritical]
get { return ExecutionContext.Default; }
}
internal bool IsPreAllocatedDefault
{
get { return this == ExecutionContext.Default; }
}
#endregion
}
#else // FEATURE_CORECLR
// Legacy desktop ExecutionContext implementation
internal struct ExecutionContextSwitcher
{
internal ExecutionContext.Reader outerEC; // previous EC we need to restore on Undo
internal bool outerECBelongsToScope;
#if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
internal SecurityContextSwitcher scsw;
#endif // #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
internal Object hecsw;
#if FEATURE_IMPERSONATION
internal WindowsIdentity wi;
internal bool cachedAlwaysFlowImpersonationPolicy;
internal bool wiIsValid;
#endif
internal Thread thread;
[System.Security.SecurityCritical] // auto-generated
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
#if FEATURE_CORRUPTING_EXCEPTIONS
[HandleProcessCorruptedStateExceptions]
#endif // FEATURE_CORRUPTING_EXCEPTIONS
internal bool UndoNoThrow(Thread currentThread)
{
try
{
Undo(currentThread);
}
catch
{
return false;
}
return true;
}
[System.Security.SecurityCritical] // auto-generated
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
internal void Undo(Thread currentThread)
{
//
// Don't use an uninitialized switcher, or one that's already been used.
//
if (thread == null)
return; // Don't do anything
Contract.Assert(Thread.CurrentThread == this.thread);
//
// Restore the HostExecutionContext before restoring the ExecutionContext.
//
#if FEATURE_CAS_POLICY
if (hecsw != null)
HostExecutionContextSwitcher.Undo(hecsw);
#endif // FEATURE_CAS_POLICY
//
// restore the saved Execution Context. Note that this will also restore the
// SynchronizationContext, Logical/IllogicalCallContext, etc.
//
ExecutionContext.Reader innerEC = currentThread.GetExecutionContextReader();
currentThread.SetExecutionContext(outerEC, outerECBelongsToScope);
#if DEBUG
try
{
currentThread.ForbidExecutionContextMutation = true;
#endif
//
// Tell the SecurityContext to do the side-effects of restoration.
//
#if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
if (scsw.currSC != null)
{
// Any critical failure inside scsw will cause FailFast
scsw.Undo();
}
#endif // #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
#if FEATURE_IMPERSONATION
if (wiIsValid)
SecurityContext.RestoreCurrentWI(outerEC, innerEC, wi, cachedAlwaysFlowImpersonationPolicy);
#endif
thread = null; // this will prevent the switcher object being used again
#if DEBUG
}
finally
{
currentThread.ForbidExecutionContextMutation = false;
}
#endif
ExecutionContext.OnAsyncLocalContextChanged(innerEC.DangerousGetRawExecutionContext(), outerEC.DangerousGetRawExecutionContext());
}
}
public struct AsyncFlowControl: IDisposable
{
private bool useEC;
private ExecutionContext _ec;
#if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
private SecurityContext _sc;
#endif // #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
private Thread _thread;
#if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
[SecurityCritical]
internal void Setup(SecurityContextDisableFlow flags)
{
useEC = false;
Thread currentThread = Thread.CurrentThread;
_sc = currentThread.GetMutableExecutionContext().SecurityContext;
_sc._disableFlow = flags;
_thread = currentThread;
}
#endif // #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
[SecurityCritical]
internal void Setup()
{
useEC = true;
Thread currentThread = Thread.CurrentThread;
_ec = currentThread.GetMutableExecutionContext();
_ec.isFlowSuppressed = true;
_thread = currentThread;
}
public void Dispose()
{
Undo();
}
[SecuritySafeCritical]
public void Undo()
{
if (_thread == null)
{
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CannotUseAFCMultiple"));
}
if (_thread != Thread.CurrentThread)
{
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CannotUseAFCOtherThread"));
}
if (useEC)
{
if (Thread.CurrentThread.GetMutableExecutionContext() != _ec)
{
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_AsyncFlowCtrlCtxMismatch"));
}
ExecutionContext.RestoreFlow();
}
#if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
else
{
if (!Thread.CurrentThread.GetExecutionContextReader().SecurityContext.IsSame(_sc))
{
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_AsyncFlowCtrlCtxMismatch"));
}
SecurityContext.RestoreFlow();
}
#endif // #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
_thread = null;
}
public override int GetHashCode()
{
return _thread == null ? ToString().GetHashCode() : _thread.GetHashCode();
}
public override bool Equals(Object obj)
{
if (obj is AsyncFlowControl)
return Equals((AsyncFlowControl)obj);
else
return false;
}
public bool Equals(AsyncFlowControl obj)
{
return obj.useEC == useEC && obj._ec == _ec &&
#if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
obj._sc == _sc &&
#endif // #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
obj._thread == _thread;
}
public static bool operator ==(AsyncFlowControl a, AsyncFlowControl b)
{
return a.Equals(b);
}
public static bool operator !=(AsyncFlowControl a, AsyncFlowControl b)
{
return !(a == b);
}
}
#if FEATURE_SERIALIZATION
[Serializable]
#endif
public sealed class ExecutionContext : IDisposable, ISerializable
{
/*=========================================================================
** Data accessed from managed code that needs to be defined in
** ExecutionContextObject to maintain alignment between the two classes.
** DON'T CHANGE THESE UNLESS YOU MODIFY ExecutionContextObject in vm\object.h
=========================================================================*/
#if FEATURE_CAS_POLICY
private HostExecutionContext _hostExecutionContext;
#endif // FEATURE_CAS_POLICY
private SynchronizationContext _syncContext;
private SynchronizationContext _syncContextNoFlow;
#if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
private SecurityContext _securityContext;
#endif // #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
#if FEATURE_REMOTING
[System.Security.SecurityCritical] // auto-generated
private LogicalCallContext _logicalCallContext;
private IllogicalCallContext _illogicalCallContext; // this call context follows the physical thread
#endif // #if FEATURE_REMOTING
enum Flags
{
None = 0x0,
IsNewCapture = 0x1,
IsFlowSuppressed = 0x2,
IsPreAllocatedDefault = 0x4
}
private Flags _flags;
private Dictionary<IAsyncLocal, object> _localValues;
private List<IAsyncLocal> _localChangeNotifications;
internal bool isNewCapture
{
get
{
return (_flags & (Flags.IsNewCapture | Flags.IsPreAllocatedDefault)) != Flags.None;
}
set
{
Contract.Assert(!IsPreAllocatedDefault);
if (value)
_flags |= Flags.IsNewCapture;
else
_flags &= ~Flags.IsNewCapture;
}
}
internal bool isFlowSuppressed
{
get
{
return (_flags & Flags.IsFlowSuppressed) != Flags.None;
}
set
{
Contract.Assert(!IsPreAllocatedDefault);
if (value)
_flags |= Flags.IsFlowSuppressed;
else
_flags &= ~Flags.IsFlowSuppressed;
}
}
private static readonly ExecutionContext s_dummyDefaultEC = new ExecutionContext(isPreAllocatedDefault: true);
static internal ExecutionContext PreAllocatedDefault
{
[SecuritySafeCritical]
get { return s_dummyDefaultEC; }
}
internal bool IsPreAllocatedDefault
{
get
{
// we use _flags instead of a direct comparison w/ s_dummyDefaultEC to avoid the static access on
// hot code paths.
if ((_flags & Flags.IsPreAllocatedDefault) != Flags.None)
{
Contract.Assert(this == s_dummyDefaultEC);
return true;
}
else
{
return false;
}
}
}
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal ExecutionContext()
{
}
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal ExecutionContext(bool isPreAllocatedDefault)
{
if (isPreAllocatedDefault)
_flags = Flags.IsPreAllocatedDefault;
}
// Read-only wrapper around ExecutionContext. This enables safe reading of an ExecutionContext without accidentally modifying it.
internal struct Reader
{
ExecutionContext m_ec;
public Reader(ExecutionContext ec) { m_ec = ec; }
public ExecutionContext DangerousGetRawExecutionContext() { return m_ec; }
public bool IsNull { get { return m_ec == null; } }
[SecurityCritical]
public bool IsDefaultFTContext(bool ignoreSyncCtx) { return m_ec.IsDefaultFTContext(ignoreSyncCtx); }
public bool IsFlowSuppressed
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get { return IsNull ? false : m_ec.isFlowSuppressed; }
}
//public Thread Thread { get { return m_ec._thread; } }
public bool IsSame(ExecutionContext.Reader other) { return m_ec == other.m_ec; }
public SynchronizationContext SynchronizationContext { get { return IsNull ? null : m_ec.SynchronizationContext; } }
public SynchronizationContext SynchronizationContextNoFlow { get { return IsNull ? null : m_ec.SynchronizationContextNoFlow; } }
#if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
public SecurityContext.Reader SecurityContext
{
[SecurityCritical]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get { return new SecurityContext.Reader(IsNull ? null : m_ec.SecurityContext); }
}
#endif
#if FEATURE_REMOTING
public LogicalCallContext.Reader LogicalCallContext
{
[SecurityCritical]
get { return new LogicalCallContext.Reader(IsNull ? null : m_ec.LogicalCallContext); }
}
public IllogicalCallContext.Reader IllogicalCallContext
{
[SecurityCritical]
get { return new IllogicalCallContext.Reader(IsNull ? null : m_ec.IllogicalCallContext); }
}
#endif
[SecurityCritical]
public object GetLocalValue(IAsyncLocal local)
{
if (IsNull)
return null;
if (m_ec._localValues == null)
return null;
object value;
m_ec._localValues.TryGetValue(local, out value);
return value;
}
[SecurityCritical]
public bool HasSameLocalValues(ExecutionContext other)
{
var thisLocalValues = IsNull ? null : m_ec._localValues;
var otherLocalValues = other == null ? null : other._localValues;
return thisLocalValues == otherLocalValues;
}
[SecurityCritical]
public bool HasLocalValues()
{
return !this.IsNull && m_ec._localValues != null;
}
}
[SecurityCritical]
internal static object GetLocalValue(IAsyncLocal local)
{
return Thread.CurrentThread.GetExecutionContextReader().GetLocalValue(local);
}
[SecurityCritical]
internal static void SetLocalValue(IAsyncLocal local, object newValue, bool needChangeNotifications)
{
ExecutionContext current = Thread.CurrentThread.GetMutableExecutionContext();
object previousValue = null;
bool hadPreviousValue = current._localValues != null && current._localValues.TryGetValue(local, out previousValue);
if (previousValue == newValue)
return;
if (current._localValues == null)
current._localValues = new Dictionary<IAsyncLocal, object>();
else
current._localValues = new Dictionary<IAsyncLocal, object>(current._localValues);
current._localValues[local] = newValue;
if (needChangeNotifications)
{
if (hadPreviousValue)
{
Contract.Assert(current._localChangeNotifications != null);
Contract.Assert(current._localChangeNotifications.Contains(local));
}
else
{
if (current._localChangeNotifications == null)
current._localChangeNotifications = new List<IAsyncLocal>();
else
current._localChangeNotifications = new List<IAsyncLocal>(current._localChangeNotifications);
current._localChangeNotifications.Add(local);
}
local.OnValueChanged(previousValue, newValue, false);
}
}
[SecurityCritical]
[HandleProcessCorruptedStateExceptions]
internal static void OnAsyncLocalContextChanged(ExecutionContext previous, ExecutionContext current)
{
List<IAsyncLocal> previousLocalChangeNotifications = (previous == null) ? null : previous._localChangeNotifications;
if (previousLocalChangeNotifications != null)
{
foreach (IAsyncLocal local in previousLocalChangeNotifications)
{
object previousValue = null;
if (previous != null && previous._localValues != null)
previous._localValues.TryGetValue(local, out previousValue);
object currentValue = null;
if (current != null && current._localValues != null)
current._localValues.TryGetValue(local, out currentValue);
if (previousValue != currentValue)
local.OnValueChanged(previousValue, currentValue, true);
}
}
List<IAsyncLocal> currentLocalChangeNotifications = (current == null) ? null : current._localChangeNotifications;
if (currentLocalChangeNotifications != null && currentLocalChangeNotifications != previousLocalChangeNotifications)
{
try
{
foreach (IAsyncLocal local in currentLocalChangeNotifications)
{
// If the local has a value in the previous context, we already fired the event for that local
// in the code above.
object previousValue = null;
if (previous == null ||
previous._localValues == null ||
!previous._localValues.TryGetValue(local, out previousValue))
{
object currentValue = null;
if (current != null && current._localValues != null)
current._localValues.TryGetValue(local, out currentValue);
if (previousValue != currentValue)
local.OnValueChanged(previousValue, currentValue, true);
}
}
}
catch (Exception ex)
{
Environment.FailFast(
Environment.GetResourceString("ExecutionContext_ExceptionInAsyncLocalNotification"),
ex);
}
}
}
#if FEATURE_REMOTING
internal LogicalCallContext LogicalCallContext
{
[System.Security.SecurityCritical] // auto-generated
get
{
if (_logicalCallContext == null)
{
_logicalCallContext = new LogicalCallContext();
}
return _logicalCallContext;
}
[System.Security.SecurityCritical] // auto-generated
set
{
Contract.Assert(this != s_dummyDefaultEC);
_logicalCallContext = value;
}
}
internal IllogicalCallContext IllogicalCallContext
{
get
{
if (_illogicalCallContext == null)
{
_illogicalCallContext = new IllogicalCallContext();
}
return _illogicalCallContext;
}
set
{
Contract.Assert(this != s_dummyDefaultEC);
_illogicalCallContext = value;
}
}
#endif // #if FEATURE_REMOTING
internal SynchronizationContext SynchronizationContext
{
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
get
{
return _syncContext;
}
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
set
{
Contract.Assert(this != s_dummyDefaultEC);
_syncContext = value;
}
}
internal SynchronizationContext SynchronizationContextNoFlow
{
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
get
{
return _syncContextNoFlow;
}
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
set
{
Contract.Assert(this != s_dummyDefaultEC);
_syncContextNoFlow = value;
}
}
#if FEATURE_CAS_POLICY
internal HostExecutionContext HostExecutionContext
{
get
{
return _hostExecutionContext;
}
set
{
Contract.Assert(this != s_dummyDefaultEC);
_hostExecutionContext = value;
}
}
#endif // FEATURE_CAS_POLICY
#if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
internal SecurityContext SecurityContext
{
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
get
{
return _securityContext;
}
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
set
{
Contract.Assert(this != s_dummyDefaultEC);
// store the new security context
_securityContext = value;
// perform the reverse link too
if (value != null)
_securityContext.ExecutionContext = this;
}
}
#endif // #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
public void Dispose()
{
if(this.IsPreAllocatedDefault)
return; //Do nothing if this is the default context
#if FEATURE_CAS_POLICY
if (_hostExecutionContext != null)
_hostExecutionContext.Dispose();
#endif // FEATURE_CAS_POLICY
#if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
if (_securityContext != null)
_securityContext.Dispose();
#endif //FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
}
[DynamicSecurityMethod]
[System.Security.SecurityCritical] // auto-generated_required
public static void Run(ExecutionContext executionContext, ContextCallback callback, Object state)
{
if (executionContext == null)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NullContext"));
if (!executionContext.isNewCapture)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotNewCaptureContext"));
Run(executionContext, callback, state, false);
}
// This method is special from a security perspective - the VM will not allow a stack walk to
// continue past the call to ExecutionContext.Run. If you change the signature to this method, make
// sure to update SecurityStackWalk::IsSpecialRunFrame in the VM to search for the new signature.
[DynamicSecurityMethod]
[SecurityCritical]
[FriendAccessAllowed]
internal static void Run(ExecutionContext executionContext, ContextCallback callback, Object state, bool preserveSyncCtx)
{
RunInternal(executionContext, callback, state, preserveSyncCtx);
}
// Actual implementation of Run is here, in a non-DynamicSecurityMethod, because the JIT seems to refuse to inline callees into
// a DynamicSecurityMethod.
[SecurityCritical]
[SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "Reviewed for thread safety")]
[HandleProcessCorruptedStateExceptions]
internal static void RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, bool preserveSyncCtx)
{
Contract.Assert(executionContext != null);
if (executionContext.IsPreAllocatedDefault)
{
Contract.Assert(executionContext.IsDefaultFTContext(preserveSyncCtx));
}
else
{
Contract.Assert(executionContext.isNewCapture);
executionContext.isNewCapture = false;
}
Thread currentThread = Thread.CurrentThread;
ExecutionContextSwitcher ecsw = default(ExecutionContextSwitcher);
RuntimeHelpers.PrepareConstrainedRegions();
try
{
ExecutionContext.Reader ec = currentThread.GetExecutionContextReader();
if ( (ec.IsNull || ec.IsDefaultFTContext(preserveSyncCtx)) &&
#if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
SecurityContext.CurrentlyInDefaultFTSecurityContext(ec) &&
#endif // #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
executionContext.IsDefaultFTContext(preserveSyncCtx) &&
ec.HasSameLocalValues(executionContext)
)
{
// Neither context is interesting, so we don't need to set the context.
// We do need to reset any changes made by the user's callback,
// so here we establish a "copy-on-write scope". Any changes will
// result in a copy of the context being made, preserving the original
// context.
EstablishCopyOnWriteScope(currentThread, true, ref ecsw);
}
else
{
if (executionContext.IsPreAllocatedDefault)
executionContext = new ExecutionContext();
ecsw = SetExecutionContext(executionContext, preserveSyncCtx);
}
//
// Call the user's callback
//
callback(state);
}
finally
{
ecsw.Undo(currentThread);
}
}
[SecurityCritical]
static internal void EstablishCopyOnWriteScope(Thread currentThread, ref ExecutionContextSwitcher ecsw)
{
EstablishCopyOnWriteScope(currentThread, false, ref ecsw);
}
[SecurityCritical]
static private void EstablishCopyOnWriteScope(Thread currentThread, bool knownNullWindowsIdentity, ref ExecutionContextSwitcher ecsw)
{
Contract.Assert(currentThread == Thread.CurrentThread);
ecsw.outerEC = currentThread.GetExecutionContextReader();
ecsw.outerECBelongsToScope = currentThread.ExecutionContextBelongsToCurrentScope;
#if FEATURE_IMPERSONATION
ecsw.cachedAlwaysFlowImpersonationPolicy = SecurityContext.AlwaysFlowImpersonationPolicy;
if (knownNullWindowsIdentity)
Contract.Assert(SecurityContext.GetCurrentWI(ecsw.outerEC, ecsw.cachedAlwaysFlowImpersonationPolicy) == null);
else
ecsw.wi = SecurityContext.GetCurrentWI(ecsw.outerEC, ecsw.cachedAlwaysFlowImpersonationPolicy);
ecsw.wiIsValid = true;
#endif
currentThread.ExecutionContextBelongsToCurrentScope = false;
ecsw.thread = currentThread;
}
// Sets the given execution context object on the thread.
// Returns the previous one.
[System.Security.SecurityCritical] // auto-generated
[DynamicSecurityMethodAttribute()]
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
#if FEATURE_CORRUPTING_EXCEPTIONS
[HandleProcessCorruptedStateExceptions]
#endif // FEATURE_CORRUPTING_EXCEPTIONS
internal static ExecutionContextSwitcher SetExecutionContext(ExecutionContext executionContext, bool preserveSyncCtx)
{
#if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
#endif // #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
Contract.Assert(executionContext != null);
Contract.Assert(executionContext != s_dummyDefaultEC);
// Set up the switcher object to return;
ExecutionContextSwitcher ecsw = new ExecutionContextSwitcher();
Thread currentThread = Thread.CurrentThread;
ExecutionContext.Reader outerEC = currentThread.GetExecutionContextReader();
ecsw.thread = currentThread;
ecsw.outerEC = outerEC;
ecsw.outerECBelongsToScope = currentThread.ExecutionContextBelongsToCurrentScope;
if (preserveSyncCtx)
executionContext.SynchronizationContext = outerEC.SynchronizationContext;
executionContext.SynchronizationContextNoFlow = outerEC.SynchronizationContextNoFlow;
currentThread.SetExecutionContext(executionContext, belongsToCurrentScope: true);
RuntimeHelpers.PrepareConstrainedRegions();
try
{
OnAsyncLocalContextChanged(outerEC.DangerousGetRawExecutionContext(), executionContext);
#if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
//set the security context
SecurityContext sc = executionContext.SecurityContext;
if (sc != null)
{
// non-null SC: needs to be set
SecurityContext.Reader prevSeC = outerEC.SecurityContext;
ecsw.scsw = SecurityContext.SetSecurityContext(sc, prevSeC, false, ref stackMark);
}
else if (!SecurityContext.CurrentlyInDefaultFTSecurityContext(ecsw.outerEC))
{
// null incoming SC, but we're currently not in FT: use static FTSC to set
SecurityContext.Reader prevSeC = outerEC.SecurityContext;
ecsw.scsw = SecurityContext.SetSecurityContext(SecurityContext.FullTrustSecurityContext, prevSeC, false, ref stackMark);
}
#endif // #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
#if FEATURE_CAS_POLICY
// set the Host Context
HostExecutionContext hostContext = executionContext.HostExecutionContext;
if (hostContext != null)
{
ecsw.hecsw = HostExecutionContextManager.SetHostExecutionContextInternal(hostContext);
}
#endif // FEATURE_CAS_POLICY
}
catch
{
ecsw.UndoNoThrow(currentThread);
throw;
}
return ecsw;
}
//
// Public CreateCopy. Used to copy captured ExecutionContexts so they can be reused multiple times.
// This should only copy the portion of the context that we actually capture.
//
[SecuritySafeCritical]
public ExecutionContext CreateCopy()
{
if (!isNewCapture)
{
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CannotCopyUsedContext"));
}
ExecutionContext ec = new ExecutionContext();
ec.isNewCapture = true;
ec._syncContext = _syncContext == null ? null : _syncContext.CreateCopy();
ec._localValues = _localValues;
ec._localChangeNotifications = _localChangeNotifications;
#if FEATURE_CAS_POLICY
// capture the host execution context
ec._hostExecutionContext = _hostExecutionContext == null ? null : _hostExecutionContext.CreateCopy();
#endif // FEATURE_CAS_POLICY
#if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
if (_securityContext != null)
{
ec._securityContext = _securityContext.CreateCopy();
ec._securityContext.ExecutionContext = ec;
}
#endif // #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
#if FEATURE_REMOTING
if (this._logicalCallContext != null)
ec.LogicalCallContext = (LogicalCallContext)this.LogicalCallContext.Clone();
Contract.Assert(this._illogicalCallContext == null);
#endif // #if FEATURE_REMOTING
return ec;
}
//
// Creates a complete copy, used for copy-on-write.
//
[SecuritySafeCritical]
internal ExecutionContext CreateMutableCopy()
{
Contract.Assert(!this.isNewCapture);
ExecutionContext ec = new ExecutionContext();
// We don't deep-copy the SyncCtx, since we're still in the same context after copy-on-write.
ec._syncContext = this._syncContext;
ec._syncContextNoFlow = this._syncContextNoFlow;
#if FEATURE_CAS_POLICY
// capture the host execution context
ec._hostExecutionContext = this._hostExecutionContext == null ? null : _hostExecutionContext.CreateCopy();
#endif // FEATURE_CAS_POLICY
#if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
if (_securityContext != null)
{
ec._securityContext = this._securityContext.CreateMutableCopy();
ec._securityContext.ExecutionContext = ec;
}
#endif // #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
#if FEATURE_REMOTING
if (this._logicalCallContext != null)
ec.LogicalCallContext = (LogicalCallContext)this.LogicalCallContext.Clone();
if (this._illogicalCallContext != null)
ec.IllogicalCallContext = (IllogicalCallContext)this.IllogicalCallContext.CreateCopy();
#endif // #if FEATURE_REMOTING
ec._localValues = this._localValues;
ec._localChangeNotifications = this._localChangeNotifications;
ec.isFlowSuppressed = this.isFlowSuppressed;
return ec;
}
[System.Security.SecurityCritical] // auto-generated_required
public static AsyncFlowControl SuppressFlow()
{
if (IsFlowSuppressed())
{
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CannotSupressFlowMultipleTimes"));
}
Contract.EndContractBlock();
AsyncFlowControl afc = new AsyncFlowControl();
afc.Setup();
return afc;
}
[SecuritySafeCritical]
public static void RestoreFlow()
{
ExecutionContext ec = Thread.CurrentThread.GetMutableExecutionContext();
if (!ec.isFlowSuppressed)
{
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CannotRestoreUnsupressedFlow"));
}
ec.isFlowSuppressed = false;
}
[Pure]
public static bool IsFlowSuppressed()
{
return Thread.CurrentThread.GetExecutionContextReader().IsFlowSuppressed;
}
[System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public static ExecutionContext Capture()
{
// set up a stack mark for finding the caller
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return ExecutionContext.Capture(ref stackMark, CaptureOptions.None);
}
//
// Captures an ExecutionContext with optimization for the "default" case, and captures a "null" synchronization context.
// When calling ExecutionContext.Run on the returned context, specify ignoreSyncCtx = true
//
[System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
[FriendAccessAllowed]
internal static ExecutionContext FastCapture()
{
// set up a stack mark for finding the caller
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return ExecutionContext.Capture(ref stackMark, CaptureOptions.IgnoreSyncCtx | CaptureOptions.OptimizeDefaultCase);
}
[Flags]
internal enum CaptureOptions
{
None = 0x00,
IgnoreSyncCtx = 0x01, //Don't flow SynchronizationContext
OptimizeDefaultCase = 0x02, //Faster in the typical case, but can't show the result to users
// because they could modify the shared default EC.
// Use this only if you won't be exposing the captured EC to users.
}
// internal helper to capture the current execution context using a passed in stack mark
[System.Security.SecurityCritical] // auto-generated
static internal ExecutionContext Capture(ref StackCrawlMark stackMark, CaptureOptions options)
{
ExecutionContext.Reader ecCurrent = Thread.CurrentThread.GetExecutionContextReader();
// check to see if Flow is suppressed
if (ecCurrent.IsFlowSuppressed)
return null;
//
// Attempt to capture context. There may be nothing to capture...
//
#if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
// capture the security context
SecurityContext secCtxNew = SecurityContext.Capture(ecCurrent, ref stackMark);
#endif // #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
#if FEATURE_CAS_POLICY
// capture the host execution context
HostExecutionContext hostCtxNew = HostExecutionContextManager.CaptureHostExecutionContext();
#endif // FEATURE_CAS_POLICY
SynchronizationContext syncCtxNew = null;
#if FEATURE_REMOTING
LogicalCallContext logCtxNew = null;
#endif
if (!ecCurrent.IsNull)
{
// capture the sync context
if (0 == (options & CaptureOptions.IgnoreSyncCtx))
syncCtxNew = (ecCurrent.SynchronizationContext == null) ? null : ecCurrent.SynchronizationContext.CreateCopy();
#if FEATURE_REMOTING
// copy over the Logical Call Context
if (ecCurrent.LogicalCallContext.HasInfo)
logCtxNew = ecCurrent.LogicalCallContext.Clone();
#endif // #if FEATURE_REMOTING
}
Dictionary<IAsyncLocal, object> localValues = null;
List<IAsyncLocal> localChangeNotifications = null;
if (!ecCurrent.IsNull)
{
localValues = ecCurrent.DangerousGetRawExecutionContext()._localValues;
localChangeNotifications = ecCurrent.DangerousGetRawExecutionContext()._localChangeNotifications;
}
//
// If we didn't get anything but defaults, and we're allowed to return the
// dummy default EC, don't bother allocating a new context.
//
if (0 != (options & CaptureOptions.OptimizeDefaultCase) &&
#if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
secCtxNew == null &&
#endif
#if FEATURE_CAS_POLICY
hostCtxNew == null &&
#endif // FEATURE_CAS_POLICY
syncCtxNew == null &&
#if FEATURE_REMOTING
(logCtxNew == null || !logCtxNew.HasInfo) &&
#endif // #if FEATURE_REMOTING
localValues == null &&
localChangeNotifications == null
)
{
return s_dummyDefaultEC;
}
//
// Allocate the new context, and fill it in.
//
ExecutionContext ecNew = new ExecutionContext();
#if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
ecNew.SecurityContext = secCtxNew;
if (ecNew.SecurityContext != null)
ecNew.SecurityContext.ExecutionContext = ecNew;
#endif
#if FEATURE_CAS_POLICY
ecNew._hostExecutionContext = hostCtxNew;
#endif // FEATURE_CAS_POLICY
ecNew._syncContext = syncCtxNew;
#if FEATURE_REMOTING
ecNew.LogicalCallContext = logCtxNew;
#endif // #if FEATURE_REMOTING
ecNew._localValues = localValues;
ecNew._localChangeNotifications = localChangeNotifications;
ecNew.isNewCapture = true;
return ecNew;
}
//
// Implementation of ISerializable
//
[System.Security.SecurityCritical] // auto-generated_required
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info==null)
throw new ArgumentNullException("info");
Contract.EndContractBlock();
#if FEATURE_REMOTING
if (_logicalCallContext != null)
{
info.AddValue("LogicalCallContext", _logicalCallContext, typeof(LogicalCallContext));
}
#endif // #if FEATURE_REMOTING
}
[System.Security.SecurityCritical] // auto-generated
private ExecutionContext(SerializationInfo info, StreamingContext context)
{
SerializationInfoEnumerator e = info.GetEnumerator();
while (e.MoveNext())
{
#if FEATURE_REMOTING
if (e.Name.Equals("LogicalCallContext"))
{
_logicalCallContext = (LogicalCallContext) e.Value;
}
#endif // #if FEATURE_REMOTING
}
} // ObjRef .ctor
[System.Security.SecurityCritical] // auto-generated
internal bool IsDefaultFTContext(bool ignoreSyncCtx)
{
#if FEATURE_CAS_POLICY
if (_hostExecutionContext != null)
return false;
#endif // FEATURE_CAS_POLICY
if (!ignoreSyncCtx && _syncContext != null)
return false;
#if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
if (_securityContext != null && !_securityContext.IsDefaultFTSecurityContext())
return false;
#endif //#if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
#if FEATURE_REMOTING
if (_logicalCallContext != null && _logicalCallContext.HasInfo)
return false;
if (_illogicalCallContext != null && _illogicalCallContext.HasUserData)
return false;
#endif //#if FEATURE_REMOTING
return true;
}
} // class ExecutionContext
#endif //FEATURE_CORECLR
}
| |
// ReSharper disable All
using System.Collections.Generic;
using System.Data;
using System.Dynamic;
using System.Linq;
using Frapid.DataAccess;
using Frapid.DataAccess.Models;
using Frapid.DbPolicy;
using Frapid.Framework.Extensions;
using Npgsql;
using Serilog;
using Frapid.NPoco;
namespace Frapid.WebsiteBuilder.DataAccess
{
/// <summary>
/// Provides simplified data access features to perform SCRUD operation on the database view "website.tag_view".
/// </summary>
public class TagView : DbAccess, ITagViewRepository
{
/// <summary>
/// The schema of this view. Returns literal "website".
/// </summary>
public override string _ObjectNamespace => "website";
/// <summary>
/// The schema unqualified name of this view. Returns literal "tag_view".
/// </summary>
public override string _ObjectName => "tag_view";
/// <summary>
/// Login id of application user accessing this view.
/// </summary>
public long _LoginId { get; set; }
/// <summary>
/// User id of application user accessing this table.
/// </summary>
public int _UserId { get; set; }
/// <summary>
/// The name of the database on which queries are being executed to.
/// </summary>
public string _Catalog { get; set; }
/// <summary>
/// Performs SQL count on the view "website.tag_view".
/// </summary>
/// <returns>Returns the number of rows of the view "website.tag_view".</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public long Count()
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return 0;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to count entity \"TagView\" was denied to the user with Login ID {LoginId}", this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "SELECT COUNT(*) FROM website.tag_view;";
return Factory.Scalar<long>(this._Catalog, sql);
}
/// <summary>
/// Executes a select query on the view "website.tag_view" to return all instances of the "TagView" class.
/// </summary>
/// <returns>Returns a non-live, non-mapped instances of "TagView" class.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public IEnumerable<Frapid.WebsiteBuilder.Entities.TagView> Get()
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.ExportData, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to the export entity \"TagView\" was denied to the user with Login ID {LoginId}", this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "SELECT * FROM website.tag_view ORDER BY 1;";
return Factory.Get<Frapid.WebsiteBuilder.Entities.TagView>(this._Catalog, sql);
}
/// <summary>
/// Performs a select statement on the view "website.tag_view" producing a paginated result of 10.
/// </summary>
/// <returns>Returns the first page of collection of "TagView" class.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public IEnumerable<Frapid.WebsiteBuilder.Entities.TagView> GetPaginatedResult()
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to the first page of the entity \"TagView\" was denied to the user with Login ID {LoginId}.", this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string sql = "SELECT * FROM website.tag_view ORDER BY 1 LIMIT 10 OFFSET 0;";
return Factory.Get<Frapid.WebsiteBuilder.Entities.TagView>(this._Catalog, sql);
}
/// <summary>
/// Performs a select statement on the view "website.tag_view" producing a paginated result of 10.
/// </summary>
/// <param name="pageNumber">Enter the page number to produce the paginated result.</param>
/// <returns>Returns collection of "TagView" class.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public IEnumerable<Frapid.WebsiteBuilder.Entities.TagView> GetPaginatedResult(long pageNumber)
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to Page #{Page} of the entity \"TagView\" was denied to the user with Login ID {LoginId}.", pageNumber, this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
long offset = (pageNumber - 1) * 10;
const string sql = "SELECT * FROM website.tag_view ORDER BY 1 LIMIT 10 OFFSET @0;";
return Factory.Get<Frapid.WebsiteBuilder.Entities.TagView>(this._Catalog, sql, offset);
}
public List<Frapid.DataAccess.Models.Filter> GetFilters(string catalog, string filterName)
{
const string sql = "SELECT * FROM config.filters WHERE object_name='website.tag_view' AND lower(filter_name)=lower(@0);";
return Factory.Get<Frapid.DataAccess.Models.Filter>(catalog, sql, filterName).ToList();
}
/// <summary>
/// Performs a filtered count on view "website.tag_view".
/// </summary>
/// <param name="filters">The list of filter conditions.</param>
/// <returns>Returns number of rows of "TagView" class using the filter.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public long CountWhere(List<Frapid.DataAccess.Models.Filter> filters)
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return 0;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to count entity \"TagView\" was denied to the user with Login ID {LoginId}. Filters: {Filters}.", this._LoginId, filters);
throw new UnauthorizedException("Access is denied.");
}
}
Sql sql = Sql.Builder.Append("SELECT COUNT(*) FROM website.tag_view WHERE 1 = 1");
Frapid.DataAccess.FilterManager.AddFilters(ref sql, new Frapid.WebsiteBuilder.Entities.TagView(), filters);
return Factory.Scalar<long>(this._Catalog, sql);
}
/// <summary>
/// Performs a filtered select statement on view "website.tag_view" producing a paginated result of 10.
/// </summary>
/// <param name="pageNumber">Enter the page number to produce the paginated result. If you provide a negative number, the result will not be paginated.</param>
/// <param name="filters">The list of filter conditions.</param>
/// <returns>Returns collection of "TagView" class.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public IEnumerable<Frapid.WebsiteBuilder.Entities.TagView> GetWhere(long pageNumber, List<Frapid.DataAccess.Models.Filter> filters)
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to Page #{Page} of the filtered entity \"TagView\" was denied to the user with Login ID {LoginId}. Filters: {Filters}.", pageNumber, this._LoginId, filters);
throw new UnauthorizedException("Access is denied.");
}
}
long offset = (pageNumber - 1) * 10;
Sql sql = Sql.Builder.Append("SELECT * FROM website.tag_view WHERE 1 = 1");
Frapid.DataAccess.FilterManager.AddFilters(ref sql, new Frapid.WebsiteBuilder.Entities.TagView(), filters);
sql.OrderBy("1");
if (pageNumber > 0)
{
sql.Append("LIMIT @0", 10);
sql.Append("OFFSET @0", offset);
}
return Factory.Get<Frapid.WebsiteBuilder.Entities.TagView>(this._Catalog, sql);
}
/// <summary>
/// Performs a filtered count on view "website.tag_view".
/// </summary>
/// <param name="filterName">The named filter.</param>
/// <returns>Returns number of rows of "TagView" class using the filter.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public long CountFiltered(string filterName)
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return 0;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to count entity \"TagView\" was denied to the user with Login ID {LoginId}. Filter: {Filter}.", this._LoginId, filterName);
throw new UnauthorizedException("Access is denied.");
}
}
List<Frapid.DataAccess.Models.Filter> filters = this.GetFilters(this._Catalog, filterName);
Sql sql = Sql.Builder.Append("SELECT COUNT(*) FROM website.tag_view WHERE 1 = 1");
Frapid.DataAccess.FilterManager.AddFilters(ref sql, new Frapid.WebsiteBuilder.Entities.TagView(), filters);
return Factory.Scalar<long>(this._Catalog, sql);
}
/// <summary>
/// Performs a filtered select statement on view "website.tag_view" producing a paginated result of 10.
/// </summary>
/// <param name="pageNumber">Enter the page number to produce the paginated result. If you provide a negative number, the result will not be paginated.</param>
/// <param name="filterName">The named filter.</param>
/// <returns>Returns collection of "TagView" class.</returns>
/// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
public IEnumerable<Frapid.WebsiteBuilder.Entities.TagView> GetFiltered(long pageNumber, string filterName)
{
if (string.IsNullOrWhiteSpace(this._Catalog))
{
return null;
}
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
}
if (!this.HasAccess)
{
Log.Information("Access to Page #{Page} of the filtered entity \"TagView\" was denied to the user with Login ID {LoginId}. Filter: {Filter}.", pageNumber, this._LoginId, filterName);
throw new UnauthorizedException("Access is denied.");
}
}
List<Frapid.DataAccess.Models.Filter> filters = this.GetFilters(this._Catalog, filterName);
long offset = (pageNumber - 1) * 10;
Sql sql = Sql.Builder.Append("SELECT * FROM website.tag_view WHERE 1 = 1");
Frapid.DataAccess.FilterManager.AddFilters(ref sql, new Frapid.WebsiteBuilder.Entities.TagView(), filters);
sql.OrderBy("1");
if (pageNumber > 0)
{
sql.Append("LIMIT @0", 10);
sql.Append("OFFSET @0", offset);
}
return Factory.Get<Frapid.WebsiteBuilder.Entities.TagView>(this._Catalog, sql);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.