context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="PlotView.cs" company="OxyPlot">
// Copyright (c) 2014 OxyPlot contributors
// </copyright>
// <summary>
// Provides a view that can show a <see cref="PlotModel" />.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace OxyPlot.Xamarin.iOS
{
using Foundation;
using OxyPlot;
using System;
using System.Collections.Generic;
using System.Linq;
using UIKit;
/// <summary>
/// Provides a view that can show a <see cref="PlotModel" />.
/// </summary>
[Register("PlotView")]
public class PlotView : UIView, IPlotView
{
/// <summary>
/// The current plot model.
/// </summary>
private PlotModel model;
/// <summary>
/// The default plot controller.
/// </summary>
private IPlotController defaultController;
private PanZoomGestureRecognizer panZoomGesture = new PanZoomGestureRecognizer();
/// <summary>
/// Initializes a new instance of the <see cref="OxyPlot.Xamarin.iOS.PlotView"/> class.
/// </summary>
public PlotView()
{
this.Initialize ();
}
/// <summary>
/// Initializes a new instance of the <see cref="OxyPlot.Xamarin.iOS.PlotView"/> class.
/// </summary>
/// <param name="frame">The initial frame.</param>
public PlotView(CoreGraphics.CGRect frame) : base(frame)
{
this.Initialize ();
}
/// <summary>
/// Initializes a new instance of the <see cref="OxyPlot.Xamarin.iOS.PlotView"/> class.
/// </summary>
/// <param name="coder">Coder.</param>
[Export ("initWithCoder:")]
public PlotView(NSCoder coder) : base (coder)
{
this.Initialize ();
}
/// <summary>
/// Uses the new layout.
/// </summary>
/// <returns><c>true</c>, if new layout was used, <c>false</c> otherwise.</returns>
[Export ("requiresConstraintBasedLayout")]
bool UseNewLayout ()
{
return true;
}
/// <summary>
/// Initialize the view.
/// </summary>
private void Initialize() {
this.UserInteractionEnabled = true;
this.MultipleTouchEnabled = true;
this.BackgroundColor = UIColor.White;
this.KeepAspectRatioWhenPinching = true;
this.panZoomGesture.AddTarget(HandlePanZoomGesture);
// Do not intercept touches on overlapping views
this.panZoomGesture.ShouldReceiveTouch += (recognizer, touch) => touch.View == this;
}
/// <summary>
/// Gets or sets the <see cref="PlotModel"/> to show in the view.
/// </summary>
/// <value>The <see cref="PlotModel"/>.</value>
public PlotModel Model
{
get
{
return this.model;
}
set
{
if (this.model != value)
{
if (this.model != null)
{
((IPlotModel)this.model).AttachPlotView(null);
this.model = null;
}
if (value != null)
{
((IPlotModel)value).AttachPlotView(this);
this.model = value;
}
this.InvalidatePlot();
}
}
}
/// <summary>
/// Gets or sets the <see cref="IPlotController"/> that handles input events.
/// </summary>
/// <value>The <see cref="IPlotController"/>.</value>
public IPlotController Controller { get; set; }
/// <summary>
/// Gets the actual model in the view.
/// </summary>
/// <value>
/// The actual model.
/// </value>
Model IView.ActualModel
{
get
{
return this.Model;
}
}
/// <summary>
/// Gets the actual <see cref="PlotModel"/> to show.
/// </summary>
/// <value>The actual model.</value>
public PlotModel ActualModel
{
get
{
return this.Model;
}
}
/// <summary>
/// Gets the actual controller.
/// </summary>
/// <value>
/// The actual <see cref="IController" />.
/// </value>
IController IView.ActualController
{
get
{
return this.ActualController;
}
}
/// <summary>
/// Gets the coordinates of the client area of the view.
/// </summary>
public OxyRect ClientArea
{
get
{
// TODO
return new OxyRect(0, 0, 100, 100);
}
}
/// <summary>
/// Gets the actual <see cref="IPlotController"/>.
/// </summary>
/// <value>The actual plot controller.</value>
public IPlotController ActualController
{
get
{
return this.Controller ?? (this.defaultController ?? (this.defaultController = new PlotController()));
}
}
/// <summary>
/// Gets or sets a value indicating whether this <see cref="OxyPlot.Xamarin.iOS.PlotView"/> keeps the aspect ratio when pinching.
/// </summary>
/// <value><c>true</c> if keep aspect ratio when pinching; otherwise, <c>false</c>.</value>
public bool KeepAspectRatioWhenPinching
{
get { return this.panZoomGesture.KeepAspectRatioWhenPinching; }
set { this.panZoomGesture.KeepAspectRatioWhenPinching = value; }
}
/// <summary>
/// How far apart touch points must be on a certain axis to enable scaling that axis.
/// (only applies if KeepAspectRatioWhenPinching == false)
/// </summary>
public double ZoomThreshold
{
get { return this.panZoomGesture.ZoomThreshold; }
set { this.panZoomGesture.ZoomThreshold = value; }
}
/// <summary>
/// If <c>true</c>, and KeepAspectRatioWhenPinching is <c>false</c>, a zoom-out gesture
/// can turn into a zoom-in gesture if the fingers cross. Setting to <c>false</c> will
/// instead simply stop the zoom at that point.
/// </summary>
public bool AllowPinchPastZero
{
get { return this.panZoomGesture.AllowPinchPastZero; }
set { this.panZoomGesture.AllowPinchPastZero = value; }
}
/// <summary>
/// Hides the tracker.
/// </summary>
public void HideTracker()
{
}
/// <summary>
/// Hides the zoom rectangle.
/// </summary>
public void HideZoomRectangle()
{
}
/// <summary>
/// Invalidates the plot (not blocking the UI thread)
/// </summary>
/// <param name="updateData">If set to <c>true</c> update data.</param>
public void InvalidatePlot(bool updateData = true)
{
var actualModel = this.model;
if (actualModel != null)
{
// TODO: update the model on a background thread
((IPlotModel)actualModel).Update(updateData);
}
this.SetNeedsDisplay();
}
/// <summary>
/// Sets the cursor type.
/// </summary>
/// <param name="cursorType">The cursor type.</param>
public void SetCursorType(CursorType cursorType)
{
// No cursor on iOS
}
/// <summary>
/// Shows the tracker.
/// </summary>
/// <param name="trackerHitResult">The tracker data.</param>
public void ShowTracker(TrackerHitResult trackerHitResult)
{
// TODO: how to show a tracker on iOS
// the tracker must be moved away from the finger...
}
/// <summary>
/// Shows the zoom rectangle.
/// </summary>
/// <param name="rectangle">The rectangle.</param>
public void ShowZoomRectangle(OxyRect rectangle)
{
// Not needed - better with pinch events on iOS?
}
/// <summary>
/// Stores text on the clipboard.
/// </summary>
/// <param name="text">The text.</param>
public void SetClipboardText(string text)
{
UIPasteboard.General.SetValue(new NSString(text), "public.utf8-plain-text");
}
/// <summary>
/// Draws the content of the view.
/// </summary>
/// <param name="rect">The rectangle to draw.</param>
public override void Draw(CoreGraphics.CGRect rect)
{
var actualModel = (IPlotModel)this.model;
if (actualModel != null)
{
var context = UIGraphics.GetCurrentContext ();
using (var renderer = new CoreGraphicsRenderContext(context))
{
if (actualModel.Background.IsVisible())
{
context.SetFillColor (actualModel.Background.ToCGColor ());
context.FillRect (rect);
}
actualModel.Render(renderer, rect.Width, rect.Height);
}
}
}
/// <summary>
/// Method invoked when a motion (a shake) has started.
/// </summary>
/// <param name="motion">The motion subtype.</param>
/// <param name="evt">The event arguments.</param>
public override void MotionBegan(UIEventSubtype motion, UIEvent evt)
{
base.MotionBegan(motion, evt);
if (motion == UIEventSubtype.MotionShake)
{
this.ActualController.HandleGesture(this, new OxyShakeGesture(), new OxyKeyEventArgs());
}
}
/// <summary>
/// Used to add/remove the gesture recognizer so that it
/// doesn't prevent the PlotView from being garbage-collected.
/// </summary>
/// <param name="newsuper">New superview</param>
public override void WillMoveToSuperview (UIView newsuper)
{
if (newsuper == null)
{
this.RemoveGestureRecognizer (this.panZoomGesture);
}
else if (this.Superview == null)
{
this.AddGestureRecognizer (this.panZoomGesture);
}
base.WillMoveToSuperview (newsuper);
}
private void HandlePanZoomGesture()
{
switch (panZoomGesture.State)
{
case UIGestureRecognizerState.Began:
ActualController.HandleTouchStarted(this, panZoomGesture.TouchEventArgs);
break;
case UIGestureRecognizerState.Changed:
ActualController.HandleTouchDelta(this, panZoomGesture.TouchEventArgs);
break;
case UIGestureRecognizerState.Ended:
case UIGestureRecognizerState.Cancelled:
ActualController.HandleTouchCompleted(this, panZoomGesture.TouchEventArgs);
break;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using FluentAssertions;
using JsonApiDotNetCore.Serialization.Objects;
using TestBuildingBlocks;
using Xunit;
namespace JsonApiDotNetCoreTests.IntegrationTests.ReadWrite.Fetching
{
public sealed class FetchResourceTests : IClassFixture<IntegrationTestContext<TestableStartup<ReadWriteDbContext>, ReadWriteDbContext>>
{
private readonly IntegrationTestContext<TestableStartup<ReadWriteDbContext>, ReadWriteDbContext> _testContext;
private readonly ReadWriteFakers _fakers = new();
public FetchResourceTests(IntegrationTestContext<TestableStartup<ReadWriteDbContext>, ReadWriteDbContext> testContext)
{
_testContext = testContext;
testContext.UseController<WorkItemsController>();
testContext.UseController<UserAccountsController>();
}
[Fact]
public async Task Can_get_primary_resources()
{
// Arrange
List<WorkItem> workItems = _fakers.WorkItem.Generate(2);
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
await dbContext.ClearTableAsync<WorkItem>();
dbContext.WorkItems.AddRange(workItems);
await dbContext.SaveChangesAsync();
});
const string route = "/workItems";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
responseDocument.Data.ManyValue.Should().HaveCount(2);
ResourceObject item1 = responseDocument.Data.ManyValue.Single(resource => resource.Id == workItems[0].StringId);
item1.Type.Should().Be("workItems");
item1.Attributes["description"].Should().Be(workItems[0].Description);
item1.Attributes["dueAt"].As<DateTimeOffset?>().Should().BeCloseTo(workItems[0].DueAt.GetValueOrDefault());
item1.Attributes["priority"].Should().Be(workItems[0].Priority);
item1.Relationships.Should().NotBeEmpty();
ResourceObject item2 = responseDocument.Data.ManyValue.Single(resource => resource.Id == workItems[1].StringId);
item2.Type.Should().Be("workItems");
item2.Attributes["description"].Should().Be(workItems[1].Description);
item2.Attributes["dueAt"].As<DateTimeOffset?>().Should().BeCloseTo(workItems[1].DueAt.GetValueOrDefault());
item2.Attributes["priority"].Should().Be(workItems[1].Priority);
item2.Relationships.Should().NotBeEmpty();
}
[Fact]
public async Task Cannot_get_primary_resources_for_unknown_type()
{
// Arrange
const string route = "/" + Unknown.ResourceType;
// Act
(HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecuteGetAsync<string>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.NotFound);
responseDocument.Should().BeEmpty();
}
[Fact]
public async Task Can_get_primary_resource_by_ID()
{
// Arrange
WorkItem workItem = _fakers.WorkItem.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.WorkItems.Add(workItem);
await dbContext.SaveChangesAsync();
});
string route = $"/workItems/{workItem.StringId}";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
responseDocument.Data.SingleValue.Should().NotBeNull();
responseDocument.Data.SingleValue.Type.Should().Be("workItems");
responseDocument.Data.SingleValue.Id.Should().Be(workItem.StringId);
responseDocument.Data.SingleValue.Attributes["description"].Should().Be(workItem.Description);
responseDocument.Data.SingleValue.Attributes["dueAt"].As<DateTimeOffset?>().Should().BeCloseTo(workItem.DueAt.GetValueOrDefault());
responseDocument.Data.SingleValue.Attributes["priority"].Should().Be(workItem.Priority);
responseDocument.Data.SingleValue.Relationships.Should().NotBeEmpty();
}
[Fact]
public async Task Cannot_get_primary_resource_for_unknown_type()
{
// Arrange
string route = $"/{Unknown.ResourceType}/{Unknown.StringId.Int32}";
// Act
(HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecuteGetAsync<string>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.NotFound);
responseDocument.Should().BeEmpty();
}
[Fact]
public async Task Cannot_get_primary_resource_for_unknown_ID()
{
// Arrange
string workItemId = Unknown.StringId.For<WorkItem, int>();
string route = $"/workItems/{workItemId}";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.NotFound);
responseDocument.Errors.Should().HaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.NotFound);
error.Title.Should().Be("The requested resource does not exist.");
error.Detail.Should().Be($"Resource of type 'workItems' with ID '{workItemId}' does not exist.");
}
[Fact]
public async Task Can_get_secondary_ManyToOne_resource()
{
// Arrange
WorkItem workItem = _fakers.WorkItem.Generate();
workItem.Assignee = _fakers.UserAccount.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.WorkItems.Add(workItem);
await dbContext.SaveChangesAsync();
});
string route = $"/workItems/{workItem.StringId}/assignee";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
responseDocument.Data.SingleValue.Should().NotBeNull();
responseDocument.Data.SingleValue.Type.Should().Be("userAccounts");
responseDocument.Data.SingleValue.Id.Should().Be(workItem.Assignee.StringId);
responseDocument.Data.SingleValue.Attributes["firstName"].Should().Be(workItem.Assignee.FirstName);
responseDocument.Data.SingleValue.Attributes["lastName"].Should().Be(workItem.Assignee.LastName);
responseDocument.Data.SingleValue.Relationships.Should().NotBeEmpty();
}
[Fact]
public async Task Can_get_unknown_secondary_ManyToOne_resource()
{
// Arrange
WorkItem workItem = _fakers.WorkItem.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.WorkItems.Add(workItem);
await dbContext.SaveChangesAsync();
});
string route = $"/workItems/{workItem.StringId}/assignee";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
responseDocument.Data.Value.Should().BeNull();
}
[Fact]
public async Task Can_get_secondary_OneToMany_resources()
{
// Arrange
UserAccount userAccount = _fakers.UserAccount.Generate();
userAccount.AssignedItems = _fakers.WorkItem.Generate(2).ToHashSet();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.UserAccounts.Add(userAccount);
await dbContext.SaveChangesAsync();
});
string route = $"/userAccounts/{userAccount.StringId}/assignedItems";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
responseDocument.Data.ManyValue.Should().HaveCount(2);
ResourceObject item1 = responseDocument.Data.ManyValue.Single(resource => resource.Id == userAccount.AssignedItems.ElementAt(0).StringId);
item1.Type.Should().Be("workItems");
item1.Attributes["description"].Should().Be(userAccount.AssignedItems.ElementAt(0).Description);
item1.Attributes["dueAt"].As<DateTimeOffset?>().Should().BeCloseTo(userAccount.AssignedItems.ElementAt(0).DueAt.GetValueOrDefault());
item1.Attributes["priority"].Should().Be(userAccount.AssignedItems.ElementAt(0).Priority);
item1.Relationships.Should().NotBeEmpty();
ResourceObject item2 = responseDocument.Data.ManyValue.Single(resource => resource.Id == userAccount.AssignedItems.ElementAt(1).StringId);
item2.Type.Should().Be("workItems");
item2.Attributes["description"].Should().Be(userAccount.AssignedItems.ElementAt(1).Description);
item2.Attributes["dueAt"].As<DateTimeOffset?>().Should().BeCloseTo(userAccount.AssignedItems.ElementAt(1).DueAt.GetValueOrDefault());
item2.Attributes["priority"].Should().Be(userAccount.AssignedItems.ElementAt(1).Priority);
item2.Relationships.Should().NotBeEmpty();
}
[Fact]
public async Task Can_get_unknown_secondary_OneToMany_resource()
{
// Arrange
UserAccount userAccount = _fakers.UserAccount.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.UserAccounts.Add(userAccount);
await dbContext.SaveChangesAsync();
});
string route = $"/userAccounts/{userAccount.StringId}/assignedItems";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
responseDocument.Data.ManyValue.Should().BeEmpty();
}
[Fact]
public async Task Can_get_secondary_ManyToMany_resources()
{
// Arrange
WorkItem workItem = _fakers.WorkItem.Generate();
workItem.Tags = _fakers.WorkTag.Generate(2).ToHashSet();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.WorkItems.Add(workItem);
await dbContext.SaveChangesAsync();
});
string route = $"/workItems/{workItem.StringId}/tags";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
responseDocument.Data.ManyValue.Should().HaveCount(2);
ResourceObject item1 = responseDocument.Data.ManyValue.Single(resource => resource.Id == workItem.Tags.ElementAt(0).StringId);
item1.Type.Should().Be("workTags");
item1.Attributes["text"].Should().Be(workItem.Tags.ElementAt(0).Text);
item1.Attributes["isBuiltIn"].Should().Be(workItem.Tags.ElementAt(0).IsBuiltIn);
item1.Relationships.Should().NotBeEmpty();
ResourceObject item2 = responseDocument.Data.ManyValue.Single(resource => resource.Id == workItem.Tags.ElementAt(1).StringId);
item2.Type.Should().Be("workTags");
item2.Attributes["text"].Should().Be(workItem.Tags.ElementAt(1).Text);
item2.Attributes["isBuiltIn"].Should().Be(workItem.Tags.ElementAt(1).IsBuiltIn);
item2.Relationships.Should().NotBeEmpty();
}
[Fact]
public async Task Can_get_unknown_secondary_ManyToMany_resources()
{
// Arrange
WorkItem workItem = _fakers.WorkItem.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.WorkItems.Add(workItem);
await dbContext.SaveChangesAsync();
});
string route = $"/workItems/{workItem.StringId}/tags";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
responseDocument.Data.ManyValue.Should().BeEmpty();
}
[Fact]
public async Task Cannot_get_secondary_resource_for_unknown_primary_type()
{
// Arrange
string route = $"/{Unknown.ResourceType}/{Unknown.StringId.Int32}/assignee";
// Act
(HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecuteGetAsync<string>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.NotFound);
responseDocument.Should().BeEmpty();
}
[Fact]
public async Task Cannot_get_secondary_resource_for_unknown_primary_ID()
{
// Arrange
string workItemId = Unknown.StringId.For<WorkItem, int>();
string route = $"/workItems/{workItemId}/assignee";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.NotFound);
responseDocument.Errors.Should().HaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.NotFound);
error.Title.Should().Be("The requested resource does not exist.");
error.Detail.Should().Be($"Resource of type 'workItems' with ID '{workItemId}' does not exist.");
}
[Fact]
public async Task Cannot_get_secondary_resource_for_unknown_secondary_type()
{
// Arrange
WorkItem workItem = _fakers.WorkItem.Generate();
workItem.Assignee = _fakers.UserAccount.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.WorkItems.Add(workItem);
await dbContext.SaveChangesAsync();
});
string route = $"/workItems/{workItem.StringId}/{Unknown.Relationship}";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.NotFound);
responseDocument.Errors.Should().HaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.NotFound);
error.Title.Should().Be("The requested relationship does not exist.");
error.Detail.Should().Be($"Resource of type 'workItems' does not contain a relationship named '{Unknown.Relationship}'.");
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="SingleInstance.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <summary>
// This class checks to make sure that only one instance of
// this application is running at a time.
// </summary>
//-----------------------------------------------------------------------
namespace Microsoft.Shell
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Ipc;
using System.Runtime.Serialization.Formatters;
using System.Threading;
using System.Windows;
using System.Windows.Threading;
using System.Xml.Serialization;
using System.Security;
using System.Runtime.InteropServices;
using System.ComponentModel;
internal enum WM
{
NULL = 0x0000,
CREATE = 0x0001,
DESTROY = 0x0002,
MOVE = 0x0003,
SIZE = 0x0005,
ACTIVATE = 0x0006,
SETFOCUS = 0x0007,
KILLFOCUS = 0x0008,
ENABLE = 0x000A,
SETREDRAW = 0x000B,
SETTEXT = 0x000C,
GETTEXT = 0x000D,
GETTEXTLENGTH = 0x000E,
PAINT = 0x000F,
CLOSE = 0x0010,
QUERYENDSESSION = 0x0011,
QUIT = 0x0012,
QUERYOPEN = 0x0013,
ERASEBKGND = 0x0014,
SYSCOLORCHANGE = 0x0015,
SHOWWINDOW = 0x0018,
ACTIVATEAPP = 0x001C,
SETCURSOR = 0x0020,
MOUSEACTIVATE = 0x0021,
CHILDACTIVATE = 0x0022,
QUEUESYNC = 0x0023,
GETMINMAXINFO = 0x0024,
WINDOWPOSCHANGING = 0x0046,
WINDOWPOSCHANGED = 0x0047,
CONTEXTMENU = 0x007B,
STYLECHANGING = 0x007C,
STYLECHANGED = 0x007D,
DISPLAYCHANGE = 0x007E,
GETICON = 0x007F,
SETICON = 0x0080,
NCCREATE = 0x0081,
NCDESTROY = 0x0082,
NCCALCSIZE = 0x0083,
NCHITTEST = 0x0084,
NCPAINT = 0x0085,
NCACTIVATE = 0x0086,
GETDLGCODE = 0x0087,
SYNCPAINT = 0x0088,
NCMOUSEMOVE = 0x00A0,
NCLBUTTONDOWN = 0x00A1,
NCLBUTTONUP = 0x00A2,
NCLBUTTONDBLCLK = 0x00A3,
NCRBUTTONDOWN = 0x00A4,
NCRBUTTONUP = 0x00A5,
NCRBUTTONDBLCLK = 0x00A6,
NCMBUTTONDOWN = 0x00A7,
NCMBUTTONUP = 0x00A8,
NCMBUTTONDBLCLK = 0x00A9,
SYSKEYDOWN = 0x0104,
SYSKEYUP = 0x0105,
SYSCHAR = 0x0106,
SYSDEADCHAR = 0x0107,
COMMAND = 0x0111,
SYSCOMMAND = 0x0112,
MOUSEMOVE = 0x0200,
LBUTTONDOWN = 0x0201,
LBUTTONUP = 0x0202,
LBUTTONDBLCLK = 0x0203,
RBUTTONDOWN = 0x0204,
RBUTTONUP = 0x0205,
RBUTTONDBLCLK = 0x0206,
MBUTTONDOWN = 0x0207,
MBUTTONUP = 0x0208,
MBUTTONDBLCLK = 0x0209,
MOUSEWHEEL = 0x020A,
XBUTTONDOWN = 0x020B,
XBUTTONUP = 0x020C,
XBUTTONDBLCLK = 0x020D,
MOUSEHWHEEL = 0x020E,
CAPTURECHANGED = 0x0215,
ENTERSIZEMOVE = 0x0231,
EXITSIZEMOVE = 0x0232,
IME_SETCONTEXT = 0x0281,
IME_NOTIFY = 0x0282,
IME_CONTROL = 0x0283,
IME_COMPOSITIONFULL = 0x0284,
IME_SELECT = 0x0285,
IME_CHAR = 0x0286,
IME_REQUEST = 0x0288,
IME_KEYDOWN = 0x0290,
IME_KEYUP = 0x0291,
NCMOUSELEAVE = 0x02A2,
DWMCOMPOSITIONCHANGED = 0x031E,
DWMNCRENDERINGCHANGED = 0x031F,
DWMCOLORIZATIONCOLORCHANGED = 0x0320,
DWMWINDOWMAXIMIZEDCHANGE = 0x0321,
#region Windows 7
DWMSENDICONICTHUMBNAIL = 0x0323,
DWMSENDICONICLIVEPREVIEWBITMAP = 0x0326,
#endregion
USER = 0x0400,
// This is the hard-coded message value used by WinForms for Shell_NotifyIcon.
// It's relatively safe to reuse.
TRAYMOUSEMESSAGE = 0x800, //WM_USER + 1024
APP = 0x8000,
}
[SuppressUnmanagedCodeSecurity]
internal static class NativeMethods
{
/// <summary>
/// Delegate declaration that matches WndProc signatures.
/// </summary>
public delegate IntPtr MessageHandler(WM uMsg, IntPtr wParam, IntPtr lParam, out bool handled);
[DllImport("shell32.dll", EntryPoint = "CommandLineToArgvW", CharSet = CharSet.Unicode)]
private static extern IntPtr _CommandLineToArgvW([MarshalAs(UnmanagedType.LPWStr)] string cmdLine, out int numArgs);
[DllImport("kernel32.dll", EntryPoint = "LocalFree", SetLastError = true)]
private static extern IntPtr _LocalFree(IntPtr hMem);
public static string[] CommandLineToArgvW(string cmdLine)
{
IntPtr argv = IntPtr.Zero;
try
{
int numArgs = 0;
argv = _CommandLineToArgvW(cmdLine, out numArgs);
if (argv == IntPtr.Zero)
{
throw new Win32Exception();
}
var result = new string[numArgs];
for (int i = 0; i < numArgs; i++)
{
IntPtr currArg = Marshal.ReadIntPtr(argv, i * Marshal.SizeOf(typeof(IntPtr)));
result[i] = Marshal.PtrToStringUni(currArg);
}
return result;
}
finally
{
IntPtr p = _LocalFree(argv);
// Otherwise LocalFree failed.
// Assert.AreEqual(IntPtr.Zero, p);
}
}
}
public interface ISingleInstanceApp
{
bool SignalExternalCommandLineArgs(IList<string> args);
}
/// <summary>
/// This class checks to make sure that only one instance of
/// this application is running at a time.
/// </summary>
/// <remarks>
/// Note: this class should be used with some caution, because it does no
/// security checking. For example, if one instance of an app that uses this class
/// is running as Administrator, any other instance, even if it is not
/// running as Administrator, can activate it with command line arguments.
/// For most apps, this will not be much of an issue.
/// </remarks>
public static class SingleInstance<TApplication>
where TApplication: Application , ISingleInstanceApp
{
#region Private Fields
/// <summary>
/// String delimiter used in channel names.
/// </summary>
private const string Delimiter = ":";
/// <summary>
/// Suffix to the channel name.
/// </summary>
private const string ChannelNameSuffix = "SingeInstanceIPCChannel";
/// <summary>
/// Remote service name.
/// </summary>
private const string RemoteServiceName = "SingleInstanceApplicationService";
/// <summary>
/// IPC protocol used (string).
/// </summary>
private const string IpcProtocol = "ipc://";
/// <summary>
/// Application mutex.
/// </summary>
private static Mutex singleInstanceMutex;
/// <summary>
/// IPC channel for communications.
/// </summary>
private static IpcServerChannel channel;
/// <summary>
/// List of command line arguments for the application.
/// </summary>
private static IList<string> commandLineArgs;
#endregion
#region Public Properties
/// <summary>
/// Gets list of command line arguments for the application.
/// </summary>
public static IList<string> CommandLineArgs
{
get { return commandLineArgs; }
}
#endregion
#region Public Methods
/// <summary>
/// Checks if the instance of the application attempting to start is the first instance.
/// If not, activates the first instance.
/// </summary>
/// <returns>True if this is the first instance of the application.</returns>
public static bool InitializeAsFirstInstance( string uniqueName )
{
commandLineArgs = GetCommandLineArgs(uniqueName);
// Build unique application Id and the IPC channel name.
string applicationIdentifier = uniqueName + Environment.UserName;
string channelName = String.Concat(applicationIdentifier, Delimiter, ChannelNameSuffix);
// Create mutex based on unique application Id to check if this is the first instance of the application.
bool firstInstance;
singleInstanceMutex = new Mutex(true, applicationIdentifier, out firstInstance);
if (firstInstance)
{
CreateRemoteService(channelName);
}
else
{
SignalFirstInstance(channelName, commandLineArgs);
}
return firstInstance;
}
/// <summary>
/// Cleans up single-instance code, clearing shared resources, mutexes, etc.
/// </summary>
public static void Cleanup()
{
if (singleInstanceMutex != null)
{
singleInstanceMutex.Close();
singleInstanceMutex = null;
}
if (channel != null)
{
ChannelServices.UnregisterChannel(channel);
channel = null;
}
}
#endregion
#region Private Methods
/// <summary>
/// Gets command line args - for ClickOnce deployed applications, command line args may not be passed directly, they have to be retrieved.
/// </summary>
/// <returns>List of command line arg strings.</returns>
private static IList<string> GetCommandLineArgs( string uniqueApplicationName )
{
string[] args = null;
if (AppDomain.CurrentDomain.ActivationContext == null)
{
// The application was not clickonce deployed, get args from standard API's
args = Environment.GetCommandLineArgs();
}
else
{
// The application was clickonce deployed
// Clickonce deployed apps cannot recieve traditional commandline arguments
// As a workaround commandline arguments can be written to a shared location before
// the app is launched and the app can obtain its commandline arguments from the
// shared location
string appFolderPath = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), uniqueApplicationName);
string cmdLinePath = Path.Combine(appFolderPath, "cmdline.txt");
if (File.Exists(cmdLinePath))
{
try
{
using (TextReader reader = new StreamReader(cmdLinePath, System.Text.Encoding.Unicode))
{
args = NativeMethods.CommandLineToArgvW(reader.ReadToEnd());
}
File.Delete(cmdLinePath);
}
catch (IOException)
{
}
}
}
if (args == null)
{
args = new string[] { };
}
return new List<string>(args);
}
/// <summary>
/// Creates a remote service for communication.
/// </summary>
/// <param name="channelName">Application's IPC channel name.</param>
private static void CreateRemoteService(string channelName)
{
BinaryServerFormatterSinkProvider serverProvider = new BinaryServerFormatterSinkProvider();
serverProvider.TypeFilterLevel = TypeFilterLevel.Full;
IDictionary props = new Dictionary<string, string>();
props["name"] = channelName;
props["portName"] = channelName;
props["exclusiveAddressUse"] = "false";
// Create the IPC Server channel with the channel properties
channel = new IpcServerChannel(props, serverProvider);
// Register the channel with the channel services
ChannelServices.RegisterChannel(channel, true);
// Expose the remote service with the REMOTE_SERVICE_NAME
IPCRemoteService remoteService = new IPCRemoteService();
RemotingServices.Marshal(remoteService, RemoteServiceName);
}
/// <summary>
/// Creates a client channel and obtains a reference to the remoting service exposed by the server -
/// in this case, the remoting service exposed by the first instance. Calls a function of the remoting service
/// class to pass on command line arguments from the second instance to the first and cause it to activate itself.
/// </summary>
/// <param name="channelName">Application's IPC channel name.</param>
/// <param name="args">
/// Command line arguments for the second instance, passed to the first instance to take appropriate action.
/// </param>
private static void SignalFirstInstance(string channelName, IList<string> args)
{
IpcClientChannel secondInstanceChannel = new IpcClientChannel();
ChannelServices.RegisterChannel(secondInstanceChannel, true);
string remotingServiceUrl = IpcProtocol + channelName + "/" + RemoteServiceName;
// Obtain a reference to the remoting service exposed by the server i.e the first instance of the application
IPCRemoteService firstInstanceRemoteServiceReference = (IPCRemoteService)RemotingServices.Connect(typeof(IPCRemoteService), remotingServiceUrl);
// Check that the remote service exists, in some cases the first instance may not yet have created one, in which case
// the second instance should just exit
if (firstInstanceRemoteServiceReference != null)
{
// Invoke a method of the remote service exposed by the first instance passing on the command line
// arguments and causing the first instance to activate itself
firstInstanceRemoteServiceReference.InvokeFirstInstance(args);
}
}
/// <summary>
/// Callback for activating first instance of the application.
/// </summary>
/// <param name="arg">Callback argument.</param>
/// <returns>Always null.</returns>
private static object ActivateFirstInstanceCallback(object arg)
{
// Get command line args to be passed to first instance
IList<string> args = arg as IList<string>;
ActivateFirstInstance(args);
return null;
}
/// <summary>
/// Activates the first instance of the application with arguments from a second instance.
/// </summary>
/// <param name="args">List of arguments to supply the first instance of the application.</param>
private static void ActivateFirstInstance(IList<string> args)
{
// Set main window state and process command line args
if (Application.Current == null)
{
return;
}
((TApplication)Application.Current).SignalExternalCommandLineArgs(args);
}
#endregion
#region Private Classes
/// <summary>
/// Remoting service class which is exposed by the server i.e the first instance and called by the second instance
/// to pass on the command line arguments to the first instance and cause it to activate itself.
/// </summary>
private class IPCRemoteService : MarshalByRefObject
{
/// <summary>
/// Activates the first instance of the application.
/// </summary>
/// <param name="args">List of arguments to pass to the first instance.</param>
public void InvokeFirstInstance(IList<string> args)
{
if (Application.Current != null)
{
// Do an asynchronous call to ActivateFirstInstance function
Application.Current.Dispatcher.BeginInvoke(
DispatcherPriority.Normal, new DispatcherOperationCallback(SingleInstance<TApplication>.ActivateFirstInstanceCallback), args);
}
}
/// <summary>
/// Remoting Object's ease expires after every 5 minutes by default. We need to override the InitializeLifetimeService class
/// to ensure that lease never expires.
/// </summary>
/// <returns>Always null.</returns>
public override object InitializeLifetimeService()
{
return null;
}
}
#endregion
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using log4net;
using Mono.Addins;
namespace OpenSim.Framework
{
/// <summary>
/// Exception thrown if an incorrect number of plugins are loaded
/// </summary>
public class PluginConstraintViolatedException : Exception
{
public PluginConstraintViolatedException () : base() {}
public PluginConstraintViolatedException (string msg) : base(msg) {}
public PluginConstraintViolatedException (string msg, Exception e) : base(msg, e) {}
}
/// <summary>
/// Classes wishing to impose constraints on plugin loading must implement
/// this class and pass it to PluginLoader AddConstraint()
/// </summary>
public interface IPluginConstraint
{
string Message { get; }
bool Apply(string extpoint);
}
/// <summary>
/// Classes wishing to select specific plugins from a range of possible options
/// must implement this class and pass it to PluginLoader Load()
/// </summary>
public interface IPluginFilter
{
bool Apply(PluginExtensionNode plugin);
}
/// <summary>
/// Generic Plugin Loader
/// </summary>
public class PluginLoader <T> : IDisposable where T : IPlugin
{
private const int max_loadable_plugins = 10000;
private List<T> loaded = new List<T>();
private List<string> extpoints = new List<string>();
private PluginInitialiserBase initialiser;
private Dictionary<string,IPluginConstraint> constraints
= new Dictionary<string,IPluginConstraint>();
private Dictionary<string,IPluginFilter> filters
= new Dictionary<string,IPluginFilter>();
private static readonly ILog log
= LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public PluginInitialiserBase Initialiser
{
set { initialiser = value; }
get { return initialiser; }
}
public List<T> Plugins
{
get { return loaded; }
}
public T Plugin
{
get { return (loaded.Count == 1)? loaded [0] : default (T); }
}
public PluginLoader()
{
Initialiser = new PluginInitialiserBase();
initialise_plugin_dir_(".");
}
public PluginLoader(PluginInitialiserBase init)
{
Initialiser = init;
initialise_plugin_dir_(".");
}
public PluginLoader(PluginInitialiserBase init, string dir)
{
Initialiser = init;
initialise_plugin_dir_(dir);
}
public void Add(string extpoint)
{
if (extpoints.Contains(extpoint))
return;
extpoints.Add(extpoint);
}
public void Add(string extpoint, IPluginConstraint cons)
{
Add(extpoint);
AddConstraint(extpoint, cons);
}
public void Add(string extpoint, IPluginFilter filter)
{
Add(extpoint);
AddFilter(extpoint, filter);
}
public void AddConstraint(string extpoint, IPluginConstraint cons)
{
constraints.Add(extpoint, cons);
}
public void AddFilter(string extpoint, IPluginFilter filter)
{
filters.Add(extpoint, filter);
}
public void Load(string extpoint)
{
Add(extpoint);
Load();
}
public void Load()
{
foreach (string ext in extpoints)
{
log.Info("[PLUGINS]: Loading extension point " + ext);
if (constraints.ContainsKey(ext))
{
IPluginConstraint cons = constraints[ext];
if (cons.Apply(ext))
log.Error("[PLUGINS]: " + ext + " failed constraint: " + cons.Message);
}
IPluginFilter filter = null;
if (filters.ContainsKey(ext))
filter = filters[ext];
List<T> loadedPlugins = new List<T>();
foreach (PluginExtensionNode node in AddinManager.GetExtensionNodes(ext))
{
log.Info("[PLUGINS]: Trying plugin " + node.Path);
if ((filter != null) && (filter.Apply(node) == false))
continue;
T plugin = (T)node.CreateInstance();
loadedPlugins.Add(plugin);
}
// We do Initialise() in a second loop after CreateInstance
// So that modules who need init before others can do it
// Example: Script Engine Component System needs to load its components before RegionLoader starts
foreach (T plugin in loadedPlugins)
{
Initialiser.Initialise(plugin);
Plugins.Add(plugin);
}
}
}
/// <summary>
/// Unregisters Mono.Addins event handlers, allowing temporary Mono.Addins
/// data to be garbage collected. Since the plugins created by this loader
/// are meant to outlive the loader itself, they must be disposed separately
/// </summary>
public void Dispose()
{
AddinManager.AddinLoadError -= on_addinloaderror_;
AddinManager.AddinLoaded -= on_addinloaded_;
}
private void initialise_plugin_dir_(string dir)
{
if (AddinManager.IsInitialized == true)
return;
log.Info("[PLUGINS]: Initializing addin manager");
AddinManager.AddinLoadError += on_addinloaderror_;
AddinManager.AddinLoaded += on_addinloaded_;
clear_registry_(dir);
suppress_console_output_(true);
AddinManager.Initialize(dir);
AddinManager.Registry.Update(null);
suppress_console_output_(false);
}
private void on_addinloaded_(object sender, AddinEventArgs args)
{
log.Info ("[PLUGINS]: Plugin Loaded: " + args.AddinId);
}
private void on_addinloaderror_(object sender, AddinErrorEventArgs args)
{
if (args.Exception == null)
log.Error ("[PLUGINS]: Plugin Error: "
+ args.Message);
else
log.Error ("[PLUGINS]: Plugin Error: "
+ args.Exception.Message + "\n"
+ args.Exception.StackTrace);
}
private void clear_registry_(string dir)
{
// The Mono addin manager (in Mono.Addins.dll version 0.2.0.0)
// occasionally seems to corrupt its addin cache
// Hence, as a temporary solution we'll remove it before each startup
try
{
if (Directory.Exists(dir + "/addin-db-000"))
Directory.Delete(dir + "/addin-db-000", true);
if (Directory.Exists(dir + "/addin-db-001"))
Directory.Delete(dir + "/addin-db-001", true);
}
catch (IOException)
{
// If multiple services are started simultaneously, they may
// each test whether the directory exists at the same time, and
// attempt to delete the directory at the same time. However,
// one of the services will likely succeed first, causing the
// second service to throw an IOException. We catch it here and
// continue on our merry way.
// Mike 2008.08.01, patch from Zaki
}
}
private static TextWriter prev_console_;
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_);
}
}
}
public class PluginExtensionNode : ExtensionNode
{
[NodeAttribute]
string id = "";
[NodeAttribute]
string provider = "";
[NodeAttribute]
string type = "";
Type typeobj;
public string ID { get { return id; } }
public string Provider { get { return provider; } }
public string TypeName { get { return type; } }
public Type TypeObject
{
get
{
if (typeobj != null)
return typeobj;
if (type.Length == 0)
throw new InvalidOperationException("Type name not specified.");
return typeobj = Addin.GetType(type, true);
}
}
public object CreateInstance()
{
return Activator.CreateInstance(TypeObject);
}
}
/// <summary>
/// Constraint that bounds the number of plugins to be loaded.
/// </summary>
public class PluginCountConstraint : IPluginConstraint
{
private int min;
private int max;
public PluginCountConstraint(int exact)
{
min = exact;
max = exact;
}
public PluginCountConstraint(int minimum, int maximum)
{
min = minimum;
max = maximum;
}
public string Message
{
get
{
return "The number of plugins is constrained to the interval ["
+ min + ", " + max + "]";
}
}
public bool Apply (string extpoint)
{
int count = AddinManager.GetExtensionNodes(extpoint).Count;
if ((count < min) || (count > max))
throw new PluginConstraintViolatedException(Message);
return true;
}
}
/// <summary>
/// Filters out which plugin to load based on the plugin name or names given. Plugin names are contained in
/// their addin.xml
/// </summary>
public class PluginProviderFilter : IPluginFilter
{
private string[] m_filters;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="p">
/// Plugin name or names on which to filter. Multiple names should be separated by commas.
/// </param>
public PluginProviderFilter(string p)
{
m_filters = p.Split(',');
for (int i = 0; i < m_filters.Length; i++)
{
m_filters[i] = m_filters[i].Trim();
}
}
/// <summary>
/// Apply this filter to the given plugin.
/// </summary>
/// <param name="plugin"></param>
/// <returns>true if the plugin's name matched one of the filters, false otherwise.</returns>
public bool Apply (PluginExtensionNode plugin)
{
for (int i = 0; i < m_filters.Length; i++)
{
if (m_filters[i] == plugin.Provider)
{
return true;
}
}
return false;
}
}
/// <summary>
/// Filters plugins according to their ID. Plugin IDs are contained in their addin.xml
/// </summary>
public class PluginIdFilter : IPluginFilter
{
private string[] m_filters;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="p">
/// Plugin ID or IDs on which to filter. Multiple names should be separated by commas.
/// </param>
public PluginIdFilter(string p)
{
m_filters = p.Split(',');
for (int i = 0; i < m_filters.Length; i++)
{
m_filters[i] = m_filters[i].Trim();
}
}
/// <summary>
/// Apply this filter to <paramref name="plugin" />.
/// </summary>
/// <param name="plugin">PluginExtensionNode instance to check whether it passes the filter.</param>
/// <returns>true if the plugin's ID matches one of the filters, false otherwise.</returns>
public bool Apply (PluginExtensionNode plugin)
{
for (int i = 0; i < m_filters.Length; i++)
{
if (m_filters[i] == plugin.ID)
{
return true;
}
}
return false;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.RecoveryServices.Backup
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Azure.Management.RecoveryServices;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Microsoft.Rest.Azure.OData;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// BackupJobsOperations operations.
/// </summary>
internal partial class BackupJobsOperations : IServiceOperations<RecoveryServicesBackupClient>, IBackupJobsOperations
{
/// <summary>
/// Initializes a new instance of the BackupJobsOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal BackupJobsOperations(RecoveryServicesBackupClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the RecoveryServicesBackupClient
/// </summary>
public RecoveryServicesBackupClient Client { get; private set; }
/// <summary>
/// Provides a pageable list of jobs.
/// </summary>
/// <param name='vaultName'>
/// The name of the recovery services vault.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group where the recovery services vault is
/// present.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='skipToken'>
/// skipToken Filter.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<JobResource>>> ListWithHttpMessagesAsync(string vaultName, string resourceGroupName, ODataQuery<JobQueryObject> odataQuery = default(ODataQuery<JobQueryObject>), string skipToken = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (vaultName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "vaultName");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2017-07-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("odataQuery", odataQuery);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("vaultName", vaultName);
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("skipToken", skipToken);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{vaultName}/backupJobs").ToString();
_url = _url.Replace("{vaultName}", System.Uri.EscapeDataString(vaultName));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (odataQuery != null)
{
var _odataFilter = odataQuery.ToString();
if (!string.IsNullOrEmpty(_odataFilter))
{
_queryParameters.Add(_odataFilter);
}
}
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (skipToken != null)
{
_queryParameters.Add(string.Format("$skipToken={0}", System.Uri.EscapeDataString(skipToken)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<JobResource>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<JobResource>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Provides a pageable list of jobs.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<JobResource>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<JobResource>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<JobResource>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
/*
* 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 OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Xml;
//using HyperGrid.Framework;
//using OpenSim.Region.Communications.Hypergrid;
namespace OpenSim.Region.CoreModules.Framework.InventoryAccess
{
public class HGAssetMapper
{
#region Fields
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
// This maps between inventory server urls and inventory server clients
// private Dictionary<string, InventoryClient> m_inventoryServers = new Dictionary<string, InventoryClient>();
private string m_HomeURI;
private Scene m_scene;
#endregion Fields
#region Constructor
public HGAssetMapper(Scene scene, string homeURL)
{
m_scene = scene;
m_HomeURI = homeURL;
}
#endregion Constructor
#region Internal functions
public bool PostAsset(string url, AssetBase asset)
{
if (string.IsNullOrEmpty(url))
return false;
if (!url.EndsWith("/") && !url.EndsWith("="))
url = url + "/";
if (asset == null)
{
m_log.Warn("[HG ASSET MAPPER]: Tried to post asset to remote server, but asset not in local cache.");
return false;
}
// See long comment in AssetCache.AddAsset
if (asset.Temporary || asset.Local)
return true;
// We need to copy the asset into a new asset, because
// we need to set its ID to be URL+UUID, so that the
// HGAssetService dispatches it to the remote grid.
// It's not pretty, but the best that can be done while
// not having a global naming infrastructure
AssetBase asset1 = new AssetBase(asset.FullID, asset.Name, asset.Type, asset.Metadata.CreatorID);
Copy(asset, asset1);
asset1.ID = url + asset.ID;
AdjustIdentifiers(asset1.Metadata);
if (asset1.Metadata.Type == (sbyte)AssetType.Object)
asset1.Data = AdjustIdentifiers(asset.Data);
else
asset1.Data = asset.Data;
string id = m_scene.AssetService.Store(asset1);
if (String.IsNullOrEmpty(id))
{
m_log.DebugFormat("[HG ASSET MAPPER]: Asset server {0} did not accept {1}", url, asset.ID);
return false;
}
else
{
m_log.DebugFormat("[HG ASSET MAPPER]: Posted copy of asset {0} from local asset server to {1}", asset1.ID, url);
return true;
}
}
protected byte[] AdjustIdentifiers(byte[] data)
{
string xml = Utils.BytesToString(data);
return Utils.StringToBytes(RewriteSOP(xml));
}
protected string RewriteSOP(string xml)
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
XmlNodeList sops = doc.GetElementsByTagName("SceneObjectPart");
foreach (XmlNode sop in sops)
{
UserAccount creator = null;
bool hasCreatorData = false;
XmlNodeList nodes = sop.ChildNodes;
foreach (XmlNode node in nodes)
{
if (node.Name == "CreatorID")
{
UUID uuid = UUID.Zero;
UUID.TryParse(node.InnerText, out uuid);
creator = m_scene.UserAccountService.GetUserAccount(m_scene.RegionInfo.ScopeID, uuid);
}
if (node.Name == "CreatorData" && node.InnerText != null && node.InnerText != string.Empty)
hasCreatorData = true;
//if (node.Name == "OwnerID")
//{
// UserAccount owner = GetUser(node.InnerText);
// if (owner != null)
// node.InnerText = m_ProfileServiceURL + "/" + node.InnerText + "/" + owner.FirstName + " " + owner.LastName;
//}
}
if (!hasCreatorData && creator != null)
{
XmlElement creatorData = doc.CreateElement("CreatorData");
creatorData.InnerText = m_HomeURI + ";" + creator.FirstName + " " + creator.LastName;
sop.AppendChild(creatorData);
}
}
using (StringWriter wr = new StringWriter())
{
doc.Save(wr);
return wr.ToString();
}
}
private void AdjustIdentifiers(AssetMetadata meta)
{
if (!string.IsNullOrEmpty(meta.CreatorID))
{
UUID uuid = UUID.Zero;
UUID.TryParse(meta.CreatorID, out uuid);
UserAccount creator = m_scene.UserAccountService.GetUserAccount(m_scene.RegionInfo.ScopeID, uuid);
if (creator != null)
meta.CreatorID = m_HomeURI + ";" + creator.FirstName + " " + creator.LastName;
}
}
private void Copy(AssetBase from, AssetBase to)
{
//to.Data = from.Data; // don't copy this, it's copied elsewhere
to.Description = from.Description;
to.FullID = from.FullID;
to.ID = from.ID;
to.Local = from.Local;
to.Name = from.Name;
to.Temporary = from.Temporary;
to.Type = from.Type;
}
private AssetBase FetchAsset(string url, UUID assetID)
{
// Test if it's already here
AssetBase asset = m_scene.AssetService.Get(assetID.ToString());
if (asset == null)
{
if (string.IsNullOrEmpty(url))
return null;
if (!url.EndsWith("/") && !url.EndsWith("="))
url = url + "/";
asset = m_scene.AssetService.Get(url + assetID.ToString());
//if (asset != null)
// m_log.DebugFormat("[HG ASSET MAPPER]: Fetched asset {0} of type {1} from {2} ", assetID, asset.Metadata.Type, url);
//else
// m_log.DebugFormat("[HG ASSET MAPPER]: Unable to fetch asset {0} from {1} ", assetID, url);
}
return asset;
}
private AssetMetadata FetchMetadata(string url, UUID assetID)
{
if (string.IsNullOrEmpty(url))
return null;
if (!url.EndsWith("/") && !url.EndsWith("="))
url = url + "/";
AssetMetadata meta = m_scene.AssetService.GetMetadata(url + assetID.ToString());
if (meta != null)
m_log.DebugFormat("[HG ASSET MAPPER]: Fetched metadata for asset {0} of type {1} from {2} ", assetID, meta.Type, url);
else
m_log.DebugFormat("[HG ASSET MAPPER]: Unable to fetched metadata for asset {0} from {1} ", assetID, url);
return meta;
}
// TODO: unused
// private void Dump(Dictionary<UUID, bool> lst)
// {
// m_log.Debug("XXX -------- UUID DUMP ------- XXX");
// foreach (KeyValuePair<UUID, bool> kvp in lst)
// m_log.Debug(" >> " + kvp.Key + " (texture? " + kvp.Value + ")");
// m_log.Debug("XXX -------- UUID DUMP ------- XXX");
// }
#endregion Internal functions
#region Public interface
public void Get(UUID assetID, UUID ownerID, string userAssetURL)
{
// Get the item from the remote asset server onto the local AssetService
AssetMetadata meta = FetchMetadata(userAssetURL, assetID);
if (meta == null)
return;
// The act of gathering UUIDs downloads some assets from the remote server
// but not all...
Dictionary<UUID, sbyte> ids = new Dictionary<UUID, sbyte>();
HGUuidGatherer uuidGatherer = new HGUuidGatherer(m_scene.AssetService, userAssetURL);
uuidGatherer.GatherAssetUuids(assetID, meta.Type, ids);
m_log.DebugFormat("[HG ASSET MAPPER]: Preparing to get {0} assets", ids.Count);
bool success = true;
foreach (UUID uuid in ids.Keys)
if (FetchAsset(userAssetURL, uuid) == null)
success = false;
// maybe all pieces got here...
if (!success)
m_log.DebugFormat("[HG ASSET MAPPER]: Problems getting item {0} from asset server {1}", assetID, userAssetURL);
else
m_log.DebugFormat("[HG ASSET MAPPER]: Successfully got item {0} from asset server {1}", assetID, userAssetURL);
}
public void Post(UUID assetID, UUID ownerID, string userAssetURL)
{
m_log.DebugFormat("[HG ASSET MAPPER]: Starting to send asset {0} with children to asset server {1}", assetID, userAssetURL);
// Find all the embedded assets
AssetBase asset = m_scene.AssetService.Get(assetID.ToString());
if (asset == null)
{
m_log.DebugFormat("[HG ASSET MAPPER]: Something wrong with asset {0}, it could not be found", assetID);
return;
}
Dictionary<UUID, sbyte> ids = new Dictionary<UUID, sbyte>();
HGUuidGatherer uuidGatherer = new HGUuidGatherer(m_scene.AssetService, string.Empty);
uuidGatherer.GatherAssetUuids(asset.FullID, asset.Type, ids);
// Check which assets already exist in the destination server
string url = userAssetURL;
if (!url.EndsWith("/") && !url.EndsWith("="))
url = url + "/";
string[] remoteAssetIDs = new string[ids.Count];
int i = 0;
foreach (UUID id in ids.Keys)
remoteAssetIDs[i++] = url + id.ToString();
bool[] exist = m_scene.AssetService.AssetsExist(remoteAssetIDs);
var existSet = new HashSet<string>();
i = 0;
foreach (UUID id in ids.Keys)
{
if (exist[i])
existSet.Add(id.ToString());
++i;
}
// Send only those assets which don't already exist in the destination server
bool success = true;
foreach (UUID uuid in ids.Keys)
{
if (!existSet.Contains(uuid.ToString()))
{
asset = m_scene.AssetService.Get(uuid.ToString());
if (asset == null)
m_log.DebugFormat("[HG ASSET MAPPER]: Could not find asset {0}", uuid);
else
success &= PostAsset(userAssetURL, asset);
}
else
m_log.DebugFormat("[HG ASSET MAPPER]: Didn't post asset {0} because it already exists in asset server {1}", uuid, userAssetURL);
}
if (!success)
m_log.DebugFormat("[HG ASSET MAPPER]: Problems sending asset {0} with children to asset server {1}", assetID, userAssetURL);
else
m_log.DebugFormat("[HG ASSET MAPPER]: Successfully sent asset {0} with children to asset server {1}", assetID, userAssetURL);
}
#endregion Public interface
}
}
| |
namespace BracketPipe
{
using BracketPipe.Extensions;
using System;
using System.IO;
using System.Text;
using System.Threading;
#if !NET35
using System.Threading.Tasks;
#endif
/// <summary>
/// A string/stream abstraction to handle encoding.
/// </summary>
/// <remarks>
/// Both a <see cref="string"/> and <see cref="Stream"/> are
/// implicitly convertible to <see cref="TextSource"/> and
/// can be used in place of a <see cref="TextSource"/>
/// </remarks>
public sealed class TextSource : TextReader
{
#region Fields
const Int32 DefaultBufferSize = 4096;
readonly int _bufferSize;
readonly Stream _baseStream;
readonly MemoryStream _raw;
readonly Byte[] _buffer;
readonly Char[] _chars;
StringBuilder _content;
EncodingConfidence _confidence;
Boolean _finished;
Encoding _encoding;
Decoder _decoder;
Int32 _index;
#endregion
#region ctor
TextSource(Encoding encoding)
{
_index = 0;
_encoding = encoding ?? TextEncoding.Utf8;
_decoder = _encoding.GetDecoder();
}
/// <summary>
/// Creates a new text source from a <see cref="StringBuilder"/>. No underlying stream will
/// be used.
/// </summary>
/// <param name="source">The data source.</param>
public TextSource(StringBuilder source)
: this(TextEncoding.Utf8)
{
_finished = true;
_content = source;
_confidence = EncodingConfidence.Irrelevant;
}
/// <summary>
/// Creates a new text source from a string. No underlying stream will
/// be used.
/// </summary>
/// <param name="source">The data source.</param>
public TextSource(String source)
: this(TextEncoding.Utf8)
{
_finished = true;
_content = Pool.NewStringBuilder();
_content.Append(source);
_confidence = EncodingConfidence.Irrelevant;
}
/// <summary>
/// Creates a new text source from a string. The underlying stream is
/// used as an unknown data source.
/// </summary>
/// <param name="baseStream">
/// The underlying stream as data source.
/// </param>
/// <param name="encoding">
/// The initial encoding. Otherwise UTF-8.
/// </param>
public TextSource(Stream baseStream, Encoding encoding = null)
: this(encoding)
{
if (baseStream.CanSeek)
_bufferSize = (int)(baseStream.Length / 2);
else
_bufferSize = DefaultBufferSize;
_buffer = new Byte[_bufferSize];
_chars = new Char[_bufferSize + 1];
_raw = new MemoryStream();
_baseStream = baseStream;
_content = Pool.NewStringBuilder();
_confidence = EncodingConfidence.Tentative;
}
#endregion
#region Properties
/// <summary>
/// Gets the full text buffer.
/// </summary>
public String Text
{
get { return _content.ToString(); }
}
/// <summary>
/// Gets the character at the given position in the text buffer.
/// </summary>
/// <param name="index">The index of the character.</param>
/// <returns>The character.</returns>
public Char this[Int32 index]
{
get { return _content[index]; }
}
/// <summary>
/// Gets or sets the encoding to use.
/// </summary>
public Encoding CurrentEncoding
{
get { return _encoding; }
set
{
if (_confidence != EncodingConfidence.Tentative)
{
return;
}
if (_encoding.IsUnicode())
{
_confidence = EncodingConfidence.Certain;
return;
}
if (value.IsUnicode())
{
value = TextEncoding.Utf8;
}
if (value == _encoding)
{
_confidence = EncodingConfidence.Certain;
return;
}
_encoding = value;
_decoder = value.GetDecoder();
var raw = _raw.ToArray();
var raw_chars = new Char[_encoding.GetMaxCharCount(raw.Length)];
var charLength = _decoder.GetChars(raw, 0, raw.Length, raw_chars, 0);
var content = new String(raw_chars, 0, charLength);
var index = Math.Min(_index, content.Length);
if (content.Substring(0, index).Is(_content.ToString(0, index)))
{
//If everything seems to fit up to this point, do an
//instant switch
_confidence = EncodingConfidence.Certain;
_content.Remove(index, _content.Length - index);
_content.Append(content.Substring(index));
}
else
{
//Otherwise consider restart from beginning ...
_index = 0;
_content.Clear().Append(content);
throw new NotSupportedException();
}
}
}
/// <summary>
/// Gets or sets the current index of the insertation and read point.
/// </summary>
public Int32 Index
{
get { return _index; }
set { _index = value; }
}
/// <summary>
/// Gets the length of the text buffer.
/// </summary>
public Int32 Length
{
get { return _content.Length; }
}
#endregion
#region Disposable
/// <summary>
/// Disposes the text source by freeing the underlying stream, if any.
/// </summary>
protected override void Dispose(bool disposing)
{
var isDisposed = _content == null;
if (!isDisposed)
{
if (_raw != null)
_raw.Dispose();
_content.Clear().ToPool();
_content = null;
}
}
#endregion
/// <summary>
/// Returns a <see cref="System.String" /> that represents the full text buffer.
/// </summary>
/// <returns>
/// A <see cref="System.String" /> that represents the full text buffer.
/// </returns>
public override string ToString()
{
return _content.ToString();
}
/// <summary>
/// Converts the value of a substring of this buffer to a <see cref="System.String" />.
/// </summary>
/// <param name="start">The starting position of the substring in this instance.</param>
/// <param name="length">The length of the substring.</param>
/// <returns>
/// A <see cref="System.String" /> whose value is the same as the specified substring of this buffer.
/// </returns>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="start"/> or <paramref name="length"/>
/// is less than zero.
/// -or- The sum of <paramref name="start"/> and <paramref name="length"/>
/// is greater than the length of the current buffer.</exception>
public string ToString(int start, int length)
{
return _content.ToString(start, length);
}
public char[] ToCharArray(int start, int length)
{
var dest = new char[length];
_content.CopyTo(start, dest, 0, length);
return dest;
}
#region Text Methods
/// <summary>Reads the next character without changing the state of the reader or the character source. Returns the next available character without actually reading it from the reader.</summary>
/// <returns>An integer representing the next character to be read, or -1 if no more characters are available or the reader does not support seeking.</returns>
/// <exception cref="T:System.ObjectDisposedException">The <see cref="T:System.IO.TextReader" /> is closed. </exception>
/// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception>
public override int Peek()
{
var result = Read();
_index--;
return result;
}
/// <summary>Reads the next character from the text reader and advances the character position by one character.</summary>
/// <returns>The next character from the text reader, or -1 if no more characters are available. The default implementation returns -1.</returns>
/// <exception cref="T:System.ObjectDisposedException">The <see cref="T:System.IO.TextReader" /> is closed. </exception>
/// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception>
public override int Read()
{
var result = ReadCharacter();
if (result == Symbols.EndOfFile)
return -1;
return result;
}
/// <summary>
/// Reads the next character from the buffer or underlying stream, if
/// any.
/// </summary>
/// <returns>The next character.</returns>
public Char ReadCharacter()
{
if (_index < _content.Length)
{
return _content[_index++];
}
ExpandBuffer(_bufferSize);
var index = _index++;
return index < _content.Length ? _content[index] : Symbols.EndOfFile;
}
/// <summary>Reads a specified maximum number of characters from the current reader and writes the data to a buffer, beginning at the specified index.</summary>
/// <returns>The number of characters that have been read. The number will be less than or equal to <paramref name="count" />, depending on whether the data is available within the reader. This method returns 0 (zero) if it is called when no more characters are left to read.</returns>
/// <param name="buffer">When this method returns, contains the specified character array with the values between <paramref name="index" /> and (<paramref name="index" /> + <paramref name="count" /> - 1) replaced by the characters read from the current source. </param>
/// <param name="index">The position in <paramref name="buffer" /> at which to begin writing. </param>
/// <param name="count">The maximum number of characters to read. If the end of the reader is reached before the specified number of characters is read into the buffer, the method returns. </param>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="buffer" /> is null. </exception>
/// <exception cref="T:System.ArgumentException">The buffer length minus <paramref name="index" /> is less than <paramref name="count" />. </exception>
/// <exception cref="T:System.ArgumentOutOfRangeException">
/// <paramref name="index" /> or <paramref name="count" /> is negative. </exception>
/// <exception cref="T:System.ObjectDisposedException">The <see cref="T:System.IO.TextReader" /> is closed. </exception>
/// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception>
public override int Read(char[] buffer, int index, int count)
{
var start = _index;
var end = start + count;
if (end <= _content.Length)
{
_content.CopyTo(_index, buffer, index, count);
_index += count;
return count;
}
ExpandBuffer(Math.Max(_bufferSize, count));
count = Math.Min(count, _content.Length - start);
_content.CopyTo(_index, buffer, index, count);
_index += count;
return count;
}
/// <summary>Reads a specified maximum number of characters from the current text reader and writes the data to a buffer, beginning at the specified index.</summary>
/// <returns>The number of characters that have been read. The number will be less than or equal to <paramref name="count" />, depending on whether all input characters have been read.</returns>
/// <param name="buffer">When this method returns, this parameter contains the specified character array with the values between <paramref name="index" /> and (<paramref name="index" /> + <paramref name="count" /> -1) replaced by the characters read from the current source. </param>
/// <param name="index">The position in <paramref name="buffer" /> at which to begin writing.</param>
/// <param name="count">The maximum number of characters to read. </param>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="buffer" /> is null. </exception>
/// <exception cref="T:System.ArgumentException">The buffer length minus <paramref name="index" /> is less than <paramref name="count" />. </exception>
/// <exception cref="T:System.ArgumentOutOfRangeException">
/// <paramref name="index" /> or <paramref name="count" /> is negative. </exception>
/// <exception cref="T:System.ObjectDisposedException">The <see cref="T:System.IO.TextReader" /> is closed. </exception>
/// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception>
public override int ReadBlock(char[] buffer, int index, int count)
{
return Read(buffer, index, count);
}
/// <summary>
/// Reads the upcoming numbers of characters from the buffer or
/// underlying stream, if any.
/// </summary>
/// <param name="characters">The number of characters to read.</param>
/// <returns>The string with the next characters.</returns>
public String ReadCharacters(Int32 characters)
{
var start = _index;
var end = start + characters;
if (end <= _content.Length)
{
_index += characters;
return _content.ToString(start, characters);
}
ExpandBuffer(Math.Max(_bufferSize, characters));
_index += characters;
characters = Math.Min(characters, _content.Length - start);
return _content.ToString(start, characters);
}
#if INCLUDE_ASYNC
/// <summary>
/// Reads the next character from the buffer or underlying stream
/// asynchronously, if any.
/// </summary>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The task resulting in the next character.</returns>
public async Task<Char> ReadCharacterAsync(CancellationToken cancellationToken)
{
if (_index >= _content.Length)
{
await ExpandBufferAsync(_bufferSize, cancellationToken).ConfigureAwait(false);
var index = _index++;
return index < _content.Length ? _content[index] : Char.MaxValue;
}
return _content[_index++];
}
/// <summary>
/// Reads the upcoming numbers of characters from the buffer or
/// underlying stream asynchronously.
/// </summary>
/// <param name="characters">The number of characters to read.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The string with the next characters.</returns>
public async Task<String> ReadCharactersAsync(Int32 characters, CancellationToken cancellationToken)
{
var start = _index;
var end = start + characters;
if (end <= _content.Length)
{
_index += characters;
return _content.ToString(start, characters);
}
await ExpandBufferAsync(Math.Max(_bufferSize, characters), cancellationToken).ConfigureAwait(false);
_index += characters;
characters = Math.Min(characters, _content.Length - start);
return _content.ToString(start, characters);
}
/// <summary>
/// Prefetches the number of bytes by expanding the internal buffer.
/// </summary>
/// <param name="length">The number of bytes to prefetch.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The awaitable task.</returns>
public Task PrefetchAsync(Int32 length, CancellationToken cancellationToken)
{
return ExpandBufferAsync(length, cancellationToken);
}
/// <summary>
/// Prefetches the whole stream by expanding the internal buffer.
/// </summary>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The awaitable task.</returns>
public async Task PrefetchAllAsync(CancellationToken cancellationToken)
{
if (_content.Length == 0)
{
await DetectByteOrderMarkAsync(cancellationToken).ConfigureAwait(false);
}
while (!_finished)
{
await ReadIntoBufferAsync(cancellationToken).ConfigureAwait(false);
}
}
#endif
/// <summary>
/// Inserts the given content at the current insertation mark. Moves the
/// insertation mark.
/// </summary>
/// <param name="content">The content to insert.</param>
public void InsertText(String content)
{
if (_index >= 0 && _index < _content.Length)
{
_content.Insert(_index, content);
}
else
{
_content.Append(content);
}
_index += content.Length;
}
#endregion
#region Helpers
#if INCLUDE_ASYNC
async Task DetectByteOrderMarkAsync(CancellationToken cancellationToken)
{
var count = await _baseStream.ReadAsync(_buffer, 0, _bufferSize).ConfigureAwait(false);
var offset = 0;
if (count > 2 && _buffer[0] == 0xef && _buffer[1] == 0xbb && _buffer[2] == 0xbf)
{
_encoding = TextEncoding.Utf8;
offset = 3;
}
else if (count > 3 && _buffer[0] == 0xff && _buffer[1] == 0xfe && _buffer[2] == 0x0 && _buffer[3] == 0x0)
{
_encoding = TextEncoding.Utf32Le;
offset = 4;
}
else if (count > 3 && _buffer[0] == 0x0 && _buffer[1] == 0x0 && _buffer[2] == 0xfe && _buffer[3] == 0xff)
{
_encoding = TextEncoding.Utf32Be;
offset = 4;
}
else if (count > 1 && _buffer[0] == 0xfe && _buffer[1] == 0xff)
{
_encoding = TextEncoding.Utf16Be;
offset = 2;
}
else if (count > 1 && _buffer[0] == 0xff && _buffer[1] == 0xfe)
{
_encoding = TextEncoding.Utf16Le;
offset = 2;
}
else if (count > 3 && _buffer[0] == 0x84 && _buffer[1] == 0x31 && _buffer[2] == 0x95 && _buffer[3] == 0x33)
{
_encoding = TextEncoding.Gb18030;
offset = 4;
}
if (offset > 0)
{
count -= offset;
Array.Copy(_buffer, offset, _buffer, 0, count);
_decoder = _encoding.GetDecoder();
_confidence = EncodingConfidence.Certain;
}
AppendContentFromBuffer(count);
}
async Task ExpandBufferAsync(Int64 size, CancellationToken cancellationToken)
{
if (!_finished && _content.Length == 0)
{
await DetectByteOrderMarkAsync(cancellationToken).ConfigureAwait(false);
}
while (size + _index > _content.Length && !_finished)
{
await ReadIntoBufferAsync(cancellationToken).ConfigureAwait(false);
}
}
async Task ReadIntoBufferAsync(CancellationToken cancellationToken)
{
var returned = await _baseStream.ReadAsync(_buffer, 0, _bufferSize, cancellationToken).ConfigureAwait(false);
AppendContentFromBuffer(returned);
}
#endif
void DetectByteOrderMark()
{
var count = _baseStream.Read(_buffer, 0, _bufferSize);
var offset = 0;
if (count > 2 && _buffer[0] == 0xef && _buffer[1] == 0xbb && _buffer[2] == 0xbf)
{
_encoding = TextEncoding.Utf8;
offset = 3;
}
else if (count > 3 && _buffer[0] == 0xff && _buffer[1] == 0xfe && _buffer[2] == 0x0 && _buffer[3] == 0x0)
{
_encoding = TextEncoding.Utf32Le;
offset = 4;
}
else if (count > 3 && _buffer[0] == 0x0 && _buffer[1] == 0x0 && _buffer[2] == 0xfe && _buffer[3] == 0xff)
{
_encoding = TextEncoding.Utf32Be;
offset = 4;
}
else if (count > 1 && _buffer[0] == 0xfe && _buffer[1] == 0xff)
{
_encoding = TextEncoding.Utf16Be;
offset = 2;
}
else if (count > 1 && _buffer[0] == 0xff && _buffer[1] == 0xfe)
{
_encoding = TextEncoding.Utf16Le;
offset = 2;
}
else if (count > 3 && _buffer[0] == 0x84 && _buffer[1] == 0x31 && _buffer[2] == 0x95 && _buffer[3] == 0x33)
{
_encoding = TextEncoding.Gb18030;
offset = 4;
}
if (offset > 0)
{
count -= offset;
Array.Copy(_buffer, offset, _buffer, 0, count);
_decoder = _encoding.GetDecoder();
_confidence = EncodingConfidence.Certain;
}
AppendContentFromBuffer(count);
}
void ExpandBuffer(Int64 size)
{
if (!_finished && _content.Length == 0)
{
DetectByteOrderMark();
}
while (size + _index > _content.Length && !_finished)
{
ReadIntoBuffer();
}
}
void ReadIntoBuffer()
{
var returned = _baseStream.Read(_buffer, 0, _bufferSize);
AppendContentFromBuffer(returned);
}
void AppendContentFromBuffer(Int32 size)
{
_finished = size == 0;
var charLength = _decoder.GetChars(_buffer, 0, size, _chars, 0);
if (_confidence != EncodingConfidence.Certain)
{
_raw.Write(_buffer, 0, size);
}
_content.Append(_chars, 0, charLength);
}
#endregion
#region Confidence
enum EncodingConfidence : byte
{
Tentative,
Certain,
Irrelevant
}
#endregion
public static implicit operator TextSource(string value)
{
return new TextSource(value);
}
public static implicit operator TextSource(Stream value)
{
return new TextSource(value);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using Microsoft.AspNetCore.Connections.Features;
using Microsoft.AspNetCore.Http.Features;
#nullable enable
namespace Microsoft.AspNetCore.Connections
{
internal partial class TransportConnection : IFeatureCollection,
IConnectionIdFeature,
IConnectionTransportFeature,
IConnectionItemsFeature,
IMemoryPoolFeature,
IConnectionLifetimeFeature
{
// Implemented features
internal protected IConnectionIdFeature? _currentIConnectionIdFeature;
internal protected IConnectionTransportFeature? _currentIConnectionTransportFeature;
internal protected IConnectionItemsFeature? _currentIConnectionItemsFeature;
internal protected IMemoryPoolFeature? _currentIMemoryPoolFeature;
internal protected IConnectionLifetimeFeature? _currentIConnectionLifetimeFeature;
// Other reserved feature slots
internal protected IPersistentStateFeature? _currentIPersistentStateFeature;
internal protected IConnectionSocketFeature? _currentIConnectionSocketFeature;
internal protected IProtocolErrorCodeFeature? _currentIProtocolErrorCodeFeature;
internal protected IStreamDirectionFeature? _currentIStreamDirectionFeature;
internal protected IStreamIdFeature? _currentIStreamIdFeature;
internal protected IStreamAbortFeature? _currentIStreamAbortFeature;
private int _featureRevision;
private List<KeyValuePair<Type, object>>? MaybeExtra;
private void FastReset()
{
_currentIConnectionIdFeature = this;
_currentIConnectionTransportFeature = this;
_currentIConnectionItemsFeature = this;
_currentIMemoryPoolFeature = this;
_currentIConnectionLifetimeFeature = this;
_currentIPersistentStateFeature = null;
_currentIConnectionSocketFeature = null;
_currentIProtocolErrorCodeFeature = null;
_currentIStreamDirectionFeature = null;
_currentIStreamIdFeature = null;
_currentIStreamAbortFeature = null;
}
// Internal for testing
internal void ResetFeatureCollection()
{
FastReset();
MaybeExtra?.Clear();
_featureRevision++;
}
private object? ExtraFeatureGet(Type key)
{
if (MaybeExtra == null)
{
return null;
}
for (var i = 0; i < MaybeExtra.Count; i++)
{
var kv = MaybeExtra[i];
if (kv.Key == key)
{
return kv.Value;
}
}
return null;
}
private void ExtraFeatureSet(Type key, object? value)
{
if (value == null)
{
if (MaybeExtra == null)
{
return;
}
for (var i = 0; i < MaybeExtra.Count; i++)
{
if (MaybeExtra[i].Key == key)
{
MaybeExtra.RemoveAt(i);
return;
}
}
}
else
{
if (MaybeExtra == null)
{
MaybeExtra = new List<KeyValuePair<Type, object>>(2);
}
for (var i = 0; i < MaybeExtra.Count; i++)
{
if (MaybeExtra[i].Key == key)
{
MaybeExtra[i] = new KeyValuePair<Type, object>(key, value);
return;
}
}
MaybeExtra.Add(new KeyValuePair<Type, object>(key, value));
}
}
bool IFeatureCollection.IsReadOnly => false;
int IFeatureCollection.Revision => _featureRevision;
object? IFeatureCollection.this[Type key]
{
get
{
object? feature = null;
if (key == typeof(IConnectionIdFeature))
{
feature = _currentIConnectionIdFeature;
}
else if (key == typeof(IConnectionTransportFeature))
{
feature = _currentIConnectionTransportFeature;
}
else if (key == typeof(IConnectionItemsFeature))
{
feature = _currentIConnectionItemsFeature;
}
else if (key == typeof(IPersistentStateFeature))
{
feature = _currentIPersistentStateFeature;
}
else if (key == typeof(IMemoryPoolFeature))
{
feature = _currentIMemoryPoolFeature;
}
else if (key == typeof(IConnectionLifetimeFeature))
{
feature = _currentIConnectionLifetimeFeature;
}
else if (key == typeof(IConnectionSocketFeature))
{
feature = _currentIConnectionSocketFeature;
}
else if (key == typeof(IProtocolErrorCodeFeature))
{
feature = _currentIProtocolErrorCodeFeature;
}
else if (key == typeof(IStreamDirectionFeature))
{
feature = _currentIStreamDirectionFeature;
}
else if (key == typeof(IStreamIdFeature))
{
feature = _currentIStreamIdFeature;
}
else if (key == typeof(IStreamAbortFeature))
{
feature = _currentIStreamAbortFeature;
}
else if (MaybeExtra != null)
{
feature = ExtraFeatureGet(key);
}
return feature ?? MultiplexedConnectionFeatures?[key];
}
set
{
_featureRevision++;
if (key == typeof(IConnectionIdFeature))
{
_currentIConnectionIdFeature = (IConnectionIdFeature?)value;
}
else if (key == typeof(IConnectionTransportFeature))
{
_currentIConnectionTransportFeature = (IConnectionTransportFeature?)value;
}
else if (key == typeof(IConnectionItemsFeature))
{
_currentIConnectionItemsFeature = (IConnectionItemsFeature?)value;
}
else if (key == typeof(IPersistentStateFeature))
{
_currentIPersistentStateFeature = (IPersistentStateFeature?)value;
}
else if (key == typeof(IMemoryPoolFeature))
{
_currentIMemoryPoolFeature = (IMemoryPoolFeature?)value;
}
else if (key == typeof(IConnectionLifetimeFeature))
{
_currentIConnectionLifetimeFeature = (IConnectionLifetimeFeature?)value;
}
else if (key == typeof(IConnectionSocketFeature))
{
_currentIConnectionSocketFeature = (IConnectionSocketFeature?)value;
}
else if (key == typeof(IProtocolErrorCodeFeature))
{
_currentIProtocolErrorCodeFeature = (IProtocolErrorCodeFeature?)value;
}
else if (key == typeof(IStreamDirectionFeature))
{
_currentIStreamDirectionFeature = (IStreamDirectionFeature?)value;
}
else if (key == typeof(IStreamIdFeature))
{
_currentIStreamIdFeature = (IStreamIdFeature?)value;
}
else if (key == typeof(IStreamAbortFeature))
{
_currentIStreamAbortFeature = (IStreamAbortFeature?)value;
}
else
{
ExtraFeatureSet(key, value);
}
}
}
TFeature? IFeatureCollection.Get<TFeature>() where TFeature : default
{
// Using Unsafe.As for the cast due to https://github.com/dotnet/runtime/issues/49614
// The type of TFeature is confirmed by the typeof() check and the As cast only accepts
// that type; however the Jit does not eliminate a regular cast in a shared generic.
TFeature? feature = default;
if (typeof(TFeature) == typeof(IConnectionIdFeature))
{
feature = Unsafe.As<IConnectionIdFeature?, TFeature?>(ref _currentIConnectionIdFeature);
}
else if (typeof(TFeature) == typeof(IConnectionTransportFeature))
{
feature = Unsafe.As<IConnectionTransportFeature?, TFeature?>(ref _currentIConnectionTransportFeature);
}
else if (typeof(TFeature) == typeof(IConnectionItemsFeature))
{
feature = Unsafe.As<IConnectionItemsFeature?, TFeature?>(ref _currentIConnectionItemsFeature);
}
else if (typeof(TFeature) == typeof(IPersistentStateFeature))
{
feature = Unsafe.As<IPersistentStateFeature?, TFeature?>(ref _currentIPersistentStateFeature);
}
else if (typeof(TFeature) == typeof(IMemoryPoolFeature))
{
feature = Unsafe.As<IMemoryPoolFeature?, TFeature?>(ref _currentIMemoryPoolFeature);
}
else if (typeof(TFeature) == typeof(IConnectionLifetimeFeature))
{
feature = Unsafe.As<IConnectionLifetimeFeature?, TFeature?>(ref _currentIConnectionLifetimeFeature);
}
else if (typeof(TFeature) == typeof(IConnectionSocketFeature))
{
feature = Unsafe.As<IConnectionSocketFeature?, TFeature?>(ref _currentIConnectionSocketFeature);
}
else if (typeof(TFeature) == typeof(IProtocolErrorCodeFeature))
{
feature = Unsafe.As<IProtocolErrorCodeFeature?, TFeature?>(ref _currentIProtocolErrorCodeFeature);
}
else if (typeof(TFeature) == typeof(IStreamDirectionFeature))
{
feature = Unsafe.As<IStreamDirectionFeature?, TFeature?>(ref _currentIStreamDirectionFeature);
}
else if (typeof(TFeature) == typeof(IStreamIdFeature))
{
feature = Unsafe.As<IStreamIdFeature?, TFeature?>(ref _currentIStreamIdFeature);
}
else if (typeof(TFeature) == typeof(IStreamAbortFeature))
{
feature = Unsafe.As<IStreamAbortFeature?, TFeature?>(ref _currentIStreamAbortFeature);
}
else if (MaybeExtra != null)
{
feature = (TFeature?)(ExtraFeatureGet(typeof(TFeature)));
}
if (feature == null && MultiplexedConnectionFeatures != null)
{
feature = MultiplexedConnectionFeatures.Get<TFeature>();
}
return feature;
}
void IFeatureCollection.Set<TFeature>(TFeature? feature) where TFeature : default
{
// Using Unsafe.As for the cast due to https://github.com/dotnet/runtime/issues/49614
// The type of TFeature is confirmed by the typeof() check and the As cast only accepts
// that type; however the Jit does not eliminate a regular cast in a shared generic.
_featureRevision++;
if (typeof(TFeature) == typeof(IConnectionIdFeature))
{
_currentIConnectionIdFeature = Unsafe.As<TFeature?, IConnectionIdFeature?>(ref feature);
}
else if (typeof(TFeature) == typeof(IConnectionTransportFeature))
{
_currentIConnectionTransportFeature = Unsafe.As<TFeature?, IConnectionTransportFeature?>(ref feature);
}
else if (typeof(TFeature) == typeof(IConnectionItemsFeature))
{
_currentIConnectionItemsFeature = Unsafe.As<TFeature?, IConnectionItemsFeature?>(ref feature);
}
else if (typeof(TFeature) == typeof(IPersistentStateFeature))
{
_currentIPersistentStateFeature = Unsafe.As<TFeature?, IPersistentStateFeature?>(ref feature);
}
else if (typeof(TFeature) == typeof(IMemoryPoolFeature))
{
_currentIMemoryPoolFeature = Unsafe.As<TFeature?, IMemoryPoolFeature?>(ref feature);
}
else if (typeof(TFeature) == typeof(IConnectionLifetimeFeature))
{
_currentIConnectionLifetimeFeature = Unsafe.As<TFeature?, IConnectionLifetimeFeature?>(ref feature);
}
else if (typeof(TFeature) == typeof(IConnectionSocketFeature))
{
_currentIConnectionSocketFeature = Unsafe.As<TFeature?, IConnectionSocketFeature?>(ref feature);
}
else if (typeof(TFeature) == typeof(IProtocolErrorCodeFeature))
{
_currentIProtocolErrorCodeFeature = Unsafe.As<TFeature?, IProtocolErrorCodeFeature?>(ref feature);
}
else if (typeof(TFeature) == typeof(IStreamDirectionFeature))
{
_currentIStreamDirectionFeature = Unsafe.As<TFeature?, IStreamDirectionFeature?>(ref feature);
}
else if (typeof(TFeature) == typeof(IStreamIdFeature))
{
_currentIStreamIdFeature = Unsafe.As<TFeature?, IStreamIdFeature?>(ref feature);
}
else if (typeof(TFeature) == typeof(IStreamAbortFeature))
{
_currentIStreamAbortFeature = Unsafe.As<TFeature?, IStreamAbortFeature?>(ref feature);
}
else
{
ExtraFeatureSet(typeof(TFeature), feature);
}
}
private IEnumerable<KeyValuePair<Type, object>> FastEnumerable()
{
if (_currentIConnectionIdFeature != null)
{
yield return new KeyValuePair<Type, object>(typeof(IConnectionIdFeature), _currentIConnectionIdFeature);
}
if (_currentIConnectionTransportFeature != null)
{
yield return new KeyValuePair<Type, object>(typeof(IConnectionTransportFeature), _currentIConnectionTransportFeature);
}
if (_currentIConnectionItemsFeature != null)
{
yield return new KeyValuePair<Type, object>(typeof(IConnectionItemsFeature), _currentIConnectionItemsFeature);
}
if (_currentIPersistentStateFeature != null)
{
yield return new KeyValuePair<Type, object>(typeof(IPersistentStateFeature), _currentIPersistentStateFeature);
}
if (_currentIMemoryPoolFeature != null)
{
yield return new KeyValuePair<Type, object>(typeof(IMemoryPoolFeature), _currentIMemoryPoolFeature);
}
if (_currentIConnectionLifetimeFeature != null)
{
yield return new KeyValuePair<Type, object>(typeof(IConnectionLifetimeFeature), _currentIConnectionLifetimeFeature);
}
if (_currentIConnectionSocketFeature != null)
{
yield return new KeyValuePair<Type, object>(typeof(IConnectionSocketFeature), _currentIConnectionSocketFeature);
}
if (_currentIProtocolErrorCodeFeature != null)
{
yield return new KeyValuePair<Type, object>(typeof(IProtocolErrorCodeFeature), _currentIProtocolErrorCodeFeature);
}
if (_currentIStreamDirectionFeature != null)
{
yield return new KeyValuePair<Type, object>(typeof(IStreamDirectionFeature), _currentIStreamDirectionFeature);
}
if (_currentIStreamIdFeature != null)
{
yield return new KeyValuePair<Type, object>(typeof(IStreamIdFeature), _currentIStreamIdFeature);
}
if (_currentIStreamAbortFeature != null)
{
yield return new KeyValuePair<Type, object>(typeof(IStreamAbortFeature), _currentIStreamAbortFeature);
}
if (MaybeExtra != null)
{
foreach (var item in MaybeExtra)
{
yield return item;
}
}
}
IEnumerator<KeyValuePair<Type, object>> IEnumerable<KeyValuePair<Type, object>>.GetEnumerator() => FastEnumerable().GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => FastEnumerable().GetEnumerator();
}
}
| |
//
// 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 System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Microsoft.Azure.Management.ApiManagement;
using Microsoft.Azure.Management.ApiManagement.SmapiModels;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.ApiManagement
{
/// <summary>
/// Operations for listing API associated Products.
/// </summary>
internal partial class ApiProductsOperations : IServiceOperations<ApiManagementClient>, IApiProductsOperations
{
/// <summary>
/// Initializes a new instance of the ApiProductsOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal ApiProductsOperations(ApiManagementClient client)
{
this._client = client;
}
private ApiManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.ApiManagement.ApiManagementClient.
/// </summary>
public ApiManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// List all API associated products.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='aid'>
/// Required. Identifier of the API.
/// </param>
/// <param name='query'>
/// Optional.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// List Products operation response details.
/// </returns>
public async Task<ProductListResponse> ListAsync(string resourceGroupName, string serviceName, string aid, QueryParameters query, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serviceName == null)
{
throw new ArgumentNullException("serviceName");
}
if (aid == null)
{
throw new ArgumentNullException("aid");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("aid", aid);
tracingParameters.Add("query", query);
TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.ApiManagement";
url = url + "/service/";
url = url + Uri.EscapeDataString(serviceName);
url = url + "/apis/";
url = url + Uri.EscapeDataString(aid);
url = url + "/products";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-02-14");
List<string> odataFilter = new List<string>();
if (query != null && query.Filter != null)
{
odataFilter.Add(Uri.EscapeDataString(query.Filter));
}
if (odataFilter.Count > 0)
{
queryParameters.Add("$filter=" + string.Join(null, odataFilter));
}
if (query != null && query.Top != null)
{
queryParameters.Add("$top=" + Uri.EscapeDataString(query.Top.Value.ToString()));
}
if (query != null && query.Skip != null)
{
queryParameters.Add("$skip=" + Uri.EscapeDataString(query.Skip.Value.ToString()));
}
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
ProductListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ProductListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
ProductPaged resultInstance = new ProductPaged();
result.Result = resultInstance;
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
ProductContract productContractInstance = new ProductContract();
resultInstance.Values.Add(productContractInstance);
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
productContractInstance.IdPath = idInstance;
}
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
productContractInstance.Name = nameInstance;
}
JToken descriptionValue = valueValue["description"];
if (descriptionValue != null && descriptionValue.Type != JTokenType.Null)
{
string descriptionInstance = ((string)descriptionValue);
productContractInstance.Description = descriptionInstance;
}
JToken termsValue = valueValue["terms"];
if (termsValue != null && termsValue.Type != JTokenType.Null)
{
string termsInstance = ((string)termsValue);
productContractInstance.Terms = termsInstance;
}
JToken subscriptionRequiredValue = valueValue["subscriptionRequired"];
if (subscriptionRequiredValue != null && subscriptionRequiredValue.Type != JTokenType.Null)
{
bool subscriptionRequiredInstance = ((bool)subscriptionRequiredValue);
productContractInstance.SubscriptionRequired = subscriptionRequiredInstance;
}
JToken approvalRequiredValue = valueValue["approvalRequired"];
if (approvalRequiredValue != null && approvalRequiredValue.Type != JTokenType.Null)
{
bool approvalRequiredInstance = ((bool)approvalRequiredValue);
productContractInstance.ApprovalRequired = approvalRequiredInstance;
}
JToken subscriptionsLimitValue = valueValue["subscriptionsLimit"];
if (subscriptionsLimitValue != null && subscriptionsLimitValue.Type != JTokenType.Null)
{
int subscriptionsLimitInstance = ((int)subscriptionsLimitValue);
productContractInstance.SubscriptionsLimit = subscriptionsLimitInstance;
}
JToken subscriptionPeriodValue = valueValue["subscriptionPeriod"];
if (subscriptionPeriodValue != null && subscriptionPeriodValue.Type != JTokenType.Null)
{
PeriodContract subscriptionPeriodInstance = new PeriodContract();
productContractInstance.SubscriptionPeriod = subscriptionPeriodInstance;
JToken valueValue2 = subscriptionPeriodValue["value"];
if (valueValue2 != null && valueValue2.Type != JTokenType.Null)
{
int valueInstance = ((int)valueValue2);
subscriptionPeriodInstance.Value = valueInstance;
}
JToken intervalValue = subscriptionPeriodValue["interval"];
if (intervalValue != null && intervalValue.Type != JTokenType.Null)
{
PeriodIntervalContract intervalInstance = ((PeriodIntervalContract)Enum.Parse(typeof(PeriodIntervalContract), ((string)intervalValue), true));
subscriptionPeriodInstance.Interval = intervalInstance;
}
}
JToken notificationPeriodValue = valueValue["notificationPeriod"];
if (notificationPeriodValue != null && notificationPeriodValue.Type != JTokenType.Null)
{
PeriodContract notificationPeriodInstance = new PeriodContract();
productContractInstance.NotificationPeriod = notificationPeriodInstance;
JToken valueValue3 = notificationPeriodValue["value"];
if (valueValue3 != null && valueValue3.Type != JTokenType.Null)
{
int valueInstance2 = ((int)valueValue3);
notificationPeriodInstance.Value = valueInstance2;
}
JToken intervalValue2 = notificationPeriodValue["interval"];
if (intervalValue2 != null && intervalValue2.Type != JTokenType.Null)
{
PeriodIntervalContract intervalInstance2 = ((PeriodIntervalContract)Enum.Parse(typeof(PeriodIntervalContract), ((string)intervalValue2), true));
notificationPeriodInstance.Interval = intervalInstance2;
}
}
JToken stateValue = valueValue["state"];
if (stateValue != null && stateValue.Type != JTokenType.Null)
{
ProductStateContract stateInstance = ((ProductStateContract)Enum.Parse(typeof(ProductStateContract), ((string)stateValue), true));
productContractInstance.State = stateInstance;
}
}
}
JToken countValue = responseDoc["count"];
if (countValue != null && countValue.Type != JTokenType.Null)
{
long countInstance = ((long)countValue);
resultInstance.TotalCount = countInstance;
}
JToken nextLinkValue = responseDoc["nextLink"];
if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
{
string nextLinkInstance = ((string)nextLinkValue);
resultInstance.NextLink = nextLinkInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// List all API associated products.
/// </summary>
/// <param name='nextLink'>
/// Required. NextLink from the previous successful call to List
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// List Products operation response details.
/// </returns>
public async Task<ProductListResponse> ListNextAsync(string nextLink, CancellationToken cancellationToken)
{
// Validate
if (nextLink == null)
{
throw new ArgumentNullException("nextLink");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextLink", nextLink);
TracingAdapter.Enter(invocationId, this, "ListNextAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + nextLink;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
ProductListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ProductListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
ProductPaged resultInstance = new ProductPaged();
result.Result = resultInstance;
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
ProductContract productContractInstance = new ProductContract();
resultInstance.Values.Add(productContractInstance);
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
productContractInstance.IdPath = idInstance;
}
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
productContractInstance.Name = nameInstance;
}
JToken descriptionValue = valueValue["description"];
if (descriptionValue != null && descriptionValue.Type != JTokenType.Null)
{
string descriptionInstance = ((string)descriptionValue);
productContractInstance.Description = descriptionInstance;
}
JToken termsValue = valueValue["terms"];
if (termsValue != null && termsValue.Type != JTokenType.Null)
{
string termsInstance = ((string)termsValue);
productContractInstance.Terms = termsInstance;
}
JToken subscriptionRequiredValue = valueValue["subscriptionRequired"];
if (subscriptionRequiredValue != null && subscriptionRequiredValue.Type != JTokenType.Null)
{
bool subscriptionRequiredInstance = ((bool)subscriptionRequiredValue);
productContractInstance.SubscriptionRequired = subscriptionRequiredInstance;
}
JToken approvalRequiredValue = valueValue["approvalRequired"];
if (approvalRequiredValue != null && approvalRequiredValue.Type != JTokenType.Null)
{
bool approvalRequiredInstance = ((bool)approvalRequiredValue);
productContractInstance.ApprovalRequired = approvalRequiredInstance;
}
JToken subscriptionsLimitValue = valueValue["subscriptionsLimit"];
if (subscriptionsLimitValue != null && subscriptionsLimitValue.Type != JTokenType.Null)
{
int subscriptionsLimitInstance = ((int)subscriptionsLimitValue);
productContractInstance.SubscriptionsLimit = subscriptionsLimitInstance;
}
JToken subscriptionPeriodValue = valueValue["subscriptionPeriod"];
if (subscriptionPeriodValue != null && subscriptionPeriodValue.Type != JTokenType.Null)
{
PeriodContract subscriptionPeriodInstance = new PeriodContract();
productContractInstance.SubscriptionPeriod = subscriptionPeriodInstance;
JToken valueValue2 = subscriptionPeriodValue["value"];
if (valueValue2 != null && valueValue2.Type != JTokenType.Null)
{
int valueInstance = ((int)valueValue2);
subscriptionPeriodInstance.Value = valueInstance;
}
JToken intervalValue = subscriptionPeriodValue["interval"];
if (intervalValue != null && intervalValue.Type != JTokenType.Null)
{
PeriodIntervalContract intervalInstance = ((PeriodIntervalContract)Enum.Parse(typeof(PeriodIntervalContract), ((string)intervalValue), true));
subscriptionPeriodInstance.Interval = intervalInstance;
}
}
JToken notificationPeriodValue = valueValue["notificationPeriod"];
if (notificationPeriodValue != null && notificationPeriodValue.Type != JTokenType.Null)
{
PeriodContract notificationPeriodInstance = new PeriodContract();
productContractInstance.NotificationPeriod = notificationPeriodInstance;
JToken valueValue3 = notificationPeriodValue["value"];
if (valueValue3 != null && valueValue3.Type != JTokenType.Null)
{
int valueInstance2 = ((int)valueValue3);
notificationPeriodInstance.Value = valueInstance2;
}
JToken intervalValue2 = notificationPeriodValue["interval"];
if (intervalValue2 != null && intervalValue2.Type != JTokenType.Null)
{
PeriodIntervalContract intervalInstance2 = ((PeriodIntervalContract)Enum.Parse(typeof(PeriodIntervalContract), ((string)intervalValue2), true));
notificationPeriodInstance.Interval = intervalInstance2;
}
}
JToken stateValue = valueValue["state"];
if (stateValue != null && stateValue.Type != JTokenType.Null)
{
ProductStateContract stateInstance = ((ProductStateContract)Enum.Parse(typeof(ProductStateContract), ((string)stateValue), true));
productContractInstance.State = stateInstance;
}
}
}
JToken countValue = responseDoc["count"];
if (countValue != null && countValue.Type != JTokenType.Null)
{
long countInstance = ((long)countValue);
resultInstance.TotalCount = countInstance;
}
JToken nextLinkValue = responseDoc["nextLink"];
if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
{
string nextLinkInstance = ((string)nextLinkValue);
resultInstance.NextLink = nextLinkInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#region Using directives
using System;
using System.Collections.Generic;
using System.Management.Automation;
using System.Collections;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Microsoft.Management.Infrastructure.CimCmdlets
{
/// <summary>
/// Returns zero, one or more CIM (dynamic) instances with the properties
/// specified in the Property parameter, KeysOnly parameter or the Select clause
/// of the Query parameter.
/// </summary>
[Cmdlet(VerbsCommon.Get, "CimInstance", DefaultParameterSetName = CimBaseCommand.ClassNameComputerSet, HelpUri = "https://go.microsoft.com/fwlink/?LinkId=227961")]
[OutputType(typeof(CimInstance))]
public class GetCimInstanceCommand : CimBaseCommand
{
#region constructor
/// <summary>
/// Constructor.
/// </summary>
public GetCimInstanceCommand()
: base(parameters, parameterSets)
{
DebugHelper.WriteLogEx();
}
#endregion
#region parameters
/// <summary>
/// <para>
/// The following is the definition of the input parameter "CimSession".
/// Identifies the CimSession which is to be used to retrieve the instances.
/// </para>
/// </summary>
[Parameter(
Mandatory = true,
ValueFromPipeline = true,
ParameterSetName = CimBaseCommand.CimInstanceSessionSet)]
[Parameter(
Mandatory = true,
ValueFromPipeline = true,
ParameterSetName = CimBaseCommand.QuerySessionSet)]
[Parameter(
Mandatory = true,
ValueFromPipeline = true,
ParameterSetName = CimBaseCommand.ClassNameSessionSet)]
[Parameter(
Mandatory = true,
ValueFromPipeline = true,
ParameterSetName = CimBaseCommand.ResourceUriSessionSet)]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public CimSession[] CimSession
{
get { return cimSession; }
set
{
cimSession = value;
base.SetParameter(value, nameCimSession);
}
}
private CimSession[] cimSession;
/// <summary>
/// <para>
/// The following is the definition of the input parameter "ClassName".
/// Define the class name for which the instances are retrieved.
/// </para>
/// </summary>
[Parameter(Mandatory = true,
Position = 0,
ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.ClassNameSessionSet)]
[Parameter(Mandatory = true,
Position = 0,
ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.ClassNameComputerSet)]
public string ClassName
{
get { return className; }
set
{
this.className = value;
base.SetParameter(value, nameClassName);
}
}
private string className;
/// <summary>
/// <para>
/// The following is the definition of the input parameter "ResourceUri".
/// Define the Resource Uri for which the instances are retrieved.
/// </para>
/// </summary>
[Parameter(Mandatory = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.ResourceUriSessionSet)]
[Parameter(Mandatory = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.ResourceUriComputerSet)]
[Parameter(
ParameterSetName = CimBaseCommand.CimInstanceComputerSet)]
[Parameter(
ParameterSetName = CimBaseCommand.CimInstanceSessionSet)]
[Parameter(
ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.QueryComputerSet)]
[Parameter(
ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.QuerySessionSet)]
public Uri ResourceUri
{
get { return resourceUri; }
set
{
this.resourceUri = value;
base.SetParameter(value, nameResourceUri);
}
}
private Uri resourceUri;
/// <summary>
/// <para>The following is the definition of the input parameter "ComputerName".
/// Provides the name of the computer from which to retrieve the instances. The
/// ComputerName is used to create a temporary CimSession with default parameter
/// values, which is then used to retrieve the instances.
/// </para>
/// <para>
/// If no ComputerName is specified the default value is "localhost"
/// </para>
/// </summary>
[Alias(AliasCN, AliasServerName)]
[Parameter(
ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.ClassNameComputerSet)]
[Parameter(
ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.ResourceUriComputerSet)]
[Parameter(
ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.QueryComputerSet)]
[Parameter(
ParameterSetName = CimBaseCommand.CimInstanceComputerSet)]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string[] ComputerName
{
get { return computerName; }
set
{
computerName = value;
base.SetParameter(value, nameComputerName);
}
}
private string[] computerName;
/// <summary>
/// <para>
/// The following is the definition of the input parameter "KeyOnly".
/// Indicates that only key properties of the retrieved instances should be
/// returned to the client.
/// </para>
/// </summary>
[Parameter(ParameterSetName = CimBaseCommand.ClassNameComputerSet)]
[Parameter(ParameterSetName = CimBaseCommand.ClassNameSessionSet)]
[Parameter(ParameterSetName = CimBaseCommand.ResourceUriComputerSet)]
[Parameter(ParameterSetName = CimBaseCommand.ResourceUriSessionSet)]
public SwitchParameter KeyOnly
{
get { return keyOnly; }
set
{
keyOnly = value;
base.SetParameter(value, nameKeyOnly);
}
}
private SwitchParameter keyOnly;
/// <summary>
/// <para>
/// The following is the definition of the input parameter "Namespace".
/// Identifies the Namespace in which the class, indicated by ClassName, is
/// registered.
/// </para>
/// <para>
/// Default namespace is 'root\cimv2' if this property is not specified.
/// </para>
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.ClassNameComputerSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.ClassNameSessionSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.ResourceUriComputerSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.ResourceUriSessionSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.QueryComputerSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.QuerySessionSet)]
public string Namespace
{
get { return nameSpace; }
set
{
nameSpace = value;
base.SetParameter(value, nameNamespace);
}
}
private string nameSpace;
/// <summary>
/// <para>
/// The following is the definition of the input parameter "OperationTimeoutSec".
/// Specifies the operation timeout after which the client operation should be
/// canceled. The default is the CimSession operation timeout. If this parameter
/// is specified, then this value takes precedence over the CimSession
/// OperationTimeout.
/// </para>
/// </summary>
[Alias(AliasOT)]
[Parameter]
public UInt32 OperationTimeoutSec
{
get { return operationTimeout; }
set { operationTimeout = value; }
}
private UInt32 operationTimeout;
/// <summary>
/// <para>The following is the definition of the input parameter "InputObject".
/// Provides the <see cref="CimInstance"/> that containing the [Key] properties,
/// based on the key properties to retrieve the <see cref="CimInstance"/>.
/// </para>
/// <para>
/// User can call New-CimInstance to create the CimInstance with key only
/// properties, for example:
/// New-CimInstance -ClassName C -Namespace root\cimv2
/// -Property @{CreationClassName="CIM_VirtualComputerSystem";Name="VM3358"}
/// -Keys {"CreationClassName", "Name"} -Local
/// </para>
/// </summary>
[Parameter(
Mandatory = true,
Position = 0,
ValueFromPipeline = true,
ParameterSetName = CimBaseCommand.CimInstanceComputerSet)]
[Parameter(
Mandatory = true,
Position = 0,
ValueFromPipeline = true,
ParameterSetName = CimBaseCommand.CimInstanceSessionSet)]
[Alias(CimBaseCommand.AliasCimInstance)]
public CimInstance InputObject
{
get { return cimInstance; }
set
{
cimInstance = value;
base.SetParameter(value, nameCimInstance);
}
}
/// <summary>
/// Property for internal usage purpose.
/// </summary>
internal CimInstance CimInstance
{
get { return cimInstance; }
}
private CimInstance cimInstance;
/// <summary>
/// The following is the definition of the input parameter "Query".
/// Specifies the query string for what instances, and what properties of those
/// instances, should be retrieve.
/// </summary>
[Parameter(Mandatory = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.QueryComputerSet)]
[Parameter(Mandatory = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.QuerySessionSet)]
public string Query
{
get { return query; }
set
{
query = value;
base.SetParameter(value, nameQuery);
}
}
private string query;
/// <summary>
/// <para>
/// The following is the definition of the input parameter "QueryDialect".
/// Specifies the dialect used by the query Engine that interprets the Query
/// string.
/// </para>
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.QueryComputerSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.QuerySessionSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.ClassNameSessionSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.ClassNameComputerSet)]
public string QueryDialect
{
get { return queryDialect; }
set
{
queryDialect = value;
base.SetParameter(value, nameQueryDialect);
}
}
private string queryDialect;
/// <summary>
/// <para>
/// The following is the definition of the input parameter "Shallow".
/// If the switch is set to True, only instance of the class identified by
/// Namespace + ClassName will be returned. If the switch is not set, instances
/// of the above class and of all of its descendents will be returned (the
/// enumeration will cascade the class inheritance hierarchy).
/// </para>
/// </summary>
[Parameter(ParameterSetName = CimBaseCommand.ClassNameComputerSet)]
[Parameter(ParameterSetName = CimBaseCommand.ClassNameSessionSet)]
[Parameter(ParameterSetName = CimBaseCommand.ResourceUriSessionSet)]
[Parameter(ParameterSetName = CimBaseCommand.ResourceUriComputerSet)]
[Parameter(ParameterSetName = CimBaseCommand.QueryComputerSet)]
[Parameter(ParameterSetName = CimBaseCommand.QuerySessionSet)]
public SwitchParameter Shallow
{
get { return shallow; }
set
{
shallow = value;
base.SetParameter(value, nameShallow);
}
}
private SwitchParameter shallow;
/// <summary>
/// <para>
/// The following is the definition of the input parameter "Filter".
/// Specifies the where clause of the query.
/// </para>
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.ClassNameSessionSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.ClassNameComputerSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.ResourceUriSessionSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.ResourceUriComputerSet)]
public string Filter
{
get { return filter; }
set
{
filter = value;
base.SetParameter(value, nameFilter);
}
}
private string filter;
/// <summary>
/// <para>
/// The following is the definition of the input parameter "Property".
/// Specifies the selected properties of result instances.
/// </para>
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.ClassNameSessionSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.ClassNameComputerSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.ResourceUriSessionSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.ResourceUriComputerSet)]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
[Alias("SelectProperties")]
public string[] Property
{
get { return property; }
set
{
property = value;
base.SetParameter(value, nameSelectProperties);
}
}
/// <summary>
/// Property for internal usage.
/// </summary>
internal string[] SelectProperties
{
get { return property; }
}
private string[] property;
#endregion
#region cmdlet methods
/// <summary>
/// BeginProcessing method.
/// </summary>
protected override void BeginProcessing()
{
this.CmdletOperation = new CmdletOperationBase(this);
this.AtBeginProcess = false;
}
/// <summary>
/// ProcessRecord method.
/// </summary>
protected override void ProcessRecord()
{
base.CheckParameterSet();
this.CheckArgument();
CimGetInstance cimGetInstance = this.GetOperationAgent();
if (cimGetInstance == null)
{
cimGetInstance = CreateOperationAgent();
}
cimGetInstance.GetCimInstance(this);
cimGetInstance.ProcessActions(this.CmdletOperation);
}
/// <summary>
/// EndProcessing method.
/// </summary>
protected override void EndProcessing()
{
CimGetInstance cimGetInstance = this.GetOperationAgent();
if (cimGetInstance != null)
{
cimGetInstance.ProcessRemainActions(this.CmdletOperation);
}
}
#endregion
#region helper methods
/// <summary>
/// <para>
/// Get <see cref="CimGetInstance"/> object, which is
/// used to delegate all Get-CimInstance operations, such
/// as enumerate instances, get instance, query instance.
/// </para>
/// </summary>
CimGetInstance GetOperationAgent()
{
return (this.AsyncOperation as CimGetInstance);
}
/// <summary>
/// <para>
/// Create <see cref="CimGetInstance"/> object, which is
/// used to delegate all Get-CimInstance operations, such
/// as enumerate instances, get instance, query instance.
/// </para>
/// </summary>
/// <returns></returns>
CimGetInstance CreateOperationAgent()
{
CimGetInstance cimGetInstance = new CimGetInstance();
this.AsyncOperation = cimGetInstance;
return cimGetInstance;
}
/// <summary>
/// Check argument value.
/// </summary>
private void CheckArgument()
{
switch (this.ParameterSetName)
{
case CimBaseCommand.ClassNameComputerSet:
case CimBaseCommand.ClassNameSessionSet:
// validate the classname & property
this.className = ValidationHelper.ValidateArgumentIsValidName(nameClassName, this.className);
this.property = ValidationHelper.ValidateArgumentIsValidName(nameSelectProperties, this.property);
break;
default:
break;
}
}
#endregion
#region private members
#region const string of parameter names
internal const string nameCimInstance = "InputObject";
internal const string nameCimSession = "CimSession";
internal const string nameClassName = "ClassName";
internal const string nameResourceUri = "ResourceUri";
internal const string nameComputerName = "ComputerName";
internal const string nameFilter = "Filter";
internal const string nameKeyOnly = "KeyOnly";
internal const string nameNamespace = "Namespace";
internal const string nameOperationTimeoutSec = "OperationTimeoutSec";
internal const string nameQuery = "Query";
internal const string nameQueryDialect = "QueryDialect";
internal const string nameSelectProperties = "Property";
internal const string nameShallow = "Shallow";
#endregion
/// <summary>
/// Static parameter definition entries.
/// </summary>
static Dictionary<string, HashSet<ParameterDefinitionEntry>> parameters = new Dictionary<string, HashSet<ParameterDefinitionEntry>>
{
{
nameCimSession, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.QuerySessionSet, true),
new ParameterDefinitionEntry(CimBaseCommand.CimInstanceSessionSet, true),
new ParameterDefinitionEntry(CimBaseCommand.ClassNameSessionSet, true),
new ParameterDefinitionEntry(CimBaseCommand.ResourceUriSessionSet, true),
}
},
{
nameResourceUri, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.ResourceUriSessionSet, true),
new ParameterDefinitionEntry(CimBaseCommand.ResourceUriComputerSet, true),
new ParameterDefinitionEntry(CimBaseCommand.CimInstanceComputerSet, false),
new ParameterDefinitionEntry(CimBaseCommand.CimInstanceSessionSet, false),
new ParameterDefinitionEntry(CimBaseCommand.QueryComputerSet, false),
new ParameterDefinitionEntry(CimBaseCommand.QuerySessionSet, false),
}
},
{
nameClassName, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.ClassNameSessionSet, true),
new ParameterDefinitionEntry(CimBaseCommand.ClassNameComputerSet, true),
}
},
{
nameComputerName, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.ClassNameComputerSet, false),
new ParameterDefinitionEntry(CimBaseCommand.QueryComputerSet, false),
new ParameterDefinitionEntry(CimBaseCommand.CimInstanceComputerSet, false),
new ParameterDefinitionEntry(CimBaseCommand.ResourceUriComputerSet, false),
}
},
{
nameKeyOnly, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.ClassNameComputerSet, false),
new ParameterDefinitionEntry(CimBaseCommand.ClassNameSessionSet, false),
new ParameterDefinitionEntry(CimBaseCommand.ResourceUriSessionSet, false),
new ParameterDefinitionEntry(CimBaseCommand.ResourceUriComputerSet, false),
}
},
{
nameNamespace, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.ClassNameComputerSet, false),
new ParameterDefinitionEntry(CimBaseCommand.ClassNameSessionSet, false),
new ParameterDefinitionEntry(CimBaseCommand.ResourceUriSessionSet, false),
new ParameterDefinitionEntry(CimBaseCommand.ResourceUriComputerSet, false),
new ParameterDefinitionEntry(CimBaseCommand.QueryComputerSet, false),
new ParameterDefinitionEntry(CimBaseCommand.QuerySessionSet, false),
}
},
{
nameCimInstance, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.CimInstanceComputerSet, true),
new ParameterDefinitionEntry(CimBaseCommand.CimInstanceSessionSet, true),
}
},
{
nameQuery, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.QuerySessionSet, true),
new ParameterDefinitionEntry(CimBaseCommand.QueryComputerSet, true),
}
},
{
nameQueryDialect, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.QuerySessionSet, false),
new ParameterDefinitionEntry(CimBaseCommand.QueryComputerSet, false),
new ParameterDefinitionEntry(CimBaseCommand.ClassNameSessionSet, false),
new ParameterDefinitionEntry(CimBaseCommand.ClassNameComputerSet, false),
}
},
{
nameShallow, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.QuerySessionSet, false),
new ParameterDefinitionEntry(CimBaseCommand.QueryComputerSet, false),
new ParameterDefinitionEntry(CimBaseCommand.ResourceUriSessionSet, false),
new ParameterDefinitionEntry(CimBaseCommand.ResourceUriComputerSet, false),
new ParameterDefinitionEntry(CimBaseCommand.ClassNameSessionSet, false),
new ParameterDefinitionEntry(CimBaseCommand.ClassNameComputerSet, false),
}
},
{
nameFilter, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.ClassNameSessionSet, false),
new ParameterDefinitionEntry(CimBaseCommand.ClassNameComputerSet, false),
new ParameterDefinitionEntry(CimBaseCommand.ResourceUriSessionSet, false),
new ParameterDefinitionEntry(CimBaseCommand.ResourceUriComputerSet, false),
}
},
{
nameSelectProperties, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.ClassNameSessionSet, false),
new ParameterDefinitionEntry(CimBaseCommand.ClassNameComputerSet, false),
new ParameterDefinitionEntry(CimBaseCommand.ResourceUriSessionSet, false),
new ParameterDefinitionEntry(CimBaseCommand.ResourceUriComputerSet, false),
}
},
};
/// <summary>
/// Static parameter set entries.
/// </summary>
static Dictionary<string, ParameterSetEntry> parameterSets = new Dictionary<string, ParameterSetEntry>
{
{ CimBaseCommand.CimInstanceComputerSet, new ParameterSetEntry(1) },
{ CimBaseCommand.CimInstanceSessionSet, new ParameterSetEntry(2) },
{ CimBaseCommand.ClassNameComputerSet, new ParameterSetEntry(1, true) },
{ CimBaseCommand.ClassNameSessionSet, new ParameterSetEntry(2) },
{ CimBaseCommand.QueryComputerSet, new ParameterSetEntry(1) },
{ CimBaseCommand.ResourceUriSessionSet, new ParameterSetEntry(2) },
{ CimBaseCommand.ResourceUriComputerSet, new ParameterSetEntry(1) },
{ CimBaseCommand.QuerySessionSet, new ParameterSetEntry(2) }
};
#endregion
}
}
| |
#region Copyright
/*
Copyright 2014 Cluster Reply s.r.l.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#endregion
/// -----------------------------------------------------------------------------------------------------------
/// Module : FileAdapterBinding.cs
/// Description : This is the class used while creating a binding for an adapter
/// -----------------------------------------------------------------------------------------------------------
#region Using Directives
using System;
using System.Collections.Generic;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Configuration;
using Microsoft.ServiceModel.Channels.Common;
#endregion
namespace Reply.Cluster.Mercury.Adapters.File
{
public class FileAdapterBinding : AdapterBinding
{
// Scheme in Binding does not have to be the same as Adapter Scheme.
// Over write this value as appropriate.
private const string BindingScheme = "file";
/// <summary>
/// Initializes a new instance of the AdapterBinding class
/// </summary>
public FileAdapterBinding() { }
/// <summary>
/// Initializes a new instance of the AdapterBinding class with a configuration name
/// </summary>
public FileAdapterBinding(string configName)
{
ApplyConfiguration(configName);
}
/// <summary>
/// Applies the current configuration to the FileAdapterBindingCollectionElement
/// </summary>
private void ApplyConfiguration(string configurationName)
{
BindingsSection bindingsSection = (BindingsSection)System.Configuration.ConfigurationManager.GetSection("system.serviceModel/bindings");
FileAdapterBindingCollectionElement bindingCollectionElement = (FileAdapterBindingCollectionElement)bindingsSection["fileBinding"];
FileAdapterBindingElement element = bindingCollectionElement.Bindings[configurationName];
if (element != null)
{
element.ApplyConfiguration(this);
}
}
#region Private Fields
private FileAdapter binding;
#endregion Private Fields
#region Custom Generated Fields
private PollingType pollingType;
private int pollingInterval;
private string scheduleName;
private string tempFolder;
private string remoteBackup;
private string localBackup;
private OverwriteAction overwriteAction;
#endregion Custom Generated Fields
#region Public Properties
/// <summary>
/// Gets the URI transport scheme that is used by the channel and listener factories that are built by the bindings.
/// </summary>
public override string Scheme
{
get
{
return BindingScheme;
}
}
/// <summary>
/// Returns a value indicating whether this binding supports metadata browsing.
/// </summary>
public override bool SupportsMetadataBrowse
{
get
{
return false;
}
}
/// <summary>
/// Returns a value indicating whether this binding supports metadata retrieval.
/// </summary>
public override bool SupportsMetadataGet
{
get
{
return false;
}
}
/// <summary>
/// Returns a value indicating whether this binding supports metadata searching.
/// </summary>
public override bool SupportsMetadataSearch
{
get
{
return false;
}
}
/// <summary>
/// Returns the custom type of the ConnectionUri.
/// </summary>
public override Type ConnectionUriType
{
get
{
return typeof(FileAdapterConnectionUri);
}
}
#endregion Public Properties
#region Custom Generated Properties
[System.Configuration.ConfigurationProperty("pollingType", DefaultValue = PollingType.Event)]
public PollingType PollingType
{
get
{
return this.pollingType;
}
set
{
this.pollingType = value;
}
}
[System.Configuration.ConfigurationProperty("pollingInterval", DefaultValue = 60)]
public int PollingInterval
{
get
{
return this.pollingInterval;
}
set
{
this.pollingInterval = value;
}
}
[System.Configuration.ConfigurationProperty("ScheduleName")]
public string ScheduleName
{
get
{
return this.scheduleName;
}
set
{
this.scheduleName = value;
}
}
[System.Configuration.ConfigurationProperty("TempFolder")]
public string TempFolder
{
get
{
return this.tempFolder;
}
set
{
this.tempFolder = value;
}
}
[System.Configuration.ConfigurationProperty("RemoteBackup")]
public string RemoteBackup
{
get
{
return this.remoteBackup;
}
set
{
this.remoteBackup = value;
}
}
[System.Configuration.ConfigurationProperty("LocalBackup")]
public string LocalBackup
{
get
{
return this.localBackup;
}
set
{
this.localBackup = value;
}
}
[System.Configuration.ConfigurationProperty("overwriteAction", DefaultValue = OverwriteAction.None)]
public OverwriteAction OverwriteAction
{
get
{
return this.overwriteAction;
}
set
{
this.overwriteAction = value;
}
}
#endregion Custom Generated Properties
#region Private Properties
private FileAdapter BindingElement
{
get
{
if (binding == null)
binding = new FileAdapter();
binding.PollingType = this.PollingType;
binding.PollingInterval = this.PollingInterval;
binding.ScheduleName = this.ScheduleName;
binding.TempFolder = this.TempFolder;
binding.RemoteBackup = this.RemoteBackup;
binding.LocalBackup = this.LocalBackup;
binding.OverwriteAction = this.OverwriteAction;
return binding;
}
}
#endregion Private Properties
#region Public Methods
/// <summary>
/// Creates a clone of the existing BindingElement and returns it
/// </summary>
public override BindingElementCollection CreateBindingElements()
{
BindingElementCollection bindingElements = new BindingElementCollection();
//Only create once
bindingElements.Add(this.BindingElement);
//Return the clone
return bindingElements.Clone();
}
#endregion Public Methods
}
}
| |
using System;
using System.Collections.Generic;
using Avalonia.Media;
using Avalonia.Platform;
using Avalonia.Rendering;
using Avalonia.Rendering.SceneGraph;
using Avalonia.Utilities;
using Avalonia.Visuals.Media.Imaging;
using SharpDX;
using SharpDX.Direct2D1;
using SharpDX.Mathematics.Interop;
using BitmapInterpolationMode = Avalonia.Visuals.Media.Imaging.BitmapInterpolationMode;
namespace Avalonia.Direct2D1.Media
{
/// <summary>
/// Draws using Direct2D1.
/// </summary>
public class DrawingContextImpl : IDrawingContextImpl
{
private readonly IVisualBrushRenderer _visualBrushRenderer;
private readonly ILayerFactory _layerFactory;
private readonly SharpDX.Direct2D1.RenderTarget _renderTarget;
private readonly DeviceContext _deviceContext;
private readonly bool _ownsDeviceContext;
private readonly SharpDX.DXGI.SwapChain1 _swapChain;
private readonly Action _finishedCallback;
/// <summary>
/// Initializes a new instance of the <see cref="DrawingContextImpl"/> class.
/// </summary>
/// <param name="visualBrushRenderer">The visual brush renderer.</param>
/// <param name="renderTarget">The render target to draw to.</param>
/// <param name="layerFactory">
/// An object to use to create layers. May be null, in which case a
/// <see cref="WicRenderTargetBitmapImpl"/> will created when a new layer is requested.
/// </param>
/// <param name="swapChain">An optional swap chain associated with this drawing context.</param>
/// <param name="finishedCallback">An optional delegate to be called when context is disposed.</param>
public DrawingContextImpl(
IVisualBrushRenderer visualBrushRenderer,
ILayerFactory layerFactory,
SharpDX.Direct2D1.RenderTarget renderTarget,
SharpDX.DXGI.SwapChain1 swapChain = null,
Action finishedCallback = null)
{
_visualBrushRenderer = visualBrushRenderer;
_layerFactory = layerFactory;
_renderTarget = renderTarget;
_swapChain = swapChain;
_finishedCallback = finishedCallback;
if (_renderTarget is DeviceContext deviceContext)
{
_deviceContext = deviceContext;
_ownsDeviceContext = false;
}
else
{
_deviceContext = _renderTarget.QueryInterface<DeviceContext>();
_ownsDeviceContext = true;
}
_deviceContext.BeginDraw();
}
/// <summary>
/// Gets the current transform of the drawing context.
/// </summary>
public Matrix Transform
{
get { return _deviceContext.Transform.ToAvalonia(); }
set { _deviceContext.Transform = value.ToDirect2D(); }
}
/// <inheritdoc/>
public void Clear(Color color)
{
_deviceContext.Clear(color.ToDirect2D());
}
/// <summary>
/// Ends a draw operation.
/// </summary>
public void Dispose()
{
foreach (var layer in _layerPool)
{
layer.Dispose();
}
try
{
_deviceContext.EndDraw();
_swapChain?.Present(1, SharpDX.DXGI.PresentFlags.None);
_finishedCallback?.Invoke();
}
catch (SharpDXException ex) when ((uint)ex.HResult == 0x8899000C) // D2DERR_RECREATE_TARGET
{
throw new RenderTargetCorruptedException(ex);
}
finally
{
if (_ownsDeviceContext)
{
_deviceContext.Dispose();
}
}
}
/// <summary>
/// Draws a bitmap image.
/// </summary>
/// <param name="source">The bitmap image.</param>
/// <param name="opacity">The opacity to draw with.</param>
/// <param name="sourceRect">The rect in the image to draw.</param>
/// <param name="destRect">The rect in the output to draw to.</param>
/// <param name="bitmapInterpolationMode">The bitmap interpolation mode.</param>
public void DrawBitmap(IRef<IBitmapImpl> source, double opacity, Rect sourceRect, Rect destRect, BitmapInterpolationMode bitmapInterpolationMode)
{
using (var d2d = ((BitmapImpl)source.Item).GetDirect2DBitmap(_deviceContext))
{
var interpolationMode = GetInterpolationMode(bitmapInterpolationMode);
// TODO: How to implement CompositeMode here?
_deviceContext.DrawBitmap(
d2d.Value,
destRect.ToSharpDX(),
(float)opacity,
interpolationMode,
sourceRect.ToSharpDX(),
null);
}
}
private static InterpolationMode GetInterpolationMode(BitmapInterpolationMode interpolationMode)
{
switch (interpolationMode)
{
case BitmapInterpolationMode.LowQuality:
return InterpolationMode.NearestNeighbor;
case BitmapInterpolationMode.MediumQuality:
return InterpolationMode.Linear;
case BitmapInterpolationMode.HighQuality:
return InterpolationMode.HighQualityCubic;
case BitmapInterpolationMode.Default:
return InterpolationMode.Linear;
default:
throw new ArgumentOutOfRangeException(nameof(interpolationMode), interpolationMode, null);
}
}
public static CompositeMode GetCompositeMode(BitmapBlendingMode blendingMode)
{
switch (blendingMode)
{
case BitmapBlendingMode.SourceIn:
return CompositeMode.SourceIn;
case BitmapBlendingMode.SourceOut:
return CompositeMode.SourceOut;
case BitmapBlendingMode.SourceOver:
return CompositeMode.SourceOver;
case BitmapBlendingMode.SourceAtop:
return CompositeMode.SourceAtop;
case BitmapBlendingMode.DestinationIn:
return CompositeMode.DestinationIn;
case BitmapBlendingMode.DestinationOut:
return CompositeMode.DestinationOut;
case BitmapBlendingMode.DestinationOver:
return CompositeMode.DestinationOver;
case BitmapBlendingMode.DestinationAtop:
return CompositeMode.DestinationAtop;
case BitmapBlendingMode.Xor:
return CompositeMode.Xor;
case BitmapBlendingMode.Plus:
return CompositeMode.Plus;
default:
throw new ArgumentOutOfRangeException(nameof(blendingMode), blendingMode, null);
}
}
/// <summary>
/// Draws a bitmap image.
/// </summary>
/// <param name="source">The bitmap image.</param>
/// <param name="opacityMask">The opacity mask to draw with.</param>
/// <param name="opacityMaskRect">The destination rect for the opacity mask.</param>
/// <param name="destRect">The rect in the output to draw to.</param>
public void DrawBitmap(IRef<IBitmapImpl> source, IBrush opacityMask, Rect opacityMaskRect, Rect destRect)
{
using (var d2dSource = ((BitmapImpl)source.Item).GetDirect2DBitmap(_deviceContext))
using (var sourceBrush = new BitmapBrush(_deviceContext, d2dSource.Value))
using (var d2dOpacityMask = CreateBrush(opacityMask, opacityMaskRect))
using (var geometry = new SharpDX.Direct2D1.RectangleGeometry(Direct2D1Platform.Direct2D1Factory, destRect.ToDirect2D()))
{
if (d2dOpacityMask.PlatformBrush != null)
{
d2dOpacityMask.PlatformBrush.Transform = Matrix.CreateTranslation(opacityMaskRect.Position).ToDirect2D();
}
_deviceContext.FillGeometry(
geometry,
sourceBrush,
d2dOpacityMask.PlatformBrush);
}
}
/// <summary>
/// Draws a line.
/// </summary>
/// <param name="pen">The stroke pen.</param>
/// <param name="p1">The first point of the line.</param>
/// <param name="p2">The second point of the line.</param>
public void DrawLine(IPen pen, Point p1, Point p2)
{
if (pen != null)
{
using (var d2dBrush = CreateBrush(pen.Brush, new Rect(p1, p2).Normalize()))
using (var d2dStroke = pen.ToDirect2DStrokeStyle(_deviceContext))
{
if (d2dBrush.PlatformBrush != null)
{
_deviceContext.DrawLine(
p1.ToSharpDX(),
p2.ToSharpDX(),
d2dBrush.PlatformBrush,
(float)pen.Thickness,
d2dStroke);
}
}
}
}
/// <summary>
/// Draws a geometry.
/// </summary>
/// <param name="brush">The fill brush.</param>
/// <param name="pen">The stroke pen.</param>
/// <param name="geometry">The geometry.</param>
public void DrawGeometry(IBrush brush, IPen pen, IGeometryImpl geometry)
{
if (brush != null)
{
using (var d2dBrush = CreateBrush(brush, geometry.Bounds))
{
if (d2dBrush.PlatformBrush != null)
{
var impl = (GeometryImpl)geometry;
_deviceContext.FillGeometry(impl.Geometry, d2dBrush.PlatformBrush);
}
}
}
if (pen != null)
{
using (var d2dBrush = CreateBrush(pen.Brush, geometry.GetRenderBounds(pen)))
using (var d2dStroke = pen.ToDirect2DStrokeStyle(_deviceContext))
{
if (d2dBrush.PlatformBrush != null)
{
var impl = (GeometryImpl)geometry;
_deviceContext.DrawGeometry(impl.Geometry, d2dBrush.PlatformBrush, (float)pen.Thickness, d2dStroke);
}
}
}
}
/// <inheritdoc />
public void DrawRectangle(IBrush brush, IPen pen, RoundedRect rrect, BoxShadows boxShadow = default)
{
var rc = rrect.Rect.ToDirect2D();
var rect = rrect.Rect;
var radiusX = Math.Max(rrect.RadiiTopLeft.X,
Math.Max(rrect.RadiiTopRight.X, Math.Max(rrect.RadiiBottomRight.X, rrect.RadiiBottomLeft.X)));
var radiusY = Math.Max(rrect.RadiiTopLeft.Y,
Math.Max(rrect.RadiiTopRight.Y, Math.Max(rrect.RadiiBottomRight.Y, rrect.RadiiBottomLeft.Y)));
var isRounded = !MathUtilities.IsZero(radiusX) || !MathUtilities.IsZero(radiusY);
if (brush != null)
{
using (var b = CreateBrush(brush, rect))
{
if (b.PlatformBrush != null)
{
if (isRounded)
{
_deviceContext.FillRoundedRectangle(
new RoundedRectangle
{
Rect = new RawRectangleF(
(float)rect.X,
(float)rect.Y,
(float)rect.Right,
(float)rect.Bottom),
RadiusX = (float)radiusX,
RadiusY = (float)radiusY
},
b.PlatformBrush);
}
else
{
_deviceContext.FillRectangle(rc, b.PlatformBrush);
}
}
}
}
if (pen?.Brush != null)
{
using (var wrapper = CreateBrush(pen.Brush, rect))
using (var d2dStroke = pen.ToDirect2DStrokeStyle(_deviceContext))
{
if (wrapper.PlatformBrush != null)
{
if (isRounded)
{
_deviceContext.DrawRoundedRectangle(
new RoundedRectangle { Rect = rc, RadiusX = (float)radiusX, RadiusY = (float)radiusY },
wrapper.PlatformBrush,
(float)pen.Thickness,
d2dStroke);
}
else
{
_deviceContext.DrawRectangle(
rc,
wrapper.PlatformBrush,
(float)pen.Thickness,
d2dStroke);
}
}
}
}
}
/// <summary>
/// Draws text.
/// </summary>
/// <param name="foreground">The foreground brush.</param>
/// <param name="origin">The upper-left corner of the text.</param>
/// <param name="text">The text.</param>
public void DrawText(IBrush foreground, Point origin, IFormattedTextImpl text)
{
if (!string.IsNullOrEmpty(text.Text))
{
var impl = (FormattedTextImpl)text;
using (var brush = CreateBrush(foreground, impl.Bounds))
using (var renderer = new AvaloniaTextRenderer(this, _deviceContext, brush.PlatformBrush))
{
if (brush.PlatformBrush != null)
{
impl.TextLayout.Draw(renderer, (float)origin.X, (float)origin.Y);
}
}
}
}
/// <summary>
/// Draws a glyph run.
/// </summary>
/// <param name="foreground">The foreground.</param>
/// <param name="glyphRun">The glyph run.</param>
public void DrawGlyphRun(IBrush foreground, GlyphRun glyphRun)
{
using (var brush = CreateBrush(foreground, new Rect(glyphRun.Size)))
{
var glyphRunImpl = (GlyphRunImpl)glyphRun.GlyphRunImpl;
_renderTarget.DrawGlyphRun(glyphRun.BaselineOrigin.ToSharpDX(), glyphRunImpl.GlyphRun,
brush.PlatformBrush, MeasuringMode.Natural);
}
}
public IDrawingContextLayerImpl CreateLayer(Size size)
{
if (_layerFactory != null)
{
return _layerFactory.CreateLayer(size);
}
else
{
var platform = AvaloniaLocator.Current.GetService<IPlatformRenderInterface>();
var dpi = new Vector(_deviceContext.DotsPerInch.Width, _deviceContext.DotsPerInch.Height);
var pixelSize = PixelSize.FromSizeWithDpi(size, dpi);
return (IDrawingContextLayerImpl)platform.CreateRenderTargetBitmap(pixelSize, dpi);
}
}
/// <summary>
/// Pushes a clip rectange.
/// </summary>
/// <param name="clip">The clip rectangle.</param>
/// <returns>A disposable used to undo the clip rectangle.</returns>
public void PushClip(Rect clip)
{
_deviceContext.PushAxisAlignedClip(clip.ToSharpDX(), AntialiasMode.PerPrimitive);
}
public void PushClip(RoundedRect clip)
{
//TODO: radius
_deviceContext.PushAxisAlignedClip(clip.Rect.ToDirect2D(), AntialiasMode.PerPrimitive);
}
public void PopClip()
{
_deviceContext.PopAxisAlignedClip();
}
readonly Stack<Layer> _layers = new Stack<Layer>();
private readonly Stack<Layer> _layerPool = new Stack<Layer>();
/// <summary>
/// Pushes an opacity value.
/// </summary>
/// <param name="opacity">The opacity.</param>
/// <returns>A disposable used to undo the opacity.</returns>
public void PushOpacity(double opacity)
{
if (opacity < 1)
{
var parameters = new LayerParameters
{
ContentBounds = PrimitiveExtensions.RectangleInfinite,
MaskTransform = PrimitiveExtensions.Matrix3x2Identity,
Opacity = (float)opacity,
};
var layer = _layerPool.Count != 0 ? _layerPool.Pop() : new Layer(_deviceContext);
_deviceContext.PushLayer(ref parameters, layer);
_layers.Push(layer);
}
else
_layers.Push(null);
}
public void PopOpacity()
{
PopLayer();
}
private void PopLayer()
{
var layer = _layers.Pop();
if (layer != null)
{
_deviceContext.PopLayer();
_layerPool.Push(layer);
}
}
/// <summary>
/// Creates a Direct2D brush wrapper for a Avalonia brush.
/// </summary>
/// <param name="brush">The avalonia brush.</param>
/// <param name="destinationRect">The brush's target area.</param>
/// <returns>The Direct2D brush wrapper.</returns>
public BrushImpl CreateBrush(IBrush brush, Rect destinationRect)
{
var solidColorBrush = brush as ISolidColorBrush;
var linearGradientBrush = brush as ILinearGradientBrush;
var radialGradientBrush = brush as IRadialGradientBrush;
var conicGradientBrush = brush as IConicGradientBrush;
var imageBrush = brush as IImageBrush;
var visualBrush = brush as IVisualBrush;
if (solidColorBrush != null)
{
return new SolidColorBrushImpl(solidColorBrush, _deviceContext);
}
else if (linearGradientBrush != null)
{
return new LinearGradientBrushImpl(linearGradientBrush, _deviceContext, destinationRect);
}
else if (radialGradientBrush != null)
{
return new RadialGradientBrushImpl(radialGradientBrush, _deviceContext, destinationRect);
}
else if (conicGradientBrush != null)
{
// there is no Direct2D implementation of Conic Gradients so use Radial as a stand-in
return new SolidColorBrushImpl(conicGradientBrush, _deviceContext);
}
else if (imageBrush?.Source != null)
{
return new ImageBrushImpl(
imageBrush,
_deviceContext,
(BitmapImpl)imageBrush.Source.PlatformImpl.Item,
destinationRect.Size);
}
else if (visualBrush != null)
{
if (_visualBrushRenderer != null)
{
var intermediateSize = _visualBrushRenderer.GetRenderTargetSize(visualBrush);
if (intermediateSize.Width >= 1 && intermediateSize.Height >= 1)
{
// We need to ensure the size we're requesting is an integer pixel size, otherwise
// D2D alters the DPI of the render target, which messes stuff up. PixelSize.FromSize
// will do the rounding for us.
var dpi = new Vector(_deviceContext.DotsPerInch.Width, _deviceContext.DotsPerInch.Height);
var pixelSize = PixelSize.FromSizeWithDpi(intermediateSize, dpi);
using (var intermediate = new BitmapRenderTarget(
_deviceContext,
CompatibleRenderTargetOptions.None,
pixelSize.ToSizeWithDpi(dpi).ToSharpDX()))
{
using (var ctx = new RenderTarget(intermediate).CreateDrawingContext(_visualBrushRenderer))
{
intermediate.Clear(null);
_visualBrushRenderer.RenderVisualBrush(ctx, visualBrush);
}
return new ImageBrushImpl(
visualBrush,
_deviceContext,
new D2DBitmapImpl(intermediate.Bitmap),
destinationRect.Size);
}
}
}
else
{
throw new NotSupportedException("No IVisualBrushRenderer was supplied to DrawingContextImpl.");
}
}
return new SolidColorBrushImpl(null, _deviceContext);
}
public void PushGeometryClip(IGeometryImpl clip)
{
var parameters = new LayerParameters
{
ContentBounds = PrimitiveExtensions.RectangleInfinite,
MaskTransform = PrimitiveExtensions.Matrix3x2Identity,
Opacity = 1,
GeometricMask = ((GeometryImpl)clip).Geometry,
MaskAntialiasMode = AntialiasMode.PerPrimitive
};
var layer = _layerPool.Count != 0 ? _layerPool.Pop() : new Layer(_deviceContext);
_deviceContext.PushLayer(ref parameters, layer);
_layers.Push(layer);
}
public void PopGeometryClip()
{
PopLayer();
}
public void PushBitmapBlendMode(BitmapBlendingMode blendingMode)
{
// TODO: Stubs for now
}
public void PopBitmapBlendMode()
{
// TODO: Stubs for now
}
public void PushOpacityMask(IBrush mask, Rect bounds)
{
var parameters = new LayerParameters
{
ContentBounds = PrimitiveExtensions.RectangleInfinite,
MaskTransform = PrimitiveExtensions.Matrix3x2Identity,
Opacity = 1,
OpacityBrush = CreateBrush(mask, bounds).PlatformBrush
};
var layer = _layerPool.Count != 0 ? _layerPool.Pop() : new Layer(_deviceContext);
_deviceContext.PushLayer(ref parameters, layer);
_layers.Push(layer);
}
public void PopOpacityMask()
{
PopLayer();
}
public void Custom(ICustomDrawOperation custom) => custom.Render(this);
}
}
| |
#region --- License ---
/*
Copyright (c) 2006 - 2008 The Open Toolkit library.
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.Runtime.InteropServices;
namespace OpenTK
{
/// <summary>
/// Represents a 3x3 matrix containing 3D rotation and scale with double-precision components.
/// </summary>
[Serializable]
[StructLayout(LayoutKind.Sequential)]
public struct Matrix3d : IEquatable<Matrix3d>
{
#region Fields
/// <summary>
/// First row of the matrix.
/// </summary>
public Vector3d Row0;
/// <summary>
/// Second row of the matrix.
/// </summary>
public Vector3d Row1;
/// <summary>
/// Third row of the matrix.
/// </summary>
public Vector3d Row2;
/// <summary>
/// The identity matrix.
/// </summary>
public static Matrix3d Identity = new Matrix3d(Vector3d.UnitX, Vector3d.UnitY, Vector3d.UnitZ);
#endregion
#region Constructors
/// <summary>
/// Constructs a new instance.
/// </summary>
/// <param name="row0">Top row of the matrix</param>
/// <param name="row1">Second row of the matrix</param>
/// <param name="row2">Bottom row of the matrix</param>
public Matrix3d(Vector3d row0, Vector3d row1, Vector3d row2)
{
Row0 = row0;
Row1 = row1;
Row2 = row2;
}
/// <summary>
/// Constructs a new instance.
/// </summary>
/// <param name="m00">First item of the first row of the matrix.</param>
/// <param name="m01">Second item of the first row of the matrix.</param>
/// <param name="m02">Third item of the first row of the matrix.</param>
/// <param name="m10">First item of the second row of the matrix.</param>
/// <param name="m11">Second item of the second row of the matrix.</param>
/// <param name="m12">Third item of the second row of the matrix.</param>
/// <param name="m20">First item of the third row of the matrix.</param>
/// <param name="m21">Second item of the third row of the matrix.</param>
/// <param name="m22">Third item of the third row of the matrix.</param>
public Matrix3d(
double m00, double m01, double m02,
double m10, double m11, double m12,
double m20, double m21, double m22)
{
Row0 = new Vector3d(m00, m01, m02);
Row1 = new Vector3d(m10, m11, m12);
Row2 = new Vector3d(m20, m21, m22);
}
/// <summary>
/// Constructs a new instance.
/// </summary>
/// <param name="matrix">A Matrix4d to take the upper-left 3x3 from.</param>
public Matrix3d(Matrix4d matrix)
{
Row0 = matrix.Row0.Xyz;
Row1 = matrix.Row1.Xyz;
Row2 = matrix.Row2.Xyz;
}
#endregion
#region Public Members
#region Properties
/// <summary>
/// Gets the determinant of this matrix.
/// </summary>
public double Determinant
{
get
{
double m11 = Row0.X, m12 = Row0.Y, m13 = Row0.Z,
m21 = Row1.X, m22 = Row1.Y, m23 = Row1.Z,
m31 = Row2.X, m32 = Row2.Y, m33 = Row2.Z;
return
m11 * m22 * m33 + m12 * m23 * m31 + m13 * m21 * m32
- m13 * m22 * m31 - m11 * m23 * m32 - m12 * m21 * m33;
}
}
/// <summary>
/// Gets the first column of this matrix.
/// </summary>
public Vector3d Column0
{
get { return new Vector3d(Row0.X, Row1.X, Row2.X); }
}
/// <summary>
/// Gets the second column of this matrix.
/// </summary>
public Vector3d Column1
{
get { return new Vector3d(Row0.Y, Row1.Y, Row2.Y); }
}
/// <summary>
/// Gets the third column of this matrix.
/// </summary>
public Vector3d Column2
{
get { return new Vector3d(Row0.Z, Row1.Z, Row2.Z); }
}
/// <summary>
/// Gets or sets the value at row 1, column 1 of this instance.
/// </summary>
public double M11 { get { return Row0.X; } set { Row0.X = value; } }
/// <summary>
/// Gets or sets the value at row 1, column 2 of this instance.
/// </summary>
public double M12 { get { return Row0.Y; } set { Row0.Y = value; } }
/// <summary>
/// Gets or sets the value at row 1, column 3 of this instance.
/// </summary>
public double M13 { get { return Row0.Z; } set { Row0.Z = value; } }
/// <summary>
/// Gets or sets the value at row 2, column 1 of this instance.
/// </summary>
public double M21 { get { return Row1.X; } set { Row1.X = value; } }
/// <summary>
/// Gets or sets the value at row 2, column 2 of this instance.
/// </summary>
public double M22 { get { return Row1.Y; } set { Row1.Y = value; } }
/// <summary>
/// Gets or sets the value at row 2, column 3 of this instance.
/// </summary>
public double M23 { get { return Row1.Z; } set { Row1.Z = value; } }
/// <summary>
/// Gets or sets the value at row 3, column 1 of this instance.
/// </summary>
public double M31 { get { return Row2.X; } set { Row2.X = value; } }
/// <summary>
/// Gets or sets the value at row 3, column 2 of this instance.
/// </summary>
public double M32 { get { return Row2.Y; } set { Row2.Y = value; } }
/// <summary>
/// Gets or sets the value at row 3, column 3 of this instance.
/// </summary>
public double M33 { get { return Row2.Z; } set { Row2.Z = value; } }
/// <summary>
/// Gets or sets the values along the main diagonal of the matrix.
/// </summary>
public Vector3d Diagonal
{
get
{
return new Vector3d(Row0.X, Row1.Y, Row2.Z);
}
set
{
Row0.X = value.X;
Row1.Y = value.Y;
Row2.Z = value.Z;
}
}
/// <summary>
/// Gets the trace of the matrix, the sum of the values along the diagonal.
/// </summary>
public double Trace { get { return Row0.X + Row1.Y + Row2.Z; } }
#endregion
#region Indexers
/// <summary>
/// Gets or sets the value at a specified row and column.
/// </summary>
public double this[int rowIndex, int columnIndex]
{
get
{
if (rowIndex == 0) return Row0[columnIndex];
else if (rowIndex == 1) return Row1[columnIndex];
else if (rowIndex == 2) return Row2[columnIndex];
throw new IndexOutOfRangeException("You tried to access this matrix at: (" + rowIndex + ", " + columnIndex + ")");
}
set
{
if (rowIndex == 0) Row0[columnIndex] = value;
else if (rowIndex == 1) Row1[columnIndex] = value;
else if (rowIndex == 2) Row2[columnIndex] = value;
else throw new IndexOutOfRangeException("You tried to set this matrix at: (" + rowIndex + ", " + columnIndex + ")");
}
}
#endregion
#region Instance
#region public void Invert()
/// <summary>
/// Converts this instance into its inverse.
/// </summary>
public void Invert()
{
this = Matrix3d.Invert(this);
}
#endregion
#region public void Transpose()
/// <summary>
/// Converts this instance into its transpose.
/// </summary>
public void Transpose()
{
this = Matrix3d.Transpose(this);
}
#endregion
/// <summary>
/// Returns a normalised copy of this instance.
/// </summary>
public Matrix3d Normalized()
{
Matrix3d m = this;
m.Normalize();
return m;
}
/// <summary>
/// Divides each element in the Matrix by the <see cref="Determinant"/>.
/// </summary>
public void Normalize()
{
var determinant = this.Determinant;
Row0 /= determinant;
Row1 /= determinant;
Row2 /= determinant;
}
/// <summary>
/// Returns an inverted copy of this instance.
/// </summary>
public Matrix3d Inverted()
{
Matrix3d m = this;
if (m.Determinant != 0)
m.Invert();
return m;
}
/// <summary>
/// Returns a copy of this Matrix3 without scale.
/// </summary>
public Matrix3d ClearScale()
{
Matrix3d m = this;
m.Row0 = m.Row0.Normalized();
m.Row1 = m.Row1.Normalized();
m.Row2 = m.Row2.Normalized();
return m;
}
/// <summary>
/// Returns a copy of this Matrix3 without rotation.
/// </summary>
public Matrix3d ClearRotation()
{
Matrix3d m = this;
m.Row0 = new Vector3d(m.Row0.Length, 0, 0);
m.Row1 = new Vector3d(0, m.Row1.Length, 0);
m.Row2 = new Vector3d(0, 0, m.Row2.Length);
return m;
}
/// <summary>
/// Returns the scale component of this instance.
/// </summary>
public Vector3d ExtractScale() { return new Vector3d(Row0.Length, Row1.Length, Row2.Length); }
/// <summary>
/// Returns the rotation component of this instance. Quite slow.
/// </summary>
/// <param name="row_normalise">Whether the method should row-normalise (i.e. remove scale from) the Matrix. Pass false if you know it's already normalised.</param>
public Quaterniond ExtractRotation(bool row_normalise = true)
{
var row0 = Row0;
var row1 = Row1;
var row2 = Row2;
if (row_normalise)
{
row0 = row0.Normalized();
row1 = row1.Normalized();
row2 = row2.Normalized();
}
// code below adapted from Blender
Quaterniond q = new Quaterniond();
double trace = 0.25 * (row0[0] + row1[1] + row2[2] + 1.0);
if (trace > 0)
{
double sq = Math.Sqrt(trace);
q.W = sq;
sq = 1.0 / (4.0 * sq);
q.X = (row1[2] - row2[1]) * sq;
q.Y = (row2[0] - row0[2]) * sq;
q.Z = (row0[1] - row1[0]) * sq;
}
else if (row0[0] > row1[1] && row0[0] > row2[2])
{
double sq = 2.0 * Math.Sqrt(1.0 + row0[0] - row1[1] - row2[2]);
q.X = 0.25 * sq;
sq = 1.0 / sq;
q.W = (row2[1] - row1[2]) * sq;
q.Y = (row1[0] + row0[1]) * sq;
q.Z = (row2[0] + row0[2]) * sq;
}
else if (row1[1] > row2[2])
{
double sq = 2.0 * Math.Sqrt(1.0 + row1[1] - row0[0] - row2[2]);
q.Y = 0.25 * sq;
sq = 1.0 / sq;
q.W = (row2[0] - row0[2]) * sq;
q.X = (row1[0] + row0[1]) * sq;
q.Z = (row2[1] + row1[2]) * sq;
}
else
{
double sq = 2.0 * Math.Sqrt(1.0 + row2[2] - row0[0] - row1[1]);
q.Z = 0.25 * sq;
sq = 1.0 / sq;
q.W = (row1[0] - row0[1]) * sq;
q.X = (row2[0] + row0[2]) * sq;
q.Y = (row2[1] + row1[2]) * sq;
}
q.Normalize();
return q;
}
#endregion
#region Static
#region CreateFromAxisAngle
/// <summary>
/// Build a rotation matrix from the specified axis/angle rotation.
/// </summary>
/// <param name="axis">The axis to rotate about.</param>
/// <param name="angle">Angle in radians to rotate counter-clockwise (looking in the direction of the given axis).</param>
/// <param name="result">A matrix instance.</param>
public static void CreateFromAxisAngle(Vector3d axis, double angle, out Matrix3d result)
{
//normalize and create a local copy of the vector.
axis.Normalize();
double axisX = axis.X, axisY = axis.Y, axisZ = axis.Z;
//calculate angles
double cos = System.Math.Cos(-angle);
double sin = System.Math.Sin(-angle);
double t = 1.0f - cos;
//do the conversion math once
double tXX = t * axisX * axisX,
tXY = t * axisX * axisY,
tXZ = t * axisX * axisZ,
tYY = t * axisY * axisY,
tYZ = t * axisY * axisZ,
tZZ = t * axisZ * axisZ;
double sinX = sin * axisX,
sinY = sin * axisY,
sinZ = sin * axisZ;
result.Row0.X = tXX + cos;
result.Row0.Y = tXY - sinZ;
result.Row0.Z = tXZ + sinY;
result.Row1.X = tXY + sinZ;
result.Row1.Y = tYY + cos;
result.Row1.Z = tYZ - sinX;
result.Row2.X = tXZ - sinY;
result.Row2.Y = tYZ + sinX;
result.Row2.Z = tZZ + cos;
}
/// <summary>
/// Build a rotation matrix from the specified axis/angle rotation.
/// </summary>
/// <param name="axis">The axis to rotate about.</param>
/// <param name="angle">Angle in radians to rotate counter-clockwise (looking in the direction of the given axis).</param>
/// <returns>A matrix instance.</returns>
public static Matrix3d CreateFromAxisAngle(Vector3d axis, double angle)
{
Matrix3d result;
CreateFromAxisAngle(axis, angle, out result);
return result;
}
#endregion
#region CreateFromQuaternion
/// <summary>
/// Build a rotation matrix from the specified quaternion.
/// </summary>
/// <param name="q">Quaternion to translate.</param>
/// <param name="result">Matrix result.</param>
public static void CreateFromQuaternion(ref Quaterniond q, out Matrix3d result)
{
Vector3d axis;
double angle;
q.ToAxisAngle(out axis, out angle);
CreateFromAxisAngle(axis, angle, out result);
}
/// <summary>
/// Build a rotation matrix from the specified quaternion.
/// </summary>
/// <param name="q">Quaternion to translate.</param>
/// <returns>A matrix instance.</returns>
public static Matrix3d CreateFromQuaternion(Quaterniond q)
{
Matrix3d result;
CreateFromQuaternion(ref q, out result);
return result;
}
#endregion
#region CreateRotation[XYZ]
/// <summary>
/// Builds a rotation matrix for a rotation around the x-axis.
/// </summary>
/// <param name="angle">The counter-clockwise angle in radians.</param>
/// <param name="result">The resulting Matrix3d instance.</param>
public static void CreateRotationX(double angle, out Matrix3d result)
{
double cos = System.Math.Cos(angle);
double sin = System.Math.Sin(angle);
result = Identity;
result.Row1.Y = cos;
result.Row1.Z = sin;
result.Row2.Y = -sin;
result.Row2.Z = cos;
}
/// <summary>
/// Builds a rotation matrix for a rotation around the x-axis.
/// </summary>
/// <param name="angle">The counter-clockwise angle in radians.</param>
/// <returns>The resulting Matrix3d instance.</returns>
public static Matrix3d CreateRotationX(double angle)
{
Matrix3d result;
CreateRotationX(angle, out result);
return result;
}
/// <summary>
/// Builds a rotation matrix for a rotation around the y-axis.
/// </summary>
/// <param name="angle">The counter-clockwise angle in radians.</param>
/// <param name="result">The resulting Matrix3d instance.</param>
public static void CreateRotationY(double angle, out Matrix3d result)
{
double cos = System.Math.Cos(angle);
double sin = System.Math.Sin(angle);
result = Identity;
result.Row0.X = cos;
result.Row0.Z = -sin;
result.Row2.X = sin;
result.Row2.Z = cos;
}
/// <summary>
/// Builds a rotation matrix for a rotation around the y-axis.
/// </summary>
/// <param name="angle">The counter-clockwise angle in radians.</param>
/// <returns>The resulting Matrix3d instance.</returns>
public static Matrix3d CreateRotationY(double angle)
{
Matrix3d result;
CreateRotationY(angle, out result);
return result;
}
/// <summary>
/// Builds a rotation matrix for a rotation around the z-axis.
/// </summary>
/// <param name="angle">The counter-clockwise angle in radians.</param>
/// <param name="result">The resulting Matrix3d instance.</param>
public static void CreateRotationZ(double angle, out Matrix3d result)
{
double cos = System.Math.Cos(angle);
double sin = System.Math.Sin(angle);
result = Identity;
result.Row0.X = cos;
result.Row0.Y = sin;
result.Row1.X = -sin;
result.Row1.Y = cos;
}
/// <summary>
/// Builds a rotation matrix for a rotation around the z-axis.
/// </summary>
/// <param name="angle">The counter-clockwise angle in radians.</param>
/// <returns>The resulting Matrix3d instance.</returns>
public static Matrix3d CreateRotationZ(double angle)
{
Matrix3d result;
CreateRotationZ(angle, out result);
return result;
}
#endregion
#region CreateScale
/// <summary>
/// Creates a scale matrix.
/// </summary>
/// <param name="scale">Single scale factor for the x, y, and z axes.</param>
/// <returns>A scale matrix.</returns>
public static Matrix3d CreateScale(double scale)
{
Matrix3d result;
CreateScale(scale, out result);
return result;
}
/// <summary>
/// Creates a scale matrix.
/// </summary>
/// <param name="scale">Scale factors for the x, y, and z axes.</param>
/// <returns>A scale matrix.</returns>
public static Matrix3d CreateScale(Vector3d scale)
{
Matrix3d result;
CreateScale(ref scale, out result);
return result;
}
/// <summary>
/// Creates a scale matrix.
/// </summary>
/// <param name="x">Scale factor for the x axis.</param>
/// <param name="y">Scale factor for the y axis.</param>
/// <param name="z">Scale factor for the z axis.</param>
/// <returns>A scale matrix.</returns>
public static Matrix3d CreateScale(double x, double y, double z)
{
Matrix3d result;
CreateScale(x, y, z, out result);
return result;
}
/// <summary>
/// Creates a scale matrix.
/// </summary>
/// <param name="scale">Single scale factor for the x, y, and z axes.</param>
/// <param name="result">A scale matrix.</param>
public static void CreateScale(double scale, out Matrix3d result)
{
result = Identity;
result.Row0.X = scale;
result.Row1.Y = scale;
result.Row2.Z = scale;
}
/// <summary>
/// Creates a scale matrix.
/// </summary>
/// <param name="scale">Scale factors for the x, y, and z axes.</param>
/// <param name="result">A scale matrix.</param>
public static void CreateScale(ref Vector3d scale, out Matrix3d result)
{
result = Identity;
result.Row0.X = scale.X;
result.Row1.Y = scale.Y;
result.Row2.Z = scale.Z;
}
/// <summary>
/// Creates a scale matrix.
/// </summary>
/// <param name="x">Scale factor for the x axis.</param>
/// <param name="y">Scale factor for the y axis.</param>
/// <param name="z">Scale factor for the z axis.</param>
/// <param name="result">A scale matrix.</param>
public static void CreateScale(double x, double y, double z, out Matrix3d result)
{
result = Identity;
result.Row0.X = x;
result.Row1.Y = y;
result.Row2.Z = z;
}
#endregion
#region Multiply Functions
/// <summary>
/// Multiplies two instances.
/// </summary>
/// <param name="left">The left operand of the multiplication.</param>
/// <param name="right">The right operand of the multiplication.</param>
/// <returns>A new instance that is the result of the multiplication</returns>
public static Matrix3d Mult(Matrix3d left, Matrix3d right)
{
Matrix3d result;
Mult(ref left, ref right, out result);
return result;
}
/// <summary>
/// Multiplies two instances.
/// </summary>
/// <param name="left">The left operand of the multiplication.</param>
/// <param name="right">The right operand of the multiplication.</param>
/// <param name="result">A new instance that is the result of the multiplication</param>
public static void Mult(ref Matrix3d left, ref Matrix3d right, out Matrix3d result)
{
double lM11 = left.Row0.X, lM12 = left.Row0.Y, lM13 = left.Row0.Z,
lM21 = left.Row1.X, lM22 = left.Row1.Y, lM23 = left.Row1.Z,
lM31 = left.Row2.X, lM32 = left.Row2.Y, lM33 = left.Row2.Z,
rM11 = right.Row0.X, rM12 = right.Row0.Y, rM13 = right.Row0.Z,
rM21 = right.Row1.X, rM22 = right.Row1.Y, rM23 = right.Row1.Z,
rM31 = right.Row2.X, rM32 = right.Row2.Y, rM33 = right.Row2.Z;
result.Row0.X = ((lM11 * rM11) + (lM12 * rM21)) + (lM13 * rM31);
result.Row0.Y = ((lM11 * rM12) + (lM12 * rM22)) + (lM13 * rM32);
result.Row0.Z = ((lM11 * rM13) + (lM12 * rM23)) + (lM13 * rM33);
result.Row1.X = ((lM21 * rM11) + (lM22 * rM21)) + (lM23 * rM31);
result.Row1.Y = ((lM21 * rM12) + (lM22 * rM22)) + (lM23 * rM32);
result.Row1.Z = ((lM21 * rM13) + (lM22 * rM23)) + (lM23 * rM33);
result.Row2.X = ((lM31 * rM11) + (lM32 * rM21)) + (lM33 * rM31);
result.Row2.Y = ((lM31 * rM12) + (lM32 * rM22)) + (lM33 * rM32);
result.Row2.Z = ((lM31 * rM13) + (lM32 * rM23)) + (lM33 * rM33);
}
#endregion
#region Invert Functions
/// <summary>
/// Calculate the inverse of the given matrix
/// </summary>
/// <param name="mat">The matrix to invert</param>
/// <param name="result">The inverse of the given matrix if it has one, or the input if it is singular</param>
/// <exception cref="InvalidOperationException">Thrown if the Matrix3d is singular.</exception>
public static void Invert(ref Matrix3d mat, out Matrix3d result)
{
int[] colIdx = { 0, 0, 0 };
int[] rowIdx = { 0, 0, 0 };
int[] pivotIdx = { -1, -1, -1 };
double[,] inverse = {{mat.Row0.X, mat.Row0.Y, mat.Row0.Z},
{mat.Row1.X, mat.Row1.Y, mat.Row1.Z},
{mat.Row2.X, mat.Row2.Y, mat.Row2.Z}};
int icol = 0;
int irow = 0;
for (int i = 0; i < 3; i++)
{
double maxPivot = 0.0;
for (int j = 0; j < 3; j++)
{
if (pivotIdx[j] != 0)
{
for (int k = 0; k < 3; ++k)
{
if (pivotIdx[k] == -1)
{
double absVal = System.Math.Abs(inverse[j, k]);
if (absVal > maxPivot)
{
maxPivot = absVal;
irow = j;
icol = k;
}
}
else if (pivotIdx[k] > 0)
{
result = mat;
return;
}
}
}
}
++(pivotIdx[icol]);
if (irow != icol)
{
for (int k = 0; k < 3; ++k)
{
double f = inverse[irow, k];
inverse[irow, k] = inverse[icol, k];
inverse[icol, k] = f;
}
}
rowIdx[i] = irow;
colIdx[i] = icol;
double pivot = inverse[icol, icol];
if (pivot == 0.0)
{
throw new InvalidOperationException("Matrix is singular and cannot be inverted.");
}
double oneOverPivot = 1.0 / pivot;
inverse[icol, icol] = 1.0;
for (int k = 0; k < 3; ++k)
inverse[icol, k] *= oneOverPivot;
for (int j = 0; j < 3; ++j)
{
if (icol != j)
{
double f = inverse[j, icol];
inverse[j, icol] = 0.0;
for (int k = 0; k < 3; ++k)
inverse[j, k] -= inverse[icol, k] * f;
}
}
}
for (int j = 2; j >= 0; --j)
{
int ir = rowIdx[j];
int ic = colIdx[j];
for (int k = 0; k < 3; ++k)
{
double f = inverse[k, ir];
inverse[k, ir] = inverse[k, ic];
inverse[k, ic] = f;
}
}
result.Row0.X = inverse[0, 0];
result.Row0.Y = inverse[0, 1];
result.Row0.Z = inverse[0, 2];
result.Row1.X = inverse[1, 0];
result.Row1.Y = inverse[1, 1];
result.Row1.Z = inverse[1, 2];
result.Row2.X = inverse[2, 0];
result.Row2.Y = inverse[2, 1];
result.Row2.Z = inverse[2, 2];
}
/// <summary>
/// Calculate the inverse of the given matrix
/// </summary>
/// <param name="mat">The matrix to invert</param>
/// <returns>The inverse of the given matrix if it has one, or the input if it is singular</returns>
/// <exception cref="InvalidOperationException">Thrown if the Matrix4 is singular.</exception>
public static Matrix3d Invert(Matrix3d mat)
{
Matrix3d result;
Invert(ref mat, out result);
return result;
}
#endregion
#region Transpose
/// <summary>
/// Calculate the transpose of the given matrix
/// </summary>
/// <param name="mat">The matrix to transpose</param>
/// <returns>The transpose of the given matrix</returns>
public static Matrix3d Transpose(Matrix3d mat)
{
return new Matrix3d(mat.Column0, mat.Column1, mat.Column2);
}
/// <summary>
/// Calculate the transpose of the given matrix
/// </summary>
/// <param name="mat">The matrix to transpose</param>
/// <param name="result">The result of the calculation</param>
public static void Transpose(ref Matrix3d mat, out Matrix3d result)
{
result.Row0 = mat.Column0;
result.Row1 = mat.Column1;
result.Row2 = mat.Column2;
}
#endregion
#endregion
#region Operators
/// <summary>
/// Matrix multiplication
/// </summary>
/// <param name="left">left-hand operand</param>
/// <param name="right">right-hand operand</param>
/// <returns>A new Matrix3d which holds the result of the multiplication</returns>
public static Matrix3d operator *(Matrix3d left, Matrix3d right)
{
return Matrix3d.Mult(left, right);
}
/// <summary>
/// Compares two instances for equality.
/// </summary>
/// <param name="left">The first instance.</param>
/// <param name="right">The second instance.</param>
/// <returns>True, if left equals right; false otherwise.</returns>
public static bool operator ==(Matrix3d left, Matrix3d right)
{
return left.Equals(right);
}
/// <summary>
/// Compares two instances for inequality.
/// </summary>
/// <param name="left">The first instance.</param>
/// <param name="right">The second instance.</param>
/// <returns>True, if left does not equal right; false otherwise.</returns>
public static bool operator !=(Matrix3d left, Matrix3d right)
{
return !left.Equals(right);
}
#endregion
#region Overrides
#region public override string ToString()
/// <summary>
/// Returns a System.String that represents the current Matrix3d.
/// </summary>
/// <returns>The string representation of the matrix.</returns>
public override string ToString()
{
return String.Format("{0}\n{1}\n{2}", Row0, Row1, Row2);
}
#endregion
#region public override int GetHashCode()
/// <summary>
/// Returns the hashcode for this instance.
/// </summary>
/// <returns>A System.Int32 containing the unique hashcode for this instance.</returns>
public override int GetHashCode()
{
return Row0.GetHashCode() ^ Row1.GetHashCode() ^ Row2.GetHashCode();
}
#endregion
#region public override bool Equals(object obj)
/// <summary>
/// Indicates whether this instance and a specified object are equal.
/// </summary>
/// <param name="obj">The object to compare to.</param>
/// <returns>True if the instances are equal; false otherwise.</returns>
public override bool Equals(object obj)
{
if (!(obj is Matrix3d))
return false;
return this.Equals((Matrix3d)obj);
}
#endregion
#endregion
#endregion
#region IEquatable<Matrix3d> Members
/// <summary>Indicates whether the current matrix is equal to another matrix.</summary>
/// <param name="other">A matrix to compare with this matrix.</param>
/// <returns>true if the current matrix is equal to the matrix parameter; otherwise, false.</returns>
public bool Equals(Matrix3d other)
{
return
Row0 == other.Row0 &&
Row1 == other.Row1 &&
Row2 == other.Row2;
}
#endregion
}
}
| |
#region namespace
using System;
using System.Collections.Generic;
using System.Text;
using System.Web.Security;
using System.Configuration;
using umbraco.BusinessLogic;
using System.Security.Cryptography;
using System.Web.Util;
using System.Collections.Specialized;
using System.Configuration.Provider;
using umbraco.cms.businesslogic;
using umbraco.cms.businesslogic.member;
using System.Security;
using System.Security.Permissions;
using System.Runtime.CompilerServices;
#endregion
namespace umbraco.providers.members
{
/// <summary>
/// Custom Membership Provider for Umbraco Members (User authentication for Frontend applications NOT umbraco CMS)
/// </summary>
public class UmbracoMembershipProvider : MembershipProvider
{
#region Fields
private string m_ApplicationName;
private bool m_EnablePasswordReset;
private bool m_EnablePasswordRetrieval;
private int m_MaxInvalidPasswordAttempts;
private int m_MinRequiredNonAlphanumericCharacters;
private int m_MinRequiredPasswordLength;
private int m_PasswordAttemptWindow;
private MembershipPasswordFormat m_PasswordFormat;
private string m_PasswordStrengthRegularExpression;
private bool m_RequiresQuestionAndAnswer;
private bool m_RequiresUniqueEmail;
private string m_DefaultMemberTypeAlias;
private string m_LockPropertyTypeAlias;
private string m_FailedPasswordAttemptsPropertyTypeAlias;
private string m_ApprovedPropertyTypeAlias;
private string m_CommentPropertyTypeAlias;
private string m_LastLoginPropertyTypeAlias;
private string m_PasswordRetrievalQuestionPropertyTypeAlias;
private string m_PasswordRetrievalAnswerPropertyTypeAlias;
private string m_providerName = Member.UmbracoMemberProviderName;
#endregion
#region Properties
/// <summary>
/// The name of the application using the custom membership provider.
/// </summary>
/// <value></value>
/// <returns>The name of the application using the custom membership provider.</returns>
public override string ApplicationName
{
get
{
return m_ApplicationName;
}
set
{
if (string.IsNullOrEmpty(value))
throw new ProviderException("ApplicationName cannot be empty.");
if (value.Length > 0x100)
throw new ProviderException("Provider application name too long.");
m_ApplicationName = value;
}
}
/// <summary>
/// Indicates whether the membership provider is configured to allow users to reset their passwords.
/// </summary>
/// <value></value>
/// <returns>true if the membership provider supports password reset; otherwise, false. The default is true.</returns>
public override bool EnablePasswordReset
{
get { return m_EnablePasswordReset; }
}
/// <summary>
/// Indicates whether the membership provider is configured to allow users to retrieve their passwords.
/// </summary>
/// <value></value>
/// <returns>true if the membership provider is configured to support password retrieval; otherwise, false. The default is false.</returns>
public override bool EnablePasswordRetrieval
{
get { return m_EnablePasswordRetrieval; }
}
/// <summary>
/// Gets the number of invalid password or password-answer attempts allowed before the membership user is locked out.
/// </summary>
/// <value></value>
/// <returns>The number of invalid password or password-answer attempts allowed before the membership user is locked out.</returns>
public override int MaxInvalidPasswordAttempts
{
get { return m_MaxInvalidPasswordAttempts; }
}
/// <summary>
/// Gets the minimum number of special characters that must be present in a valid password.
/// </summary>
/// <value></value>
/// <returns>The minimum number of special characters that must be present in a valid password.</returns>
public override int MinRequiredNonAlphanumericCharacters
{
get { return m_MinRequiredNonAlphanumericCharacters; }
}
/// <summary>
/// Gets the minimum length required for a password.
/// </summary>
/// <value></value>
/// <returns>The minimum length required for a password. </returns>
public override int MinRequiredPasswordLength
{
get { return m_MinRequiredPasswordLength; }
}
/// <summary>
/// Gets the number of minutes in which a maximum number of invalid password or password-answer attempts are allowed before the membership user is locked out.
/// </summary>
/// <value></value>
/// <returns>The number of minutes in which a maximum number of invalid password or password-answer attempts are allowed before the membership user is locked out.</returns>
public override int PasswordAttemptWindow
{
get { return m_PasswordAttemptWindow; }
}
/// <summary>
/// Gets a value indicating the format for storing passwords in the membership data store.
/// </summary>
/// <value></value>
/// <returns>One of the <see cref="T:System.Web.Security.MembershipPasswordFormat"></see> values indicating the format for storing passwords in the data store.</returns>
public override MembershipPasswordFormat PasswordFormat
{
get { return m_PasswordFormat; }
}
/// <summary>
/// Gets the regular expression used to evaluate a password.
/// </summary>
/// <value></value>
/// <returns>A regular expression used to evaluate a password.</returns>
public override string PasswordStrengthRegularExpression
{
get { return m_PasswordStrengthRegularExpression; }
}
/// <summary>
/// Gets a value indicating whether the membership provider is configured to require the user to answer a password question for password reset and retrieval.
/// </summary>
/// <value></value>
/// <returns>true if a password answer is required for password reset and retrieval; otherwise, false. The default is true.</returns>
public override bool RequiresQuestionAndAnswer
{
get { return m_RequiresQuestionAndAnswer; }
}
/// <summary>
/// Gets a value indicating whether the membership provider is configured to require a unique e-mail address for each user name.
/// </summary>
/// <value></value>
/// <returns>true if the membership provider requires a unique e-mail address; otherwise, false. The default is true.</returns>
public override bool RequiresUniqueEmail
{
get { return m_RequiresUniqueEmail; }
}
#endregion
#region Initialization Method
/// <summary>
/// Initializes the provider.
/// </summary>
/// <param name="name">The friendly name of the provider.</param>
/// <param name="config">A collection of the name/value pairs representing the provider-specific attributes specified in the configuration for this provider.</param>
/// <exception cref="T:System.ArgumentNullException">The name of the provider is null.</exception>
/// <exception cref="T:System.InvalidOperationException">An attempt is made to call
/// <see cref="M:System.Configuration.Provider.ProviderBase.Initialize(System.String,System.Collections.Specialized.NameValueCollection)"></see> on a provider after the provider
/// has already been initialized.</exception>
/// <exception cref="T:System.ArgumentException">The name of the provider has a length of zero.</exception>
public override void Initialize(string name, NameValueCollection config)
{
// Intialize values from web.config
if (config == null) throw new ArgumentNullException("config");
if (string.IsNullOrEmpty(name)) name = "UmbracoMembershipProvider";
// Initialize base provider class
base.Initialize(name, config);
m_providerName = name;
this.m_EnablePasswordRetrieval = SecUtility.GetBooleanValue(config, "enablePasswordRetrieval", false);
this.m_EnablePasswordReset = SecUtility.GetBooleanValue(config, "enablePasswordReset", false);
this.m_RequiresQuestionAndAnswer = SecUtility.GetBooleanValue(config, "requiresQuestionAndAnswer", false);
this.m_RequiresUniqueEmail = SecUtility.GetBooleanValue(config, "requiresUniqueEmail", true);
this.m_MaxInvalidPasswordAttempts = SecUtility.GetIntValue(config, "maxInvalidPasswordAttempts", 5, false, 0);
this.m_PasswordAttemptWindow = SecUtility.GetIntValue(config, "passwordAttemptWindow", 10, false, 0);
this.m_MinRequiredPasswordLength = SecUtility.GetIntValue(config, "minRequiredPasswordLength", 7, true, 0x80);
this.m_MinRequiredNonAlphanumericCharacters = SecUtility.GetIntValue(config, "minRequiredNonalphanumericCharacters", 1, true, 0x80);
this.m_PasswordStrengthRegularExpression = config["passwordStrengthRegularExpression"];
this.m_ApplicationName = config["applicationName"];
if (string.IsNullOrEmpty(this.m_ApplicationName))
this.m_ApplicationName = SecUtility.GetDefaultAppName();
// make sure password format is clear by default.
string str = config["passwordFormat"];
if (str == null) str = "Clear";
switch (str.ToLower())
{
case "clear":
this.m_PasswordFormat = MembershipPasswordFormat.Clear;
break;
case "encrypted":
this.m_PasswordFormat = MembershipPasswordFormat.Encrypted;
break;
case "hashed":
this.m_PasswordFormat = MembershipPasswordFormat.Hashed;
break;
default:
throw new ProviderException("Provider bad password format");
}
if ((this.PasswordFormat == MembershipPasswordFormat.Hashed) && this.EnablePasswordRetrieval)
throw new ProviderException("Provider can not retrieve hashed password");
// test for membertype (if not specified, choose the first member type available)
if (config["defaultMemberTypeAlias"] != null)
m_DefaultMemberTypeAlias = config["defaultMemberTypeAlias"];
else if (MemberType.GetAll.Length == 1)
m_DefaultMemberTypeAlias = MemberType.GetAll[0].Alias;
else
throw new ProviderException("No default MemberType alias is specified in the web.config string. Please add a 'defaultMemberTypeAlias' to the add element in the provider declaration in web.config");
// test for approve status
if (config["umbracoApprovePropertyTypeAlias"] != null)
{
m_ApprovedPropertyTypeAlias = config["umbracoApprovePropertyTypeAlias"];
}
// test for lock attempts
if (config["umbracoLockPropertyTypeAlias"] != null)
{
m_LockPropertyTypeAlias = config["umbracoLockPropertyTypeAlias"];
}
if (config["umbracoFailedPasswordAttemptsPropertyTypeAlias"] != null)
{
m_FailedPasswordAttemptsPropertyTypeAlias = config["umbracoFailedPasswordAttemptsPropertyTypeAlias"];
}
// comment property
if (config["umbracoCommentPropertyTypeAlias"] != null)
{
m_CommentPropertyTypeAlias = config["umbracoCommentPropertyTypeAlias"];
}
// last login date
if (config["umbracoLastLoginPropertyTypeAlias"] != null)
{
m_LastLoginPropertyTypeAlias = config["umbracoLastLoginPropertyTypeAlias"];
}
// password retrieval
if (config["umbracoPasswordRetrievalQuestionPropertyTypeAlias"] != null)
{
m_PasswordRetrievalQuestionPropertyTypeAlias = config["umbracoPasswordRetrievalQuestionPropertyTypeAlias"];
}
if (config["umbracoPasswordRetrievalAnswerPropertyTypeAlias"] != null)
{
m_PasswordRetrievalAnswerPropertyTypeAlias = config["umbracoPasswordRetrievalAnswerPropertyTypeAlias"];
}
}
#endregion
#region Methods
/// <summary>
/// Processes a request to update the password for a membership user.
/// </summary>
/// <param name="username">The user to update the password for.</param>
/// <param name="oldPassword">The current password for the specified user.</param>
/// <param name="newPassword">The new password for the specified user.</param>
/// <returns>
/// true if the password was updated successfully; otherwise, false.
/// </returns>
public override bool ChangePassword(string username, string oldPassword, string newPassword)
{
// in order to support updating passwords from the umbraco core, we can't validate the old password
Member m = Member.GetMemberFromLoginNameAndPassword(username, oldPassword);
if (m == null) return false;
ValidatePasswordEventArgs args = new ValidatePasswordEventArgs(username, newPassword, false);
OnValidatingPassword(args);
if (args.Cancel)
{
if (args.FailureInformation != null)
throw args.FailureInformation;
else
throw new MembershipPasswordException("Change password canceled due to new password validation failure.");
}
string encodedPassword = EncodePassword(newPassword);
m.ChangePassword(encodedPassword);
return (m.Password == encodedPassword) ? true : false;
}
/// <summary>
/// Processes a request to update the password question and answer for a membership user.
/// </summary>
/// <param name="username">The user to change the password question and answer for.</param>
/// <param name="password">The password for the specified user.</param>
/// <param name="newPasswordQuestion">The new password question for the specified user.</param>
/// <param name="newPasswordAnswer">The new password answer for the specified user.</param>
/// <returns>
/// true if the password question and answer are updated successfully; otherwise, false.
/// </returns>
public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer)
{
if (!String.IsNullOrEmpty(m_PasswordRetrievalQuestionPropertyTypeAlias) && !String.IsNullOrEmpty(m_PasswordRetrievalAnswerPropertyTypeAlias))
{
if (ValidateUser(username, password))
{
Member m = Member.GetMemberFromLoginName(username);
if (m != null)
{
UpdateMemberProperty(m, m_PasswordRetrievalQuestionPropertyTypeAlias, newPasswordQuestion);
UpdateMemberProperty(m, m_PasswordRetrievalAnswerPropertyTypeAlias, newPasswordAnswer);
m.Save();
return true;
}
else
{
throw new MembershipPasswordException("The supplied user is not found!");
}
}
else {
throw new MembershipPasswordException("Invalid user/password combo");
}
}
else
{
throw new NotSupportedException("Updating the password Question and Answer is not valid if the properties aren't set in the config file");
}
}
/// <summary>
/// Adds a new membership user to the data source.
/// </summary>
/// <param name="username">The user name for the new user.</param>
/// <param name="password">The password for the new user.</param>
/// <param name="email">The e-mail address for the new user.</param>
/// <param name="passwordQuestion">The password question for the new user.</param>
/// <param name="passwordAnswer">The password answer for the new user</param>
/// <param name="isApproved">Whether or not the new user is approved to be validated.</param>
/// <param name="providerUserKey">The unique identifier from the membership data source for the user.</param>
/// <param name="status">A <see cref="T:System.Web.Security.MembershipCreateStatus"></see> enumeration value indicating whether the user was created successfully.</param>
/// <returns>
/// A <see cref="T:System.Web.Security.MembershipUser"></see> object populated with the information for the newly created user.
/// </returns>
public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion,
string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status)
{
if (Member.GetMemberFromLoginName(username) != null)
status = MembershipCreateStatus.DuplicateUserName;
else if (Member.GetMemberFromEmail(email) != null && RequiresUniqueEmail)
status = MembershipCreateStatus.DuplicateEmail;
else
{
Member m = Member.MakeNew(username, email, MemberType.GetByAlias(m_DefaultMemberTypeAlias), User.GetUser(0));
m.Password = password;
MembershipUser mUser =
ConvertToMembershipUser(m);
// custom fields
if (!String.IsNullOrEmpty(m_PasswordRetrievalQuestionPropertyTypeAlias))
UpdateMemberProperty(m, m_PasswordRetrievalQuestionPropertyTypeAlias, passwordQuestion);
if (!String.IsNullOrEmpty(m_PasswordRetrievalAnswerPropertyTypeAlias))
UpdateMemberProperty(m, m_PasswordRetrievalAnswerPropertyTypeAlias, passwordAnswer);
if (!String.IsNullOrEmpty(m_ApprovedPropertyTypeAlias))
UpdateMemberProperty(m, m_ApprovedPropertyTypeAlias, isApproved);
if (!String.IsNullOrEmpty(m_LastLoginPropertyTypeAlias)) {
mUser.LastActivityDate = DateTime.Now;
UpdateMemberProperty(m, m_LastLoginPropertyTypeAlias, mUser.LastActivityDate);
}
// save
m.Save();
status = MembershipCreateStatus.Success;
return mUser;
}
return null;
}
/// <summary>
/// Removes a user from the membership data source.
/// </summary>
/// <param name="username">The name of the user to delete.</param>
/// <param name="deleteAllRelatedData">true to delete data related to the user from the database; false to leave data related to the user in the database.</param>
/// <returns>
/// true if the user was successfully deleted; otherwise, false.
/// </returns>
public override bool DeleteUser(string username, bool deleteAllRelatedData)
{
Member m = Member.GetMemberFromLoginName(username);
if (m == null) return false;
else
{
m.delete();
return true;
}
}
/// <summary>
/// Gets a collection of membership users where the e-mail address contains the specified e-mail address to match.
/// </summary>
/// <param name="emailToMatch">The e-mail address to search for.</param>
/// <param name="pageIndex">The index of the page of results to return. pageIndex is zero-based.</param>
/// <param name="pageSize">The size of the page of results to return.</param>
/// <param name="totalRecords">The total number of matched users.</param>
/// <returns>
/// A <see cref="T:System.Web.Security.MembershipUserCollection"></see> collection that contains a page of pageSize<see cref="T:System.Web.Security.MembershipUser"></see> objects beginning at the page specified by pageIndex.
/// </returns>
public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords)
{
throw new Exception("The method or operation is not implemented.");
}
/// <summary>
/// Gets a collection of membership users where the user name contains the specified user name to match.
/// </summary>
/// <param name="usernameToMatch">The user name to search for.</param>
/// <param name="pageIndex">The index of the page of results to return. pageIndex is zero-based.</param>
/// <param name="pageSize">The size of the page of results to return.</param>
/// <param name="totalRecords">The total number of matched users.</param>
/// <returns>
/// A <see cref="T:System.Web.Security.MembershipUserCollection"></see> collection that contains a page of pageSize<see cref="T:System.Web.Security.MembershipUser"></see> objects beginning at the page specified by pageIndex.
/// </returns>
public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords)
{
int counter = 0;
int startIndex = pageSize * pageIndex;
int endIndex = startIndex + pageSize - 1;
MembershipUserCollection membersList = new MembershipUserCollection();
Member[] memberArray = Member.GetMemberByName(usernameToMatch, false);
totalRecords = memberArray.Length;
foreach (Member m in memberArray)
{
if (counter >= startIndex)
membersList.Add(ConvertToMembershipUser(m));
if (counter >= endIndex) break;
counter++;
}
return membersList;
}
/// <summary>
/// Gets a collection of all the users in the data source in pages of data.
/// </summary>
/// <param name="pageIndex">The index of the page of results to return. pageIndex is zero-based.</param>
/// <param name="pageSize">The size of the page of results to return.</param>
/// <param name="totalRecords">The total number of matched users.</param>
/// <returns>
/// A <see cref="T:System.Web.Security.MembershipUserCollection"></see> collection that contains a page of pageSize<see cref="T:System.Web.Security.MembershipUser"></see> objects beginning at the page specified by pageIndex.
/// </returns>
public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
{
int counter = 0;
int startIndex = pageSize * pageIndex;
int endIndex = startIndex + pageSize - 1;
MembershipUserCollection membersList = new MembershipUserCollection();
Member[] memberArray = Member.GetAll;
totalRecords = memberArray.Length;
foreach (Member m in memberArray)
{
if (counter >= startIndex)
membersList.Add(ConvertToMembershipUser(m));
if (counter >= endIndex) break;
counter++;
}
return membersList;
}
/// <summary>
/// Gets the number of users currently accessing the application.
/// </summary>
/// <returns>
/// The number of users currently accessing the application.
/// </returns>
public override int GetNumberOfUsersOnline()
{
return Member.CachedMembers().Count;
}
/// <summary>
/// Gets the password for the specified user name from the data source.
/// </summary>
/// <param name="username">The user to retrieve the password for.</param>
/// <param name="answer">The password answer for the user.</param>
/// <returns>
/// The password for the specified user name.
/// </returns>
public override string GetPassword(string username, string answer)
{
if (!EnablePasswordRetrieval)
throw new ProviderException("Password Retrieval Not Enabled.");
if (PasswordFormat == MembershipPasswordFormat.Hashed)
throw new ProviderException("Cannot retrieve Hashed passwords.");
Member m = Member.GetMemberFromLoginName(username);
if (m != null)
{
if (RequiresQuestionAndAnswer)
{
// check if password answer property alias is set
if (!String.IsNullOrEmpty(m_PasswordRetrievalAnswerPropertyTypeAlias))
{
// check if user is locked out
if (!String.IsNullOrEmpty(m_LockPropertyTypeAlias))
{
bool isLockedOut = false;
bool.TryParse(GetMemberProperty(m, m_LockPropertyTypeAlias, true), out isLockedOut);
if (isLockedOut)
{
throw new MembershipPasswordException("The supplied user is locked out");
}
}
// match password answer
if (GetMemberProperty(m, m_PasswordRetrievalAnswerPropertyTypeAlias, false) != answer)
{
throw new MembershipPasswordException("Incorrect password answer");
}
}
else
{
throw new ProviderException("Password retrieval answer property alias is not set! To automatically support password question/answers you'll need to add references to the membertype properties in the 'Member' element in web.config by adding their aliases to the 'umbracoPasswordRetrievalQuestionPropertyTypeAlias' and 'umbracoPasswordRetrievalAnswerPropertyTypeAlias' attributes");
}
}
}
if (m == null)
{
throw new MembershipPasswordException("The supplied user is not found");
}
else
{
return m.Password;
}
}
/// <summary>
/// Gets information from the data source for a user. Provides an option to update the last-activity date/time stamp for the user.
/// </summary>
/// <param name="username">The name of the user to get information for.</param>
/// <param name="userIsOnline">true to update the last-activity date/time stamp for the user; false to return user information without updating the last-activity date/time stamp for the user.</param>
/// <returns>
/// A <see cref="T:System.Web.Security.MembershipUser"></see> object populated with the specified user's information from the data source.
/// </returns>
public override MembershipUser GetUser(string username, bool userIsOnline)
{
if (String.IsNullOrEmpty(username))
return null;
Member m = Member.GetMemberFromLoginName(username);
if (m == null) return null;
else return ConvertToMembershipUser(m);
}
/// <summary>
/// Gets information from the data source for a user based on the unique identifier for the membership user. Provides an option to update the last-activity date/time stamp for the user.
/// </summary>
/// <param name="providerUserKey">The unique identifier for the membership user to get information for.</param>
/// <param name="userIsOnline">true to update the last-activity date/time stamp for the user; false to return user information without updating the last-activity date/time stamp for the user.</param>
/// <returns>
/// A <see cref="T:System.Web.Security.MembershipUser"></see> object populated with the specified user's information from the data source.
/// </returns>
public override MembershipUser GetUser(object providerUserKey, bool userIsOnline)
{
if (String.IsNullOrEmpty(providerUserKey.ToString()))
return null;
Member m = new Member(Convert.ToInt32(providerUserKey));
if (m == null) return null;
else return ConvertToMembershipUser(m);
}
/// <summary>
/// Gets the user name associated with the specified e-mail address.
/// </summary>
/// <param name="email">The e-mail address to search for.</param>
/// <returns>
/// The user name associated with the specified e-mail address. If no match is found, return null.
/// </returns>
public override string GetUserNameByEmail(string email)
{
Member m = Member.GetMemberFromEmail(email);
if (m == null) return null;
else return m.LoginName;
}
/// <summary>
/// Resets a user's password to a new, automatically generated password.
/// </summary>
/// <param name="username">The user to reset the password for.</param>
/// <param name="answer">The password answer for the specified user (not used with Umbraco).</param>
/// <returns>The new password for the specified user.</returns>
public override string ResetPassword(string username, string answer)
{
if (!EnablePasswordReset)
{
throw new NotSupportedException("Password reset is not supported");
}
Member m = Member.GetMemberFromLoginName(username);
if (m == null)
throw new MembershipPasswordException("The supplied user is not found");
else
{
if (RequiresQuestionAndAnswer)
{
// check if password answer property alias is set
if (!String.IsNullOrEmpty(m_PasswordRetrievalAnswerPropertyTypeAlias))
{
// check if user is locked out
if (!String.IsNullOrEmpty(m_LockPropertyTypeAlias))
{
bool isLockedOut = false;
bool.TryParse(GetMemberProperty(m, m_LockPropertyTypeAlias, true), out isLockedOut);
if (isLockedOut)
{
throw new MembershipPasswordException("The supplied user is locked out");
}
}
// match password answer
if (GetMemberProperty(m, m_PasswordRetrievalAnswerPropertyTypeAlias, false) != answer)
{
throw new MembershipPasswordException("Incorrect password answer");
}
}
else
{
throw new ProviderException("Password retrieval answer property alias is not set! To automatically support password question/answers you'll need to add references to the membertype properties in the 'Member' element in web.config by adding their aliases to the 'umbracoPasswordRetrievalQuestionPropertyTypeAlias' and 'umbracoPasswordRetrievalAnswerPropertyTypeAlias' attributes");
}
}
string newPassword = Membership.GeneratePassword(MinRequiredPasswordLength, MinRequiredNonAlphanumericCharacters);
m.Password = newPassword;
return newPassword;
}
}
/// <summary>
/// Clears a lock so that the membership user can be validated.
/// </summary>
/// <param name="userName">The membership user to clear the lock status for.</param>
/// <returns>
/// true if the membership user was successfully unlocked; otherwise, false.
/// </returns>
public override bool UnlockUser(string userName)
{
if (!String.IsNullOrEmpty(m_LockPropertyTypeAlias))
{
Member m = Member.GetMemberFromLoginName(userName);
if (m != null)
{
UpdateMemberProperty(m, m_LockPropertyTypeAlias, false);
return true;
}
else
{
throw new Exception(String.Format("No member with the username '{0}' found", userName));
}
}
else
{
throw new ProviderException("To enable lock/unlocking, you need to add a 'bool' property on your membertype and add the alias of the property in the 'umbracoLockPropertyTypeAlias' attribute of the membership element in the web.config.");
}
}
/// <summary>
/// Updates e-mail and potentially approved status, lock status and comment on a user.
/// Note: To automatically support lock, approve and comments you'll need to add references to the membertype properties in the
/// 'Member' element in web.config by adding their aliases to the 'umbracoApprovePropertyTypeAlias', 'umbracoLockPropertyTypeAlias' and 'umbracoCommentPropertyTypeAlias' attributes
/// </summary>
/// <param name="user">A <see cref="T:System.Web.Security.MembershipUser"></see> object that represents the user to update and the updated information for the user.</param>
public override void UpdateUser(MembershipUser user)
{
Member m = Member.GetMemberFromLoginName(user.UserName);
m.Email = user.Email;
// if supported, update approve status
UpdateMemberProperty(m, m_ApprovedPropertyTypeAlias, user.IsApproved);
// if supported, update lock status
UpdateMemberProperty(m, m_LockPropertyTypeAlias, user.IsLockedOut);
// if supported, update comment
UpdateMemberProperty(m, m_CommentPropertyTypeAlias, user.Comment);
m.Save();
}
private static void UpdateMemberProperty(Member m, string propertyAlias, object propertyValue)
{
if (!String.IsNullOrEmpty(propertyAlias))
{
if (m.getProperty(propertyAlias) != null)
{
m.getProperty(propertyAlias).Value =
propertyValue;
}
}
}
private static string GetMemberProperty(Member m, string propertyAlias, bool isBool)
{
if (!String.IsNullOrEmpty(propertyAlias))
{
if (m.getProperty(propertyAlias) != null &&
m.getProperty(propertyAlias).Value != null)
{
if (isBool)
{
// Umbraco stored true as 1, which means it can be bool.tryParse'd
return m.getProperty(propertyAlias).Value.ToString().Replace("1", "true").Replace("0", "false");
}
else
return m.getProperty(propertyAlias).Value.ToString();
}
}
return null;
}
/// <summary>
/// Verifies that the specified user name and password exist in the data source.
/// </summary>
/// <param name="username">The name of the user to validate.</param>
/// <param name="password">The password for the specified user.</param>
/// <returns>
/// true if the specified username and password are valid; otherwise, false.
/// </returns>
public override bool ValidateUser(string username, string password)
{
Member m = Member.GetMemberFromLoginAndEncodedPassword(username, EncodePassword(password));
if (m != null)
{
// check for lock status. If locked, then set the member property to null
if (!String.IsNullOrEmpty(m_LockPropertyTypeAlias))
{
string lockedStatus = GetMemberProperty(m, m_LockPropertyTypeAlias, true);
if (!String.IsNullOrEmpty(lockedStatus))
{
bool isLocked = false;
if (bool.TryParse(lockedStatus, out isLocked))
{
if (isLocked)
{
m = null;
}
}
}
}
// check for approve status. If not approved, then set the member property to null
if (!CheckApproveStatus(m)) {
m = null;
}
// maybe update login date
if (m != null && !String.IsNullOrEmpty(m_LastLoginPropertyTypeAlias))
{
UpdateMemberProperty(m, m_LastLoginPropertyTypeAlias, DateTime.Now);
}
// maybe reset password attempts
if (m != null && !String.IsNullOrEmpty(m_FailedPasswordAttemptsPropertyTypeAlias))
{
UpdateMemberProperty(m, m_FailedPasswordAttemptsPropertyTypeAlias, 0);
}
// persist data
if (m != null)
m.Save();
}
else if (!String.IsNullOrEmpty(m_LockPropertyTypeAlias)
&& !String.IsNullOrEmpty(m_FailedPasswordAttemptsPropertyTypeAlias))
{
Member updateMemberDataObject = Member.GetMemberFromLoginName(username);
// update fail rate if it's approved
if (updateMemberDataObject != null && CheckApproveStatus(updateMemberDataObject))
{
int failedAttempts = 0;
int.TryParse(GetMemberProperty(updateMemberDataObject, m_FailedPasswordAttemptsPropertyTypeAlias, false), out failedAttempts);
failedAttempts = failedAttempts+1;
UpdateMemberProperty(updateMemberDataObject, m_FailedPasswordAttemptsPropertyTypeAlias, failedAttempts);
// lock user?
if (failedAttempts >= MaxInvalidPasswordAttempts)
{
UpdateMemberProperty(updateMemberDataObject, m_LockPropertyTypeAlias, true);
}
}
}
return (m != null);
}
private bool CheckApproveStatus(Member m)
{
bool isApproved = false;
if (!String.IsNullOrEmpty(m_ApprovedPropertyTypeAlias))
{
if (m != null)
{
string approveStatus = GetMemberProperty(m, m_ApprovedPropertyTypeAlias, true);
if (!String.IsNullOrEmpty(approveStatus))
{
bool.TryParse(approveStatus, out isApproved);
}
}
}
else {
// if we don't use approve statuses
isApproved = true;
}
return isApproved;
}
#endregion
#region Helper Methods
/// <summary>
/// Checks the password.
/// </summary>
/// <param name="password">The password.</param>
/// <param name="dbPassword">The dbPassword.</param>
/// <returns></returns>
internal bool CheckPassword(string password, string dbPassword)
{
string pass1 = password;
string pass2 = dbPassword;
switch (PasswordFormat)
{
case MembershipPasswordFormat.Encrypted:
pass2 = UnEncodePassword(dbPassword);
break;
case MembershipPasswordFormat.Hashed:
pass1 = EncodePassword(password);
break;
default:
break;
}
return (pass1 == pass2) ? true : false;
}
/// <summary>
/// Encodes the password.
/// </summary>
/// <param name="password">The password.</param>
/// <returns>The encoded password.</returns>
public string EncodePassword(string password)
{
string encodedPassword = password;
switch (PasswordFormat)
{
case MembershipPasswordFormat.Clear:
break;
case MembershipPasswordFormat.Encrypted:
encodedPassword =
Convert.ToBase64String(EncryptPassword(Encoding.Unicode.GetBytes(password)));
break;
case MembershipPasswordFormat.Hashed:
HMACSHA1 hash = new HMACSHA1();
hash.Key = Encoding.Unicode.GetBytes(password);
encodedPassword =
Convert.ToBase64String(hash.ComputeHash(Encoding.Unicode.GetBytes(password)));
break;
default:
throw new ProviderException("Unsupported password format.");
}
return encodedPassword;
}
/// <summary>
/// Unencode password.
/// </summary>
/// <param name="encodedPassword">The encoded password.</param>
/// <returns>The unencoded password.</returns>
public string UnEncodePassword(string encodedPassword)
{
string password = encodedPassword;
switch (PasswordFormat)
{
case MembershipPasswordFormat.Clear:
break;
case MembershipPasswordFormat.Encrypted:
password = Encoding.Unicode.GetString(DecryptPassword(Convert.FromBase64String(password)));
break;
case MembershipPasswordFormat.Hashed:
throw new ProviderException("Cannot decrypt a hashed password.");
default:
throw new ProviderException("Unsupported password format.");
}
return password;
}
/// <summary>
/// Converts to membership user.
/// </summary>
/// <param name="m">The m.</param>
/// <returns></returns>
private MembershipUser ConvertToMembershipUser(Member m)
{
if (m == null) return null;
else
{
DateTime lastLogin = DateTime.Now;
bool isApproved = true;
bool isLocked = false;
string comment = "";
string passwordQuestion = "";
// last login
if (!String.IsNullOrEmpty(m_LastLoginPropertyTypeAlias))
{
DateTime.TryParse(GetMemberProperty(m, m_LastLoginPropertyTypeAlias, false), out lastLogin);
}
// approved
if (!String.IsNullOrEmpty(m_ApprovedPropertyTypeAlias))
{
bool.TryParse(GetMemberProperty(m, m_ApprovedPropertyTypeAlias, true), out isApproved);
}
// locked
if (!String.IsNullOrEmpty(m_LockPropertyTypeAlias))
{
bool.TryParse(GetMemberProperty(m, m_LockPropertyTypeAlias, true), out isLocked);
}
// comment
if (!String.IsNullOrEmpty(m_CommentPropertyTypeAlias))
{
comment = GetMemberProperty(m, m_CommentPropertyTypeAlias, false);
}
// password question
if (!String.IsNullOrEmpty(m_PasswordRetrievalQuestionPropertyTypeAlias))
{
passwordQuestion = GetMemberProperty(m, m_PasswordRetrievalQuestionPropertyTypeAlias, false);
}
return new MembershipUser(m_providerName, m.LoginName, m.Id, m.Email, passwordQuestion, comment, isApproved, isLocked, m.CreateDateTime, lastLogin,
DateTime.Now, DateTime.Now, DateTime.Now);
}
}
#endregion
}
}
| |
// 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.OperationalInsights
{
using System.Linq;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// SavedSearchesOperations operations.
/// </summary>
internal partial class SavedSearchesOperations : Microsoft.Rest.IServiceOperations<OperationalInsightsManagementClient>, ISavedSearchesOperations
{
/// <summary>
/// Initializes a new instance of the SavedSearchesOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal SavedSearchesOperations(OperationalInsightsManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the OperationalInsightsManagementClient
/// </summary>
public OperationalInsightsManagementClient Client { get; private set; }
/// <summary>
/// Deletes the specified saved search in a given workspace.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group to get. The name is case insensitive.
/// </param>
/// <param name='workspaceName'>
/// Log Analytics workspace name
/// </param>
/// <param name='savedSearchName'>
/// Name of the saved search.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string workspaceName, string savedSearchName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (resourceGroupName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName");
}
if (resourceGroupName != null)
{
if (resourceGroupName.Length > 90)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.MaxLength, "resourceGroupName", 90);
}
if (resourceGroupName.Length < 1)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.MinLength, "resourceGroupName", 1);
}
if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+$"))
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._\\(\\)]+$");
}
}
if (workspaceName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "workspaceName");
}
if (savedSearchName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "savedSearchName");
}
if (this.Client.SubscriptionId == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2015-03-20";
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("workspaceName", workspaceName);
tracingParameters.Add("savedSearchName", savedSearchName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "Delete", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.OperationalInsights/workspaces/{workspaceName}/savedSearches/{savedSearchName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{workspaceName}", System.Uri.EscapeDataString(workspaceName));
_url = _url.Replace("{savedSearchName}", System.Uri.EscapeDataString(savedSearchName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId));
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("DELETE");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Creates or updates a saved search for a given workspace.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group to get. The name is case insensitive.
/// </param>
/// <param name='workspaceName'>
/// Log Analytics workspace name
/// </param>
/// <param name='savedSearchName'>
/// The id of the saved search.
/// </param>
/// <param name='parameters'>
/// The parameters required to save a search.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<SavedSearch>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string workspaceName, string savedSearchName, SavedSearch parameters, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (resourceGroupName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName");
}
if (resourceGroupName != null)
{
if (resourceGroupName.Length > 90)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.MaxLength, "resourceGroupName", 90);
}
if (resourceGroupName.Length < 1)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.MinLength, "resourceGroupName", 1);
}
if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+$"))
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._\\(\\)]+$");
}
}
if (workspaceName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "workspaceName");
}
if (savedSearchName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "savedSearchName");
}
if (parameters == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "parameters");
}
if (parameters != null)
{
parameters.Validate();
}
if (this.Client.SubscriptionId == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2015-03-20";
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("workspaceName", workspaceName);
tracingParameters.Add("savedSearchName", savedSearchName);
tracingParameters.Add("parameters", parameters);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdate", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.OperationalInsights/workspaces/{workspaceName}/savedSearches/{savedSearchName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{workspaceName}", System.Uri.EscapeDataString(workspaceName));
_url = _url.Replace("{savedSearchName}", System.Uri.EscapeDataString(savedSearchName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId));
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(parameters != null)
{
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, this.Client.SerializationSettings);
_httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse<SavedSearch>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<SavedSearch>(_responseContent, this.Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets the specified saved search for a given workspace.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group to get. The name is case insensitive.
/// </param>
/// <param name='workspaceName'>
/// Log Analytics workspace name
/// </param>
/// <param name='savedSearchName'>
/// The id of the saved search.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<SavedSearch>> GetWithHttpMessagesAsync(string resourceGroupName, string workspaceName, string savedSearchName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (resourceGroupName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName");
}
if (resourceGroupName != null)
{
if (resourceGroupName.Length > 90)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.MaxLength, "resourceGroupName", 90);
}
if (resourceGroupName.Length < 1)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.MinLength, "resourceGroupName", 1);
}
if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+$"))
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._\\(\\)]+$");
}
}
if (workspaceName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "workspaceName");
}
if (savedSearchName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "savedSearchName");
}
if (this.Client.SubscriptionId == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2015-03-20";
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("workspaceName", workspaceName);
tracingParameters.Add("savedSearchName", savedSearchName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.OperationalInsights/workspaces/{workspaceName}/savedSearches/{savedSearchName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{workspaceName}", System.Uri.EscapeDataString(workspaceName));
_url = _url.Replace("{savedSearchName}", System.Uri.EscapeDataString(savedSearchName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId));
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse<SavedSearch>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<SavedSearch>(_responseContent, this.Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets the saved searches for a given Log Analytics Workspace
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group to get. The name is case insensitive.
/// </param>
/// <param name='workspaceName'>
/// Log Analytics workspace name
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<SavedSearchesListResult>> ListByWorkspaceWithHttpMessagesAsync(string resourceGroupName, string workspaceName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (resourceGroupName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName");
}
if (resourceGroupName != null)
{
if (resourceGroupName.Length > 90)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.MaxLength, "resourceGroupName", 90);
}
if (resourceGroupName.Length < 1)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.MinLength, "resourceGroupName", 1);
}
if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+$"))
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._\\(\\)]+$");
}
}
if (workspaceName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "workspaceName");
}
if (this.Client.SubscriptionId == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2015-03-20";
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("workspaceName", workspaceName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "ListByWorkspace", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.OperationalInsights/workspaces/{workspaceName}/savedSearches").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{workspaceName}", System.Uri.EscapeDataString(workspaceName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId));
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse<SavedSearchesListResult>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<SavedSearchesListResult>(_responseContent, this.Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets the results from a saved search for a given workspace.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group to get. The name is case insensitive.
/// </param>
/// <param name='workspaceName'>
/// Log Analytics workspace name
/// </param>
/// <param name='savedSearchName'>
/// The name of the saved search.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<SearchResultsResponse>> GetResultsWithHttpMessagesAsync(string resourceGroupName, string workspaceName, string savedSearchName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (resourceGroupName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName");
}
if (resourceGroupName != null)
{
if (resourceGroupName.Length > 90)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.MaxLength, "resourceGroupName", 90);
}
if (resourceGroupName.Length < 1)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.MinLength, "resourceGroupName", 1);
}
if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+$"))
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._\\(\\)]+$");
}
}
if (workspaceName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "workspaceName");
}
if (savedSearchName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "savedSearchName");
}
if (this.Client.SubscriptionId == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2015-03-20";
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("workspaceName", workspaceName);
tracingParameters.Add("savedSearchName", savedSearchName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "GetResults", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.OperationalInsights/workspaces/{workspaceName}/savedSearches/{savedSearchName}/results").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{workspaceName}", System.Uri.EscapeDataString(workspaceName));
_url = _url.Replace("{savedSearchName}", System.Uri.EscapeDataString(savedSearchName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId));
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse<SearchResultsResponse>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<SearchResultsResponse>(_responseContent, this.Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
// Copyright (c) 2004-2010 Azavea, Inc.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using Azavea.Open.Common.Collections;
using NUnit.Framework;
namespace Azavea.Open.Common.Tests
{
/// <exclude/>
[TestFixture]
public class CollectionTests
{
private readonly IDictionary<string, string> _testOld = new Dictionary<string, string>();
private readonly IDictionary<string, string> _testChecked = new CheckedDictionary<string, string>();
/// <exclude/>
[Test]
public void TestDictionaryAdd()
{
AssertDictionaryException(delegate(IDictionary<string, string> dict)
{
dict.Add(new KeyValuePair<string, string>(null, "two"));
}, new string[] { "null", "key", "two" });
AssertDictionaryException(delegate(IDictionary<string, string> dict)
{
// ReSharper disable AssignNullToNotNullAttribute
// This is sort of the point.
dict.Add(null, "two");
// ReSharper restore AssignNullToNotNullAttribute
}, new string[] { "null", "key", "two" });
AssertDictionaryException(delegate(IDictionary<string, string> dict)
{
dict.Clear();
dict.Add(new KeyValuePair<string, string>("one", "two"));
dict.Add(new KeyValuePair<string, string>("one", "three"));
}, new string[] { "one", "two", "three" });
AssertDictionaryException(delegate(IDictionary<string, string> dict)
{
dict.Clear();
dict.Add("one", "two");
dict.Add("one", "three");
}, new string[] { "one", "two", "three" });
}
/// <exclude/>
[Test]
public void TestDictionaryContains()
{
AssertDictionaryException(delegate(IDictionary<string, string> dict)
{
dict.Contains(new KeyValuePair<string, string>(null, "two"));
}, new string[] { "null", "key", "two" });
AssertDictionaryException(delegate(IDictionary<string, string> dict)
{
// ReSharper disable AssignNullToNotNullAttribute
// This is sort of the point.
dict.ContainsKey(null);
// ReSharper restore AssignNullToNotNullAttribute
}, new string[] { "null", "key" });
AssertDictionaryNoException(delegate(IDictionary<string, string> dict)
{
dict.Contains(new KeyValuePair<string, string>("blah", "two"));
});
AssertDictionaryNoException(delegate(IDictionary<string, string> dict)
{
dict.ContainsKey("blah");
});
}
/// <exclude/>
[Test]
public void TestDictionaryCopyTo()
{
AssertDictionaryException(delegate(IDictionary<string, string> dict)
{
dict.CopyTo(null, 10);
}, new string[] { "10", "null", "array" });
AssertDictionaryException(delegate(IDictionary<string, string> dict)
{
KeyValuePair<string,string>[] arr = new KeyValuePair<string, string>[10];
dict.CopyTo(arr, -1);
}, new string[] { "less", "zero", "array", "-1" });
AssertDictionaryNoException(delegate(IDictionary<string, string> dict)
{
KeyValuePair<string, string>[] arr = new KeyValuePair<string, string>[10];
dict.Clear();
dict.CopyTo(arr, 10);
});
AssertDictionaryException(delegate(IDictionary<string, string> dict)
{
KeyValuePair<string, string>[] arr = new KeyValuePair<string, string>[10];
dict["one"] = "two";
dict.CopyTo(arr, 10);
}, new string[] { "10", "end", "array" });
AssertDictionaryException(delegate(IDictionary<string, string> dict)
{
dict.Clear();
dict["one"] = "two";
dict["two"] = "three";
dict["three"] = "four";
dict["four"] = "five";
KeyValuePair<string, string>[] arr = new KeyValuePair<string, string>[10];
dict.CopyTo(arr, 7);
}, new string[] { "10", "7", "end", "array", "4" });
}
/// <exclude/>
[Test]
public void TestDictionaryRemove()
{
AssertDictionaryException(delegate(IDictionary<string, string> dict)
{
dict.Remove(new KeyValuePair<string, string>(null, "two"));
}, new string[] { "null", "key", "two" });
AssertDictionaryException(delegate(IDictionary<string, string> dict)
{
// ReSharper disable AssignNullToNotNullAttribute
// This is sort of the point.
dict.Remove(null);
// ReSharper restore AssignNullToNotNullAttribute
}, new string[] { "null", "key" });
AssertDictionaryNoException(delegate(IDictionary<string, string> dict)
{
dict.Clear();
dict.Remove(new KeyValuePair<string, string>("blah", "two"));
});
AssertDictionaryNoException(delegate(IDictionary<string, string> dict)
{
dict.Clear();
dict.Remove("blah");
});
}
/// <exclude/>
[Test]
public void TestDictionaryTryGetValue()
{
AssertDictionaryException(delegate(IDictionary<string, string> dict)
{
string value;
// ReSharper disable AssignNullToNotNullAttribute
// This is sort of the point.
dict.TryGetValue(null, out value);
// ReSharper restore AssignNullToNotNullAttribute
}, new string[] { "null", "key" });
AssertDictionaryNoException(delegate(IDictionary<string, string> dict)
{
dict.Clear();
string value;
dict.TryGetValue("notthere", out value);
Assert.IsNull(value, "Value should be set to null now.");
});
}
/// <exclude/>
[Test]
public void TestDictionaryBracketGet()
{
AssertDictionaryException(delegate(IDictionary<string, string> dict)
{
// ReSharper disable AssignNullToNotNullAttribute
// This is sort of the point.
#pragma warning disable 168
string x = dict[null];
#pragma warning restore 168
// ReSharper restore AssignNullToNotNullAttribute
}, new string[] { "null", "key", "get" });
AssertDictionaryException(delegate(IDictionary<string, string> dict)
{
dict.Clear();
dict["two"] = "a";
dict["three"] = "b";
#pragma warning disable 168
string x = dict["one"];
#pragma warning restore 168
}, new string[] { "one", "key", "get", "two", "three" });
}
/// <exclude/>
[Test]
public void TestDictionaryBracketSet()
{
AssertDictionaryException(delegate(IDictionary<string, string> dict)
{
// ReSharper disable AssignNullToNotNullAttribute
// This is sort of the point.
dict[null] = "one";
// ReSharper restore AssignNullToNotNullAttribute
}, new string[] { "null", "key", "set", "one"});
AssertDictionaryNoException(delegate(IDictionary<string, string> dict)
{
dict.Clear();
string value;
dict.TryGetValue("notthere", out value);
Assert.IsNull(value, "Value should be set to null now.");
});
}
private void AssertDictionaryNoException(DictionaryCaller callMe)
{
try
{
callMe.Invoke(_testOld);
}
catch (Exception e)
{
Assert.Fail("Original dictionary threw an exception: " + e);
}
try
{
callMe.Invoke(_testChecked);
}
catch (Exception e)
{
Assert.Fail("Checked dictionary threw an exception: " + e);
}
}
private void AssertDictionaryException(DictionaryCaller callMe, IEnumerable<string> messageComponents)
{
Exception oldEx = null;
try
{
callMe.Invoke(_testOld);
}
catch(Exception e)
{
oldEx = e;
}
Assert.IsNotNull(oldEx, "Original dictionary didn't throw exception.");
Exception newEx = null;
try
{
callMe.Invoke(_testChecked);
}
catch (Exception e)
{
newEx = e;
}
Assert.IsNotNull(newEx, "Checked dictionary didn't throw exception.");
Assert.AreEqual(oldEx.GetType(), newEx.GetType(), "Threw wrong type of exception: " + newEx);
foreach (string component in messageComponents)
{
Assert.Greater(newEx.Message.IndexOf(component), -1, "Message did not contain '" +
component + "'. Exception: " + newEx);
}
Console.WriteLine("Threw correct exception: " + newEx);
}
private delegate void DictionaryCaller(IDictionary<string, string> dict);
}
}
| |
using System;
using ChainUtils.BouncyCastle.Crypto.Parameters;
using ChainUtils.BouncyCastle.Crypto.Utilities;
namespace ChainUtils.BouncyCastle.Crypto.Engines
{
/**
* HC-128 is a software-efficient stream cipher created by Hongjun Wu. It
* generates keystream from a 128-bit secret key and a 128-bit initialization
* vector.
* <p>
* http://www.ecrypt.eu.org/stream/p3ciphers/hc/hc128_p3.pdf
* </p><p>
* It is a third phase candidate in the eStream contest, and is patent-free.
* No attacks are known as of today (April 2007). See
*
* http://www.ecrypt.eu.org/stream/hcp3.html
* </p>
*/
public class HC128Engine
: IStreamCipher
{
private uint[] p = new uint[512];
private uint[] q = new uint[512];
private uint cnt = 0;
private static uint F1(uint x)
{
return RotateRight(x, 7) ^ RotateRight(x, 18) ^ (x >> 3);
}
private static uint F2(uint x)
{
return RotateRight(x, 17) ^ RotateRight(x, 19) ^ (x >> 10);
}
private uint G1(uint x, uint y, uint z)
{
return (RotateRight(x, 10) ^ RotateRight(z, 23)) + RotateRight(y, 8);
}
private uint G2(uint x, uint y, uint z)
{
return (RotateLeft(x, 10) ^ RotateLeft(z, 23)) + RotateLeft(y, 8);
}
private static uint RotateLeft(uint x, int bits)
{
return (x << bits) | (x >> -bits);
}
private static uint RotateRight(uint x, int bits)
{
return (x >> bits) | (x << -bits);
}
private uint H1(uint x)
{
return q[x & 0xFF] + q[((x >> 16) & 0xFF) + 256];
}
private uint H2(uint x)
{
return p[x & 0xFF] + p[((x >> 16) & 0xFF) + 256];
}
private static uint Mod1024(uint x)
{
return x & 0x3FF;
}
private static uint Mod512(uint x)
{
return x & 0x1FF;
}
private static uint Dim(uint x, uint y)
{
return Mod512(x - y);
}
private uint Step()
{
var j = Mod512(cnt);
uint ret;
if (cnt < 512)
{
p[j] += G1(p[Dim(j, 3)], p[Dim(j, 10)], p[Dim(j, 511)]);
ret = H1(p[Dim(j, 12)]) ^ p[j];
}
else
{
q[j] += G2(q[Dim(j, 3)], q[Dim(j, 10)], q[Dim(j, 511)]);
ret = H2(q[Dim(j, 12)]) ^ q[j];
}
cnt = Mod1024(cnt + 1);
return ret;
}
private byte[] key, iv;
private bool initialised;
private void Init()
{
if (key.Length != 16)
throw new ArgumentException("The key must be 128 bits long");
cnt = 0;
var w = new uint[1280];
for (var i = 0; i < 16; i++)
{
w[i >> 2] |= ((uint)key[i] << (8 * (i & 0x3)));
}
Array.Copy(w, 0, w, 4, 4);
for (var i = 0; i < iv.Length && i < 16; i++)
{
w[(i >> 2) + 8] |= ((uint)iv[i] << (8 * (i & 0x3)));
}
Array.Copy(w, 8, w, 12, 4);
for (uint i = 16; i < 1280; i++)
{
w[i] = F2(w[i - 2]) + w[i - 7] + F1(w[i - 15]) + w[i - 16] + i;
}
Array.Copy(w, 256, p, 0, 512);
Array.Copy(w, 768, q, 0, 512);
for (var i = 0; i < 512; i++)
{
p[i] = Step();
}
for (var i = 0; i < 512; i++)
{
q[i] = Step();
}
cnt = 0;
}
public string AlgorithmName
{
get { return "HC-128"; }
}
/**
* Initialise a HC-128 cipher.
*
* @param forEncryption whether or not we are for encryption. Irrelevant, as
* encryption and decryption are the same.
* @param params the parameters required to set up the cipher.
* @throws ArgumentException if the params argument is
* inappropriate (ie. the key is not 128 bit long).
*/
public void Init(
bool forEncryption,
ICipherParameters parameters)
{
var keyParam = parameters;
if (parameters is ParametersWithIV)
{
iv = ((ParametersWithIV)parameters).GetIV();
keyParam = ((ParametersWithIV)parameters).Parameters;
}
else
{
iv = new byte[0];
}
if (keyParam is KeyParameter)
{
key = ((KeyParameter)keyParam).GetKey();
Init();
}
else
{
throw new ArgumentException(
"Invalid parameter passed to HC128 init - " + parameters.GetType().Name,
"parameters");
}
initialised = true;
}
private byte[] buf = new byte[4];
private int idx = 0;
private byte GetByte()
{
if (idx == 0)
{
Pack.UInt32_To_LE(Step(), buf);
}
var ret = buf[idx];
idx = idx + 1 & 0x3;
return ret;
}
public void ProcessBytes(
byte[] input,
int inOff,
int len,
byte[] output,
int outOff)
{
if (!initialised)
throw new InvalidOperationException(AlgorithmName + " not initialised");
if ((inOff + len) > input.Length)
throw new DataLengthException("input buffer too short");
if ((outOff + len) > output.Length)
throw new DataLengthException("output buffer too short");
for (var i = 0; i < len; i++)
{
output[outOff + i] = (byte)(input[inOff + i] ^ GetByte());
}
}
public void Reset()
{
idx = 0;
Init();
}
public byte ReturnByte(byte input)
{
return (byte)(input ^ GetByte());
}
}
}
| |
using System;
using System.Numerics;
namespace Nethereum.Util
{
public class UnitConversion
{
public enum EthUnit
{
Wei,
Kwei,
Ada,
Femtoether,
Mwei,
Babbage,
Picoether,
Gwei,
Shannon,
Nanoether,
Nano,
Szabo,
Microether,
Micro,
Finney,
Milliether,
Milli,
Ether,
Kether,
Grand,
Einstein,
Mether,
Gether,
Tether
}
private static UnitConversion _convert;
public static UnitConversion Convert
{
get
{
if (_convert == null) _convert = new UnitConversion();
return _convert;
}
}
/// <summary>
/// Converts from wei to a unit, NOTE: When the total number of digits is bigger than 29 they will be rounded the less
/// significant digits
/// </summary>
public decimal FromWei(BigInteger value, BigInteger toUnit)
{
return FromWei(value, GetEthUnitValueLength(toUnit));
}
/// <summary>
/// Converts from wei to a unit, NOTE: When the total number of digits is bigger than 29 they will be rounded the less
/// significant digits
/// </summary>
public decimal FromWei(BigInteger value, EthUnit toUnit = EthUnit.Ether)
{
return FromWei(value, GetEthUnitValue(toUnit));
}
/// <summary>
/// Converts from wei to a unit, NOTE: When the total number of digits is bigger than 29 they will be rounded the less
/// significant digits
/// </summary>
public decimal FromWei(BigInteger value, int decimalPlacesToUnit)
{
return (decimal) new BigDecimal(value, decimalPlacesToUnit * -1);
}
public BigDecimal FromWeiToBigDecimal(BigInteger value, int decimalPlacesToUnit)
{
return new BigDecimal(value, decimalPlacesToUnit * -1);
}
public BigDecimal FromWeiToBigDecimal(BigInteger value, EthUnit toUnit = EthUnit.Ether)
{
return FromWeiToBigDecimal(value, GetEthUnitValue(toUnit));
}
public BigDecimal FromWeiToBigDecimal(BigInteger value, BigInteger toUnit)
{
return FromWeiToBigDecimal(value, GetEthUnitValueLength(toUnit));
}
private int GetEthUnitValueLength(BigInteger unitValue)
{
return unitValue.ToStringInvariant().Length - 1;
}
public BigInteger GetEthUnitValue(EthUnit ethUnit)
{
switch (ethUnit)
{
case EthUnit.Wei:
return BigIntegerExtensions.ParseInvariant("1");
case EthUnit.Kwei:
return BigIntegerExtensions.ParseInvariant("1000");
case EthUnit.Babbage:
return BigIntegerExtensions.ParseInvariant("1000");
case EthUnit.Femtoether:
return BigIntegerExtensions.ParseInvariant("1000");
case EthUnit.Mwei:
return BigIntegerExtensions.ParseInvariant("1000000");
case EthUnit.Picoether:
return BigIntegerExtensions.ParseInvariant("1000000");
case EthUnit.Gwei:
return BigIntegerExtensions.ParseInvariant("1000000000");
case EthUnit.Shannon:
return BigIntegerExtensions.ParseInvariant("1000000000");
case EthUnit.Nanoether:
return BigIntegerExtensions.ParseInvariant("1000000000");
case EthUnit.Nano:
return BigIntegerExtensions.ParseInvariant("1000000000");
case EthUnit.Szabo:
return BigIntegerExtensions.ParseInvariant("1000000000000");
case EthUnit.Microether:
return BigIntegerExtensions.ParseInvariant("1000000000000");
case EthUnit.Micro:
return BigIntegerExtensions.ParseInvariant("1000000000000");
case EthUnit.Finney:
return BigIntegerExtensions.ParseInvariant("1000000000000000");
case EthUnit.Milliether:
return BigIntegerExtensions.ParseInvariant("1000000000000000");
case EthUnit.Milli:
return BigIntegerExtensions.ParseInvariant("1000000000000000");
case EthUnit.Ether:
return BigIntegerExtensions.ParseInvariant("1000000000000000000");
case EthUnit.Kether:
return BigIntegerExtensions.ParseInvariant("1000000000000000000000");
case EthUnit.Grand:
return BigIntegerExtensions.ParseInvariant("1000000000000000000000");
case EthUnit.Einstein:
return BigIntegerExtensions.ParseInvariant("1000000000000000000000");
case EthUnit.Mether:
return BigIntegerExtensions.ParseInvariant("1000000000000000000000000");
case EthUnit.Gether:
return BigIntegerExtensions.ParseInvariant("1000000000000000000000000000");
case EthUnit.Tether:
return BigIntegerExtensions.ParseInvariant("1000000000000000000000000000000");
}
throw new NotImplementedException();
}
public bool TryValidateUnitValue(BigInteger ethUnit)
{
if (ethUnit.ToStringInvariant().Trim('0') == "1") return true;
throw new Exception("Invalid unit value, it should be a power of 10 ");
}
public BigInteger ToWeiFromUnit(decimal amount, BigInteger fromUnit)
{
return ToWeiFromUnit((BigDecimal) amount, fromUnit);
}
public BigInteger ToWeiFromUnit(BigDecimal amount, BigInteger fromUnit)
{
TryValidateUnitValue(fromUnit);
var bigDecimalFromUnit = new BigDecimal(fromUnit, 0);
var conversion = amount * bigDecimalFromUnit;
return conversion.Floor().Mantissa;
}
public BigInteger ToWei(BigDecimal amount, EthUnit fromUnit = EthUnit.Ether)
{
return ToWeiFromUnit(amount, GetEthUnitValue(fromUnit));
}
public BigInteger ToWei(BigDecimal amount, int decimalPlacesFromUnit)
{
if (decimalPlacesFromUnit == 0) ToWei(amount, 1);
return ToWeiFromUnit(amount, BigInteger.Pow(10, decimalPlacesFromUnit));
}
public BigInteger ToWei(decimal amount, int decimalPlacesFromUnit)
{
if (decimalPlacesFromUnit == 0) ToWei(amount, 1);
return ToWeiFromUnit(amount, BigInteger.Pow(10, decimalPlacesFromUnit));
}
public BigInteger ToWei(decimal amount, EthUnit fromUnit = EthUnit.Ether)
{
return ToWeiFromUnit(amount, GetEthUnitValue(fromUnit));
}
public BigInteger ToWei(BigInteger value, EthUnit fromUnit = EthUnit.Ether)
{
return value * GetEthUnitValue(fromUnit);
}
public BigInteger ToWei(int value, EthUnit fromUnit = EthUnit.Ether)
{
return ToWei(new BigInteger(value), fromUnit);
}
public BigInteger ToWei(double value, EthUnit fromUnit = EthUnit.Ether)
{
return ToWei(System.Convert.ToDecimal(value), fromUnit);
}
public BigInteger ToWei(float value, EthUnit fromUnit = EthUnit.Ether)
{
return ToWei(System.Convert.ToDecimal(value), fromUnit);
}
public BigInteger ToWei(long value, EthUnit fromUnit = EthUnit.Ether)
{
return ToWei(new BigInteger(value), fromUnit);
}
public BigInteger ToWei(string value, EthUnit fromUnit = EthUnit.Ether)
{
return ToWei(decimal.Parse(value), fromUnit);
}
private BigInteger CalculateNumberOfDecimalPlaces(double value, int maxNumberOfDecimals,
int currentNumberOfDecimals = 0)
{
return CalculateNumberOfDecimalPlaces(System.Convert.ToDecimal(value), maxNumberOfDecimals,
currentNumberOfDecimals);
}
private BigInteger CalculateNumberOfDecimalPlaces(float value, int maxNumberOfDecimals,
int currentNumberOfDecimals = 0)
{
return CalculateNumberOfDecimalPlaces(System.Convert.ToDecimal(value), maxNumberOfDecimals,
currentNumberOfDecimals);
}
private int CalculateNumberOfDecimalPlaces(decimal value, int maxNumberOfDecimals,
int currentNumberOfDecimals = 0)
{
if (currentNumberOfDecimals == 0)
{
if (value.ToStringInvariant() == Math.Round(value).ToStringInvariant()) return 0;
currentNumberOfDecimals = 1;
}
if (currentNumberOfDecimals == maxNumberOfDecimals) return maxNumberOfDecimals;
var multiplied = value * (decimal) BigInteger.Pow(10, currentNumberOfDecimals);
if (Math.Round(multiplied) == multiplied)
return currentNumberOfDecimals;
return CalculateNumberOfDecimalPlaces(value, maxNumberOfDecimals, currentNumberOfDecimals + 1);
}
//public BigInteger ToWei(decimal amount, BigInteger fromUnit)
//{
//var maxDigits = fromUnit.ToStringInvariant().Length - 1;
//var stringAmount = amount.ToStringInvariant("#.#############################", System.Globalization.CultureInfo.InvariantCulture);
//if (stringAmount.IndexOf(".") == -1)
//{
// return BigIntegerExtensions.ParseInvariant(stringAmount) * fromUnit;
//}
//stringAmount = stringAmount.TrimEnd('0');
//var decimalPosition = stringAmount.IndexOf('.');
//var decimalPlaces = decimalPosition == -1 ? 0 : stringAmount.Length - decimalPosition - 1;
//if (decimalPlaces > maxDigits)
//{
// return BigIntegerExtensions.ParseInvariant(stringAmount.Substring(0, decimalPosition) + stringAmount.Substring(decimalPosition + 1, maxDigits));
//}
//return BigIntegerExtensions.ParseInvariant(stringAmount.Substring(0, decimalPosition) + stringAmount.Substring(decimalPosition + 1).PadRight(maxDigits, '0'));
//}
}
}
| |
//
// SourceView.cs
//
// Author:
// Aaron Bockover <abockover@novell.com>
//
// Copyright (C) 2005-2008 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Linq;
using System.Collections.Generic;
using Gtk;
using Cairo;
using Mono.Unix;
using Hyena;
using Hyena.Gui;
using Hyena.Gui.Theming;
using Hyena.Gui.Theatrics;
using Banshee.Configuration;
using Banshee.ServiceStack;
using Banshee.Sources;
using Banshee.Playlist;
using Banshee.Gui;
namespace Banshee.Sources.Gui
{
// Note: This is a partial class - the drag and drop code is split
// out into a separate file to make this class more manageable.
// See SourceView_DragAndDrop.cs for the DnD code.
public partial class SourceView : TreeView
{
private SourceRowRenderer renderer;
private Theme theme;
private Cairo.Context cr;
private Stage<TreeIter> notify_stage = new Stage<TreeIter> (2000);
private TreeViewColumn focus_column;
private TreeIter highlight_iter = TreeIter.Zero;
private SourceModel store;
private int current_timeout = -1;
private bool editing_row = false;
private bool need_resort = false;
protected SourceView (IntPtr ptr) : base (ptr) {}
public SourceView ()
{
BuildColumns ();
store = new SourceModel ();
store.SourceRowInserted += OnSourceRowInserted;
store.SourceRowRemoved += OnSourceRowRemoved;
store.RowChanged += OnRowChanged;
Model = store;
EnableSearch = false;
ConfigureDragAndDrop ();
store.Refresh ();
ConnectEvents ();
RowSeparatorFunc = RowSeparatorHandler;
ResetSelection ();
}
#region Setup Methods
private void BuildColumns ()
{
// Hidden expander column
TreeViewColumn col = new TreeViewColumn ();
col.Visible = false;
AppendColumn (col);
ExpanderColumn = col;
focus_column = new TreeViewColumn ();
renderer = new SourceRowRenderer ();
renderer.RowHeight = RowHeight.Get ();
renderer.Padding = RowPadding.Get ();
focus_column.PackStart (renderer, true);
focus_column.SetCellDataFunc (renderer, new CellLayoutDataFunc (SourceRowRenderer.CellDataHandler));
AppendColumn (focus_column);
HeadersVisible = false;
}
private void ConnectEvents ()
{
ServiceManager.SourceManager.ActiveSourceChanged += delegate (SourceEventArgs args) {
ThreadAssist.ProxyToMain (ResetSelection);
};
ServiceManager.SourceManager.SourceUpdated += delegate (SourceEventArgs args) {
ThreadAssist.ProxyToMain (delegate {
lock (args.Source) {
TreeIter iter = store.FindSource (args.Source);
if (!TreeIter.Zero.Equals (iter)) {
if (args.Source.Expanded) {
Expand (args.Source);
}
need_resort = true;
QueueDraw ();
}
}
});
};
ServiceManager.PlaybackController.NextSourceChanged += delegate {
ThreadAssist.ProxyToMain (QueueDraw);
};
notify_stage.ActorStep += delegate (Actor<TreeIter> actor) {
ThreadAssist.AssertInMainThread ();
if (!store.IterIsValid (actor.Target)) {
return false;
}
using (var path = store.GetPath (actor.Target) ) {
Gdk.Rectangle rect = GetBackgroundArea (path, focus_column);
QueueDrawArea (rect.X, rect.Y, rect.Width, rect.Height);
}
return true;
};
ServiceManager.Get<InterfaceActionService> ().SourceActions["OpenSourceSwitcher"].Activated += delegate {
new SourceSwitcherEntry (this);
};
}
#endregion
#region Gtk.Widget Overrides
protected override void OnStyleSet (Style old_style)
{
base.OnStyleSet (old_style);
theme = Hyena.Gui.Theming.ThemeEngine.CreateTheme (this);
}
protected override bool OnButtonPressEvent (Gdk.EventButton press)
{
TreePath path;
TreeViewColumn column;
if (press.Button == 1) {
ResetHighlight ();
}
// If there is not a row at the click position let the base handler take care of the press
if (!GetPathAtPos ((int)press.X, (int)press.Y, out path, out column)) {
return base.OnButtonPressEvent (press);
}
Source source = store.GetSource (path);
// From F-Spot's SaneTreeView class
int expander_size = (int)StyleGetProperty ("expander-size");
int horizontal_separator = (int)StyleGetProperty ("horizontal-separator");
bool on_expander = press.X <= horizontal_separator * 2 + path.Depth * expander_size;
if (on_expander) {
bool ret = base.OnButtonPressEvent (press);
// If the active source is a child of this source, and we are about to collapse it, switch
// the active source to the parent.
if (source == ServiceManager.SourceManager.ActiveSource.Parent && GetRowExpanded (path)) {
ServiceManager.SourceManager.SetActiveSource (source);
}
return ret;
}
// For Sources that can't be activated, when they're clicked just
// expand or collapse them and return.
if (press.Button == 1 && !source.CanActivate) {
if (!source.Expanded) {
ExpandRow (path, false);
} else {
CollapseRow (path);
}
return false;
}
if (press.Button == 3) {
TreeIter iter;
if (Model.GetIter (out iter, path)) {
HighlightIter (iter);
OnPopupMenu ();
return true;
}
}
if (!source.CanActivate) {
return false;
}
if (press.Button == 1) {
if (ServiceManager.SourceManager.ActiveSource != source) {
ServiceManager.SourceManager.SetActiveSource (source);
}
}
if ((press.State & Gdk.ModifierType.ControlMask) != 0) {
if (press.Type == Gdk.EventType.TwoButtonPress && press.Button == 1) {
ActivateRow (path, null);
}
return true;
}
return base.OnButtonPressEvent (press);
}
protected override bool OnPopupMenu ()
{
ServiceManager.Get<InterfaceActionService> ().SourceActions["SourceContextMenuAction"].Activate ();
return true;
}
protected override bool OnExposeEvent (Gdk.EventExpose evnt)
{
if (need_resort) {
need_resort = false;
// Resort the tree store. This is performed in an event handler
// known not to conflict with gtk_tree_view_bin_expose() to prevent
// errors about corrupting the TreeView's internal state.
foreach (Source dsource in ServiceManager.SourceManager.Sources) {
TreeIter iter = store.FindSource (dsource);
if (!TreeIter.Zero.Equals (iter) && (int)store.GetValue (iter, 1) != dsource.Order) {
store.SetValue (iter, 1, dsource.Order);
}
}
QueueDraw ();
}
try {
cr = Gdk.CairoHelper.Create (evnt.Window);
base.OnExposeEvent (evnt);
if (Hyena.PlatformDetection.IsMeeGo) {
theme.DrawFrameBorder (cr, new Gdk.Rectangle (0, 0,
Allocation.Width, Allocation.Height));
}
return true;
} finally {
CairoExtensions.DisposeContext (cr);
cr = null;
}
}
#endregion
#region Gtk.TreeView Overrides
protected override void OnRowExpanded (TreeIter iter, TreePath path)
{
base.OnRowExpanded (iter, path);
store.GetSource (iter).Expanded = true;
}
protected override void OnRowCollapsed (TreeIter iter, TreePath path)
{
base.OnRowCollapsed (iter, path);
store.GetSource (iter).Expanded = false;
}
protected override void OnCursorChanged ()
{
if (current_timeout < 0) {
current_timeout = (int)GLib.Timeout.Add (200, OnCursorChangedTimeout);
}
}
private bool OnCursorChangedTimeout ()
{
TreeIter iter;
TreeModel model;
current_timeout = -1;
if (!Selection.GetSelected (out model, out iter)) {
return false;
}
Source new_source = store.GetValue (iter, 0) as Source;
if (ServiceManager.SourceManager.ActiveSource == new_source) {
return false;
}
ServiceManager.SourceManager.SetActiveSource (new_source);
QueueDraw ();
return false;
}
private bool RowSeparatorHandler (TreeModel model, TreeIter iter)
{
return (bool)store.GetValue (iter, 2);
}
#endregion
#region Add/Remove Sources / SourceManager interaction
private void OnSourceRowInserted (object o, SourceRowEventArgs args)
{
args.Source.UserNotifyUpdated += OnSourceUserNotifyUpdated;
if (args.Source.Parent != null && args.Source.Parent.AutoExpand == true) {
Expand (args.ParentIter);
}
if (args.Source.Expanded || args.Source.AutoExpand == true) {
Expand (args.Iter);
}
UpdateView ();
}
private void OnSourceRowRemoved (object o, SourceRowEventArgs args)
{
args.Source.UserNotifyUpdated -= OnSourceUserNotifyUpdated;
UpdateView ();
}
private void OnRowChanged (object o, RowChangedArgs args)
{
QueueDraw ();
}
internal void Expand (Source src)
{
Expand (store.FindSource (src));
src.Expanded = true;
}
private void Expand (TreeIter iter)
{
using (var path = store.GetPath (iter)) {
ExpandRow (path, true);
}
}
private void OnSourceUserNotifyUpdated (object o, EventArgs args)
{
ThreadAssist.ProxyToMain (delegate {
TreeIter iter = store.FindSource ((Source)o);
if (iter.Equals (TreeIter.Zero)) {
return;
}
notify_stage.AddOrReset (iter);
});
}
#endregion
#region List/View Utility Methods
private bool UpdateView ()
{
for (int i = 0, m = store.IterNChildren (); i < m; i++) {
TreeIter iter = TreeIter.Zero;
if (!store.IterNthChild (out iter, i)) {
continue;
}
if (store.IterNChildren (iter) > 0) {
ExpanderColumn = Columns[1];
return true;
}
}
ExpanderColumn = Columns[0];
return false;
}
internal void UpdateRow (TreePath path, string text)
{
TreeIter iter;
if (!store.GetIter (out iter, path)) {
return;
}
Source source = store.GetValue (iter, 0) as Source;
source.Rename (text);
}
public void BeginRenameSource (Source source)
{
TreeIter iter = store.FindSource (source);
if (iter.Equals (TreeIter.Zero)) {
return;
}
renderer.Editable = true;
using (var path = store.GetPath (iter)) {
SetCursor (path, focus_column, true);
}
renderer.Editable = false;
}
private void ResetSelection ()
{
TreeIter iter = store.FindSource (ServiceManager.SourceManager.ActiveSource);
if (!iter.Equals (TreeIter.Zero)){
Selection.SelectIter (iter);
}
}
public void HighlightIter (TreeIter iter)
{
highlight_iter = iter;
QueueDraw ();
}
public void ResetHighlight ()
{
highlight_iter = TreeIter.Zero;
QueueDraw ();
}
#endregion
#region Public Properties
public Source HighlightedSource {
get {
if (TreeIter.Zero.Equals (highlight_iter)) {
return null;
}
return store.GetValue (highlight_iter, 0) as Source;
}
}
public bool EditingRow {
get { return editing_row; }
set {
editing_row = value;
QueueDraw ();
}
}
#endregion
#region Internal Properties
internal TreeIter HighlightedIter {
get { return highlight_iter; }
}
internal Cairo.Context Cr {
get { return cr; }
}
internal Theme Theme {
get { return theme; }
}
internal Stage<TreeIter> NotifyStage {
get { return notify_stage; }
}
internal Source NewPlaylistSource {
get {
return new_playlist_source ??
(new_playlist_source = new PlaylistSource (Catalog.GetString ("New Playlist"),
ServiceManager.SourceManager.MusicLibrary));
}
}
#endregion
#region Property Schemas
private static SchemaEntry<int> RowHeight = new SchemaEntry<int> (
"player_window", "source_view_row_height", 22, "The height of each source row in the SourceView. 22 is the default.", "");
private static SchemaEntry<int> RowPadding = new SchemaEntry<int> (
"player_window", "source_view_row_padding", 5, "The padding between sources in the SourceView. 5 is the default.", "");
#endregion
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.Compute.V1.Snippets
{
using Google.Api.Gax;
using System;
using System.Linq;
using System.Threading.Tasks;
/// <summary>Generated snippets.</summary>
public sealed class AllGeneratedRegionsClientSnippets
{
/// <summary>Snippet for Get</summary>
public void GetRequestObject()
{
// Snippet: Get(GetRegionRequest, CallSettings)
// Create client
RegionsClient regionsClient = RegionsClient.Create();
// Initialize request argument(s)
GetRegionRequest request = new GetRegionRequest
{
Region = "",
Project = "",
};
// Make the request
Region response = regionsClient.Get(request);
// End snippet
}
/// <summary>Snippet for GetAsync</summary>
public async Task GetRequestObjectAsync()
{
// Snippet: GetAsync(GetRegionRequest, CallSettings)
// Additional: GetAsync(GetRegionRequest, CancellationToken)
// Create client
RegionsClient regionsClient = await RegionsClient.CreateAsync();
// Initialize request argument(s)
GetRegionRequest request = new GetRegionRequest
{
Region = "",
Project = "",
};
// Make the request
Region response = await regionsClient.GetAsync(request);
// End snippet
}
/// <summary>Snippet for Get</summary>
public void Get()
{
// Snippet: Get(string, string, CallSettings)
// Create client
RegionsClient regionsClient = RegionsClient.Create();
// Initialize request argument(s)
string project = "";
string region = "";
// Make the request
Region response = regionsClient.Get(project, region);
// End snippet
}
/// <summary>Snippet for GetAsync</summary>
public async Task GetAsync()
{
// Snippet: GetAsync(string, string, CallSettings)
// Additional: GetAsync(string, string, CancellationToken)
// Create client
RegionsClient regionsClient = await RegionsClient.CreateAsync();
// Initialize request argument(s)
string project = "";
string region = "";
// Make the request
Region response = await regionsClient.GetAsync(project, region);
// End snippet
}
/// <summary>Snippet for List</summary>
public void ListRequestObject()
{
// Snippet: List(ListRegionsRequest, CallSettings)
// Create client
RegionsClient regionsClient = RegionsClient.Create();
// Initialize request argument(s)
ListRegionsRequest request = new ListRegionsRequest
{
OrderBy = "",
Project = "",
Filter = "",
ReturnPartialSuccess = false,
};
// Make the request
PagedEnumerable<RegionList, Region> response = regionsClient.List(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (Region item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (RegionList page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Region item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Region> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Region item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListAsync</summary>
public async Task ListRequestObjectAsync()
{
// Snippet: ListAsync(ListRegionsRequest, CallSettings)
// Create client
RegionsClient regionsClient = await RegionsClient.CreateAsync();
// Initialize request argument(s)
ListRegionsRequest request = new ListRegionsRequest
{
OrderBy = "",
Project = "",
Filter = "",
ReturnPartialSuccess = false,
};
// Make the request
PagedAsyncEnumerable<RegionList, Region> response = regionsClient.ListAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Region item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((RegionList page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Region item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Region> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Region item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for List</summary>
public void List()
{
// Snippet: List(string, string, int?, CallSettings)
// Create client
RegionsClient regionsClient = RegionsClient.Create();
// Initialize request argument(s)
string project = "";
// Make the request
PagedEnumerable<RegionList, Region> response = regionsClient.List(project);
// Iterate over all response items, lazily performing RPCs as required
foreach (Region item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (RegionList page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Region item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Region> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Region item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListAsync</summary>
public async Task ListAsync()
{
// Snippet: ListAsync(string, string, int?, CallSettings)
// Create client
RegionsClient regionsClient = await RegionsClient.CreateAsync();
// Initialize request argument(s)
string project = "";
// Make the request
PagedAsyncEnumerable<RegionList, Region> response = regionsClient.ListAsync(project);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Region item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((RegionList page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Region item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Region> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Region item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
}
}
| |
// Copyright (c) 2009 DotNetAnywhere
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.CompilerServices;
namespace System.Net.Sockets {
public class Socket : IDisposable {
#region Internal Methods
[MethodImpl(MethodImplOptions.InternalCall)]
extern private static IntPtr Internal_CreateSocket(int family, int type, int proto, out int error);
[MethodImpl(MethodImplOptions.InternalCall)]
extern private static void Internal_Close(IntPtr native);
[MethodImpl(MethodImplOptions.InternalCall)]
extern private static void Internal_Bind(IntPtr native, uint address, int port, out int error);
[MethodImpl(MethodImplOptions.InternalCall)]
extern private static void Internal_Listen(IntPtr native, int backLog, out int error);
[MethodImpl(MethodImplOptions.InternalCall)]
extern private static IntPtr Internal_Accept(IntPtr native, out int error);
[MethodImpl(MethodImplOptions.InternalCall)]
extern private static void Internal_Connect(IntPtr native, uint address, int port, out int error);
[MethodImpl(MethodImplOptions.InternalCall)]
extern private static int Internal_Receive(IntPtr native, byte[] buffer, int offset, int size, int flags, out int error);
[MethodImpl(MethodImplOptions.InternalCall)]
extern private static int Internal_Send(IntPtr native, byte[] buffer, int offset, int size, int flags, out int error);
#endregion
private IntPtr native;
private AddressFamily family;
private SocketType type;
private ProtocolType proto;
public Socket(AddressFamily family, SocketType type, ProtocolType proto) {
this.family = family;
this.type = type;
this.proto = proto;
int error;
this.native = Internal_CreateSocket((int)family, (int)type, (int)proto, out error);
this.CheckError(error);
}
private Socket(AddressFamily family, SocketType type, ProtocolType proto, IntPtr native) {
this.family = family;
this.type = type;
this.proto = proto;
this.native = native;
}
~Socket() {
this.Dispose(false);
}
private void Dispose(bool disposing) {
if (this.native != IntPtr.Zero) {
Internal_Close(this.native);
this.native = IntPtr.Zero;
if (disposing) {
GC.SuppressFinalize(this);
}
}
}
void IDisposable.Dispose() {
this.Dispose(true);
}
public void Close() {
this.Dispose(true);
}
private void CheckDisposed() {
if (this.native == IntPtr.Zero) {
throw new ObjectDisposedException(this.GetType().ToString());
}
}
private void CheckError(int error) {
if (error != 0) {
Console.WriteLine("SOCKET_ERROR {0}", error);
throw new SocketException(error);
}
}
private void GetIPInfo(EndPoint ep, out uint addr, out int port) {
if (ep.AddressFamily != AddressFamily.InterNetwork) {
throw new ArgumentException("EndPoint", "Can only handle IPv4 addresses");
}
SocketAddress sockAddr = ep.Serialize();
port = (((int)sockAddr[2]) << 8) | sockAddr[3];
addr = ((((uint)sockAddr[7]) << 24) | (((uint)sockAddr[6]) << 16) |
(((uint)sockAddr[5]) << 8) | (uint)sockAddr[4]);
}
public void Bind(EndPoint epLocal) {
this.CheckDisposed();
if (epLocal == null) {
throw new ArgumentNullException("epLocal");
}
int port;
uint addr;
this.GetIPInfo(epLocal, out addr, out port);
int error;
Internal_Bind(this.native, addr, port, out error);
this.CheckError(error);
}
public void Listen(int backLog) {
this.CheckDisposed();
int error;
Internal_Listen(this.native, backLog, out error);
this.CheckError(error);
}
public Socket Accept() {
this.CheckDisposed();
int error;
IntPtr socket = Internal_Accept(this.native, out error);
this.CheckError(error);
return new Socket(this.family, this.type, this.proto, socket);
}
public void Connect(EndPoint epRemote) {
this.CheckDisposed();
if (epRemote == null) {
throw new ArgumentNullException("epRemote");
}
int port;
uint addr;
this.GetIPInfo(epRemote, out addr, out port);
int error;
Internal_Connect(this.native, addr, port, out error);
this.CheckError(error);
}
public int Send(byte[] buffer) {
return this.Send(buffer, 0, buffer.Length, SocketFlags.None);
}
public int Send(byte[] buffer, SocketFlags flags) {
return this.Send(buffer, 0, buffer.Length, flags);
}
public int Send(byte[] buffer, int size, SocketFlags flags) {
return this.Send(buffer, 0, size, flags);
}
public int Send(byte[] buffer, int offset, int size, SocketFlags flags) {
this.CheckDisposed();
if (buffer == null) {
throw new ArgumentNullException("buffer");
}
if (offset < 0 || size < 0 || offset + size > buffer.Length) {
throw new ArgumentOutOfRangeException();
}
int error;
int ret = Internal_Send(this.native, buffer, offset, size, (int)flags, out error);
this.CheckError(error);
return ret;
}
public int Receive(byte[] buffer) {
return this.Receive(buffer, 0, buffer.Length, SocketFlags.None);
}
public int Receive(byte[] buffer, SocketFlags flags) {
return this.Receive(buffer, 0, buffer.Length, flags);
}
public int Receive(byte[] buffer, int size, SocketFlags flags) {
return this.Receive(buffer, 0, size, flags);
}
public int Receive(byte[] buffer, int offset, int size, SocketFlags flags) {
this.CheckDisposed();
if (buffer == null) {
throw new ArgumentNullException("buffer");
}
if (offset < 0 || size < 0 || offset + size > buffer.Length) {
throw new ArgumentOutOfRangeException();
}
int error;
int ret = Internal_Receive(this.native, buffer, offset, size, (int)flags, out error);
this.CheckError(error);
return ret;
}
}
}
| |
using System;
using System.Collections.Generic;
using Voron.Data.Fixed;
namespace Voron.Impl.FreeSpace
{
public class FreeSpaceHandling : IFreeSpaceHandling
{
private static readonly Slice FreeSpaceKey = Slice.From(StorageEnvironment.LabelsContext, "$free-space", Sparrow.ByteStringType.Immutable);
private readonly FreeSpaceHandlingDisabler _disableStatus = new FreeSpaceHandlingDisabler();
private readonly FreeSpaceRecursiveCallGuard _guard = new FreeSpaceRecursiveCallGuard();
internal const int NumberOfPagesInSection = 2048;
public static bool IsFreeSpaceTreeName(string name)
{
return name == "$free-space";
}
public event Action<long> PageFreed;
public long? TryAllocateFromFreeSpace(LowLevelTransaction tx, int num)
{
if (tx.RootObjects == null)
return null;
if (_disableStatus.DisableCount > 0)
return null;
using (_guard.Enter())
{
var freeSpaceTree = GetFreeSpaceTree(tx);
if (freeSpaceTree.NumberOfEntries == 0)
return null;
using (var it = freeSpaceTree.Iterate())
{
if (it.Seek(0) == false)
return null;
if (num < NumberOfPagesInSection)
{
return TryFindSmallValue(tx, freeSpaceTree, it, num);
}
return TryFindLargeValue(tx, freeSpaceTree, it, num);
}
}
}
private long? TryFindLargeValue(LowLevelTransaction tx, FixedSizeTree freeSpaceTree, FixedSizeTree.IFixedSizeIterator it, int num)
{
int numberOfNeededFullSections = num / NumberOfPagesInSection;
int numberOfExtraBitsNeeded = num % NumberOfPagesInSection;
var info = new FoundSectionsInfo();
do
{
var stream = it.CreateReaderForCurrent();
{
var current = new StreamBitArray(stream);
var currentSectionId = it.CurrentKey;
//need to find full free pages
if (current.SetCount < NumberOfPagesInSection)
{
info.Clear();
continue;
}
//those sections are not following each other in the memory
if (info.StartSectionId != null && currentSectionId != info.StartSectionId + info.Sections.Count)
{
info.Clear();
}
//set the first section of the sequence
if (info.StartSection == -1)
{
info.StartSection = it.CurrentKey;
info.StartSectionId = currentSectionId;
}
info.Sections.Add(it.CurrentKey);
if (info.Sections.Count != numberOfNeededFullSections)
continue;
//we found enough full sections now we need just a bit more
if (numberOfExtraBitsNeeded == 0)
{
foreach (var section in info.Sections)
{
freeSpaceTree.Delete(section);
}
return info.StartSectionId * NumberOfPagesInSection;
}
var nextSectionId = currentSectionId + 1;
var read = freeSpaceTree.Read(nextSectionId);
if (!read.HasValue)
{
//not a following next section
info.Clear();
continue;
}
var next = new StreamBitArray(read.CreateReader());
if (next.HasStartRangeCount(numberOfExtraBitsNeeded) == false)
{
//not enough start range count
info.Clear();
continue;
}
//mark selected bits to false
if (next.SetCount == numberOfExtraBitsNeeded)
{
freeSpaceTree.Delete(nextSectionId);
}
else
{
for (int i = 0; i < numberOfExtraBitsNeeded; i++)
{
next.Set(i, false);
}
freeSpaceTree.Add(nextSectionId, next.ToSlice(tx.Allocator));
}
foreach (var section in info.Sections)
{
freeSpaceTree.Delete(section);
}
return info.StartSectionId * NumberOfPagesInSection;
}
} while (it.MoveNext());
return null;
}
private class FoundSectionsInfo
{
public List<long> Sections = new List<long>();
public long StartSection = -1;
public long? StartSectionId;
public void Clear()
{
StartSection = -1;
StartSectionId = null;
Sections.Clear();
}
}
private long? TryFindSmallValue(LowLevelTransaction tx, FixedSizeTree freeSpaceTree, FixedSizeTree.IFixedSizeIterator it, int num)
{
do
{
var current = new StreamBitArray(it.CreateReaderForCurrent());
long? page;
if (current.SetCount < num)
{
if (TryFindSmallValueMergingTwoSections(tx, freeSpaceTree, it.CurrentKey, num, current, out page))
return page;
continue;
}
if (TryFindContinuousRange(tx, freeSpaceTree, it, num, current, it.CurrentKey, out page))
return page;
//could not find a continuous so trying to merge
if (TryFindSmallValueMergingTwoSections(tx, freeSpaceTree, it.CurrentKey, num, current, out page))
return page;
}
while (it.MoveNext());
return null;
}
private bool TryFindContinuousRange(LowLevelTransaction tx, FixedSizeTree freeSpaceTree, FixedSizeTree.IFixedSizeIterator it, int num,
StreamBitArray current, long currentSectionId, out long? page)
{
page = -1;
var start = -1;
var count = 0;
for (int i = 0; i < NumberOfPagesInSection; i++)
{
if (current.Get(i))
{
if (start == -1)
start = i;
count++;
if (count == num)
{
page = currentSectionId * NumberOfPagesInSection + start;
break;
}
}
else
{
start = -1;
count = 0;
}
}
if (count != num)
return false;
if (current.SetCount == num)
{
freeSpaceTree.Delete(it.CurrentKey);
}
else
{
for (int i = 0; i < num; i++)
{
current.Set(i + start, false);
}
freeSpaceTree.Add(it.CurrentKey, current.ToSlice(tx.Allocator));
}
return true;
}
private static bool TryFindSmallValueMergingTwoSections(LowLevelTransaction tx, FixedSizeTree freeSpacetree, long currentSectionId, int num,
StreamBitArray current, out long? result)
{
result = -1;
var currentEndRange = current.GetEndRangeCount();
if (currentEndRange == 0)
return false;
var nextSectionId = currentSectionId + 1;
var read = freeSpacetree.Read(nextSectionId);
if (!read.HasValue)
return false;
var next = new StreamBitArray(read.CreateReader());
var nextRange = num - currentEndRange;
if (next.HasStartRangeCount(nextRange) == false)
return false;
if (next.SetCount == nextRange)
{
freeSpacetree.Delete(nextSectionId);
}
else
{
for (int i = 0; i < nextRange; i++)
{
next.Set(i, false);
}
freeSpacetree.Add(nextSectionId, next.ToSlice(tx.Allocator));
}
if (current.SetCount == currentEndRange)
{
freeSpacetree.Delete(currentSectionId);
}
else
{
for (int i = 0; i < currentEndRange; i++)
{
current.Set(NumberOfPagesInSection - 1 - i, false);
}
freeSpacetree.Add(currentSectionId, current.ToSlice(tx.Allocator));
}
result = currentSectionId * NumberOfPagesInSection + (NumberOfPagesInSection - currentEndRange);
return true;
}
public List<long> AllPages(LowLevelTransaction tx)
{
var freeSpaceTree = GetFreeSpaceTree(tx);
if (freeSpaceTree.NumberOfEntries == 0)
return new List<long>();
using (var it = freeSpaceTree.Iterate())
{
if (it.Seek(0) == false)
return new List<long>();
var freePages = new List<long>();
do
{
var stream = it.CreateReaderForCurrent();
var current = new StreamBitArray(stream);
var currentSectionId = it.CurrentKey;
for (var i = 0; i < NumberOfPagesInSection; i++)
{
if (current.Get(i))
freePages.Add(currentSectionId * NumberOfPagesInSection + i);
}
} while (it.MoveNext());
return freePages;
}
}
public void FreePage(LowLevelTransaction tx, long pageNumber)
{
using (_guard.Enter())
{
var freeSpaceTree = GetFreeSpaceTree(tx);
var section = pageNumber/NumberOfPagesInSection;
var result = freeSpaceTree.Read(section);
var sba = !result.HasValue ? new StreamBitArray() : new StreamBitArray(result.CreateReader());
sba.Set((int)(pageNumber%NumberOfPagesInSection), true);
freeSpaceTree.Add(section, sba.ToSlice(tx.Allocator));
var onPageFreed = PageFreed;
onPageFreed?.Invoke(pageNumber);
}
}
public long GetFreePagesOverhead(LowLevelTransaction tx)
{
return GetFreeSpaceTree(tx).PageCount;
}
public IEnumerable<long> GetFreePagesOverheadPages(LowLevelTransaction tx)
{
return GetFreeSpaceTree(tx).AllPages();
}
public FreeSpaceHandlingDisabler Disable()
{
_disableStatus.DisableCount++;
return _disableStatus;
}
private static FixedSizeTree GetFreeSpaceTree(LowLevelTransaction tx)
{
return new FixedSizeTree(tx, tx.RootObjects, FreeSpaceKey, 260)
{
FreeSpaceTree =true
};
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//
namespace System.Reflection.Emit
{
using System;
using System.Reflection;
using System.Collections;
using System.Globalization;
using System.Diagnostics.Contracts;
internal sealed class TypeBuilderInstantiation : TypeInfo
{
public override bool IsAssignableFrom(System.Reflection.TypeInfo typeInfo){
if(typeInfo==null) return false;
return IsAssignableFrom(typeInfo.AsType());
}
#region Static Members
internal static Type MakeGenericType(Type type, Type[] typeArguments)
{
Contract.Requires(type != null, "this is only called from RuntimeType.MakeGenericType and TypeBuilder.MakeGenericType so 'type' cannot be null");
if (!type.IsGenericTypeDefinition)
throw new InvalidOperationException();
if (typeArguments == null)
throw new ArgumentNullException("typeArguments");
Contract.EndContractBlock();
foreach (Type t in typeArguments)
{
if (t == null)
throw new ArgumentNullException("typeArguments");
}
return new TypeBuilderInstantiation(type, typeArguments);
}
#endregion
#region Private Data Mebers
private Type m_type;
private Type[] m_inst;
private string m_strFullQualName;
internal Hashtable m_hashtable = new Hashtable();
#endregion
#region Constructor
private TypeBuilderInstantiation(Type type, Type[] inst)
{
m_type = type;
m_inst = inst;
m_hashtable = new Hashtable();
}
#endregion
#region Object Overrides
public override String ToString()
{
return TypeNameBuilder.ToString(this, TypeNameBuilder.Format.ToString);
}
#endregion
#region MemberInfo Overrides
public override Type DeclaringType { get { return m_type.DeclaringType; } }
public override Type ReflectedType { get { return m_type.ReflectedType; } }
public override String Name { get { return m_type.Name; } }
public override Module Module { get { return m_type.Module; } }
#endregion
#region Type Overrides
public override Type MakePointerType()
{
return SymbolType.FormCompoundType("*".ToCharArray(), this, 0);
}
public override Type MakeByRefType()
{
return SymbolType.FormCompoundType("&".ToCharArray(), this, 0);
}
public override Type MakeArrayType()
{
return SymbolType.FormCompoundType("[]".ToCharArray(), this, 0);
}
public override Type MakeArrayType(int rank)
{
if (rank <= 0)
throw new IndexOutOfRangeException();
Contract.EndContractBlock();
string comma = "";
for(int i = 1; i < rank; i++)
comma += ",";
string s = String.Format(CultureInfo.InvariantCulture, "[{0}]", comma);
return SymbolType.FormCompoundType(s.ToCharArray(), this, 0);
}
public override Guid GUID { get { throw new NotSupportedException(); } }
public override Object InvokeMember(String name, BindingFlags invokeAttr, Binder binder, Object target, Object[] args, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParameters) { throw new NotSupportedException(); }
public override Assembly Assembly { get { return m_type.Assembly; } }
public override RuntimeTypeHandle TypeHandle { get { throw new NotSupportedException(); } }
public override String FullName
{
get
{
if (m_strFullQualName == null)
m_strFullQualName = TypeNameBuilder.ToString(this, TypeNameBuilder.Format.FullName);
return m_strFullQualName;
}
}
public override String Namespace { get { return m_type.Namespace; } }
public override String AssemblyQualifiedName { get { return TypeNameBuilder.ToString(this, TypeNameBuilder.Format.AssemblyQualifiedName); } }
private Type Substitute(Type[] substitutes)
{
Type[] inst = GetGenericArguments();
Type[] instSubstituted = new Type[inst.Length];
for (int i = 0; i < instSubstituted.Length; i++)
{
Type t = inst[i];
if (t is TypeBuilderInstantiation)
{
instSubstituted[i] = (t as TypeBuilderInstantiation).Substitute(substitutes);
}
else if (t is GenericTypeParameterBuilder)
{
// Substitute
instSubstituted[i] = substitutes[t.GenericParameterPosition];
}
else
{
instSubstituted[i] = t;
}
}
return GetGenericTypeDefinition().MakeGenericType(instSubstituted);
}
public override Type BaseType
{
// B<A,B,C>
// D<T,S> : B<S,List<T>,char>
// D<string,int> : B<int,List<string>,char>
// D<S,T> : B<T,List<S>,char>
// D<S,string> : B<string,List<S>,char>
get
{
Type typeBldrBase = m_type.BaseType;
if (typeBldrBase == null)
return null;
TypeBuilderInstantiation typeBldrBaseAs = typeBldrBase as TypeBuilderInstantiation;
if (typeBldrBaseAs == null)
return typeBldrBase;
return typeBldrBaseAs.Substitute(GetGenericArguments());
}
}
protected override ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { throw new NotSupportedException(); }
[System.Runtime.InteropServices.ComVisible(true)]
public override ConstructorInfo[] GetConstructors(BindingFlags bindingAttr) { throw new NotSupportedException(); }
protected override MethodInfo GetMethodImpl(String name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { throw new NotSupportedException(); }
public override MethodInfo[] GetMethods(BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override FieldInfo GetField(String name, BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override FieldInfo[] GetFields(BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override Type GetInterface(String name, bool ignoreCase) { throw new NotSupportedException(); }
public override Type[] GetInterfaces() { throw new NotSupportedException(); }
public override EventInfo GetEvent(String name, BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override EventInfo[] GetEvents() { throw new NotSupportedException(); }
protected override PropertyInfo GetPropertyImpl(String name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers) { throw new NotSupportedException(); }
public override PropertyInfo[] GetProperties(BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override Type[] GetNestedTypes(BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override Type GetNestedType(String name, BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override MemberInfo[] GetMember(String name, MemberTypes type, BindingFlags bindingAttr) { throw new NotSupportedException(); }
[System.Runtime.InteropServices.ComVisible(true)]
public override InterfaceMapping GetInterfaceMap(Type interfaceType) { throw new NotSupportedException(); }
public override EventInfo[] GetEvents(BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override MemberInfo[] GetMembers(BindingFlags bindingAttr) { throw new NotSupportedException(); }
protected override TypeAttributes GetAttributeFlagsImpl() { return m_type.Attributes; }
protected override bool IsArrayImpl() { return false; }
protected override bool IsByRefImpl() { return false; }
protected override bool IsPointerImpl() { return false; }
protected override bool IsPrimitiveImpl() { return false; }
protected override bool IsCOMObjectImpl() { return false; }
public override Type GetElementType() { throw new NotSupportedException(); }
protected override bool HasElementTypeImpl() { return false; }
public override Type UnderlyingSystemType { get { return this; } }
public override Type[] GetGenericArguments() { return m_inst; }
public override bool IsGenericTypeDefinition { get { return false; } }
public override bool IsGenericType { get { return true; } }
public override bool IsConstructedGenericType { get { return true; } }
public override bool IsGenericParameter { get { return false; } }
public override int GenericParameterPosition { get { throw new InvalidOperationException(); } }
protected override bool IsValueTypeImpl() { return m_type.IsValueType; }
public override bool ContainsGenericParameters
{
get
{
for (int i = 0; i < m_inst.Length; i++)
{
if (m_inst[i].ContainsGenericParameters)
return true;
}
return false;
}
}
public override MethodBase DeclaringMethod { get { return null; } }
public override Type GetGenericTypeDefinition() { return m_type; }
public override Type MakeGenericType(params Type[] inst) { throw new InvalidOperationException(Environment.GetResourceString("Arg_NotGenericTypeDefinition")); }
public override bool IsAssignableFrom(Type c) { throw new NotSupportedException(); }
[System.Runtime.InteropServices.ComVisible(true)]
[Pure]
public override bool IsSubclassOf(Type c)
{
throw new NotSupportedException();
}
#endregion
#region ICustomAttributeProvider Implementation
public override Object[] GetCustomAttributes(bool inherit) { throw new NotSupportedException(); }
public override Object[] GetCustomAttributes(Type attributeType, bool inherit) { throw new NotSupportedException(); }
public override bool IsDefined(Type attributeType, bool inherit) { throw new NotSupportedException(); }
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
namespace EncompassRest.Loans
{
/// <summary>
/// LockRequestLog
/// </summary>
public sealed partial class LockRequestLog : DirtyExtensibleObject, IIdentifiable
{
private DirtyList<LogAlert>? _alerts;
private DirtyValue<string?>? _alertsXml;
private DirtyValue<DateTime?>? _buySideExpirationDate;
private DirtyValue<DateTime?>? _buySideNewLockExtensionDate;
private DirtyValue<int?>? _buySideNumDayExtended;
private DirtyValue<int?>? _buySideNumDayLocked;
private DirtyList<LogComment>? _commentList;
private DirtyValue<string?>? _commentListXml;
private DirtyValue<string?>? _comments;
private DirtyValue<int?>? _cumulatedDaystoExtend;
private DirtyValue<DateTime?>? _dateUtc;
private DirtyValue<bool?>? _fileAttachmentsMigrated;
private DirtyValue<string?>? _guid;
private DirtyValue<bool?>? _hideLogIndicator;
private DirtyValue<string?>? _id;
private DirtyValue<string?>? _investorCommitment;
private DirtyValue<string?>? _investorName;
private DirtyValue<bool?>? _isFakeRequestIndicator;
private DirtyValue<bool?>? _isLockCancellationIndicator;
private DirtyValue<bool?>? _isLockExtensionIndicator;
private DirtyValue<bool?>? _isReLockIndicator;
private DirtyValue<bool?>? _isSystemSpecificIndicator;
private DirtyValue<int?>? _logRecordIndex;
private DirtyValue<int?>? _numDayLocked;
private DirtyValue<string?>? _parentLockGuid;
private DirtyValue<string?>? _rateLockAction;
private DirtyValue<int?>? _reLockSequenceNumberForInactiveLock;
private DirtyValue<string?>? _requestedBy;
private DirtyValue<string?>? _requestedName;
private DirtyValue<string?>? _requestedStatus;
private DirtyValue<string?>? _reviseAction;
private DirtyValue<string?>? _sellSideDeliveredBy;
private DirtyValue<DateTime?>? _sellSideDeliveryDate;
private DirtyValue<DateTime?>? _sellSideExpirationDate;
private DirtyValue<DateTime?>? _sellSideNewLockExtensionDate;
private DirtyValue<int?>? _sellSideNumDayExtended;
private DirtyValue<string?>? _snapshotXml;
private DirtyValue<string?>? _systemId;
private DirtyValue<string?>? _timeRequested;
private DirtyValue<DateTime?>? _updatedDateUtc;
/// <summary>
/// LockRequestLog Alerts
/// </summary>
[AllowNull]
public IList<LogAlert> Alerts { get => GetField(ref _alerts); set => SetField(ref _alerts, value); }
/// <summary>
/// LockRequestLog AlertsXml
/// </summary>
public string? AlertsXml { get => _alertsXml; set => SetField(ref _alertsXml, value); }
/// <summary>
/// LockRequestLog BuySideExpirationDate
/// </summary>
public DateTime? BuySideExpirationDate { get => _buySideExpirationDate; set => SetField(ref _buySideExpirationDate, value); }
/// <summary>
/// LockRequestLog BuySideNewLockExtensionDate
/// </summary>
public DateTime? BuySideNewLockExtensionDate { get => _buySideNewLockExtensionDate; set => SetField(ref _buySideNewLockExtensionDate, value); }
/// <summary>
/// LockRequestLog BuySideNumDayExtended
/// </summary>
public int? BuySideNumDayExtended { get => _buySideNumDayExtended; set => SetField(ref _buySideNumDayExtended, value); }
/// <summary>
/// LockRequestLog BuySideNumDayLocked
/// </summary>
public int? BuySideNumDayLocked { get => _buySideNumDayLocked; set => SetField(ref _buySideNumDayLocked, value); }
/// <summary>
/// LockRequestLog CommentList
/// </summary>
[AllowNull]
public IList<LogComment> CommentList { get => GetField(ref _commentList); set => SetField(ref _commentList, value); }
/// <summary>
/// LockRequestLog CommentListXml
/// </summary>
public string? CommentListXml { get => _commentListXml; set => SetField(ref _commentListXml, value); }
/// <summary>
/// LockRequestLog Comments
/// </summary>
public string? Comments { get => _comments; set => SetField(ref _comments, value); }
/// <summary>
/// LockRequestLog CumulatedDaystoExtend
/// </summary>
public int? CumulatedDaystoExtend { get => _cumulatedDaystoExtend; set => SetField(ref _cumulatedDaystoExtend, value); }
/// <summary>
/// LockRequestLog DateUtc
/// </summary>
public DateTime? DateUtc { get => _dateUtc; set => SetField(ref _dateUtc, value); }
/// <summary>
/// LockRequestLog FileAttachmentsMigrated
/// </summary>
public bool? FileAttachmentsMigrated { get => _fileAttachmentsMigrated; set => SetField(ref _fileAttachmentsMigrated, value); }
/// <summary>
/// LockRequestLog Guid
/// </summary>
public string? Guid { get => _guid; set => SetField(ref _guid, value); }
/// <summary>
/// LockRequestLog HideLogIndicator
/// </summary>
public bool? HideLogIndicator { get => _hideLogIndicator; set => SetField(ref _hideLogIndicator, value); }
/// <summary>
/// LockRequestLog Id
/// </summary>
public string? Id { get => _id; set => SetField(ref _id, value); }
/// <summary>
/// LockRequestLog InvestorCommitment
/// </summary>
public string? InvestorCommitment { get => _investorCommitment; set => SetField(ref _investorCommitment, value); }
/// <summary>
/// LockRequestLog InvestorName
/// </summary>
public string? InvestorName { get => _investorName; set => SetField(ref _investorName, value); }
/// <summary>
/// LockRequestLog IsFakeRequestIndicator
/// </summary>
public bool? IsFakeRequestIndicator { get => _isFakeRequestIndicator; set => SetField(ref _isFakeRequestIndicator, value); }
/// <summary>
/// LockRequestLog IsLockCancellationIndicator
/// </summary>
public bool? IsLockCancellationIndicator { get => _isLockCancellationIndicator; set => SetField(ref _isLockCancellationIndicator, value); }
/// <summary>
/// LockRequestLog IsLockExtensionIndicator
/// </summary>
public bool? IsLockExtensionIndicator { get => _isLockExtensionIndicator; set => SetField(ref _isLockExtensionIndicator, value); }
/// <summary>
/// LockRequestLog IsReLockIndicator
/// </summary>
public bool? IsReLockIndicator { get => _isReLockIndicator; set => SetField(ref _isReLockIndicator, value); }
/// <summary>
/// LockRequestLog IsSystemSpecificIndicator
/// </summary>
public bool? IsSystemSpecificIndicator { get => _isSystemSpecificIndicator; set => SetField(ref _isSystemSpecificIndicator, value); }
/// <summary>
/// LockRequestLog LogRecordIndex
/// </summary>
public int? LogRecordIndex { get => _logRecordIndex; set => SetField(ref _logRecordIndex, value); }
/// <summary>
/// LockRequestLog NumDayLocked
/// </summary>
public int? NumDayLocked { get => _numDayLocked; set => SetField(ref _numDayLocked, value); }
/// <summary>
/// LockRequestLog ParentLockGuid
/// </summary>
public string? ParentLockGuid { get => _parentLockGuid; set => SetField(ref _parentLockGuid, value); }
/// <summary>
/// LockRequestLog RateLockAction
/// </summary>
public string? RateLockAction { get => _rateLockAction; set => SetField(ref _rateLockAction, value); }
/// <summary>
/// LockRequestLog ReLockSequenceNumberForInactiveLock
/// </summary>
public int? ReLockSequenceNumberForInactiveLock { get => _reLockSequenceNumberForInactiveLock; set => SetField(ref _reLockSequenceNumberForInactiveLock, value); }
/// <summary>
/// LockRequestLog RequestedBy
/// </summary>
public string? RequestedBy { get => _requestedBy; set => SetField(ref _requestedBy, value); }
/// <summary>
/// LockRequestLog RequestedName
/// </summary>
public string? RequestedName { get => _requestedName; set => SetField(ref _requestedName, value); }
/// <summary>
/// LockRequestLog RequestedStatus
/// </summary>
public string? RequestedStatus { get => _requestedStatus; set => SetField(ref _requestedStatus, value); }
/// <summary>
/// LockRequestLog ReviseAction
/// </summary>
public string? ReviseAction { get => _reviseAction; set => SetField(ref _reviseAction, value); }
/// <summary>
/// LockRequestLog SellSideDeliveredBy
/// </summary>
public string? SellSideDeliveredBy { get => _sellSideDeliveredBy; set => SetField(ref _sellSideDeliveredBy, value); }
/// <summary>
/// LockRequestLog SellSideDeliveryDate
/// </summary>
public DateTime? SellSideDeliveryDate { get => _sellSideDeliveryDate; set => SetField(ref _sellSideDeliveryDate, value); }
/// <summary>
/// LockRequestLog SellSideExpirationDate
/// </summary>
public DateTime? SellSideExpirationDate { get => _sellSideExpirationDate; set => SetField(ref _sellSideExpirationDate, value); }
/// <summary>
/// LockRequestLog SellSideNewLockExtensionDate
/// </summary>
public DateTime? SellSideNewLockExtensionDate { get => _sellSideNewLockExtensionDate; set => SetField(ref _sellSideNewLockExtensionDate, value); }
/// <summary>
/// LockRequestLog SellSideNumDayExtended
/// </summary>
public int? SellSideNumDayExtended { get => _sellSideNumDayExtended; set => SetField(ref _sellSideNumDayExtended, value); }
/// <summary>
/// LockRequestLog SnapshotXml
/// </summary>
public string? SnapshotXml { get => _snapshotXml; set => SetField(ref _snapshotXml, value); }
/// <summary>
/// LockRequestLog SystemId
/// </summary>
public string? SystemId { get => _systemId; set => SetField(ref _systemId, value); }
/// <summary>
/// LockRequestLog TimeRequested
/// </summary>
public string? TimeRequested { get => _timeRequested; set => SetField(ref _timeRequested, value); }
/// <summary>
/// LockRequestLog UpdatedDateUtc
/// </summary>
public DateTime? UpdatedDateUtc { get => _updatedDateUtc; set => SetField(ref _updatedDateUtc, value); }
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using Pathfinding.Serialization.JsonFx;
using Pathfinding.Serialization;
namespace Pathfinding {
/** Basic point graph.
* \ingroup graphs
* The List graph is the most basic graph structure, it consists of a number of interconnected points in space, waypoints or nodes.\n
* The list graph takes a Transform object as "root", this Transform will be searched for child objects, every child object will be treated as a node.
* It will then check if any connections between the nodes can be made, first it will check if the distance between the nodes isn't too large ( #maxDistance )
* and then it will check if the axis aligned distance isn't too high. The axis aligned distance, named #limits,
* is useful because usually an AI cannot climb very high, but linking nodes far away from each other,
* but on the same Y level should still be possible. #limits and #maxDistance won't affect anything if the values are 0 (zero) though. \n
* Lastly it will check if there are any obstructions between the nodes using
* <a href="http://unity3d.com/support/documentation/ScriptReference/Physics.Raycast.html">raycasting</a> which can optionally be thick.\n
* One thing to think about when using raycasting is to either place the nodes a small
* distance above the ground in your scene or to make sure that the ground is not in the raycast \a mask to avoid the raycast from hitting the ground.\n
* \note Does not support linecast because of obvious reasons.
*
\shadowimage{pointgraph_graph.png}
\shadowimage{pointgraph_inspector.png}
*/
[JsonOptIn]
public class PointGraph : NavGraph
{
[JsonMember]
/** Childs of this transform are treated as nodes */
public Transform root;
[JsonMember]
/** If no #root is set, all nodes with the tag is used as nodes */
public string searchTag;
[JsonMember]
/** Max distance for a connection to be valid.
* The value 0 (zero) will be read as infinity and thus all nodes not restricted by
* other constraints will be added as connections.
*
* A negative value will disable any neighbours to be added.
* It will completely stop the connection processing to be done, so it can save you processing
* power if you don't these connections.
*/
public float maxDistance = 0;
[JsonMember]
/** Max distance along the axis for a connection to be valid. 0 = infinity */
public Vector3 limits;
[JsonMember]
/** Use raycasts to check connections */
public bool raycast = true;
[JsonMember]
/** Use the 2D Physics API */
public bool use2DPhysics = false;
[JsonMember]
/** Use thick raycast */
public bool thickRaycast = false;
[JsonMember]
/** Thick raycast radius */
public float thickRaycastRadius = 1;
[JsonMember]
/** Recursively search for childnodes to the #root */
public bool recursive = true;
[JsonMember]
public bool autoLinkNodes = true;
[JsonMember]
/** Layer mask to use for raycast */
public LayerMask mask;
/** All nodes in this graph.
* Note that only the first #nodeCount will be non-null.
*
* You can also use the GetNodes method to get all nodes.
*/
public PointNode[] nodes;
/** Number of nodes in this graph.
*
* \warning Do not edit directly
*/
public int nodeCount;
public override void GetNodes (GraphNodeDelegateCancelable del) {
if (nodes == null) return;
for (int i=0;i<nodeCount && del (nodes[i]);i++) {}
}
public override NNInfo GetNearest (Vector3 position, NNConstraint constraint, GraphNode hint) {
return GetNearestForce (position, constraint);
}
public override NNInfo GetNearestForce (Vector3 position, NNConstraint constraint)
{
//Debug.LogError ("This function (GetNearest) is not implemented in the navigation graph generator : Type "+this.GetType ().Name);
if (nodes == null) return new NNInfo();
float maxDistSqr = constraint.constrainDistance ? AstarPath.active.maxNearestNodeDistanceSqr : float.PositiveInfinity;
float minDist = float.PositiveInfinity;
GraphNode minNode = null;
float minConstDist = float.PositiveInfinity;
GraphNode minConstNode = null;
for (int i=0;i<nodeCount;i++) {
PointNode node = nodes[i];
float dist = (position-(Vector3)node.position).sqrMagnitude;
if (dist < minDist) {
minDist = dist;
minNode = node;
}
if (constraint == null || (dist < minConstDist && dist < maxDistSqr && constraint.Suitable (node))) {
minConstDist = dist;
minConstNode = node;
}
}
NNInfo nnInfo = new NNInfo (minNode);
nnInfo.constrainedNode = minConstNode;
if (minConstNode != null) {
nnInfo.constClampedPosition = (Vector3)minConstNode.position;
} else if (minNode != null) {
nnInfo.constrainedNode = minNode;
nnInfo.constClampedPosition = (Vector3)minNode.position;
}
return nnInfo;
}
/** Add a node to the graph at the specified position.
* \note Vector3 can be casted to Int3 using (Int3)myVector.
*/
public PointNode AddNode (Int3 position) {
return AddNode ( new PointNode (active), position );
}
/** Add a node with the specified type to the graph at the specified position.
* \note Vector3 can be casted to Int3 using (Int3)myVector.
*
* \param nd This must be a node created using T(AstarPath.active) right before the call to this method.
* The node parameter is only there because there is no new(AstarPath) constraint on
* generic type parameters.
*/
public T AddNode<T> (T nd, Int3 position) where T : PointNode {
if ( nodes == null || nodeCount == nodes.Length ) {
PointNode[] nds = new PointNode[nodes != null ? System.Math.Max (nodes.Length+4, nodes.Length*2) : 4];
for ( int i = 0; i < nodeCount; i++ ) nds[i] = nodes[i];
nodes = nds;
}
//T nd = new T( active );//new PointNode ( active );
nd.SetPosition (position);
nd.GraphIndex = graphIndex;
nd.Walkable = true;
nodes[nodeCount] = nd;
nodeCount++;
AddToLookup ( nd );
return nd;
}
/** Recursively counds children of a transform */
public static int CountChildren (Transform tr) {
int c = 0;
foreach (Transform child in tr) {
c++;
c+= CountChildren (child);
}
return c;
}
/** Recursively adds childrens of a transform as nodes */
public void AddChildren (ref int c, Transform tr) {
foreach (Transform child in tr) {
(nodes[c] as PointNode).SetPosition ((Int3)child.position);
nodes[c].Walkable = true;
nodes[c].gameObject = child.gameObject;
c++;
AddChildren (ref c,child);
}
}
/** Rebuilds the lookup structure for nodes.
*
* This is used when #optimizeForSparseGraph is enabled.
*
* You should call this method every time you move a node in the graph manually and
* you are using #optimizeForSparseGraph, otherwise pathfinding might not work correctly.
*
* \astarpro
*/
public void RebuildNodeLookup () {
// A* Pathfinding Project Pro Only
}
public void AddToLookup ( PointNode node ) {
// A* Pathfinding Project Pro Only
}
public override void ScanInternal (OnScanStatus statusCallback) {
if (root == null) {
//If there is no root object, try to find nodes with the specified tag instead
GameObject[] gos = GameObject.FindGameObjectsWithTag (searchTag);
if (gos == null) {
nodes = new PointNode[0];
nodeCount = 0;
return;
}
//Create and set up the found nodes
nodes = new PointNode[gos.Length];
nodeCount = nodes.Length;
for (int i=0;i<nodes.Length;i++) nodes[i] = new PointNode(active);
//CreateNodes (gos.Length);
for (int i=0;i<gos.Length;i++) {
(nodes[i] as PointNode).SetPosition ((Int3)gos[i].transform.position);
nodes[i].Walkable = true;
nodes[i].gameObject = gos[i].gameObject;
}
} else {
//Search the root for children and create nodes for them
if (!recursive) {
nodes = new PointNode[root.childCount];
nodeCount = nodes.Length;
for (int i=0;i<nodes.Length;i++) nodes[i] = new PointNode(active);
int c = 0;
foreach (Transform child in root) {
(nodes[c] as PointNode).SetPosition ((Int3)child.position);
nodes[c].Walkable = true;
nodes[c].gameObject = child.gameObject;
c++;
}
} else {
nodes = new PointNode[CountChildren(root)];
nodeCount = nodes.Length;
for (int i=0;i<nodes.Length;i++) nodes[i] = new PointNode(active);
//CreateNodes (CountChildren (root));
int startID = 0;
AddChildren (ref startID,root);
}
}
if (maxDistance >= 0) {
//To avoid too many allocations, these lists are reused for each node
List<PointNode> connections = new List<PointNode>(3);
List<uint> costs = new List<uint>(3);
//Loop through all nodes and add connections to other nodes
for (int i=0;i<nodes.Length;i++) {
connections.Clear ();
costs.Clear ();
PointNode node = nodes[i];
// Only brute force is available in the free version
for (int j=0;j<nodes.Length;j++) {
if (i == j) continue;
PointNode other = nodes[j];
float dist = 0;
if (IsValidConnection (node,other,out dist)) {
connections.Add (other);
/** \todo Is this equal to .costMagnitude */
costs.Add ((uint)Mathf.RoundToInt (dist*Int3.FloatPrecision));
}
}
node.connections = connections.ToArray();
node.connectionCosts = costs.ToArray();
}
}
}
/** Returns if the connection between \a a and \a b is valid.
* Checks for obstructions using raycasts (if enabled) and checks for height differences.\n
* As a bonus, it outputs the distance between the nodes too if the connection is valid */
public virtual bool IsValidConnection (GraphNode a, GraphNode b, out float dist) {
dist = 0;
if (!a.Walkable || !b.Walkable) return false;
Vector3 dir = (Vector3)(a.position-b.position);
if (
(!Mathf.Approximately (limits.x,0) && Mathf.Abs (dir.x) > limits.x) ||
(!Mathf.Approximately (limits.y,0) && Mathf.Abs (dir.y) > limits.y) ||
(!Mathf.Approximately (limits.z,0) && Mathf.Abs (dir.z) > limits.z))
{
return false;
}
dist = dir.magnitude;
if (maxDistance == 0 || dist < maxDistance) {
if (raycast) {
Ray ray = new Ray ((Vector3)a.position,(Vector3)(b.position-a.position));
Ray invertRay = new Ray ((Vector3)b.position,(Vector3)(a.position-b.position));
if (use2DPhysics) {
if (thickRaycast) {
#if UNITY_4_4 || UNITY_4_3 || UNITY_4_2 || UNITY_4_1 || UNITY_4_0
// These version do not support this API
return true;
#else
if (!Physics2D.CircleCast (ray.origin, thickRaycastRadius, ray.direction, dist,mask) &&
!Physics2D.CircleCast (invertRay.origin,thickRaycastRadius, invertRay.direction, dist,mask)) {
return true;
}
#endif
} else {
if (!Physics2D.Linecast ((Vector2)(Vector3)a.position,(Vector2)(Vector3)b.position,mask) &&
!Physics2D.Linecast ((Vector2)(Vector3)b.position,(Vector2)(Vector3)a.position,mask)) {
return true;
}
}
} else {
if (thickRaycast) {
if (!Physics.SphereCast (ray,thickRaycastRadius,dist,mask) && !Physics.SphereCast (invertRay,thickRaycastRadius,dist,mask)) {
return true;
}
} else {
if (!Physics.Linecast ((Vector3)a.position,(Vector3)b.position,mask) && !Physics.Linecast ((Vector3)b.position,(Vector3)a.position,mask)) {
return true;
}
}
}
} else {
return true;
}
}
return false;
}
public override void PostDeserialization ()
{
RebuildNodeLookup ();
}
public override void RelocateNodes (Matrix4x4 oldMatrix, Matrix4x4 newMatrix)
{
base.RelocateNodes (oldMatrix, newMatrix);
RebuildNodeLookup ();
}
public override void SerializeExtraInfo (GraphSerializationContext ctx)
{
if (nodes == null) ctx.writer.Write (-1);
ctx.writer.Write (nodeCount);
for (int i=0;i<nodeCount;i++) {
if (nodes[i] == null) ctx.writer.Write (-1);
else {
ctx.writer.Write (0);
nodes[i].SerializeNode(ctx);
}
}
}
public override void DeserializeExtraInfo (GraphSerializationContext ctx) {
int count = ctx.reader.ReadInt32();
if (count == -1) {
nodes = null;
return;
}
nodes = new PointNode[count];
nodeCount = count;
for (int i=0;i<nodes.Length;i++) {
if (ctx.reader.ReadInt32() == -1) continue;
nodes[i] = new PointNode(active);
nodes[i].DeserializeNode(ctx);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace WebHostedWebApiApplication.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
/*
* _AppDomain.cs - Implementation of the "System._AppDomain" interface.
*
* Copyright (C) 2001, 2003 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
*/
namespace System
{
#if CONFIG_RUNTIME_INFRA
using System.Reflection;
using System.Reflection.Emit;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Runtime.Remoting;
using System.Security;
using System.Security.Policy;
using System.Security.Principal;
#if ECMA_COMPAT
[CLSCompliant(false)]
internal
#else
[CLSCompliant(false)]
[Guid("05F696DC-2B29-3663-AD8B-C4389CF2A713")]
#if CONFIG_COM_INTEROP
[InterfaceType(ComInterfaceType.InterfaceIsDual)]
#endif
public
#endif
interface _AppDomain
{
// Get the friendly name associated with this application domain.
String FriendlyName { get; }
// Event that is emitted when an assembly is loaded into this domain.
event AssemblyLoadEventHandler AssemblyLoad;
// Event that is emitted when an application domain is unloaded.
event EventHandler DomainUnload;
// Event that is emitted when an exception is unhandled by the domain.
event UnhandledExceptionEventHandler UnhandledException;
#if !ECMA_COMPAT
// Base directory used to resolve assemblies.
String BaseDirectory { get; }
// Base directory used to resolve dynamically-created assemblies.
String DynamicDirectory { get; }
// Get the security evidence for this application domain.
Evidence Evidence { get; }
// Search path, relative to "BaseDirectory", for private assemblies.
String RelativeSearchPath { get; }
// Determine if the assemblies in the application domain are shadow copies.
bool ShadowCopyFiles { get; }
// Append a directory to the private path.
void AppendPrivatePath(String path);
// Clear the private path.
void ClearPrivatePath();
// Clear the shadow copy path.
void ClearShadowCopyPath();
#if CONFIG_REFLECTION_EMIT
// Define a dynamic assembly within this application domain.
AssemblyBuilder DefineDynamicAssembly
(AssemblyName name, AssemblyBuilderAccess access);
AssemblyBuilder DefineDynamicAssembly
(AssemblyName name, AssemblyBuilderAccess access,
Evidence evidence);
AssemblyBuilder DefineDynamicAssembly
(AssemblyName name, AssemblyBuilderAccess access,
String dir);
AssemblyBuilder DefineDynamicAssembly
(AssemblyName name, AssemblyBuilderAccess access,
String dir, Evidence evidence);
AssemblyBuilder DefineDynamicAssembly
(AssemblyName name, AssemblyBuilderAccess access,
PermissionSet requiredPermissions,
PermissionSet optionalPermissions,
PermissionSet refusedPersmissions);
AssemblyBuilder DefineDynamicAssembly
(AssemblyName name, AssemblyBuilderAccess access,
Evidence evidence, PermissionSet requiredPermissions,
PermissionSet optionalPermissions,
PermissionSet refusedPersmissions);
AssemblyBuilder DefineDynamicAssembly
(AssemblyName name, AssemblyBuilderAccess access,
String dir, PermissionSet requiredPermissions,
PermissionSet optionalPermissions,
PermissionSet refusedPersmissions);
AssemblyBuilder DefineDynamicAssembly
(AssemblyName name, AssemblyBuilderAccess access,
String dir, Evidence evidence,
PermissionSet requiredPermissions,
PermissionSet optionalPermissions,
PermissionSet refusedPersmissions);
AssemblyBuilder DefineDynamicAssembly
(AssemblyName name, AssemblyBuilderAccess access,
String dir, Evidence evidence,
PermissionSet requiredPermissions,
PermissionSet optionalPermissions,
PermissionSet refusedPersmissions,
bool isSynchronized);
#endif // CONFIG_REFLECTION_EMIT
// Execute a particular assembly within this application domain.
int ExecuteAssembly(String assemblyFile);
int ExecuteAssembly(String assemblyFile, Evidence assemblySecurity);
int ExecuteAssembly(String assemblyFile, Evidence assemblySecurity,
String[] args);
// Get a list of all assemblies in this application domain.
Assembly[] GetAssemblies();
// Fetch the object associated with a particular data name.
Object GetData(String name);
// Load an assembly into this application domain by name.
Assembly Load(AssemblyName assemblyRef);
Assembly Load(AssemblyName assemblyRef, Evidence assemblySecurity);
// Load an assembly into this application domain by string name.
Assembly Load(String assemblyString);
Assembly Load(String assemblyString, Evidence assemblySecurity);
// Load an assembly into this application domain by explicit definition.
Assembly Load(byte[] rawAssembly);
Assembly Load(byte[] rawAssembly, byte[] rawSymbolStore);
Assembly Load(byte[] rawAssembly, byte[] rawSymbolStore,
Evidence assemblySecurity);
#if CONFIG_POLICY_OBJECTS
// Set policy information for this application domain.
void SetAppDomainPolicy(PolicyLevel domainPolicy);
// Set the policy for principals.
void SetPrincipalPolicy(PrincipalPolicy policy);
// Set the default principal object for a thread.
void SetThreadPrincipal(IPrincipal principal);
#endif
// Set the cache location for shadow copied assemblies.
void SetCachePath(String s);
// Set a data item on this application domain.
void SetData(String name, Object data);
// Set the location of the shadow copy directory.
void SetShadowCopyPath(String s);
// Methods that are normally in System.Object, but which must be
// redeclared here for some unknown reason.
bool Equals(Object obj);
int GetHashCode();
Type GetType();
String ToString();
// Event that is emitted when an assembly fails to resolve.
event ResolveEventHandler AssemblyResolve;
// Event that is emitted when a process exits within this domain.
event EventHandler ProcessExit;
// Event that is emitted when a resource fails to resolve.
event ResolveEventHandler ResourceResolve;
// Event that is emitted when a type fails to resolve.
event ResolveEventHandler TypeResolve;
#endif // !ECMA_COMPAT
#if CONFIG_REMOTING
// Create an instance of a type within this application domain.
ObjectHandle CreateInstance(String assemblyName, String typeName);
ObjectHandle CreateInstance(String assemblyName, String typeName,
Object[] activationAttributes);
ObjectHandle CreateInstance(String assemblyName, String typeName,
bool ignoreCase, BindingFlags bindingAttr,
Binder binder, Object[] args,
CultureInfo culture,
Object[] activationAttributes,
Evidence securityAttributes);
// Create a remote instance of a type within this application domain.
ObjectHandle CreateInstanceFrom(String assemblyName, String typeName);
ObjectHandle CreateInstanceFrom(String assemblyName, String typeName,
Object[] activationAttributes);
ObjectHandle CreateInstanceFrom(String assemblyName, String typeName,
bool ignoreCase, BindingFlags bindingAttr,
Binder binder, Object[] args,
CultureInfo culture,
Object[] activationAttributes,
Evidence securityAttributes);
// Execute a delegate in a foreign application domain.
void DoCallBack(CrossAppDomainDelegate theDelegate);
// Get an object for controlling the lifetime service.
Object GetLifetimeService();
// Give the application domain an infinite lifetime service.
Object InitializeLifetimeService();
#endif // CONFIG_REMOTING
}; // interface _AppDomain
#endif // CONFIG_RUNTIME_INFRA
}; // namespace System
| |
// 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.IO;
using System.IO.Pipes;
using System.Threading;
using System.Threading.Tasks;
namespace System.Data.SqlClient.SNI
{
/// <summary>
/// SSL encapsulated over TDS transport. During SSL handshake, SSL packets are
/// transported in TDS packet type 0x12. Once SSL handshake has completed, SSL
/// packets are sent transparently.
/// </summary>
internal sealed class SslOverTdsStream : Stream
{
private readonly Stream _stream;
private int _packetBytes = 0;
private bool _encapsulate;
private const int PACKET_SIZE_WITHOUT_HEADER = TdsEnums.DEFAULT_LOGIN_PACKET_SIZE - TdsEnums.HEADER_LEN;
private const int PRELOGIN_PACKET_TYPE = 0x12;
/// <summary>
/// Constructor
/// </summary>
/// <param name="stream">Underlying stream</param>
public SslOverTdsStream(Stream stream)
{
_stream = stream;
_encapsulate = true;
}
/// <summary>
/// Finish SSL handshake. Stop encapsulating in TDS.
/// </summary>
public void FinishHandshake()
{
_encapsulate = false;
}
/// <summary>
/// Read buffer
/// </summary>
/// <param name="buffer">Buffer</param>
/// <param name="offset">Offset</param>
/// <param name="count">Byte count</param>
/// <returns>Bytes read</returns>
public override int Read(byte[] buffer, int offset, int count) =>
ReadInternal(buffer, offset, count, CancellationToken.None, async: false).GetAwaiter().GetResult();
/// <summary>
/// Write Buffer
/// </summary>
/// <param name="buffer"></param>
/// <param name="offset"></param>
/// <param name="count"></param>
public override void Write(byte[] buffer, int offset, int count)
=> WriteInternal(buffer, offset, count, CancellationToken.None, async: false).Wait();
/// <summary>
/// Write Buffer Asynchronosly
/// </summary>
/// <param name="buffer"></param>
/// <param name="offset"></param>
/// <param name="count"></param>
/// <param name="token"></param>
/// <returns></returns>
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken token)
=> WriteInternal(buffer, offset, count, token, async: true);
/// <summary>
/// Read Buffer Asynchronosly
/// </summary>
/// <param name="buffer"></param>
/// <param name="offset"></param>
/// <param name="count"></param>
/// <param name="token"></param>
/// <returns></returns>
public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken token)
=> ReadInternal(buffer, offset, count, token, async: true);
/// <summary>
/// Read Internal is called synchronosly when async is false
/// </summary>
private async Task<int> ReadInternal(byte[] buffer, int offset, int count, CancellationToken token, bool async)
{
int readBytes = 0;
byte[] packetData = null;
byte[] readTarget = buffer;
int readOffset = offset;
if (_encapsulate)
{
packetData = ArrayPool<byte>.Shared.Rent(count < TdsEnums.HEADER_LEN ? TdsEnums.HEADER_LEN : count);
readTarget = packetData;
readOffset = 0;
if (_packetBytes == 0)
{
// Account for split packets
while (readBytes < TdsEnums.HEADER_LEN)
{
var readBytesForHeader = async ?
await _stream.ReadAsync(packetData, readBytes, TdsEnums.HEADER_LEN - readBytes, token).ConfigureAwait(false) :
_stream.Read(packetData, readBytes, TdsEnums.HEADER_LEN - readBytes);
if (readBytesForHeader == 0)
{
throw new EndOfStreamException("End of stream reached");
}
readBytes += readBytesForHeader;
}
_packetBytes = (packetData[TdsEnums.HEADER_LEN_FIELD_OFFSET] << 8) | packetData[TdsEnums.HEADER_LEN_FIELD_OFFSET + 1];
_packetBytes -= TdsEnums.HEADER_LEN;
}
if (count > _packetBytes)
{
count = _packetBytes;
}
}
readBytes = async ?
await _stream.ReadAsync(readTarget, readOffset, count, token).ConfigureAwait(false) :
_stream.Read(readTarget, readOffset, count);
if (_encapsulate)
{
_packetBytes -= readBytes;
}
if (packetData != null)
{
Buffer.BlockCopy(packetData, 0, buffer, offset, readBytes);
ArrayPool<byte>.Shared.Return(packetData, clearArray: true);
}
return readBytes;
}
/// <summary>
/// The internal write method calls Sync APIs when Async flag is false
/// </summary>
private async Task WriteInternal(byte[] buffer, int offset, int count, CancellationToken token, bool async)
{
int currentCount = 0;
int currentOffset = offset;
while (count > 0)
{
// During the SSL negotiation phase, SSL is tunnelled over TDS packet type 0x12. After
// negotiation, the underlying socket only sees SSL frames.
//
if (_encapsulate)
{
if (count > PACKET_SIZE_WITHOUT_HEADER)
{
currentCount = PACKET_SIZE_WITHOUT_HEADER;
}
else
{
currentCount = count;
}
count -= currentCount;
// Prepend buffer data with TDS prelogin header
int combinedLength = TdsEnums.HEADER_LEN + currentCount;
byte[] combinedBuffer = ArrayPool<byte>.Shared.Rent(combinedLength);
// We can only send 4088 bytes in one packet. Header[1] is set to 1 if this is a
// partial packet (whether or not count != 0).
//
combinedBuffer[7] = 0; // touch this first for the jit bounds check
combinedBuffer[0] = PRELOGIN_PACKET_TYPE;
combinedBuffer[1] = (byte)(count > 0 ? 0 : 1);
combinedBuffer[2] = (byte)((currentCount + TdsEnums.HEADER_LEN) / 0x100);
combinedBuffer[3] = (byte)((currentCount + TdsEnums.HEADER_LEN) % 0x100);
combinedBuffer[4] = 0;
combinedBuffer[5] = 0;
combinedBuffer[6] = 0;
Array.Copy(buffer, currentOffset, combinedBuffer, TdsEnums.HEADER_LEN, (combinedLength - TdsEnums.HEADER_LEN));
if (async)
{
await _stream.WriteAsync(combinedBuffer, 0, combinedLength, token).ConfigureAwait(false);
}
else
{
_stream.Write(combinedBuffer, 0, combinedLength);
}
Array.Clear(combinedBuffer, 0, combinedLength);
ArrayPool<byte>.Shared.Return(combinedBuffer);
}
else
{
currentCount = count;
count = 0;
if (async)
{
await _stream.WriteAsync(buffer, currentOffset, currentCount, token).ConfigureAwait(false);
}
else
{
_stream.Write(buffer, currentOffset, currentCount);
}
}
if (async)
{
await _stream.FlushAsync().ConfigureAwait(false);
}
else
{
_stream.Flush();
}
currentOffset += currentCount;
}
}
/// <summary>
/// Set stream length.
/// </summary>
/// <param name="value">Length</param>
public override void SetLength(long value)
{
throw new NotSupportedException();
}
/// <summary>
/// Flush stream
/// </summary>
public override void Flush()
{
// Can sometimes get Pipe broken errors from flushing a PipeStream.
// PipeStream.Flush() also doesn't do anything, anyway.
if (!(_stream is PipeStream))
{
_stream.Flush();
}
}
/// <summary>
/// Get/set stream position
/// </summary>
public override long Position
{
get
{
throw new NotSupportedException();
}
set
{
throw new NotSupportedException();
}
}
/// <summary>
/// Seek in stream
/// </summary>
/// <param name="offset">Offset</param>
/// <param name="origin">Origin</param>
/// <returns>Position</returns>
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException();
}
/// <summary>
/// Check if stream can be read from
/// </summary>
public override bool CanRead
{
get { return _stream.CanRead; }
}
/// <summary>
/// Check if stream can be written to
/// </summary>
public override bool CanWrite
{
get { return _stream.CanWrite; }
}
/// <summary>
/// Check if stream can be seeked
/// </summary>
public override bool CanSeek
{
get { return false; } // Seek not supported
}
/// <summary>
/// Get stream length
/// </summary>
public override long Length
{
get
{
throw new NotSupportedException();
}
}
}
}
| |
// <copyright file="MatlabWriterTests.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;
using System.IO;
using System.Numerics;
using MathNet.Numerics.Data.Matlab;
using MathNet.Numerics.LinearAlgebra;
using MathNet.Numerics.LinearAlgebra.Storage;
using NUnit.Framework;
namespace MathNet.Numerics.Data.UnitTests.Matlab
{
/// <summary>
/// MATLAB matrix writer tests.
/// </summary>
[TestFixture]
public class MatlabWriterTests
{
[Test]
public void WriteBadMatricesThrowsArgumentException()
{
Matrix<float> matrix = Matrix<float>.Build.Dense(1, 1);
Assert.Throws<ArgumentException>(() => MatlabWriter.Write("somefile3", matrix, string.Empty));
Assert.Throws<ArgumentException>(() => MatlabWriter.Write("somefile3", matrix, null));
Assert.Throws<ArgumentException>(() => MatlabWriter.Write("somefile3", matrix, "some matrix"));
Assert.Throws<ArgumentException>(() => MatlabWriter.Write("somefile3", new[] { matrix }, new[] { string.Empty }));
Assert.Throws<ArgumentException>(() => MatlabWriter.Write("somefile3", new[] { matrix }, new string[] { null }));
Assert.Throws<ArgumentException>(() => MatlabWriter.Write("somefile3", new[] { matrix, matrix }, new[] { "matrix" }));
Assert.Throws<ArgumentException>(() => MatlabWriter.Write("somefile3", new[] { matrix }, new[] { "some matrix" }));
}
[Test]
public void CanWriteDoubleMatrices()
{
Matrix<double> mat1 = Matrix<double>.Build.Dense(5, 5);
for (var i = 0; i < mat1.ColumnCount; i++)
{
mat1[i, i] = i + .1;
}
Matrix<double> mat2 = Matrix<double>.Build.Dense(4, 5);
for (var i = 0; i < mat2.RowCount; i++)
{
mat2[i, i] = i + .1;
}
Matrix<double> mat3 = Matrix<double>.Build.Sparse(5, 4);
mat3[0, 0] = 1.1;
mat3[0, 2] = 2.2;
mat3[4, 3] = 3.3;
Matrix<double> mat4 = Matrix<double>.Build.Sparse(3, 5);
mat4[0, 0] = 1.1;
mat4[0, 2] = 2.2;
mat4[2, 4] = 3.3;
Matrix<double>[] write = { mat1, mat2, mat3, mat4 };
string[] names = { "mat1", "dense_matrix_2", "s1", "sparse2" };
if (File.Exists("testd.mat"))
{
File.Delete("testd.mat");
}
MatlabWriter.Write("testd.mat", write, names);
var read = MatlabReader.ReadAll<double>("testd.mat", names);
Assert.AreEqual(write.Length, read.Count);
for (var i = 0; i < write.Length; i++)
{
var w = write[i];
var r = read[names[i]];
Assert.AreEqual(w.RowCount, r.RowCount);
Assert.AreEqual(w.ColumnCount, r.ColumnCount);
Assert.IsTrue(w.Equals(r));
}
File.Delete("testd.mat");
}
[Test]
public void CanWriteFloatMatrices()
{
Matrix<float> mat1 = Matrix<float>.Build.Dense(5, 3);
for (var i = 0; i < mat1.ColumnCount; i++)
{
mat1[i, i] = i + .1f;
}
Matrix<float> mat2 = Matrix<float>.Build.Dense(4, 5);
for (var i = 0; i < mat2.RowCount; i++)
{
mat2[i, i] = i + .1f;
}
Matrix<float> mat3 = Matrix<float>.Build.Sparse(5, 4);
mat3[0, 0] = 1.1f;
mat3[0, 2] = 2.2f;
mat3[4, 3] = 3.3f;
Matrix<float> mat4 = Matrix<float>.Build.Sparse(3, 5);
mat4[0, 0] = 1.1f;
mat4[0, 2] = 2.2f;
mat4[2, 4] = 3.3f;
Matrix<float>[] write = { mat1, mat2, mat3, mat4 };
string[] names = { "mat1", "dense_matrix_2", "s1", "sparse2" };
if (File.Exists("tests.mat"))
{
File.Delete("tests.mat");
}
MatlabWriter.Write("tests.mat", write, names);
var read = MatlabReader.ReadAll<float>("tests.mat", names);
Assert.AreEqual(write.Length, read.Count);
for (var i = 0; i < write.Length; i++)
{
var w = write[i];
var r = read[names[i]];
Assert.AreEqual(w.RowCount, r.RowCount);
Assert.AreEqual(w.ColumnCount, r.ColumnCount);
Assert.IsTrue(w.Equals(r));
}
File.Delete("tests.mat");
}
/// <summary>
/// Can write complex32 matrices.
/// </summary>
[Test]
public void CanWriteComplex32Matrices()
{
Matrix<Complex32> mat1 = Matrix<Complex32>.Build.Dense(5, 3);
for (var i = 0; i < mat1.ColumnCount; i++)
{
mat1[i, i] = new Complex32(i + .1f, i + .1f);
}
Matrix<Complex32> mat2 = Matrix<Complex32>.Build.Dense(4, 5);
for (var i = 0; i < mat2.RowCount; i++)
{
mat2[i, i] = new Complex32(i + .1f, i + .1f);
}
Matrix<Complex32> mat3 = Matrix<Complex32>.Build.Sparse(5, 4);
mat3[0, 0] = new Complex32(1.1f, 1.1f);
mat3[0, 2] = new Complex32(2.2f, 2.2f);
mat3[4, 3] = new Complex32(3.3f, 3.3f);
Matrix<Complex32> mat4 = Matrix<Complex32>.Build.Sparse(3, 5);
mat4[0, 0] = new Complex32(1.1f, 1.1f);
mat4[0, 2] = new Complex32(2.2f, 2.2f);
mat4[2, 4] = new Complex32(3.3f, 3.3f);
Matrix<Complex32>[] write = { mat1, mat2, mat3, mat4 };
string[] names = { "mat1", "dense_matrix_2", "s1", "sparse2" };
if (File.Exists("testc.mat"))
{
File.Delete("testc.mat");
}
MatlabWriter.Write("testc.mat", write, names);
var read = MatlabReader.ReadAll<Complex32>("testc.mat", names);
Assert.AreEqual(write.Length, read.Count);
for (var i = 0; i < write.Length; i++)
{
var w = write[i];
var r = read[names[i]];
Assert.AreEqual(w.RowCount, r.RowCount);
Assert.AreEqual(w.ColumnCount, r.ColumnCount);
Assert.IsTrue(w.Equals(r));
}
File.Delete("testc.mat");
}
/// <summary>
/// Can write complex matrices.
/// </summary>
[Test]
public void CanWriteComplexMatrices()
{
Matrix<Complex> mat1 = Matrix<Complex>.Build.Dense(5, 3);
for (var i = 0; i < mat1.ColumnCount; i++)
{
mat1[i, i] = new Complex(i + .1, i + .1);
}
Matrix<Complex> mat2 = Matrix<Complex>.Build.Dense(4, 5);
for (var i = 0; i < mat2.RowCount; i++)
{
mat2[i, i] = new Complex(i + .1, i + .1);
}
Matrix<Complex> mat3 = Matrix<Complex>.Build.Sparse(5, 4);
mat3[0, 0] = new Complex(1.1, 1.1);
mat3[0, 2] = new Complex(2.2, 2.2);
mat3[4, 3] = new Complex(3.3, 3.3);
Matrix<Complex> mat4 = Matrix<Complex>.Build.Sparse(3, 5);
mat4[0, 0] = new Complex(1.1, 1.1);
mat4[0, 2] = new Complex(2.2, 2.2);
mat4[2, 4] = new Complex(3.3, 3.3);
Matrix<Complex>[] write = { mat1, mat2, mat3, mat4 };
string[] names = { "mat1", "dense_matrix_2", "s1", "sparse2" };
if (File.Exists("testz.mat"))
{
File.Delete("testz.mat");
}
MatlabWriter.Write("testz.mat", write, names);
var read = MatlabReader.ReadAll<Complex>("testz.mat", names);
Assert.AreEqual(write.Length, read.Count);
for (var i = 0; i < write.Length; i++)
{
var w = write[i];
var r = read[names[i]];
Assert.AreEqual(w.RowCount, r.RowCount);
Assert.AreEqual(w.ColumnCount, r.ColumnCount);
Assert.IsTrue(w.Equals(r));
}
File.Delete("testz.mat");
}
/// <summary>
/// Write bad matrix throws <c>ArgumentException</c>.
/// </summary>
[Test]
public void WriteBadMatrixThrowsArgumentException()
{
var matrix = Matrix<float>.Build.Dense(1, 1);
Assert.Throws<ArgumentException>(() => MatlabWriter.Write("somefile1", matrix, string.Empty));
Assert.Throws<ArgumentException>(() => MatlabWriter.Write("somefile1", matrix, null));
}
/// <summary>
/// Write <c>null</c> matrix throws <c>ArgumentNullException</c>.
/// </summary>
[Test]
public void WriteNullMatrixThrowsArgumentNullException()
{
Assert.Throws<ArgumentNullException>(() => MatlabWriter.Write<double>("somefile2", null, "matrix"));
}
[Test]
public void MatlabMatrixRoundtrip()
{
var denseDouble = Matrix<double>.Build.Random(20, 20);
var denseComplex = Matrix<Complex>.Build.Random(10, 10);
var diagonalDouble = Matrix<double>.Build.DiagonalOfDiagonalArray(new[] { 1.0, 2.0, 3.0 });
var sparseDouble = Matrix<double>.Build.Sparse(20, 20, (i, j) => i%(j+1) == 2 ? i + 10*j : 0);
var denseDoubleP = MatlabWriter.Pack(denseDouble, "denseDouble");
var denseComplexP = MatlabWriter.Pack(denseComplex, "denseComplex");
var diagonalDoubleP = MatlabWriter.Pack(diagonalDouble, "diagonalDouble");
var sparseDoubleP = MatlabWriter.Pack(sparseDouble, "sparseDouble");
Assert.That(MatlabReader.Unpack<double>(denseDoubleP).Equals(denseDouble));
Assert.That(MatlabReader.Unpack<Complex>(denseComplexP).Equals(denseComplex));
Assert.That(MatlabReader.Unpack<double>(diagonalDoubleP).Equals(diagonalDouble));
Assert.That(MatlabReader.Unpack<double>(sparseDoubleP).Equals(sparseDouble));
Assert.That(MatlabReader.Unpack<double>(denseDoubleP).Storage, Is.TypeOf<DenseColumnMajorMatrixStorage<double>>());
Assert.That(MatlabReader.Unpack<Complex>(denseComplexP).Storage, Is.TypeOf<DenseColumnMajorMatrixStorage<Complex>>());
Assert.That(MatlabReader.Unpack<double>(diagonalDoubleP).Storage, Is.TypeOf<SparseCompressedRowMatrixStorage<double>>());
Assert.That(MatlabReader.Unpack<double>(sparseDoubleP).Storage, Is.TypeOf<SparseCompressedRowMatrixStorage<double>>());
if (File.Exists("testrt.mat"))
{
File.Delete("testrt.mat");
}
MatlabWriter.Store("testrt.mat", new[] { denseDoubleP, denseComplexP, diagonalDoubleP, sparseDoubleP });
Assert.That(MatlabReader.Read<double>("testrt.mat", "denseDouble").Equals(denseDouble));
Assert.That(MatlabReader.Read<Complex>("testrt.mat", "denseComplex").Equals(denseComplex));
Assert.That(MatlabReader.Read<double>("testrt.mat", "diagonalDouble").Equals(diagonalDouble));
Assert.That(MatlabReader.Read<double>("testrt.mat", "sparseDouble").Equals(sparseDouble));
Assert.That(MatlabReader.Read<double>("testrt.mat", "denseDouble").Storage, Is.TypeOf<DenseColumnMajorMatrixStorage<double>>());
Assert.That(MatlabReader.Read<Complex>("testrt.mat", "denseComplex").Storage, Is.TypeOf<DenseColumnMajorMatrixStorage<Complex>>());
Assert.That(MatlabReader.Read<double>("testrt.mat", "diagonalDouble").Storage, Is.TypeOf<SparseCompressedRowMatrixStorage<double>>());
Assert.That(MatlabReader.Read<double>("testrt.mat", "sparseDouble").Storage, Is.TypeOf<SparseCompressedRowMatrixStorage<double>>());
File.Delete("testrt.mat");
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.UsePatternMatching;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UsePatternMatching
{
public partial class CSharpAsAndNullCheckTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
{
internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace)
=> (new CSharpAsAndNullCheckDiagnosticAnalyzer(), new CSharpAsAndNullCheckCodeFixProvider());
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)]
public async Task InlineTypeCheck1()
{
await TestInRegularAndScriptAsync(
@"class C
{
void M()
{
[|var|] x = o as string;
if (x != null)
{
}
}
}",
@"class C
{
void M()
{
if (o is string x)
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)]
public async Task InlineTypeCheckInvertedCheck1()
{
await TestInRegularAndScriptAsync(
@"class C
{
void M()
{
[|var|] x = o as string;
if (null != x)
{
}
}
}",
@"class C
{
void M()
{
if (o is string x)
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)]
public async Task TestMissingInCSharp6()
{
await TestMissingAsync(
@"class C
{
void M()
{
[|var|] x = o as string;
if (x != null)
{
}
}
}", new TestParameters(parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp6)));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)]
public async Task TestMissingInWrongName()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M()
{
[|var|] y = o as string;
if (x != null)
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)]
public async Task TestMissingOnNonDeclaration()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M()
{
[|y|] = o as string;
if (x != null)
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)]
public async Task TestMissingOnIsExpression()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M()
{
[|var|] x = o is string;
if (x != null)
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)]
public async Task InlineTypeCheckComplexExpression1()
{
await TestInRegularAndScriptAsync(
@"class C
{
void M()
{
[|var|] x = (o ? z : w) as string;
if (x != null)
{
}
}
}",
@"class C
{
void M()
{
if ((o ? z : w) is string x)
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)]
public async Task TestMissingOnNullEquality()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M()
{
[|var|] x = o is string;
if (x == null)
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)]
public async Task TestInlineTypeCheckWithElse()
{
await TestInRegularAndScriptAsync(
@"class C
{
void M()
{
[|var|] x = o as string;
if (null != x)
{
}
else
{
}
}
}",
@"class C
{
void M()
{
if (o is string x)
{
}
else
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)]
public async Task TestComments1()
{
await TestInRegularAndScriptAsync(
@"class C
{
void M()
{
// prefix comment
[|var|] x = o as string;
if (x != null)
{
}
}
}",
@"class C
{
void M()
{
// prefix comment
if (o is string x)
{
}
}
}", ignoreTrivia: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)]
public async Task TestComments2()
{
await TestInRegularAndScriptAsync(
@"class C
{
void M()
{
[|var|] x = o as string; // suffix comment
if (x != null)
{
}
}
}",
@"class C
{
void M()
{
// suffix comment
if (o is string x)
{
}
}
}", ignoreTrivia: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)]
public async Task TestComments3()
{
await TestInRegularAndScriptAsync(
@"class C
{
void M()
{
// prefix comment
[|var|] x = o as string; // suffix comment
if (x != null)
{
}
}
}",
@"class C
{
void M()
{
// prefix comment
// suffix comment
if (o is string x)
{
}
}
}", ignoreTrivia: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)]
public async Task InlineTypeCheckComplexCondition1()
{
await TestInRegularAndScriptAsync(
@"class C
{
void M()
{
[|var|] x = o as string;
if (x != null ? 0 : 1)
{
}
}
}",
@"class C
{
void M()
{
if (o is string x ? 0 : 1)
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)]
public async Task InlineTypeCheckComplexCondition2()
{
await TestInRegularAndScriptAsync(
@"class C
{
void M()
{
[|var|] x = o as string;
if ((x != null))
{
}
}
}",
@"class C
{
void M()
{
if ((o is string x))
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)]
public async Task InlineTypeCheckComplexCondition3()
{
await TestInRegularAndScriptAsync(
@"class C
{
void M()
{
[|var|] x = o as string;
if (x != null && x.Length > 0)
{
}
}
}",
@"class C
{
void M()
{
if (o is string x && x.Length > 0)
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)]
public async Task TestDefiniteAssignment1()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M()
{
[|var|] x = o as string;
if (x != null && x.Length > 0)
{
}
else if (x != null)
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)]
public async Task TestDefiniteAssignment2()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M()
{
[|var|] x = o as string;
if (x != null && x.Length > 0)
{
}
Console.WriteLine(x);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)]
public async Task TestDefiniteAssignment3()
{
await TestInRegularAndScriptAsync(
@"class C
{
void M()
{
[|var|] x = o as string;
if (x != null && x.Length > 0)
{
}
x = null;
Console.WriteLine(x);
}
}",
@"class C
{
void M()
{
if (o is string x && x.Length > 0)
{
}
x = null;
Console.WriteLine(x);
}
}");
}
[WorkItem(15957, "https://github.com/dotnet/roslyn/issues/15957")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)]
public async Task TestTrivia1()
{
await TestInRegularAndScriptAsync(
@"class C
{
void M(object y)
{
if (y != null)
{
}
[|var|] x = o as string;
if (x != null)
{
}
}
}",
@"class C
{
void M(object y)
{
if (y != null)
{
}
if (o is string x)
{
}
}
}", ignoreTrivia: false);
}
[WorkItem(17129, "https://github.com/dotnet/roslyn/issues/17129")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)]
public async Task TestTrivia2()
{
await TestInRegularAndScriptAsync(
@"using System;
namespace N
{
class Program
{
public static void Main()
{
object o = null;
int i = 0;
[|var|] s = o as string;
if (s != null && i == 0 && i == 1 &&
i == 2 && i == 3 &&
i == 4 && i == 5)
{
Console.WriteLine();
}
}
}
}",
@"using System;
namespace N
{
class Program
{
public static void Main()
{
object o = null;
int i = 0;
if (o is string s && i == 0 && i == 1 &&
i == 2 && i == 3 &&
i == 4 && i == 5)
{
Console.WriteLine();
}
}
}
}", ignoreTrivia: false);
}
[WorkItem(17122, "https://github.com/dotnet/roslyn/issues/17122")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)]
public async Task TestMissingOnNullableType()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
namespace N
{
class Program
{
public static void Main()
{
object o = null;
[|var|] i = o as int?;
if (i != null)
Console.WriteLine(i);
}
}
}");
}
[WorkItem(18053, "https://github.com/dotnet/roslyn/issues/18053")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)]
public async Task TestMissingWhenTypesDoNotMatch()
{
await TestMissingInRegularAndScriptAsync(
@"class SyntaxNode
{
public SyntaxNode Parent;
}
class BaseParameterListSyntax : SyntaxNode
{
}
class ParameterSyntax : SyntaxNode
{
}
public static class C
{
static void M(ParameterSyntax parameter)
{
[|SyntaxNode|] parent = parameter.Parent as BaseParameterListSyntax;
if (parent != null)
{
parent = parent.Parent;
}
}
}");
}
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 1.1.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace ApplicationGateway
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for ExpressRouteCircuitPeeringsOperations.
/// </summary>
public static partial class ExpressRouteCircuitPeeringsOperationsExtensions
{
/// <summary>
/// Deletes the specified peering from the specified express route circuit.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='peeringName'>
/// The name of the peering.
/// </param>
public static void Delete(this IExpressRouteCircuitPeeringsOperations operations, string resourceGroupName, string circuitName, string peeringName)
{
operations.DeleteAsync(resourceGroupName, circuitName, peeringName).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes the specified peering from the specified express route circuit.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='peeringName'>
/// The name of the peering.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this IExpressRouteCircuitPeeringsOperations operations, string resourceGroupName, string circuitName, string peeringName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.DeleteWithHttpMessagesAsync(resourceGroupName, circuitName, peeringName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Gets the specified authorization from the specified express route circuit.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='peeringName'>
/// The name of the peering.
/// </param>
public static ExpressRouteCircuitPeering Get(this IExpressRouteCircuitPeeringsOperations operations, string resourceGroupName, string circuitName, string peeringName)
{
return operations.GetAsync(resourceGroupName, circuitName, peeringName).GetAwaiter().GetResult();
}
/// <summary>
/// Gets the specified authorization from the specified express route circuit.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='peeringName'>
/// The name of the peering.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ExpressRouteCircuitPeering> GetAsync(this IExpressRouteCircuitPeeringsOperations operations, string resourceGroupName, string circuitName, string peeringName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, circuitName, peeringName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Creates or updates a peering in the specified express route circuits.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='peeringName'>
/// The name of the peering.
/// </param>
/// <param name='peeringParameters'>
/// Parameters supplied to the create or update express route circuit peering
/// operation.
/// </param>
public static ExpressRouteCircuitPeering CreateOrUpdate(this IExpressRouteCircuitPeeringsOperations operations, string resourceGroupName, string circuitName, string peeringName, ExpressRouteCircuitPeering peeringParameters)
{
return operations.CreateOrUpdateAsync(resourceGroupName, circuitName, peeringName, peeringParameters).GetAwaiter().GetResult();
}
/// <summary>
/// Creates or updates a peering in the specified express route circuits.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='peeringName'>
/// The name of the peering.
/// </param>
/// <param name='peeringParameters'>
/// Parameters supplied to the create or update express route circuit peering
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ExpressRouteCircuitPeering> CreateOrUpdateAsync(this IExpressRouteCircuitPeeringsOperations operations, string resourceGroupName, string circuitName, string peeringName, ExpressRouteCircuitPeering peeringParameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, circuitName, peeringName, peeringParameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all peerings in a specified express route circuit.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
public static IPage<ExpressRouteCircuitPeering> List(this IExpressRouteCircuitPeeringsOperations operations, string resourceGroupName, string circuitName)
{
return operations.ListAsync(resourceGroupName, circuitName).GetAwaiter().GetResult();
}
/// <summary>
/// Gets all peerings in a specified express route circuit.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<ExpressRouteCircuitPeering>> ListAsync(this IExpressRouteCircuitPeeringsOperations operations, string resourceGroupName, string circuitName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(resourceGroupName, circuitName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes the specified peering from the specified express route circuit.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='peeringName'>
/// The name of the peering.
/// </param>
public static void BeginDelete(this IExpressRouteCircuitPeeringsOperations operations, string resourceGroupName, string circuitName, string peeringName)
{
operations.BeginDeleteAsync(resourceGroupName, circuitName, peeringName).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes the specified peering from the specified express route circuit.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='peeringName'>
/// The name of the peering.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginDeleteAsync(this IExpressRouteCircuitPeeringsOperations operations, string resourceGroupName, string circuitName, string peeringName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, circuitName, peeringName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Creates or updates a peering in the specified express route circuits.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='peeringName'>
/// The name of the peering.
/// </param>
/// <param name='peeringParameters'>
/// Parameters supplied to the create or update express route circuit peering
/// operation.
/// </param>
public static ExpressRouteCircuitPeering BeginCreateOrUpdate(this IExpressRouteCircuitPeeringsOperations operations, string resourceGroupName, string circuitName, string peeringName, ExpressRouteCircuitPeering peeringParameters)
{
return operations.BeginCreateOrUpdateAsync(resourceGroupName, circuitName, peeringName, peeringParameters).GetAwaiter().GetResult();
}
/// <summary>
/// Creates or updates a peering in the specified express route circuits.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='peeringName'>
/// The name of the peering.
/// </param>
/// <param name='peeringParameters'>
/// Parameters supplied to the create or update express route circuit peering
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ExpressRouteCircuitPeering> BeginCreateOrUpdateAsync(this IExpressRouteCircuitPeeringsOperations operations, string resourceGroupName, string circuitName, string peeringName, ExpressRouteCircuitPeering peeringParameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, circuitName, peeringName, peeringParameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all peerings in a specified express route circuit.
/// </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<ExpressRouteCircuitPeering> ListNext(this IExpressRouteCircuitPeeringsOperations operations, string nextPageLink)
{
return operations.ListNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Gets all peerings in a specified express route circuit.
/// </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<ExpressRouteCircuitPeering>> ListNextAsync(this IExpressRouteCircuitPeeringsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2007-2012 Charlie Poole
//
// 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;
#if CLR_2_0 || CLR_4_0
using System.Collections.Generic;
#endif
using System.Reflection;
namespace NUnit.Framework.Internal
{
/// <summary>
/// Helper methods for inspecting a type by reflection.
///
/// Many of these methods take ICustomAttributeProvider as an
/// argument to avoid duplication, even though certain attributes can
/// only appear on specific types of members, like MethodInfo or Type.
///
/// In the case where a type is being examined for the presence of
/// an attribute, interface or named member, the Reflect methods
/// operate with the full name of the member being sought. This
/// removes the necessity of the caller having a reference to the
/// assembly that defines the item being sought and allows the
/// NUnit core to inspect assemblies that reference an older
/// version of the NUnit framework.
/// </summary>
public class Reflect
{
private static readonly BindingFlags AllMembers = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.FlattenHierarchy;
// A zero-length Type array - not provided by System.Type for all CLR versions we support.
private static readonly Type[] EmptyTypes = new Type[0];
#region Get Methods of a type
/// <summary>
/// Examine a fixture type and return an array of methods having a
/// particular attribute. The array is order with base methods first.
/// </summary>
/// <param name="fixtureType">The type to examine</param>
/// <param name="attributeType">The attribute Type to look for</param>
/// <param name="inherit">Specifies whether to search the fixture type inheritance chain</param>
/// <returns>The array of methods found</returns>
public static MethodInfo[] GetMethodsWithAttribute(Type fixtureType, Type attributeType, bool inherit)
{
MethodInfoList list = new MethodInfoList();
foreach (MethodInfo method in fixtureType.GetMethods(AllMembers))
{
if (method.IsDefined(attributeType, inherit))
list.Add(method);
}
list.Sort(new BaseTypesFirstComparer());
return list.ToArray();
}
#if CLR_2_0 || CLR_4_0
private class BaseTypesFirstComparer : IComparer<MethodInfo>
{
public int Compare(MethodInfo m1, MethodInfo m2)
{
if (m1 == null || m2 == null) return 0;
Type m1Type = m1.DeclaringType;
Type m2Type = m2.DeclaringType;
if ( m1Type == m2Type ) return 0;
if ( m1Type.IsAssignableFrom(m2Type) ) return -1;
return 1;
}
}
#else
private class BaseTypesFirstComparer : IComparer
{
public int Compare(object x, object y)
{
MethodInfo m1 = x as MethodInfo;
MethodInfo m2 = y as MethodInfo;
if (m1 == null || m2 == null) return 0;
Type m1Type = m1.DeclaringType;
Type m2Type = m2.DeclaringType;
if (m1Type == m2Type) return 0;
if (m1Type.IsAssignableFrom(m2Type)) return -1;
return 1;
}
}
#endif
/// <summary>
/// Examine a fixture type and return true if it has a method with
/// a particular attribute.
/// </summary>
/// <param name="fixtureType">The type to examine</param>
/// <param name="attributeType">The attribute Type to look for</param>
/// <param name="inherit">Specifies whether to search the fixture type inheritance chain</param>
/// <returns>True if found, otherwise false</returns>
public static bool HasMethodWithAttribute(Type fixtureType, Type attributeType, bool inherit)
{
foreach (MethodInfo method in fixtureType.GetMethods(AllMembers))
{
if (method.IsDefined(attributeType, inherit))
return true;
}
return false;
}
#endregion
#region Invoke Constructors
/// <summary>
/// Invoke the default constructor on a Type
/// </summary>
/// <param name="type">The Type to be constructed</param>
/// <returns>An instance of the Type</returns>
public static object Construct(Type type)
{
ConstructorInfo ctor = type.GetConstructor(EmptyTypes);
if (ctor == null)
throw new InvalidTestFixtureException(type.FullName + " does not have a default constructor");
return ctor.Invoke(null);
}
/// <summary>
/// Invoke a constructor on a Type with arguments
/// </summary>
/// <param name="type">The Type to be constructed</param>
/// <param name="arguments">Arguments to the constructor</param>
/// <returns>An instance of the Type</returns>
public static object Construct(Type type, object[] arguments)
{
if (arguments == null) return Construct(type);
Type[] argTypes = GetTypeArray(arguments);
ConstructorInfo ctor = type.GetConstructor(argTypes);
if (ctor == null)
throw new InvalidTestFixtureException(type.FullName + " does not have a suitable constructor");
return ctor.Invoke(arguments);
}
/// <summary>
/// Returns an array of types from an array of objects.
/// Used because the compact framework doesn't support
/// Type.GetTypeArray()
/// </summary>
/// <param name="objects">An array of objects</param>
/// <returns>An array of Types</returns>
private static Type[] GetTypeArray(object[] objects)
{
Type[] types = new Type[objects.Length];
int index = 0;
foreach (object o in objects)
types[index++] = o.GetType();
return types;
}
#endregion
#region Invoke Methods
/// <summary>
/// Invoke a parameterless method returning void on an object.
/// </summary>
/// <param name="method">A MethodInfo for the method to be invoked</param>
/// <param name="fixture">The object on which to invoke the method</param>
public static object InvokeMethod( MethodInfo method, object fixture )
{
return InvokeMethod( method, fixture, null );
}
/// <summary>
/// Invoke a method, converting any TargetInvocationException to an NUnitException.
/// </summary>
/// <param name="method">A MethodInfo for the method to be invoked</param>
/// <param name="fixture">The object on which to invoke the method</param>
/// <param name="args">The argument list for the method</param>
/// <returns>The return value from the invoked method</returns>
public static object InvokeMethod( MethodInfo method, object fixture, params object[] args )
{
if(method != null)
{
#if !PORTABLE
if (fixture == null && !method.IsStatic)
Console.WriteLine("Trying to call {0} without an instance", method.Name);
#endif
try
{
return method.Invoke( fixture, args );
}
catch(Exception e)
{
if (e is TargetInvocationException)
throw new NUnitException("Rethrown", e.InnerException);
else
throw new NUnitException("Rethrown", e);
}
}
return null;
}
#endregion
#region Private Constructor for static-only class
private Reflect() { }
#endregion
#if CLR_2_0 || CLR_4_0
class MethodInfoList : List<MethodInfo> { }
#else
class MethodInfoList : ArrayList
{
public new MethodInfo[] ToArray()
{
return (MethodInfo[])base.ToArray(typeof(MethodInfo));
}
}
#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.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void Permute2x128Int322()
{
var test = new ImmBinaryOpTest__Permute2x128Int322();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class ImmBinaryOpTest__Permute2x128Int322
{
private struct TestStruct
{
public Vector256<Int32> _fld1;
public Vector256<Int32> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref testStruct._fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref testStruct._fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>());
return testStruct;
}
public void RunStructFldScenario(ImmBinaryOpTest__Permute2x128Int322 testClass)
{
var result = Avx.Permute2x128(_fld1, _fld2, 2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32);
private static Int32[] _data1 = new Int32[Op1ElementCount];
private static Int32[] _data2 = new Int32[Op2ElementCount];
private static Vector256<Int32> _clsVar1;
private static Vector256<Int32> _clsVar2;
private Vector256<Int32> _fld1;
private Vector256<Int32> _fld2;
private SimpleBinaryOpTest__DataTable<Int32, Int32, Int32> _dataTable;
static ImmBinaryOpTest__Permute2x128Int322()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>());
}
public ImmBinaryOpTest__Permute2x128Int322()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
_dataTable = new SimpleBinaryOpTest__DataTable<Int32, Int32, Int32>(_data1, _data2, new Int32[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Avx.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Avx.Permute2x128(
Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr),
2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Avx.Permute2x128(
Avx.LoadVector256((Int32*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Int32*)(_dataTable.inArray2Ptr)),
2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Avx.Permute2x128(
Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray2Ptr)),
2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Avx).GetMethod(nameof(Avx.Permute2x128), new Type[] { typeof(Vector256<Int32>), typeof(Vector256<Int32>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr),
(byte)2
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx).GetMethod(nameof(Avx.Permute2x128), new Type[] { typeof(Vector256<Int32>), typeof(Vector256<Int32>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadVector256((Int32*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Int32*)(_dataTable.inArray2Ptr)),
(byte)2
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx).GetMethod(nameof(Avx.Permute2x128), new Type[] { typeof(Vector256<Int32>), typeof(Vector256<Int32>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray2Ptr)),
(byte)2
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx.Permute2x128(
_clsVar1,
_clsVar2,
2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var left = Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr);
var result = Avx.Permute2x128(left, right, 2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var left = Avx.LoadVector256((Int32*)(_dataTable.inArray1Ptr));
var right = Avx.LoadVector256((Int32*)(_dataTable.inArray2Ptr));
var result = Avx.Permute2x128(left, right, 2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var left = Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray1Ptr));
var right = Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray2Ptr));
var result = Avx.Permute2x128(left, right, 2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new ImmBinaryOpTest__Permute2x128Int322();
var result = Avx.Permute2x128(test._fld1, test._fld2, 2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx.Permute2x128(_fld1, _fld2, 2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Avx.Permute2x128(test._fld1, test._fld2, 2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector256<Int32> left, Vector256<Int32> right, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray1 = new Int32[Op1ElementCount];
Int32[] inArray2 = new Int32[Op2ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), left);
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int32>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray1 = new Int32[Op1ElementCount];
Int32[] inArray2 = new Int32[Op2ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), (uint)Unsafe.SizeOf<Vector256<Int32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), (uint)Unsafe.SizeOf<Vector256<Int32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int32>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Int32[] left, Int32[] right, Int32[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (result[0] != right[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != (i < 4 ? right[i] : left[i-4]))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx)}.{nameof(Avx.Permute2x128)}<Int32>(Vector256<Int32>.2, Vector256<Int32>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
using System;
using System.Collections;
using System.Xml;
using System.Collections.Generic;
namespace Platform.Xml.Serialization
{
/// <summary>
/// Type serializer that supports serialization of objects supporting IDictionary.
/// </summary>
/// <example>
/// <code>
/// public class Pig
/// {
/// [XmlElement]
/// public string Name = "piglet"
/// }
///
/// public class Cow
/// {
/// [XmlAttribute]
/// public string Name = "daisy"
/// }
///
/// public class Farm
/// {
/// [DictionaryElementType(typeof(Pig), "pig")]
/// [DictionaryElementType(typeof(Cow), "cow")]
/// public IDictionary Animals;
///
/// public Farm()
/// {
/// IDictionary dictionary = new Hashtable();
/// dictionary["Piglet"] = new Pig();
/// dictionary["Daisy"] = new Cow();
/// }
/// }
/// </code>
///
/// Serialized output of Farm:
///
/// <code>
/// <Farm>
/// <Animals>
/// <Piglet typealias="pig"><name>piglet</name></Piglet>
/// <Daisy typealias="cow" name="daisy"></Daisy>
/// </Animals>
/// </Farm>
/// </code>
/// If only one DictionaryElementAttribute is present, the dictionary is assumed to only
/// contain the type specified by that attribute. The typealias is therefore not needed
/// and will be omitted from the serialized output. If a serializer with multiple type
/// aliases deserializes an element without a typealias then the first type as defined by
/// the first DictionaryElementAttribute is used.
/// </example>
public class DictionaryTypeSerializer
: ComplexTypeTypeSerializer
{
public override bool MemberBound => true;
public override Type SupportedType => typeof(System.Collections.IDictionary);
private readonly IDictionary<Type, DictionaryItem> typeToItemMap;
private readonly IDictionary<string, DictionaryItem> aliasToItemMap;
private class DictionaryItem
{
public string typeAlias;
public XmlDictionaryElementTypeAttribute attribute;
public TypeSerializer serializer;
}
public DictionaryTypeSerializer(SerializationMemberInfo memberInfo, TypeSerializerCache cache, SerializerOptions options)
: base(memberInfo, memberInfo.ReturnType, cache, options)
{
typeToItemMap = new Dictionary<Type, DictionaryItem>();
aliasToItemMap = new Dictionary<string, DictionaryItem>();
Scan(memberInfo, cache, options);
}
private void Scan(SerializationMemberInfo memberInfo, TypeSerializerCache cache, SerializerOptions options)
{
XmlSerializationAttribute[] attribs;
var attributes = new List<Attribute>();
// Get the ElementType attributes specified on the type itself as long
// as we're not the type itself!
if (memberInfo.MemberInfo != memberInfo.ReturnType)
{
var smi = new SerializationMemberInfo(memberInfo.ReturnType, options, cache);
attribs = smi.GetApplicableAttributes(typeof(XmlDictionaryElementTypeAttribute));
foreach (XmlSerializationAttribute a in attribs)
{
attributes.Add(a);
}
}
// Get the ElementType attributes specified on the member.
attribs = memberInfo.GetApplicableAttributes(typeof(XmlDictionaryElementTypeAttribute));
foreach (var a in attribs)
{
attributes.Add(a);
}
foreach (XmlDictionaryElementTypeAttribute attribute in attributes)
{
var dictionaryItem = new DictionaryItem();
var smi2 = new SerializationMemberInfo(attribute.ElementType, options, cache);
if (attribute.TypeAlias == null)
{
attribute.TypeAlias = smi2.SerializedName;
}
dictionaryItem.attribute = attribute;
dictionaryItem.typeAlias = attribute.TypeAlias;
// Check if a specific type of serializer is specified.
if (attribute.SerializerType == null)
{
// Figure out the serializer based on the type of the element.
dictionaryItem.serializer = cache.GetTypeSerializerBySupportedType(attribute.ElementType, smi2);
}
else
{
// Get the type of serializer they specify.
dictionaryItem.serializer = cache.GetTypeSerializerBySerializerType(attribute.SerializerType, smi2);
}
primaryDictionaryItem = dictionaryItem;
typeToItemMap[attribute.ElementType] = dictionaryItem;
aliasToItemMap[attribute.TypeAlias] = dictionaryItem;
}
if (aliasToItemMap.Count != 1)
{
primaryDictionaryItem = null;
}
}
private DictionaryItem primaryDictionaryItem = null;
protected override void SerializeElements(object obj, XmlWriter writer, SerializationContext state)
{
var dicObj = (IDictionary)obj;
foreach (var key in dicObj.Keys)
{
var item = this.primaryDictionaryItem ?? this.typeToItemMap[obj.GetType()];
writer.WriteStartElement(key.ToString());
if (aliasToItemMap.Count > 1)
{
writer.WriteAttributeString("typealias", item.typeAlias);
}
if (item.attribute != null
&& item.attribute.SerializeAsValueNode
&& item.attribute.ValueNodeAttributeName != null
&& item.serializer is TypeSerializerWithSimpleTextSupport)
{
writer.WriteAttributeString(item.attribute.ValueNodeAttributeName, ((TypeSerializerWithSimpleTextSupport)item.serializer).Serialize(dicObj[key], state));
}
else
{
item.serializer.Serialize(dicObj[key], writer, state);
}
writer.WriteEndElement();
}
}
protected override void DeserializeElement(object obj, XmlReader reader, SerializationContext state)
{
DictionaryItem dictionaryItem;
var typeAlias = reader.GetAttribute("typealias");
if (!string.IsNullOrEmpty(typeAlias))
{
if (!aliasToItemMap.TryGetValue(reader.GetAttribute("typealias"), out dictionaryItem))
{
dictionaryItem = primaryDictionaryItem;
}
}
else
{
dictionaryItem = primaryDictionaryItem;
}
var key = reader.LocalName;
var value = dictionaryItem.serializer.Deserialize(reader, state);
((IDictionary)obj)[key] = value;
}
}
}
| |
using UnityEngine;
using System.Collections;
[AddComponentMenu("2D Toolkit/Sprite/tk2dClippedSprite")]
[RequireComponent(typeof(MeshRenderer))]
[RequireComponent(typeof(MeshFilter))]
[ExecuteInEditMode]
/// <summary>
/// Sprite implementation that clips the sprite using normalized clip coordinates.
/// </summary>
public class tk2dClippedSprite : tk2dBaseSprite
{
Mesh mesh;
Vector2[] meshUvs;
Vector3[] meshVertices;
Color32[] meshColors;
Vector3[] meshNormals = null;
Vector4[] meshTangents = null;
int[] meshIndices;
public Vector2 _clipBottomLeft = new Vector2(0, 0);
public Vector2 _clipTopRight = new Vector2(1, 1);
// Temp cached variables
Rect _clipRect = new Rect(0, 0, 0, 0);
/// <summary>
/// Sets the clip rectangle
/// 0, 0, 1, 1 = display the entire sprite
/// </summary>
public Rect ClipRect {
get {
_clipRect.Set( _clipBottomLeft.x, _clipBottomLeft.y, _clipTopRight.x - _clipBottomLeft.x, _clipTopRight.y - _clipBottomLeft.y );
return _clipRect;
}
set {
Vector2 v = new Vector2( value.x, value.y );
clipBottomLeft = v;
v.x += value.width;
v.y += value.height;
clipTopRight = v;
}
}
/// <summary>
/// Sets the bottom left clip area.
/// 0, 0 = display full sprite
/// </summary>
public Vector2 clipBottomLeft
{
get { return _clipBottomLeft; }
set
{
if (value != _clipBottomLeft)
{
_clipBottomLeft = new Vector2(value.x, value.y);
Build();
UpdateCollider();
}
}
}
/// <summary>
/// Sets the top right clip area
/// 1, 1 = display full sprite
/// </summary>
public Vector2 clipTopRight
{
get { return _clipTopRight; }
set
{
if (value != _clipTopRight)
{
_clipTopRight = new Vector2(value.x, value.y);
Build();
UpdateCollider();
}
}
}
[SerializeField]
protected bool _createBoxCollider = false;
/// <summary>
/// Create a trimmed box collider for this sprite
/// </summary>
public bool CreateBoxCollider {
get { return _createBoxCollider; }
set {
if (_createBoxCollider != value) {
_createBoxCollider = value;
UpdateCollider();
}
}
}
new void Awake()
{
base.Awake();
// Create mesh, independently to everything else
mesh = new Mesh();
mesh.hideFlags = HideFlags.DontSave;
GetComponent<MeshFilter>().mesh = mesh;
// This will not be set when instantiating in code
// In that case, Build will need to be called
if (Collection)
{
// reset spriteId if outside bounds
// this is when the sprite collection data is corrupt
if (_spriteId < 0 || _spriteId >= Collection.Count)
_spriteId = 0;
Build();
}
}
protected void OnDestroy()
{
if (mesh)
{
#if UNITY_EDITOR
DestroyImmediate(mesh);
#else
Destroy(mesh);
#endif
}
}
new protected void SetColors(Color32[] dest)
{
if (CurrentSprite.positions.Length == 4)
{
tk2dSpriteGeomGen.SetSpriteColors (dest, 0, 4, _color, collectionInst.premultipliedAlpha);
}
}
// Calculated center and extents
Vector3 boundsCenter = Vector3.zero, boundsExtents = Vector3.zero;
protected void SetGeometry(Vector3[] vertices, Vector2[] uvs)
{
var sprite = CurrentSprite;
float colliderOffsetZ = ( boxCollider != null ) ? ( boxCollider.center.z ) : 0.0f;
float colliderExtentZ = ( boxCollider != null ) ? ( boxCollider.size.z * 0.5f ) : 0.5f;
tk2dSpriteGeomGen.SetClippedSpriteGeom( meshVertices, meshUvs, 0, out boundsCenter, out boundsExtents, sprite, _scale, _clipBottomLeft, _clipTopRight, colliderOffsetZ, colliderExtentZ );
if (meshNormals.Length > 0 || meshTangents.Length > 0) {
tk2dSpriteGeomGen.SetSpriteVertexNormals(meshVertices, meshVertices[0], meshVertices[3], sprite.normals, sprite.tangents, meshNormals, meshTangents);
}
// Only do this when there are exactly 4 polys to a sprite (i.e. the sprite isn't diced, and isnt a more complex mesh)
if (sprite.positions.Length != 4 || sprite.complexGeometry)
{
// Only supports normal sprites
for (int i = 0; i < vertices.Length; ++i)
vertices[i] = Vector3.zero;
}
}
public override void Build()
{
var spriteDef = CurrentSprite;
meshUvs = new Vector2[4];
meshVertices = new Vector3[4];
meshColors = new Color32[4];
meshNormals = new Vector3[0];
meshTangents = new Vector4[0];
if (spriteDef.normals != null && spriteDef.normals.Length > 0) {
meshNormals = new Vector3[4];
}
if (spriteDef.tangents != null && spriteDef.tangents.Length > 0) {
meshTangents = new Vector4[4];
}
SetGeometry(meshVertices, meshUvs);
SetColors(meshColors);
if (mesh == null)
{
mesh = new Mesh();
mesh.hideFlags = HideFlags.DontSave;
}
else
{
mesh.Clear();
}
mesh.vertices = meshVertices;
mesh.colors32 = meshColors;
mesh.uv = meshUvs;
mesh.normals = meshNormals;
mesh.tangents = meshTangents;
int[] indices = new int[6];
tk2dSpriteGeomGen.SetClippedSpriteIndices(indices, 0, 0, CurrentSprite);
mesh.triangles = indices;
mesh.RecalculateBounds();
mesh.bounds = AdjustedMeshBounds( mesh.bounds, renderLayer );
GetComponent<MeshFilter>().mesh = mesh;
UpdateCollider();
UpdateMaterial();
}
protected override void UpdateGeometry() { UpdateGeometryImpl(); }
protected override void UpdateColors() { UpdateColorsImpl(); }
protected override void UpdateVertices() { UpdateGeometryImpl(); }
protected void UpdateColorsImpl()
{
if (meshColors == null || meshColors.Length == 0) {
Build();
}
else {
SetColors(meshColors);
mesh.colors32 = meshColors;
}
}
protected void UpdateGeometryImpl()
{
#if UNITY_EDITOR
// This can happen with prefabs in the inspector
if (mesh == null)
return;
#endif
if (meshVertices == null || meshVertices.Length == 0) {
Build();
}
else {
SetGeometry(meshVertices, meshUvs);
mesh.vertices = meshVertices;
mesh.uv = meshUvs;
mesh.normals = meshNormals;
mesh.tangents = meshTangents;
mesh.RecalculateBounds();
mesh.bounds = AdjustedMeshBounds( mesh.bounds, renderLayer );
}
}
#region Collider
protected override void UpdateCollider()
{
if (CreateBoxCollider) {
if (CurrentSprite.physicsEngine == tk2dSpriteDefinition.PhysicsEngine.Physics3D) {
if (boxCollider != null) {
boxCollider.size = 2 * boundsExtents;
boxCollider.center = boundsCenter;
}
}
else if (CurrentSprite.physicsEngine == tk2dSpriteDefinition.PhysicsEngine.Physics2D) {
#if !(UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2)
if (boxCollider2D != null) {
boxCollider2D.size = 2 * boundsExtents;
boxCollider2D.center = boundsCenter;
}
#endif
}
}
}
#if UNITY_EDITOR
void OnDrawGizmos() {
if (mesh != null) {
Bounds b = mesh.bounds;
Gizmos.color = Color.clear;
Gizmos.matrix = transform.localToWorldMatrix;
Gizmos.DrawCube(b.center, b.extents * 2);
Gizmos.matrix = Matrix4x4.identity;
Gizmos.color = Color.white;
}
}
#endif
protected override void CreateCollider() {
UpdateCollider();
}
#if UNITY_EDITOR
public override void EditMode__CreateCollider() {
if (CreateBoxCollider) {
base.CreateSimpleBoxCollider();
}
UpdateCollider();
}
#endif
#endregion
protected override void UpdateMaterial()
{
if (renderer.sharedMaterial != collectionInst.spriteDefinitions[spriteId].materialInst)
renderer.material = collectionInst.spriteDefinitions[spriteId].materialInst;
}
protected override int GetCurrentVertexCount()
{
#if UNITY_EDITOR
if (meshVertices == null)
return 0;
#endif
return 4;
}
public override void ReshapeBounds(Vector3 dMin, Vector3 dMax) {
var sprite = CurrentSprite;
Vector3 oldMin = Vector3.Scale(sprite.untrimmedBoundsData[0] - 0.5f * sprite.untrimmedBoundsData[1], _scale);
Vector3 oldSize = Vector3.Scale(sprite.untrimmedBoundsData[1], _scale);
Vector3 newScale = oldSize + dMax - dMin;
newScale.x /= sprite.untrimmedBoundsData[1].x;
newScale.y /= sprite.untrimmedBoundsData[1].y;
Vector3 scaledMin = new Vector3(Mathf.Approximately(_scale.x, 0) ? 0 : (oldMin.x * newScale.x / _scale.x),
Mathf.Approximately(_scale.y, 0) ? 0 : (oldMin.y * newScale.y / _scale.y));
Vector3 offset = oldMin + dMin - scaledMin;
offset.z = 0;
transform.position = transform.TransformPoint(offset);
scale = new Vector3(newScale.x, newScale.y, _scale.z);
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using Platform.Support.Windows;
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
namespace Platform.Presentation.Forms
{
public sealed class DisplayHelper
{
private const int DEFAULT_DPI = 96;
private const int TWIPS_PER_INCH = 1440;
public static float TwipsToPixelsX(int twips)
{
return TwipsToPixels(twips, PixelsPerLogicalInchX);
}
public static float TwipsToPixelsY(int twips)
{
return TwipsToPixels(twips, PixelsPerLogicalInchY);
}
public static float TwipsToPixels(int twips, int pixelsPerInch)
{
if (twips < 0)
{
throw new ArgumentOutOfRangeException("twips");
}
if (pixelsPerInch <= 0)
{
throw new ArgumentOutOfRangeException("pixelsPerInch");
}
return (pixelsPerInch * twips) / (float)TWIPS_PER_INCH;
}
public static bool IsCompositionEnabled(bool flushCachedValue)
{
return DwmHelper.GetCompositionEnabled(flushCachedValue);
}
private static int? _pixelsPerLogicalInchX;
public static int PixelsPerLogicalInchX
{
get
{
if (_pixelsPerLogicalInchX == null)
{
IntPtr hWndDesktop = User32.GetDesktopWindow();
IntPtr hDCDesktop = User32.GetDC(hWndDesktop);
_pixelsPerLogicalInchX = Gdi32.GetDeviceCaps(hDCDesktop, DEVICECAPS.LOGPIXELSX);
User32.ReleaseDC(hWndDesktop, hDCDesktop);
}
return _pixelsPerLogicalInchX.Value;
}
}
public static int? _pixelsPerLogicalInchY;
public static int PixelsPerLogicalInchY
{
get
{
if (_pixelsPerLogicalInchY == null)
{
IntPtr hWndDesktop = User32.GetDesktopWindow();
IntPtr hDCDesktop = User32.GetDC(hWndDesktop);
_pixelsPerLogicalInchY = Gdi32.GetDeviceCaps(hDCDesktop, DEVICECAPS.LOGPIXELSY);
User32.ReleaseDC(hWndDesktop, hDCDesktop);
}
return _pixelsPerLogicalInchY.Value;
}
}
public static float ScaleX(float x)
{
return x * (((float)PixelsPerLogicalInchX) / ((float)DEFAULT_DPI));
}
public static float ScaleY(float y)
{
return y * (((float)PixelsPerLogicalInchY) / ((float)DEFAULT_DPI));
}
/// <summary>
/// Scales a control from 96dpi to the actual screen dpi.
/// </summary>
public static void Scale(Control c)
{
c.Scale(new SizeF((float)PixelsPerLogicalInchX / DEFAULT_DPI, (float)PixelsPerLogicalInchY / DEFAULT_DPI));
}
/// <summary>
/// When PMingLiU is rendered by GDI+ with StringFormat.LineAlignment == StringAlignment.Center
/// with at least one Chinese character, it ends up 2-3 pixels higher than it should be.
/// I couldn't find a better fix than to just move it down a couple of pixels.
///
/// Note that the stringFormat and textRect arguments will both be mutated!
/// </summary>
public static void FixupGdiPlusLineCentering(Graphics g, Font font, string text, ref StringFormat stringFormat, ref Rectangle textRect)
{
if (CultureHelper.GdiPlusLineCenteringBroken && stringFormat.LineAlignment == StringAlignment.Center)
{
// only fixup if double-byte chars exist
bool hasDoubleByte = false;
foreach (char c in text)
if (c >= 0xFF)
hasDoubleByte = true;
if (!hasDoubleByte)
return;
stringFormat.FormatFlags |= StringFormatFlags.NoClip;
textRect.Offset(0, (int)ScaleY(2));
}
}
public static Size MeasureStringGDI(IntPtr hdc, string str, Font font)
{
IntPtr hFont = font.ToHfont();
try
{
IntPtr hPrevFont = Gdi32.SelectObject(hdc, hFont);
try
{
SIZE size;
if (!Gdi32.GetTextExtentPoint32(hdc, str, str.Length, out size))
throw new Win32Exception(Marshal.GetLastWin32Error());
POINT p;
p.x = size.cx;
p.y = size.cy;
if (!Gdi32.LPtoDP(hdc, new POINT[] { p }, 1))
throw new Win32Exception(Marshal.GetLastWin32Error());
return new Size((int)Math.Ceiling(ScaleX(p.x)), (int)Math.Ceiling(ScaleY(p.y)));
}
finally
{
Gdi32.SelectObject(hdc, hPrevFont);
}
}
finally
{
Gdi32.DeleteObject(hFont);
}
}
public static int AutoFitSystemButton(Button button)
{
return AutoFitSystemButton(button, 0, int.MaxValue);
}
public static int MeasureButton(Button button)
{
return MeasureString(button, button.Text).Width + MakeEvenInt(ScaleX(10));
}
public static int GetMaxDesiredButtonWidth(bool visibleOnly, params Button[] buttons)
{
int max = 0;
foreach (Button button in buttons)
{
if (!visibleOnly || button.Visible)
max = Math.Max(max, MeasureButton(button));
}
return max;
}
public static int AutoFitSystemButton(Button button, int minWidth, int maxWidth)
{
Debug.Assert(button.FlatStyle == FlatStyle.System, "AutoFitSystemButton only works on buttons with FlatStyle.System; " + button.Name + " is " + button.FlatStyle);
return FitText(button, button.Text, MakeEvenInt(ScaleX(10)), minWidth, maxWidth);
}
public static int AutoFitSystemRadioButton(RadioButton button, int minWidth, int maxWidth)
{
Debug.Assert(button.FlatStyle == FlatStyle.System, "AutoFitSystemRadioButton only works on radio buttons with FlatStyle.System; " + button.Name + " is " + button.FlatStyle);
return FitText(button, button.Text, (int)Math.Ceiling(ScaleX(22)), minWidth, maxWidth);
}
public static int AutoFitSystemCheckBox(CheckBox button, int minWidth, int maxWidth)
{
Debug.Assert(button.FlatStyle == FlatStyle.System, "AutoFitSystemCheckBox only works on check boxes with FlatStyle.System; " + button.Name + " is " + button.FlatStyle);
return FitText(button, button.Text, (int)Math.Ceiling(ScaleX(22)), minWidth, maxWidth);
}
public static int AutoFitSystemLabel(Label label, int minWidth, int maxWidth)
{
Debug.Assert(label.FlatStyle == FlatStyle.System, "AutoFitSystemLabel only works on labels with FlatStyle.System; " + label.Name + " is " + label.FlatStyle);
return FitText(label, GetMeasurableText(label), 0, minWidth, maxWidth);
}
public static int AutoFitSystemCombo(ComboBox comboBox, int minWidth, int maxWidth, int indexToFit)
{
if (indexToFit >= 0 && indexToFit < comboBox.Items.Count)
return SizeComboTo(comboBox, minWidth, maxWidth, MeasureString(comboBox, comboBox.Items[indexToFit].ToString()).Width);
else
return AutoFitSystemCombo(comboBox, minWidth, maxWidth, true);
}
public static int AutoFitSystemCombo(ComboBox comboBox, int minWidth, int maxWidth, string stringToFit)
{
return SizeComboTo(comboBox, minWidth, maxWidth, MeasureString(comboBox, stringToFit).Width);
}
public static int AutoFitSystemCombo(ComboBox comboBox, int minWidth, int maxWidth, bool fitCurrentValueOnly)
{
int width = GetPreferredWidth(comboBox, fitCurrentValueOnly);
return SizeComboTo(comboBox, minWidth, maxWidth, width);
}
private static int GetPreferredWidth(ComboBox comboBox, bool fitCurrentValueOnly)
{
int width = MeasureString(comboBox, comboBox.Text).Width;
if (!fitCurrentValueOnly)
{
foreach (object o in comboBox.Items)
{
if (o != null)
width = Math.Max(width, MeasureString(comboBox, o.ToString()).Width);
}
}
return width;
}
public static int AutoFitSystemComboDropDown(ComboBox comboBox)
{
int width = GetPreferredWidth(comboBox, false);
comboBox.DropDownWidth = (width);
return comboBox.DropDownWidth;
}
private static int SizeComboTo(ComboBox comboBox, int minWidth, int maxWidth, int width)
{
int origWidth = comboBox.Width;
int hpadding = 34;
if (comboBox.DrawMode == DrawMode.Normal)
hpadding -= 3;
comboBox.Width = Math.Max(minWidth,
Math.Min(maxWidth,
width + (int)Math.Ceiling(ScaleX(hpadding))));
int deltaX = comboBox.Width - origWidth;
if ((comboBox.Anchor & (AnchorStyles.Right | AnchorStyles.Left)) == AnchorStyles.Right)
{
comboBox.Left -= deltaX;
}
return comboBox.Width;
}
private static int FitText(Control c, string text, int padding, int minWidth, int maxWidth)
{
IntPtr hdc = User32.GetDC(c.Handle);
try
{
int buttonWidth = c.Width;
int newButtonWidth = c.Width =
Math.Min(maxWidth, Math.Max(minWidth,
MeasureString(c, text).Width + padding));
if ((c.Anchor & (AnchorStyles.Right | AnchorStyles.Left)) == AnchorStyles.Right)
{
c.Left += buttonWidth - newButtonWidth;
}
return newButtonWidth;
}
finally
{
User32.ReleaseDC(c.Handle, hdc);
}
}
public static Size MeasureString(Control c, string text)
{
return TextRenderer.MeasureText(text, c.Font, new Size(int.MaxValue, int.MaxValue), TextFormatFlags.SingleLine | TextFormatFlags.NoClipping | TextFormatFlags.PreserveGraphicsClipping);
}
private static string GetMeasurableText(Label c)
{
if (!c.UseMnemonic || c.Text.IndexOf('&') < 0)
return c.Text;
else
{
StringBuilder sb = new StringBuilder(c.Text);
for (int i = 0; i < sb.Length; i++)
{
if (sb[i] == '&')
{
if (sb.Length == i + 1)
continue;
if (sb[i + 1] == '&')
{
i++;
continue;
}
sb.Remove(i, 1);
i--;
}
}
return sb.ToString();
}
}
private static int MakeEvenInt(float floatValue)
{
int intValue;
if ((intValue = (int)Math.Ceiling(floatValue)) % 2 == 0)
return intValue;
if ((intValue = (int)Math.Floor(floatValue)) % 2 == 0)
return intValue;
return (int)floatValue + 1;
}
}
internal class DwmHelper
{
private enum State
{
None,
LibraryNotFound,
LibraryFound
}
private static readonly object lockObj = new object();
private static State state;
private static bool isCompositionEnabled;
static DwmHelper()
{
Refresh();
}
private static void Refresh()
{
lock (lockObj)
{
if (state == State.None)
{
if (Environment.OSVersion.Version.Major < 6)
state = State.LibraryNotFound;
state = Kernel32.LoadLibrary("dwmapi.dll") != IntPtr.Zero ? State.LibraryFound : State.LibraryNotFound;
}
if (state == State.LibraryNotFound)
isCompositionEnabled = false;
else
{
try
{
bool tmp;
if (0 == Dwmapi.DwmIsCompositionEnabled(out tmp))
isCompositionEnabled = tmp;
else
isCompositionEnabled = false;
return;
}
catch (Exception e)
{
isCompositionEnabled = false;
Debug.Fail(e.ToString());
}
}
}
}
public static bool GetCompositionEnabled(bool flush)
{
if (flush)
Refresh();
return isCompositionEnabled;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using FlatRedBall.Glue.Plugins.ExportedInterfaces;
using FlatRedBall.Glue.Plugins.Interfaces;
using FlatRedBall.Glue.SaveClasses;
using FlatRedBall.Glue.Plugins;
using System.Reflection;
using FlatRedBall.Glue.Elements;
using System.IO;
using FlatRedBall.IO;
using EditorObjects.SaveClasses;
using FlatRedBall.Glue.FormHelpers.PropertyGrids;
using System.Windows.Forms;
using FlatRedBall.Glue.Controls;
using FlatRedBall.Glue.VSHelpers;
using TileGraphicsPlugin.Controllers;
using TileGraphicsPlugin.Managers;
using FlatRedBall.Content.Instructions;
using TMXGlueLib.DataTypes;
using ProjectManager = FlatRedBall.Glue.ProjectManager;
using TMXGlueLib;
using FlatRedBall.Glue.Parsing;
using TileGraphicsPlugin.CodeGeneration;
using TileGraphicsPlugin.Views;
using TileGraphicsPlugin.ViewModels;
using FlatRedBall.Glue.IO;
using TileGraphicsPlugin.Logic;
using System.ComponentModel;
using TiledPluginCore.Controls;
using TiledPluginCore.Models;
using TiledPluginCore.CodeGeneration;
using TiledPluginCore.Controllers;
using TiledPluginCore.Managers;
using TiledPluginCore.Views;
using FlatRedBall.Glue.Plugins.ExportedImplementations;
using FlatRedBall.Glue.FormHelpers;
namespace TileGraphicsPlugin
{
[Export(typeof(PluginBase))]
public class TileGraphicsPluginClass : PluginBase
{
#region Fields
string mLastFile;
PluginTab collisionTab;
PluginTab nodeNetworkTab;
PluginTab levelTab;
TiledObjectTypeCreator tiledObjectTypeCreator;
TiledToolbar tiledToolbar;
LevelScreenView levelScreenView;
#endregion
#region Properties
public override Version Version
{
// 1.0.8 introduced tile instantiation per layer
// 1.0.8.1 adds a null check around returning files referenced by a .tmx
// 1.0.9 adds TileNodeNetworkCreator
// 1.0.10 adds shape property support
// 1.0.11 Adds automatic instantiation and collision setting from shapes
// 1.0.11.1 Fixed bug where shape had a name
// 1.0.11.2 Fixed rectangle polygon creation offset bug
// 1.0.11.3
// - Fixed crash occurring when the Object layer .object property is null
// - Upped to .NET 4.5.2
// 1.0.11.4
// - Shapes now have their Z value set according to the object layer index, which may be used to position entities properly.
// 1.0.11.5
// - Fixed a bug where the Name property for tiled sprites was being ignored.
// 1.1.0
// - Introduces a MUCH faster loading system - approximately 4x as fast on large maps (680x1200)
// 1.1.1.0
// - Fixed offset issues with instantiating entities from objects
// - Added support for rotated entities
// 1.1.1.1
// - Fixed animations not setting the right and bottom texture coordinates according to offset values
// 1.1.1.2
// - Fixed attempting to set the EntityToCreate property on new entities in TileEntityInstantiator
// - Name property is set even if property is lower-case "name"
// 1.1.1.3
// - Added method to add collision in a TileShapeCollection from a single layer in the MapDrawableBatch
// 1.1.1.4
// - Fixed crash thich can occur sometimes when clicking on a TMX file due to a collection changed
// 1.1.1.5
// - Fixed possible threading issue if the project attempts to save on project startup
// 1.1.1.6
// - Updated tile entity instantiator so that it supports the latest changes to the factory pattern to support X and Y values
// 1.1.1.7
// - Added support for overriding the current TextureFilter when rendering a MapDrawableBatch
// - Entities are now offset according to their layer's position - useful for instantiating entities inside of another entity
// 1.2.0
// - Added/improved xml Type generated file creation/updating
// - Made the IDs alittle clearer - no more +1 in code
// 1.2.1
// - Added TileShapeCollection.AddCollisionFromTilesWithProperty
// 1.2.2
// - Added TileShapeCollection.SetColor
// 1.2.2.1
// - Fixed possible crash with an empty object layer
// 1.2.2.2
// - Added TileShapeCollection CollideAgainst Polygon
// 1.2.3
// - Default properties from the TileSet now get assigned on created entities for object layers
// 1.2.3.1
// - Fixed polygon conversion not doing conversions using culture invariant values - fixes games running in Finnish
// - Fixed tile entity instantiation not doing float conversions using culture invariant values - also Finnish fix.
// 1.3.0
// - Added TileShapeCollection + CollisionManager integration.
// 1.3.1
// - Removed requirement for XNA HiDef so old machines and VMs will run this plugin better, but the edit window won't show
// 1.3.2
// - Added support for adding rectangles on rotated tiles
// 1.3.3
// - Updated the TileShapeCollection CollisionRelationship classes to return bool on DoCollision to match the base implementation
// 1.4.0
// - Collision from shapes on tileset tiles will now check the name of the shape - if it has no name then it's added to a TileShapeCollection
// with the name matching the layer. If the shape does have a name then it is added to a TileShapeCollection with the same name as the shape.
// This allows games to easily organize their collision with no code and no custom properties.
// 1.4.1
// - ShapeCollections in LayeredTileMap are now cleared out, so if they're made visible in custom code
// they don't have to be made invisible manually.
// 1.5.0
// - TileEntityInstantiator can now assign properties from CSVs if the CSV dictionary is registered
// 1.5.1
// - Added creating ICollidables using EntityToCreate property on rectangles and circles
// 1.5.2
// - Fixed missing using statement in TileEntityInstantiator
// 1.6.0
// - Added support for instantiating tile entities applying properties from states
// 1.6.2
// - Fixed bug where TileNemsWith wouldn't check lower-case "name" property
// 1.7.0
// - Added support for layer Alpha
// - Added support for layer Red, Green, and Blue
// 1.7.1
// - Fixed flipped tiles not creating entities
// 1.8.1
// - The new entity window now has checkboxes for supporting creating the entity through Tiled and for
// adding the entity to all screens containing tmx files directly.
// 2.0.0
// - Added generation of adding entities from Tiled file
// 2.0.1
// - Added support for setting AnimationChains on an entity through Tiled
// 2.1.0
// - Every layer now creates a tile shape collection regardless of whether it contains shapes
// 2.1.1
// - Tile rectangle collision can now be offset
// 2.1.2
// - Fixed bug where layers weren't resetting their blend op to normal (from additive) which can
// result in additive layers.
// 2.1.3
// - Made RegisterName property public so it can be called outside of MapDrawableBatch
// 2.1.4
// - Added support for objects that are larger than the default tile size (scaled sprites in Tiled)
// 2.1.4.1
// - Fixed copy paste compile error from previous change.
// 2.1.4.2
// - Fixed Type not being copied over when specified on object instances
// 2.2
// - Huge changes allowing tile shape collections to be generated through glue plugin.
// 2.2.1
// - Added support for creating TileNodeNetworks by type
// 2.2.2
// - Removed exception occurring when a tile has a type, but no matching entity exists
// 2.3.0
// - X and Y now apply offsets to created entities, allowing entities to be centered around different points on a tile
// 2.4.0
// - Added line vs TileShapeCollection relationships, including support for closest collision for (really efficient) ray casting
// 2.4.0.1
// - Fixed tab text
// 2.5.0.0
// - TileShapeCollections will now depend on the type
// 2.5.1.0
// - TileShapeCollections now set their visibility prior to creation, speeding up the creation of
// large tipe shape collections.
// 2.5.2.0
// - Added TileShapeCollection extension method AddMergedCollisionFromTilesWithType
// - Added IsMerged checkbox to collisions from type
// 2.5.3.0
// - TileShapeCollection.Setcolor now sets polygons and rectangles.
// 2.5.4.0
// - TileShapeCollections from layes are assigned directly on constructor instead
// of after. This allows relationships to use these collision relationships.
// 2.5.5.0
// - Tiled plugin makes itself required when adding a TMX
// 2.6.0
// - Polygons on tiles can now be rotated and flipped just like the tiles.
// 2.7.0
// - Added TileShapeCollection.MergeRectangles
// 2.7.0.2
// - Added comments
// 2.8
// - CollidableVsTileShapeCollectionData.DoFirstCollisionLineVsShapeCollection is now public
// 2.9
// - Added animated, flipped tile support
// 2.10
// - Added ability to restrict instantiation to a bound
// 2.11
// - Added ability to prevent objects from being removed when creating objects from tiles
// 2.12
// - Object layers now have a Visible property
// 2.13
// - TileEntityInstantiator.GetFactory is now public making it easier for other code to instantiate objects by name
// 2.14
// - Added new tooltip
// 2.15
// - Added TileShapeCollection.AssignAllShapesToRepositionOutward
// 2.16
// - LayeredTileMap is now a FlatRedBall IPositionedSizedObject
// 2.17
// - TileShapeCollection now has RemoveCollisionFrom and RemoveCollisionFromTilesWithType
// 2.18
// - LayeredTileMap merge function now works properly on x-sorted maps (y sorted will prob come soon)
get { return new Version(2, 16, 0, 0); }
}
[Import("GlueProjectSave")]
public GlueProjectSave GlueProjectSave
{
get;
set;
}
public override string FriendlyName
{
get { return "Tiled Plugin"; }
}
static TileGraphicsPluginClass mSelf;
public static TileGraphicsPluginClass Self
{
get { return mSelf; }
}
#endregion
#region Constructor/Startup
public TileGraphicsPluginClass()
{
mSelf = this;
}
public override void StartUp()
{
CodeItemAdderManager.Self.AddFilesToCodeBuildItemAdder();
AddEvents();
this.AddErrorReporter(new ErrorReporter());
CreateToolbar();
SaveTemplateTmx();
AddCodeGenerators();
}
private void AddEvents()
{
tiledObjectTypeCreator = new TiledObjectTypeCreator();
this.TryHandleCopyFile += HandleCopyFile;
this.ReactToLoadedGluxEarly += HandleGluxLoadEarly;
this.ReactToLoadedGlux += () =>
{
HandleGluxLoad();
tiledObjectTypeCreator.RefreshFile();
};
// Adds all objects contained within a file (like TMX)
this.TryAddContainedObjects += HandleTryAddContainedObjects;
this.AdjustDisplayedReferencedFile += HandleAdjustDisplayedReferencedFile;
this.ReactToItemSelectHandler += HandleItemSelect;
this.ReactToFileChangeHandler += HandleFileChange;
this.FillWithReferencedFiles += FileReferenceManager.Self.HandleGetFilesReferencedBy;
this.CanFileReferenceContent += HandleCanFileReferenceContent;
//TilesetController.Self.EntityAssociationsChanged +=
// EntityListManager.Self.OnEntityAssociationsChanged;
//TilesetController.Self.GetTsxDirectoryRelativeToTmx = () => "../Tilesets/";
this.ReactToChangedPropertyHandler += (changedMember, oldalue, glueElement) =>
{
if(GlueState.Self.CurrentCustomVariable != null)
{
if (changedMember == nameof(CustomVariable.Name))
{
tiledObjectTypeCreator.RefreshFile();
}
}
else if(glueElement != null)
{
if (changedMember == nameof(EntitySave.CreatedByOtherEntities))
{
tiledObjectTypeCreator.RefreshFile();
}
}
};
this.ReactToElementVariableChange += (element, variable) =>
{
if ((element as EntitySave)?.CreatedByOtherEntities == true)
{
tiledObjectTypeCreator.RefreshFile();
}
};
this.ReactToVariableAdded += (newVariable) =>
{
var element = EditorObjects.IoC.Container.Get<IGlueState>().CurrentElement;
if ((element as EntitySave)?.CreatedByOtherEntities == true)
{
tiledObjectTypeCreator.RefreshFile();
}
};
this.ReactToVariableRemoved += (removedVariable) =>
{
var element = EditorObjects.IoC.Container.Get<IGlueState>().CurrentElement;
if ((element as EntitySave)?.CreatedByOtherEntities == true)
{
tiledObjectTypeCreator.RefreshFile();
}
};
this.ModifyAddEntityWindow += ModifyAddEntityWindowLogic.HandleModifyAddEntityWindow;
this.ReactToNewObjectHandler += NewObjectLogic.HandleNewObject;
this.NewEntityCreatedWithUi += NewEntityCreatedReactionLogic.ReactToNewEntityCreated;
this.ReactToNewFileHandler = ReactToNewFile;
this.AddNewFileOptionsHandler += HandleAddNewFileOptions;
//this.CreateNewFileHandler += TmxCreationManager.Self.HandleNewTmxCreation;
}
private void CreateToolbar()
{
tiledToolbar = new TiledToolbar();
tiledToolbar.Opened += HandleToolbarOpened;
//gumToolbar.GumButtonClicked += HandleToolbarButtonClick;
base.AddToToolBar(tiledToolbar, "Tools");
}
private void HandleToolbarOpened(object sender, EventArgs e)
{
var availableTmxFiles = ObjectFinder.Self.GetAllReferencedFiles()
.Where(item => item.Name?.ToLowerInvariant()?.EndsWith(".tmx") == true)
.ToList();
tiledToolbar.FillDropdown(availableTmxFiles);
tiledToolbar.HighlightFirstItem();
}
private void ReactToNewFile(ReferencedFileSave newFile)
{
var isTmx = FileManager.GetExtension(newFile.Name) == "tmx";
if(isTmx)
{
var isRequired = GlueCommands.Self.GluxCommands.GetPluginRequirement(this);
if(!isRequired)
{
GlueCommands.Self.GluxCommands.SetPluginRequirement(this, true);
GlueCommands.Self.PrintOutput("Added Tiled Plugin as a required plugin because TMX's are used");
GlueCommands.Self.GluxCommands.SaveGlux();
}
TmxCreationManager.Self.HandleNewTmx(newFile);
}
}
private static void SaveTemplateTmx()
{
Assembly assembly = Assembly.GetExecutingAssembly();
string whatToSave = "TiledPluginCore.Content.Levels.TiledMap.tmx";
//C:\Users\Victor\AppData\Roaming\Glue\FilesForAddNewFile\
string destination = FileManager.UserApplicationDataForThisApplication + "FilesForAddNewFile/" +
"TiledMap.tmx";
try
{
FileManager.SaveEmbeddedResource(assembly, whatToSave, destination);
}
catch (Exception e)
{
PluginManager.ReceiveError("Error trying to save tmx: " + e.ToString());
}
}
private void AddCodeGenerators()
{
// November 5, 2020 - I don't think we do this anymore, it's all handled with the inheritance model
//this.RegisterCodeGenerator(new LevelCodeGenerator());
this.RegisterCodeGenerator(new TmxCodeGenerator());
this.RegisterCodeGenerator(new TileShapeCollectionCodeGenerator());
this.RegisterCodeGenerator(new TileNodeNetworkCodeGenerator());
}
#endregion
#region Methods
public override bool ShutDown(FlatRedBall.Glue.Plugins.Interfaces.PluginShutDownReason reason)
{
// Do anything your plugin needs to do to shut down
// or don't shut down and return false
if (tiledToolbar != null)
{
base.RemoveFromToolbar(tiledToolbar, "Standard");
}
return true;
}
private bool HandleTryAddContainedObjects(string absoluteFile, List<string> availableObjects)
{
var isTmx = new FilePath(absoluteFile).Extension == "tmx";
if(isTmx)
{
TiledMapSave save = TiledMapSave.FromFile(absoluteFile);
// loop through each layer, adding it:
foreach(var layer in save.MapLayers)
{
availableObjects.Add($"{layer.Name} (FlatRedBall.TileCollisions.TileShapeCollection)");
}
}
return isTmx;
}
private void HandleGluxLoadEarly()
{
// Add the necessary files for performing the builds to the Libraries/tmx folder
BuildToolSaver.Self.SaveBuildToolsToDisk();
// Add Builders so that the user has the option to handle these file types
BuildToolAssociationManager.Self.UpdateBuildToolAssociations();
}
public static void ExecuteFinalGlueCommands(EntitySave entity)
{
FlatRedBall.Glue.Plugins.ExportedImplementations.GlueCommands.Self.RefreshCommands.RefreshCurrentElementTreeNode();
FlatRedBall.Glue.Plugins.ExportedImplementations.GlueCommands.Self.GluxCommands.SaveGlux();
FlatRedBall.Glue.Plugins.ExportedImplementations.GlueCommands.Self.GenerateCodeCommands.GenerateElementCode(entity);
FlatRedBall.Glue.Plugins.ExportedImplementations.GlueCommands.Self.GenerateCodeCommands.GenerateCurrentElementCode();
}
private bool HandleCanFileReferenceContent(string fileName)
{
var extension = FileManager.GetExtension(fileName);
return extension == "tilb" || extension == "tsx" || extension == "tmx";
}
private bool HandleCopyFile(string sourceFile, string sourceDirectory, string targetFile)
{
string extension = FileManager.GetExtension(sourceFile);
if (extension == "tmx")
{
if (System.IO.File.Exists(sourceFile))
{
CopyFileManager.Self.CopyTmx(sourceFile, targetFile);
}
return true;
}
return false;
}
private void HandleItemSelect(ITreeNode treeNode)
{
bool shouldRemove = true;
ReferencedFileSave rfs = treeNode?.Tag as ReferencedFileSave;
if (FileReferenceManager.Self.IsTmx(rfs))
{
shouldRemove = false;
//FileReferenceManager.Self.UpdateAvailableTsxFiles();
ReactToRfsSelected(rfs);
}
if (shouldRemove)
{
collisionTab?.Hide();
levelTab?.Hide();
nodeNetworkTab?.Hide();
}
if(TileShapeCollectionsPropertiesController.Self.IsTileShapeCollection(treeNode?.Tag as NamedObjectSave))
{
if(collisionTab == null)
{
var view = TileShapeCollectionsPropertiesController.Self.GetView();
collisionTab = base.CreateTab(view, "TileShapeCollection Properties");
}
TileShapeCollectionsPropertiesController.Self.RefreshViewModelTo(treeNode?.Tag as NamedObjectSave,
GlueState.Self.CurrentElement);
collisionTab.Show();
GlueCommands.Self.DialogCommands.FocusTab("TileShapeCollection Properties");
}
else if(collisionTab != null)
{
collisionTab?.Hide();
}
if(TileNodeNetworkPropertiesController.Self.IsTileNodeNetwork(treeNode?.Tag as NamedObjectSave))
{
if(nodeNetworkTab == null)
{
var view = TileNodeNetworkPropertiesController.Self.GetView();
nodeNetworkTab = base.CreateTab(view, "TileNodeNetwork Properties");
}
TileNodeNetworkPropertiesController.Self.RefreshViewModelTo(treeNode?.Tag as NamedObjectSave,
GlueState.Self.CurrentElement);
nodeNetworkTab.Show();
GlueCommands.Self.DialogCommands.FocusTab("TileNodeNetwork Properties");
}
else if(nodeNetworkTab != null)
{
nodeNetworkTab?.Hide();
}
// Levels are dead, long live inherited levels!
//if(LevelScreenController.Self.GetIfShouldShow())
//{
// if(levelTab == null)
// {
// var view = LevelScreenController.Self.GetView();
// levelTab = base.CreateTab(view, "Levels");
// }
// LevelScreenController.Self.RefreshViewModelTo(GlueState.Self.CurrentScreenSave);
// levelTab.Show();
// LevelScreenController.Self.HandleTabShown();
// // prob don't focus it, it's rare the user needs to mess with this
//}
//else if(levelTab != null)
//{
// levelTab?.Hide();
//}
}
private void ReactToRfsSelected(ReferencedFileSave rfs)
{
// These aren't built anymore, so no command line
//mCommandLineViewModel.ReferencedFileSave = rfs;
string fileNameToUse = rfs.Name;
if(FileManager.GetExtension(rfs.SourceFile) == "tmx")
{
fileNameToUse = rfs.SourceFile;
}
string fullFileName = FlatRedBall.Glue.ProjectManager.MakeAbsolute(fileNameToUse, true);
mLastFile = fullFileName;
EntityCreationManager.Self.ReactToRfsSelected(rfs);
}
private void HandleFileChange(string fileName)
{
string extension = FileManager.GetExtension(fileName);
var shouldRefreshErrors = false;
if(extension == "tmx")
{
shouldRefreshErrors = true;
}
if(extension == "tsx")
{
// oh boy, the user changed a shared tile set. Time to rebuild everything that uses this tileset
var allReferencedFileSaves = FileReferenceManager.Self.GetReferencedFileSavesReferencingTsx(fileName).ToArray();
// build em!
foreach(var file in allReferencedFileSaves)
{
file.PerformExternalBuild(runAsync:true);
}
shouldRefreshErrors = true;
if(allReferencedFileSaves.Length > 0)
{
var nos = GlueState.Self.CurrentNamedObjectSave;
var element = GlueState.Self.CurrentElement;
if (collisionTab?.IsShown == true && nos != null)
{
TileShapeCollectionsPropertiesController.Self.RefreshViewModelTo(nos, element);
}
}
}
// If a png changes, it may be resized. Tiled changes IDs of tiles when a PNG resizes if
// no external tileset is used, so we want to rebuild the .tmx's.
if (extension == "png")
{
var allReferencedFileSaves = FileReferenceManager.Self.GetReferencedFileSavesReferencingPng(fileName);
var toListForDebug = allReferencedFileSaves.ToList();
// build em!
foreach (var file in allReferencedFileSaves)
{
file.PerformExternalBuild(runAsync: true);
}
}
if (this.PluginTab != null && this.PluginTab.Parent != null && fileName == mLastFile)
{
if (changesToIgnore == 0)
{
//mControl?.LoadFile(fileName);
}
else
{
changesToIgnore--;
}
}
if(shouldRefreshErrors)
{
GlueCommands.Self.RefreshCommands.RefreshErrors();
}
}
private void OnClosedByUser(object sender)
{
PluginManager.ShutDownPlugin(this);
}
bool IsTmx(AssetTypeInfo ati) =>
ati?.Extension == "tmx";
private void HandleAddNewFileOptions(CustomizableNewFileWindow newFileWindow)
{
var view = new NewTmxOptionsView();
var viewModel = new NewTmxViewModel();
viewModel.IncludeDefaultTileset = true;
viewModel.IncludeGameplayLayer = true;
// January 23, 2022
// This is so common,
// at least according to
// Vic's usage, that we should
// just make it default to true.
viewModel.IsSolidCollisionBorderChecked = true;
view.DataContext = viewModel;
newFileWindow.AddCustomUi(view);
newFileWindow.SelectionChanged += (not, used) =>
{
var ati = newFileWindow.SelectedItem;
if(IsTmx(ati))
{
view.Visibility = System.Windows.Visibility.Visible;
}
else
{
view.Visibility = System.Windows.Visibility.Collapsed;
}
};
newFileWindow.GetCreationOption = () =>
{
var ati = newFileWindow.SelectedItem;
if (IsTmx(ati))
{
return viewModel;
}
else
{
return null;
}
};
}
int changesToIgnore = 0;
//public void SaveTiledMapSave(ChangeType changeType)
//{
// if(mControl != null)
// {
// string fileName = mLastFile;
// FlatRedBall.Glue.Managers.TaskManager.Self.AddSync(() =>
// {
// changesToIgnore++;
// bool saveTsxFiles = changeType == ChangeType.Tileset;
// mControl.SaveCurrentTileMap(saveTsxFiles);
// },
// "Saving tile map");
// }
//}
void HandleAdjustDisplayedReferencedFile(ReferencedFileSave rfs, ReferencedFileSavePropertyGridDisplayer displayer)
{
if (rfs.IsCsvOrTreatedAsCsv && !string.IsNullOrEmpty(rfs.SourceFile))
{
}
}
void HandleGluxLoad()
{
// Add the .cs files which include the map drawable batch classes
FlatRedBall.Glue.Managers.TaskManager.Self.Add( CodeItemAdderManager.Self.UpdateCodePresenceInProject,
"Adding Tiled .cs files to the project");
// Add the CSV entry so that Glue knows how to load a .scnx into the classes added above
AssetTypeInfoAdder.Self.UpdateAtiCsvPresence();
// Make sure the TileMapInfo CustomClassSave is there, and make sure it has all the right properties
TileMapInfoManager.Self.AddAndModifyTileMapInfoClass();
}
internal void UpdateTilesetDisplay()
{
//mControl?.UpdateTilesetDisplay();
}
public void AddStandardTilesetOnCurrentFile()
{
var rfs = GlueState.Self.CurrentReferencedFileSave;
var rfsAti = rfs?.GetAssetTypeInfo();
if (rfsAti != null && IsTmx(rfsAti))
{
TmxCreationManager.Self.IncludeDefaultTilesetOn(rfs);
}
}
public void AddGameplayLayerToCurrentFile()
{
var rfs = GlueState.Self.CurrentReferencedFileSave;
var rfsAti = rfs?.GetAssetTypeInfo();
if (rfsAti != null && IsTmx(rfsAti))
{
TmxCreationManager.Self.IncludeGameplayLayerOn(rfs);
}
}
public void AddCollisionBorderToCurrentFile()
{
var rfs = GlueState.Self.CurrentReferencedFileSave;
var rfsAti = rfs?.GetAssetTypeInfo();
if (rfsAti != null && IsTmx(rfsAti))
{
TmxCreationManager.Self.AddCollisionBorderOn(rfs);
}
}
#endregion
}
}
| |
using System.Collections.Generic;
using System.Linq;
//Helper data classes for ParserDataBuilder
// Note about using LRItemSet vs LRItemList.
// It appears that in many places the LRItemList would be a better (and faster) choice than LRItemSet.
// Many of the sets are actually lists and don't require hashset's functionality.
// But surprisingly, using LRItemSet proved to have much better performance (twice faster for lookbacks/lookaheads computation), so LRItemSet
// is used everywhere.
namespace Irony.Parsing.Construction
{
public class ParserStateData
{
public readonly LRItemSet AllItems = new LRItemSet();
public readonly TerminalSet Conflicts = new TerminalSet();
public readonly LRItemSet InitialItems = new LRItemSet();
public readonly bool IsInadequate;
public readonly LRItemSet ReduceItems = new LRItemSet();
public readonly LRItemSet ShiftItems = new LRItemSet();
public readonly TerminalSet ShiftTerminals = new TerminalSet();
public readonly BnfTermSet ShiftTerms = new BnfTermSet();
public readonly ParserState State;
private ParserStateSet _readStateSet;
private TransitionTable _transitions;
public LR0ItemSet AllCores = new LR0ItemSet();
//used for creating canonical states from core set
public ParserStateData(ParserState state, LR0ItemSet kernelCores)
{
State = state;
foreach (var core in kernelCores)
AddItem(core);
IsInadequate = ReduceItems.Count > 1 || ReduceItems.Count == 1 && ShiftItems.Count > 0;
}
public TransitionTable Transitions
{
get
{
if (_transitions == null)
_transitions = new TransitionTable();
return _transitions;
}
}
//A set of states reachable through shifts over nullable non-terminals. Computed on demand
public ParserStateSet ReadStateSet
{
get
{
if (_readStateSet == null)
{
_readStateSet = new ParserStateSet();
foreach (var shiftTerm in State.BuilderData.ShiftTerms)
if (shiftTerm.Flags.IsSet(TermFlags.IsNullable))
{
var shift = State.Actions[shiftTerm] as ShiftParserAction;
var targetState = shift.NewState;
_readStateSet.Add(targetState);
_readStateSet.UnionWith(targetState.BuilderData.ReadStateSet);
//we shouldn't get into loop here, the chain of reads is finite
}
} //if
return _readStateSet;
}
}
public void AddItem(LR0Item core)
{
//Check if a core had been already added. If yes, simply return
if (!AllCores.Add(core)) return;
//Create new item, add it to AllItems, InitialItems, ReduceItems or ShiftItems
var item = new LRItem(State, core);
AllItems.Add(item);
if (item.Core.IsFinal)
ReduceItems.Add(item);
else
ShiftItems.Add(item);
if (item.Core.IsInitial)
InitialItems.Add(item);
if (core.IsFinal) return;
//Add current term to ShiftTerms
if (!ShiftTerms.Add(core.Current)) return;
if (core.Current is Terminal)
ShiftTerminals.Add(core.Current as Terminal);
//If current term (core.Current) is a new non-terminal, expand it
var currNt = core.Current as NonTerminal;
if (currNt == null) return;
foreach (var prod in currNt.Productions)
AddItem(prod.LR0Items[0]);
} //method
public ParserState GetNextState(BnfTerm shiftTerm)
{
var shift = ShiftItems.FirstOrDefault(item => item.Core.Current == shiftTerm);
if (shift == null) return null;
return shift.ShiftedItem.State;
}
public TerminalSet GetShiftReduceConflicts()
{
var result = new TerminalSet();
result.UnionWith(Conflicts);
result.IntersectWith(ShiftTerminals);
return result;
}
public TerminalSet GetReduceReduceConflicts()
{
var result = new TerminalSet();
result.UnionWith(Conflicts);
result.ExceptWith(ShiftTerminals);
return result;
}
} //class
//An object representing inter-state transitions. Defines Includes, IncludedBy that are used for efficient lookahead computation
public class Transition
{
private readonly int _hashCode;
public readonly ParserState FromState;
public readonly TransitionSet IncludedBy = new TransitionSet();
public readonly TransitionSet Includes = new TransitionSet();
public readonly LRItemSet Items;
public readonly NonTerminal OverNonTerminal;
public readonly ParserState ToState;
public Transition(ParserState fromState, NonTerminal overNonTerminal)
{
FromState = fromState;
OverNonTerminal = overNonTerminal;
var shiftItem = fromState.BuilderData.ShiftItems.First(item => item.Core.Current == overNonTerminal);
ToState = FromState.BuilderData.GetNextState(overNonTerminal);
_hashCode = unchecked(FromState.GetHashCode() - overNonTerminal.GetHashCode());
FromState.BuilderData.Transitions.Add(overNonTerminal, this);
Items = FromState.BuilderData.ShiftItems.SelectByCurrent(overNonTerminal);
foreach (var item in Items)
{
item.Transition = this;
}
} //constructor
public void Include(Transition other)
{
if (other == this) return;
if (!IncludeTransition(other)) return;
//include children
foreach (var child in other.Includes)
{
IncludeTransition(child);
}
}
private bool IncludeTransition(Transition other)
{
if (!Includes.Add(other)) return false;
other.IncludedBy.Add(this);
//propagate "up"
foreach (var incBy in IncludedBy)
incBy.IncludeTransition(other);
return true;
}
public override string ToString()
{
return FromState.Name + " -> (over " + OverNonTerminal.Name + ") -> " + ToState.Name;
}
public override int GetHashCode()
{
return _hashCode;
}
} //class
public class TransitionSet : HashSet<Transition>
{
}
public class TransitionList : List<Transition>
{
}
public class TransitionTable : Dictionary<NonTerminal, Transition>
{
}
public class LRItem
{
private readonly int _hashCode;
public readonly LR0Item Core;
public readonly ParserState State;
public TerminalSet Lookaheads = new TerminalSet();
//Lookahead info for reduce items
public TransitionSet Lookbacks = new TransitionSet();
//these properties are used in lookahead computations
public LRItem ShiftedItem;
public Transition Transition;
public LRItem(ParserState state, LR0Item core)
{
State = state;
Core = core;
_hashCode = unchecked(state.GetHashCode() + core.GetHashCode());
}
public override string ToString()
{
return Core.ToString();
}
public override int GetHashCode()
{
return _hashCode;
}
public TerminalSet GetLookaheadsInConflict()
{
var lkhc = new TerminalSet();
lkhc.UnionWith(Lookaheads);
lkhc.IntersectWith(State.BuilderData.Conflicts);
return lkhc;
}
} //LRItem class
public class LRItemList : List<LRItem>
{
}
public class LRItemSet : HashSet<LRItem>
{
public LRItem FindByCore(LR0Item core)
{
foreach (var item in this)
if (item.Core == core) return item;
return null;
}
public LRItemSet SelectByCurrent(BnfTerm current)
{
var result = new LRItemSet();
foreach (var item in this)
if (item.Core.Current == current)
result.Add(item);
return result;
}
public LR0ItemSet GetShiftedCores()
{
var result = new LR0ItemSet();
foreach (var item in this)
if (item.Core.ShiftedItem != null)
result.Add(item.Core.ShiftedItem);
return result;
}
public LRItemSet SelectByLookahead(Terminal lookahead)
{
var result = new LRItemSet();
foreach (var item in this)
if (item.Lookaheads.Contains(lookahead))
result.Add(item);
return result;
}
} //class
public class LR0Item
{
private readonly int _hashCode;
public readonly BnfTerm Current;
//automatically generated IDs - used for building keys for lists of kernel LR0Items
// which in turn are used to quickly lookup parser states in hash
internal readonly int ID;
public readonly int Position;
public readonly Production Production;
public GrammarHintList Hints = new GrammarHintList();
public bool TailIsNullable;
public LR0Item(int id, Production production, int position, GrammarHintList hints)
{
ID = id;
Production = production;
Position = position;
Current = (Position < Production.RValues.Count) ? Production.RValues[Position] : null;
if (hints != null)
Hints.AddRange(hints);
_hashCode = ID.ToString().GetHashCode();
} //method
public LR0Item ShiftedItem
{
get
{
if (Position >= Production.LR0Items.Count - 1)
return null;
return Production.LR0Items[Position + 1];
}
}
public bool IsKernel
{
get { return Position > 0; }
}
public bool IsInitial
{
get { return Position == 0; }
}
public bool IsFinal
{
get { return Position == Production.RValues.Count; }
}
public override string ToString()
{
return Production.ProductionToString(Production, Position);
}
public override int GetHashCode()
{
return _hashCode;
}
} //LR0Item
public class LR0ItemList : List<LR0Item>
{
}
public class LR0ItemSet : HashSet<LR0Item>
{
}
} //namespace
| |
using UnityEngine;
using System.Collections;
using System;
public class MainLoop : MonoBehaviour
{
public enum eGameState
{
Init,
Ready,
FirstTap,
Running,
Done,
Exit,
};
public AudioSource GameOverSFX;
public int scoreValue = 0;
private float gameTimerValue = 10.0f;
private eGameState mGameState = eGameState.Init;
private float gameoverTimer = 0.0f;
public float gameoverTimeout = 2.0f;
/*
-----------------------------------------------------
Access to FuelHandler this pointer
-----------------------------------------------------
*/
private PropellerProduct getPropellerProductClass()
{
GameObject _propellerProductObj = GameObject.Find("PropellerProduct");
if (_propellerProductObj != null) {
PropellerProduct _propellerProductScript = _propellerProductObj.GetComponent<PropellerProduct> ();
if(_propellerProductScript != null) {
return _propellerProductScript;
}
throw new Exception();
}
throw new Exception();
}
public void setStartButtonText (string str)
{
GameObject startbuttonObj = GameObject.Find ("startTextMesh");
TextMesh tmesh = (TextMesh)startbuttonObj.GetComponent (typeof(TextMesh));
tmesh.text = str;
}
public void hideStartButtonText ()
{
GameObject startbuttonObj = GameObject.Find ("startTextMesh");
startbuttonObj.GetComponent<Renderer>().enabled = false;
}
public void updateScoreText (string str)
{
GameObject scoreObj = GameObject.Find ("Score");
TextMesh tmesh = (TextMesh)scoreObj.GetComponent (typeof(TextMesh));
tmesh.text = str;
}
public void updateFinalScoreText (string str)
{
GameObject scoreObj = GameObject.Find ("finalScore");
TextMesh tmesh = (TextMesh)scoreObj.GetComponent (typeof(TextMesh));
tmesh.text = str;
}
public void updateGameTimerText (string str)
{
GameObject gameTimerObj = GameObject.Find ("GameTimer");
TextMesh tmesh = (TextMesh)gameTimerObj.GetComponent (typeof(TextMesh));
tmesh.text = str;
}
public void updateYourAvatarText (string str)
{
GameObject gameObj = GameObject.Find ("yournameTextMesh");
TextMesh tmesh = (TextMesh)gameObj.GetComponent (typeof(TextMesh));
tmesh.text = str;
}
public void updateTheirAvatarText (string str)
{
GameObject gameObj = GameObject.Find ("theirnameTextMesh");
TextMesh tmesh = (TextMesh)gameObj.GetComponent (typeof(TextMesh));
tmesh.text = str;
}
public void updateMatchRoundText (string str)
{
GameObject gameObj = GameObject.Find ("matchroundTextMesh");
TextMesh tmesh = (TextMesh)gameObj.GetComponent (typeof(TextMesh));
tmesh.text = str;
}
void resetDynamicData ()
{
PropellerProduct _propellerProductScript = getPropellerProductClass();
gameTimerValue = (float)_propellerProductScript.getGameTime ();
int _gearShapeType = _propellerProductScript.getGearShapeType ();
float _gearFriction = _propellerProductScript.getGearFriction ();
GameObject _gearAction = GameObject.Find("GearProxy1");
gearAction _gearActionScript = _gearAction.GetComponent<gearAction>();
_gearActionScript.Reset (_gearShapeType, _gearFriction);
}
public bool isGameOver ()
{
if(mGameState == eGameState.Done){
return true;
}
return false;
}
public eGameState getGameState ()
{
return mGameState;
}
public void setGameState (eGameState state)
{
mGameState = state;
}
void InitTextMeshObjs ()
{
//init tap score
updateScoreText ( "0" );
//init game timer
updateGameTimerText ( gameTimerValue.ToString() + " sec" );
}
void Start ()
{
mGameState = eGameState.Init;
//set match data
//FuelHandler _fuelHandlerScript = getFuelHandlerClass();
//GameMatchData _data = _fuelHandlerScript.getMatchData();
PropellerProduct _propellerProductScript = getPropellerProductClass();
GameMatchData _data = _propellerProductScript.getMatchData();
if (_data.ValidMatchData == true)
{
updateYourAvatarText (_data.YourNickname);
updateTheirAvatarText (_data.TheirNickname);
updateMatchRoundText ("Round - " + _data.MatchRound.ToString ());
GameObject _gameObj = GameObject.Find("yourAvatar");
StartCoroutine(downloadImgX(_data.YourAvatarURL, _gameObj));
_gameObj = GameObject.Find("theirAvatar");
StartCoroutine(downloadImgX(_data.TheirAvatarURL, _gameObj));
}
else //Single Player
{
updateYourAvatarText ("You");
updateTheirAvatarText ("Computer");
updateMatchRoundText ("Round - X");
}
GameObject _backObj = GameObject.Find("backButton");
_backObj.GetComponent<Renderer>().enabled = false;
//Timeup Popup
GameObject _timeup = GameObject.Find("TimeUpPopup");
_timeup.GetComponent<Renderer>().enabled = false;
_timeup = GameObject.Find("finalScore");
_timeup.GetComponent<Renderer>().enabled = false;
gameoverTimer = 0.0f;
}
IEnumerator DownloadImage(string url, Texture2D tex)
{
WWW www = new WWW(url);
yield return www;
tex.LoadImage(www.bytes);
}
IEnumerator downloadImgX (string url, GameObject _gameObj)
{
Texture2D texture = new Texture2D(1,1);
WWW www = new WWW(url);
yield return www;
www.LoadImageIntoTexture(texture);
SpriteRenderer sr = _gameObj.GetComponent<SpriteRenderer>();
Debug.Log ("downloadImgX - texture.width, height : " + texture.width + ", " + texture.height);
Sprite image = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));
sr.sprite = image;
if(texture.width <= 50)
{
_gameObj.transform.localScale = new Vector3(2.5f, 2.5f, 1.0f);
}
else
{
_gameObj.transform.localScale = new Vector3(1.25f, 1.25f, 1.0f);
}
Debug.Log ("downloadImgX - tried to load image...");
}
void Update ()
{
switch (mGameState)
{
case eGameState.Init:
{
scoreValue = 0;
gameTimerValue = 10.0f;
resetDynamicData();
InitTextMeshObjs();
mGameState = eGameState.Ready;
}
break;
case eGameState.Ready:
{
//waiting for first tap
}
break;
case eGameState.FirstTap:
{
GameObject _tapsCounter = GameObject.Find("TapsCounter");
Animator _Animator = _tapsCounter.GetComponent<Animator>();
_Animator.Play ("tapCountDisplayAnim2");
_tapsCounter = GameObject.Find("MPSCounter");
_Animator = _tapsCounter.GetComponent<Animator>();
_Animator.Play ("tapCountDisplayAnim2");
mGameState = eGameState.Running;
}
break;
case eGameState.Running:
{
//update gameTimer
gameTimerValue -= Time.deltaTime;
GameObject _gearAction = GameObject.Find("GearProxy1");
gearAction _gearActionScript = _gearAction.GetComponent<gearAction>();
if(gameTimerValue <= 0)
{
mGameState = eGameState.Done;
gameTimerValue = 0.0f;
hideStartButtonText();
int maxspeed = (int)_gearActionScript.maxspinvelocity;
PropellerProduct _propellerProductScript = getPropellerProductClass();
_propellerProductScript.SetMatchScore(scoreValue, maxspeed);
GameObject _backObj = GameObject.Find("backButton");
_backObj.GetComponent<Renderer>().enabled = true;
//reset animations
GameObject _tapsCounter = GameObject.Find("TapsCounter");
Animator _Animator = _tapsCounter.GetComponent<Animator>();
_Animator.Play ("tapCountDisplayAnim");
_tapsCounter = GameObject.Find("MPSCounter");
_Animator = _tapsCounter.GetComponent<Animator>();
_Animator.Play ("tapCountDisplayAnim");
//bring the system to a grinding halt
_gearActionScript.SetFriction(0.96f);
_gearActionScript.ClearActiveBonuses();
GameOverSFX.Play();
//Timeup Popup
GameObject _timeup = GameObject.Find("TimeUpPopup");
_timeup.GetComponent<Renderer>().enabled = true;
updateFinalScoreText(scoreValue.ToString());
_timeup = GameObject.Find("finalScore");
_timeup.GetComponent<Renderer>().enabled = true;
//another complete game session
if (PlayerPrefs.HasKey ("numSessions"))
{
int numSessions = PlayerPrefs.GetInt ("numSessions");
numSessions++;
PlayerPrefs.SetInt("numSessions", numSessions);
}
}
//update game timer
if(_gearActionScript.Check5secBonus() == true)
{
gameTimerValue += 5.0f;
}
updateGameTimerText ( gameTimerValue.ToString("0") + " sec" );
updateScoreText ( scoreValue.ToString() );
GameObject spinTextObj = GameObject.Find ("speedTextMesh");
TextMesh tmesh = (TextMesh)spinTextObj.GetComponent (typeof(TextMesh));
tmesh.text = _gearActionScript.velocityStr;
}
break;
case eGameState.Done:
{
//timeout to return to main menu
gameoverTimer += Time.deltaTime;
if(gameoverTimer >= gameoverTimeout)
{
InitMainMenu.sComingFromGame = true;
Application.LoadLevel("MainMenu");
mGameState = eGameState.Exit;
}
}
break;
case eGameState.Exit:
{
}
break;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using ICSharpCode.NRefactory.TypeSystem;
using Saltarelle.Compiler;
using Saltarelle.Compiler.Compiler;
using Saltarelle.Compiler.JSModel.Expressions;
using Saltarelle.Compiler.JSModel.ExtensionMethods;
using Saltarelle.Compiler.ScriptSemantics;
namespace CoreLib.Plugin {
public class MetadataImporter : IMetadataImporter {
private static readonly ReadOnlySet<string> _unusableStaticFieldNames = new ReadOnlySet<string>(new HashSet<string>(new[] { "__defineGetter__", "__defineSetter__", "apply", "arguments", "bind", "call", "caller", "constructor", "hasOwnProperty", "isPrototypeOf", "length", "name", "propertyIsEnumerable", "prototype", "toLocaleString", "valueOf" }.Concat(Saltarelle.Compiler.JSModel.Utils.AllKeywords)));
private static readonly ReadOnlySet<string> _unusableInstanceFieldNames = new ReadOnlySet<string>(new HashSet<string>(new[] { "__defineGetter__", "__defineSetter__", "constructor", "hasOwnProperty", "isPrototypeOf", "propertyIsEnumerable", "toLocaleString", "valueOf" }.Concat(Saltarelle.Compiler.JSModel.Utils.AllKeywords)));
private class TypeSemantics {
public TypeScriptSemantics Semantics { get; private set; }
public bool IsSerializable { get; private set; }
public bool IsNamedValues { get; private set; }
public bool IsImported { get; private set; }
public TypeSemantics(TypeScriptSemantics semantics, bool isSerializable, bool isNamedValues, bool isImported) {
Semantics = semantics;
IsSerializable = isSerializable;
IsNamedValues = isNamedValues;
IsImported = isImported;
}
}
private Dictionary<ITypeDefinition, TypeSemantics> _typeSemantics;
private Dictionary<ITypeDefinition, DelegateScriptSemantics> _delegateSemantics;
private Dictionary<ITypeDefinition, HashSet<string>> _instanceMemberNamesByType;
private Dictionary<ITypeDefinition, HashSet<string>> _staticMemberNamesByType;
private Dictionary<IMethod, MethodScriptSemantics> _methodSemantics;
private Dictionary<IProperty, PropertyScriptSemantics> _propertySemantics;
private Dictionary<IField, FieldScriptSemantics> _fieldSemantics;
private Dictionary<IEvent, EventScriptSemantics> _eventSemantics;
private Dictionary<IMethod, ConstructorScriptSemantics> _constructorSemantics;
private Dictionary<IProperty, string> _propertyBackingFieldNames;
private Dictionary<IEvent, string> _eventBackingFieldNames;
private Dictionary<ITypeDefinition, int> _backingFieldCountPerType;
private Dictionary<Tuple<IAssembly, string>, int> _internalTypeCountPerAssemblyAndNamespace;
private HashSet<IMember> _ignoredMembers;
private IErrorReporter _errorReporter;
private IType _systemObject;
private ICompilation _compilation;
private bool _minimizeNames;
public MetadataImporter(IErrorReporter errorReporter, ICompilation compilation, CompilerOptions options) {
_errorReporter = errorReporter;
_compilation = compilation;
_minimizeNames = options.MinimizeScript;
_systemObject = compilation.MainAssembly.Compilation.FindType(KnownTypeCode.Object);
_typeSemantics = new Dictionary<ITypeDefinition, TypeSemantics>();
_delegateSemantics = new Dictionary<ITypeDefinition, DelegateScriptSemantics>();
_instanceMemberNamesByType = new Dictionary<ITypeDefinition, HashSet<string>>();
_staticMemberNamesByType = new Dictionary<ITypeDefinition, HashSet<string>>();
_methodSemantics = new Dictionary<IMethod, MethodScriptSemantics>();
_propertySemantics = new Dictionary<IProperty, PropertyScriptSemantics>();
_fieldSemantics = new Dictionary<IField, FieldScriptSemantics>();
_eventSemantics = new Dictionary<IEvent, EventScriptSemantics>();
_constructorSemantics = new Dictionary<IMethod, ConstructorScriptSemantics>();
_propertyBackingFieldNames = new Dictionary<IProperty, string>();
_eventBackingFieldNames = new Dictionary<IEvent, string>();
_backingFieldCountPerType = new Dictionary<ITypeDefinition, int>();
_internalTypeCountPerAssemblyAndNamespace = new Dictionary<Tuple<IAssembly, string>, int>();
_ignoredMembers = new HashSet<IMember>();
var sna = compilation.MainAssembly.AssemblyAttributes.SingleOrDefault(a => a.AttributeType.FullName == typeof(ScriptNamespaceAttribute).FullName);
if (sna != null) {
var data = AttributeReader.ReadAttribute<ScriptNamespaceAttribute>(sna);
if (data.Name == null || (data.Name != "" && !data.Name.IsValidNestedJavaScriptIdentifier())) {
Message(Messages._7002, sna.Region, "assembly");
}
}
}
private void Message(Tuple<int, MessageSeverity, string> message, DomRegion r, params object[] additionalArgs) {
_errorReporter.Region = r;
_errorReporter.Message(message, additionalArgs);
}
private void Message(Tuple<int, MessageSeverity, string> message, IEntity e, params object[] additionalArgs) {
var name = (e is IMethod && ((IMethod)e).IsConstructor ? e.DeclaringType.FullName : e.FullName);
_errorReporter.Region = e.Region;
_errorReporter.Message(message, new object[] { name }.Concat(additionalArgs).ToArray());
}
private string GetDefaultTypeName(ITypeDefinition def, bool ignoreGenericArguments) {
if (ignoreGenericArguments) {
return def.Name;
}
else {
int outerCount = (def.DeclaringTypeDefinition != null ? def.DeclaringTypeDefinition.TypeParameters.Count : 0);
return def.Name + (def.TypeParameterCount != outerCount ? "$" + (def.TypeParameterCount - outerCount).ToString(CultureInfo.InvariantCulture) : "");
}
}
private bool? IsAutoProperty(IProperty property) {
if (property.Region == default(DomRegion))
return null;
return property.Getter != null && property.Setter != null && property.Getter.BodyRegion == default(DomRegion) && property.Setter.BodyRegion == default(DomRegion);
}
private string DetermineNamespace(ITypeDefinition typeDefinition) {
while (typeDefinition.DeclaringTypeDefinition != null) {
typeDefinition = typeDefinition.DeclaringTypeDefinition;
}
var ina = AttributeReader.ReadAttribute<IgnoreNamespaceAttribute>(typeDefinition);
var sna = AttributeReader.ReadAttribute<ScriptNamespaceAttribute>(typeDefinition);
if (ina != null) {
if (sna != null) {
Message(Messages._7001, typeDefinition);
return typeDefinition.FullName;
}
else {
return "";
}
}
else {
if (sna != null) {
if (sna.Name == null || (sna.Name != "" && !sna.Name.IsValidNestedJavaScriptIdentifier()))
Message(Messages._7002, typeDefinition);
return sna.Name;
}
else {
var asna = AttributeReader.ReadAttribute<ScriptNamespaceAttribute>(typeDefinition.ParentAssembly.AssemblyAttributes);
if (asna != null) {
if (asna.Name != null && (asna.Name == "" || asna.Name.IsValidNestedJavaScriptIdentifier()))
return asna.Name;
}
return typeDefinition.Namespace;
}
}
}
private Tuple<string, string> SplitNamespacedName(string fullName) {
string nmspace;
string name;
int dot = fullName.IndexOf('.');
if (dot >= 0) {
nmspace = fullName.Substring(0, dot);
name = fullName.Substring(dot + 1 );
}
else {
nmspace = "";
name = fullName;
}
return Tuple.Create(nmspace, name);
}
private void ProcessDelegate(ITypeDefinition delegateDefinition) {
bool bindThisToFirstParameter = AttributeReader.HasAttribute<BindThisToFirstParameterAttribute>(delegateDefinition);
bool expandParams = AttributeReader.HasAttribute<ExpandParamsAttribute>(delegateDefinition);
if (bindThisToFirstParameter && delegateDefinition.GetDelegateInvokeMethod().Parameters.Count == 0) {
Message(Messages._7147, delegateDefinition, delegateDefinition.FullName);
bindThisToFirstParameter = false;
}
if (expandParams && !delegateDefinition.GetDelegateInvokeMethod().Parameters.Any(p => p.IsParams)) {
Message(Messages._7148, delegateDefinition, delegateDefinition.FullName);
expandParams = false;
}
_delegateSemantics[delegateDefinition] = new DelegateScriptSemantics(expandParams: expandParams, bindThisToFirstParameter: bindThisToFirstParameter);
}
private void ProcessType(ITypeDefinition typeDefinition) {
if (typeDefinition.Kind == TypeKind.Delegate) {
ProcessDelegate(typeDefinition);
return;
}
if (AttributeReader.HasAttribute<NonScriptableAttribute>(typeDefinition) || typeDefinition.DeclaringTypeDefinition != null && GetTypeSemantics(typeDefinition.DeclaringTypeDefinition).Type == TypeScriptSemantics.ImplType.NotUsableFromScript) {
_typeSemantics[typeDefinition] = new TypeSemantics(TypeScriptSemantics.NotUsableFromScript(), false, false, false);
return;
}
var scriptNameAttr = AttributeReader.ReadAttribute<ScriptNameAttribute>(typeDefinition);
var importedAttr = AttributeReader.ReadAttribute<ImportedAttribute>(typeDefinition.Attributes);
bool preserveName = importedAttr != null || AttributeReader.HasAttribute<PreserveNameAttribute>(typeDefinition);
bool? includeGenericArguments = typeDefinition.TypeParameterCount > 0 ? MetadataUtils.ShouldGenericArgumentsBeIncluded(typeDefinition) : false;
if (includeGenericArguments == null) {
_errorReporter.Region = typeDefinition.Region;
Message(Messages._7026, typeDefinition);
includeGenericArguments = true;
}
if (AttributeReader.HasAttribute<ResourcesAttribute>(typeDefinition)) {
if (!typeDefinition.IsStatic) {
Message(Messages._7003, typeDefinition);
}
else if (typeDefinition.TypeParameterCount > 0) {
Message(Messages._7004, typeDefinition);
}
else if (typeDefinition.Members.Any(m => !(m is IField && ((IField)m).IsConst))) {
Message(Messages._7005, typeDefinition);
}
}
string typeName, nmspace;
if (scriptNameAttr != null && scriptNameAttr.Name != null && scriptNameAttr.Name.IsValidJavaScriptIdentifier()) {
typeName = scriptNameAttr.Name;
nmspace = DetermineNamespace(typeDefinition);
}
else if (scriptNameAttr != null && string.IsNullOrEmpty(scriptNameAttr.Name) && !string.IsNullOrEmpty(MetadataUtils.GetModuleName(typeDefinition))) {
typeName = "";
nmspace = "";
}
else {
if (scriptNameAttr != null) {
Message(Messages._7006, typeDefinition);
}
if (_minimizeNames && MetadataUtils.CanBeMinimized(typeDefinition) && !preserveName) {
nmspace = DetermineNamespace(typeDefinition);
var key = Tuple.Create(typeDefinition.ParentAssembly, nmspace);
int index;
_internalTypeCountPerAssemblyAndNamespace.TryGetValue(key, out index);
_internalTypeCountPerAssemblyAndNamespace[key] = index + 1;
typeName = "$" + index.ToString(CultureInfo.InvariantCulture);
}
else {
typeName = GetDefaultTypeName(typeDefinition, !includeGenericArguments.Value);
if (typeDefinition.DeclaringTypeDefinition != null) {
if (AttributeReader.HasAttribute<IgnoreNamespaceAttribute>(typeDefinition) || AttributeReader.HasAttribute<ScriptNamespaceAttribute>(typeDefinition)) {
Message(Messages._7007, typeDefinition);
}
var declaringName = SplitNamespacedName(GetTypeSemantics(typeDefinition.DeclaringTypeDefinition).Name);
nmspace = declaringName.Item1;
typeName = declaringName.Item2 + "$" + typeName;
}
else {
nmspace = DetermineNamespace(typeDefinition);
}
if (MetadataUtils.CanBeMinimized(typeDefinition) && !preserveName && !typeName.StartsWith("$")) {
typeName = "$" + typeName;
}
}
}
bool isSerializable = MetadataUtils.IsSerializable(typeDefinition);
if (isSerializable) {
var baseClass = typeDefinition.DirectBaseTypes.Single(c => c.Kind == TypeKind.Class).GetDefinition();
if (!baseClass.Equals(_systemObject) && baseClass.FullName != "System.Record" && !GetTypeSemanticsInternal(baseClass).IsSerializable) {
Message(Messages._7009, typeDefinition);
}
foreach (var i in typeDefinition.DirectBaseTypes.Where(b => b.Kind == TypeKind.Interface && !GetTypeSemanticsInternal(b.GetDefinition()).IsSerializable)) {
Message(Messages._7010, typeDefinition, i);
}
if (typeDefinition.Events.Any(evt => !evt.IsStatic)) {
Message(Messages._7011, typeDefinition);
}
foreach (var m in typeDefinition.Members.Where(m => m.IsVirtual)) {
Message(Messages._7023, typeDefinition, m.Name);
}
foreach (var m in typeDefinition.Members.Where(m => m.IsOverride)) {
Message(Messages._7024, typeDefinition, m.Name);
}
if (typeDefinition.Kind == TypeKind.Interface && typeDefinition.Methods.Any()) {
Message(Messages._7155, typeDefinition);
}
}
else {
var globalMethodsAttr = AttributeReader.ReadAttribute<GlobalMethodsAttribute>(typeDefinition);
var mixinAttr = AttributeReader.ReadAttribute<MixinAttribute>(typeDefinition);
if (mixinAttr != null) {
if (!typeDefinition.IsStatic) {
Message(Messages._7012, typeDefinition);
}
else if (typeDefinition.Members.Any(m => !(m is IMethod) || ((IMethod)m).IsConstructor)) {
Message(Messages._7013, typeDefinition);
}
else if (typeDefinition.TypeParameterCount > 0) {
Message(Messages._7014, typeDefinition);
}
else if (string.IsNullOrEmpty(mixinAttr.Expression)) {
Message(Messages._7025, typeDefinition);
}
else {
var split = SplitNamespacedName(mixinAttr.Expression);
nmspace = split.Item1;
typeName = split.Item2;
}
}
else if (globalMethodsAttr != null) {
if (!typeDefinition.IsStatic) {
Message(Messages._7015, typeDefinition);
}
else if (typeDefinition.TypeParameterCount > 0) {
Message(Messages._7017, typeDefinition);
}
else {
nmspace = "";
typeName = "";
}
}
}
if (importedAttr != null) {
if (!string.IsNullOrEmpty(importedAttr.TypeCheckCode)) {
if (importedAttr.ObeysTypeSystem) {
Message(Messages._7158, typeDefinition);
}
ValidateInlineCode(MetadataUtils.CreateTypeCheckMethod(typeDefinition, _compilation), typeDefinition, importedAttr.TypeCheckCode, Messages._7157);
}
if (!string.IsNullOrEmpty(MetadataUtils.GetSerializableTypeCheckCode(typeDefinition))) {
Message(Messages._7159, typeDefinition);
}
}
_typeSemantics[typeDefinition] = new TypeSemantics(TypeScriptSemantics.NormalType(!string.IsNullOrEmpty(nmspace) ? nmspace + "." + typeName : typeName, ignoreGenericArguments: !includeGenericArguments.Value, generateCode: importedAttr == null), isSerializable: isSerializable, isNamedValues: MetadataUtils.IsNamedValues(typeDefinition), isImported: importedAttr != null);
}
private HashSet<string> GetInstanceMemberNames(ITypeDefinition typeDefinition) {
HashSet<string> result;
if (!_instanceMemberNamesByType.TryGetValue(typeDefinition, out result))
throw new ArgumentException("Error getting instance member names: type " + typeDefinition.FullName + " has not yet been processed.");
return result;
}
private Tuple<string, bool> DeterminePreferredMemberName(IMember member) {
var asa = AttributeReader.ReadAttribute<AlternateSignatureAttribute>(member);
if (asa != null) {
var otherMembers = member.DeclaringTypeDefinition.Methods.Where(m => m.Name == member.Name && !AttributeReader.HasAttribute<AlternateSignatureAttribute>(m) && !AttributeReader.HasAttribute<NonScriptableAttribute>(m) && !AttributeReader.HasAttribute<InlineCodeAttribute>(m)).ToList();
if (otherMembers.Count != 1) {
Message(Messages._7100, member);
return Tuple.Create(member.Name, false);
}
}
return MetadataUtils.DeterminePreferredMemberName(member, _minimizeNames);
}
private void ProcessTypeMembers(ITypeDefinition typeDefinition) {
if (typeDefinition.Kind == TypeKind.Delegate)
return;
var baseMembersByType = typeDefinition.GetAllBaseTypeDefinitions().Where(x => x != typeDefinition).Select(t => new { Type = t, MemberNames = GetInstanceMemberNames(t) }).ToList();
for (int i = 0; i < baseMembersByType.Count; i++) {
var b = baseMembersByType[i];
for (int j = i + 1; j < baseMembersByType.Count; j++) {
var b2 = baseMembersByType[j];
if (!b.Type.GetAllBaseTypeDefinitions().Contains(b2.Type) && !b2.Type.GetAllBaseTypeDefinitions().Contains(b.Type)) {
foreach (var dup in b.MemberNames.Where(x => b2.MemberNames.Contains(x))) {
Message(Messages._7018, typeDefinition, b.Type.FullName, b2.Type.FullName, dup);
}
}
}
}
var instanceMembers = baseMembersByType.SelectMany(m => m.MemberNames).Distinct().ToDictionary(m => m, m => false);
if (_instanceMemberNamesByType.ContainsKey(typeDefinition))
_instanceMemberNamesByType[typeDefinition].ForEach(s => instanceMembers[s] = true);
_unusableInstanceFieldNames.ForEach(n => instanceMembers[n] = false);
var staticMembers = _unusableStaticFieldNames.ToDictionary(n => n, n => false);
if (_staticMemberNamesByType.ContainsKey(typeDefinition))
_staticMemberNamesByType[typeDefinition].ForEach(s => staticMembers[s] = true);
var membersByName = from m in typeDefinition.GetMembers(options: GetMemberOptions.IgnoreInheritedMembers)
where !_ignoredMembers.Contains(m)
let name = DeterminePreferredMemberName(m)
group new { m, name } by name.Item1 into g
select new { Name = g.Key, Members = g.Select(x => new { Member = x.m, NameSpecified = x.name.Item2 }).ToList() };
bool isSerializable = GetTypeSemanticsInternal(typeDefinition).IsSerializable;
foreach (var current in membersByName) {
foreach (var m in current.Members.OrderByDescending(x => x.NameSpecified).ThenBy(x => x.Member, MemberOrderer.Instance)) {
if (m.Member is IMethod) {
var method = (IMethod)m.Member;
if (method.IsConstructor) {
ProcessConstructor(method, current.Name, m.NameSpecified, staticMembers);
}
else {
ProcessMethod(method, current.Name, m.NameSpecified, m.Member.IsStatic || isSerializable ? staticMembers : instanceMembers);
}
}
else if (m.Member is IProperty) {
var p = (IProperty)m.Member;
ProcessProperty(p, current.Name, m.NameSpecified, m.Member.IsStatic ? staticMembers : instanceMembers);
var ps = GetPropertySemantics(p);
if (p.CanGet)
_methodSemantics[p.Getter] = ps.Type == PropertyScriptSemantics.ImplType.GetAndSetMethods ? ps.GetMethod : MethodScriptSemantics.NotUsableFromScript();
if (p.CanSet)
_methodSemantics[p.Setter] = ps.Type == PropertyScriptSemantics.ImplType.GetAndSetMethods ? ps.SetMethod : MethodScriptSemantics.NotUsableFromScript();
}
else if (m.Member is IField) {
ProcessField((IField)m.Member, current.Name, m.NameSpecified, m.Member.IsStatic ? staticMembers : instanceMembers);
}
else if (m.Member is IEvent) {
var e = (IEvent)m.Member;
ProcessEvent((IEvent)m.Member, current.Name, m.NameSpecified, m.Member.IsStatic ? staticMembers : instanceMembers);
var es = GetEventSemantics(e);
_methodSemantics[e.AddAccessor] = es.Type == EventScriptSemantics.ImplType.AddAndRemoveMethods ? es.AddMethod : MethodScriptSemantics.NotUsableFromScript();
_methodSemantics[e.RemoveAccessor] = es.Type == EventScriptSemantics.ImplType.AddAndRemoveMethods ? es.RemoveMethod : MethodScriptSemantics.NotUsableFromScript();
}
}
}
_instanceMemberNamesByType[typeDefinition] = new HashSet<string>(instanceMembers.Where(kvp => kvp.Value).Select(kvp => kvp.Key));
_staticMemberNamesByType[typeDefinition] = new HashSet<string>(staticMembers.Where(kvp => kvp.Value).Select(kvp => kvp.Key));
}
private string GetUniqueName(string preferredName, Dictionary<string, bool> usedNames) {
return MetadataUtils.GetUniqueName(preferredName, n => !usedNames.ContainsKey(n));
}
private bool ValidateInlineCode(IMethod method, IEntity errorEntity, string code, Tuple<int, MessageSeverity, string> errorTemplate) {
var typeErrors = new List<string>();
var errors = InlineCodeMethodCompiler.ValidateLiteralCode(method, code, n => {
var type = ReflectionHelper.ParseReflectionName(n).Resolve(_compilation);
if (type.Kind == TypeKind.Unknown) {
typeErrors.Add("Unknown type '" + n + "' specified in inline implementation");
}
return JsExpression.Null;
}, t => JsExpression.Null);
if (errors.Count > 0 || typeErrors.Count > 0) {
Message(errorTemplate, errorEntity, string.Join(", ", errors.Concat(typeErrors)));
return false;
}
return true;
}
private void ProcessConstructor(IMethod constructor, string preferredName, bool nameSpecified, Dictionary<string, bool> usedNames) {
if (constructor.Parameters.Count == 1 && constructor.Parameters[0].Type.FullName == typeof(DummyTypeUsedToAddAttributeToDefaultValueTypeConstructor).FullName) {
_constructorSemantics[constructor] = ConstructorScriptSemantics.NotUsableFromScript();
return;
}
var source = (IMethod)MetadataUtils.UnwrapValueTypeConstructor(constructor);
var nsa = AttributeReader.ReadAttribute<NonScriptableAttribute>(source);
var asa = AttributeReader.ReadAttribute<AlternateSignatureAttribute>(source);
var epa = AttributeReader.ReadAttribute<ExpandParamsAttribute>(source);
var ola = AttributeReader.ReadAttribute<ObjectLiteralAttribute>(source);
if (nsa != null || GetTypeSemanticsInternal(source.DeclaringTypeDefinition).Semantics.Type == TypeScriptSemantics.ImplType.NotUsableFromScript) {
_constructorSemantics[constructor] = ConstructorScriptSemantics.NotUsableFromScript();
return;
}
if (source.IsStatic) {
_constructorSemantics[constructor] = ConstructorScriptSemantics.Unnamed(); // Whatever, it is not really used.
return;
}
if (epa != null && !source.Parameters.Any(p => p.IsParams)) {
Message(Messages._7102, constructor);
}
bool isSerializable = GetTypeSemanticsInternal(source.DeclaringTypeDefinition).IsSerializable;
bool isImported = GetTypeSemanticsInternal(source.DeclaringTypeDefinition).IsImported;
bool skipInInitializer = AttributeReader.HasAttribute<ScriptSkipAttribute>(constructor);
var ica = AttributeReader.ReadAttribute<InlineCodeAttribute>(source);
if (ica != null) {
if (!ValidateInlineCode(source, source, ica.Code, Messages._7103)) {
_constructorSemantics[constructor] = ConstructorScriptSemantics.Unnamed();
return;
}
if (ica.NonExpandedFormCode != null && !ValidateInlineCode(source, source, ica.NonExpandedFormCode, Messages._7103)) {
_constructorSemantics[constructor] = ConstructorScriptSemantics.Unnamed();
return;
}
if (ica.NonExpandedFormCode != null && !constructor.Parameters.Any(p => p.IsParams)) {
Message(Messages._7029, constructor.Region, "constructor", constructor.DeclaringType.FullName);
_constructorSemantics[constructor] = ConstructorScriptSemantics.Unnamed();
return;
}
_constructorSemantics[constructor] = ConstructorScriptSemantics.InlineCode(ica.Code, skipInInitializer: skipInInitializer, nonExpandedFormLiteralCode: ica.NonExpandedFormCode);
return;
}
else if (asa != null) {
_constructorSemantics[constructor] = preferredName == "$ctor" ? ConstructorScriptSemantics.Unnamed(generateCode: false, expandParams: epa != null, skipInInitializer: skipInInitializer) : ConstructorScriptSemantics.Named(preferredName, generateCode: false, expandParams: epa != null, skipInInitializer: skipInInitializer);
return;
}
else if (ola != null || (isSerializable && GetTypeSemanticsInternal(source.DeclaringTypeDefinition).IsImported)) {
if (isSerializable) {
bool hasError = false;
var members = source.DeclaringTypeDefinition.Members.Where(m => m.EntityType == EntityType.Property || m.EntityType == EntityType.Field).ToDictionary(m => m.Name.ToLowerInvariant());
var parameterToMemberMap = new List<IMember>();
foreach (var p in source.Parameters) {
IMember member;
if (p.IsOut || p.IsRef) {
Message(Messages._7145, p.Region, p.Name);
hasError = true;
}
else if (members.TryGetValue(p.Name.ToLowerInvariant(), out member)) {
if (p.Type.GetAllBaseTypes().Any(b => b.Equals(member.ReturnType)) || (member.ReturnType.IsKnownType(KnownTypeCode.NullableOfT) && member.ReturnType.TypeArguments[0].Equals(p.Type))) {
parameterToMemberMap.Add(member);
}
else {
Message(Messages._7144, p.Region, p.Name, p.Type.FullName, member.ReturnType.FullName);
hasError = true;
}
}
else {
Message(Messages._7143, p.Region, source.DeclaringTypeDefinition.FullName, p.Name);
hasError = true;
}
}
_constructorSemantics[constructor] = hasError ? ConstructorScriptSemantics.Unnamed() : ConstructorScriptSemantics.Json(parameterToMemberMap, skipInInitializer: skipInInitializer || constructor.Parameters.Count == 0);
}
else {
Message(Messages._7146, constructor.Region, source.DeclaringTypeDefinition.FullName);
_constructorSemantics[constructor] = ConstructorScriptSemantics.Unnamed();
}
return;
}
else if (source.Parameters.Count == 1 && source.Parameters[0].Type is ArrayType && ((ArrayType)source.Parameters[0].Type).ElementType.IsKnownType(KnownTypeCode.Object) && source.Parameters[0].IsParams && isImported) {
_constructorSemantics[constructor] = ConstructorScriptSemantics.InlineCode("ss.mkdict({" + source.Parameters[0].Name + "})", skipInInitializer: skipInInitializer);
return;
}
else if (nameSpecified) {
if (isSerializable)
_constructorSemantics[constructor] = ConstructorScriptSemantics.StaticMethod(preferredName, expandParams: epa != null, skipInInitializer: skipInInitializer);
else
_constructorSemantics[constructor] = preferredName == "$ctor" ? ConstructorScriptSemantics.Unnamed(expandParams: epa != null, skipInInitializer: skipInInitializer) : ConstructorScriptSemantics.Named(preferredName, expandParams: epa != null, skipInInitializer: skipInInitializer);
usedNames[preferredName] = true;
return;
}
else {
if (!usedNames.ContainsKey("$ctor") && !(isSerializable && _minimizeNames && MetadataUtils.CanBeMinimized(source))) { // The last part ensures that the first constructor of a serializable type can have its name minimized.
_constructorSemantics[constructor] = isSerializable ? ConstructorScriptSemantics.StaticMethod("$ctor", expandParams: epa != null, skipInInitializer: skipInInitializer) : ConstructorScriptSemantics.Unnamed(expandParams: epa != null, skipInInitializer: skipInInitializer);
usedNames["$ctor"] = true;
return;
}
else {
string name;
if (_minimizeNames && MetadataUtils.CanBeMinimized(source)) {
name = GetUniqueName(null, usedNames);
}
else {
int i = 1;
do {
name = "$ctor" + MetadataUtils.EncodeNumber(i, false);
i++;
} while (usedNames.ContainsKey(name));
}
_constructorSemantics[constructor] = isSerializable ? ConstructorScriptSemantics.StaticMethod(name, expandParams: epa != null, skipInInitializer: skipInInitializer) : ConstructorScriptSemantics.Named(name, expandParams: epa != null, skipInInitializer: skipInInitializer);
usedNames[name] = true;
return;
}
}
}
private void ProcessProperty(IProperty property, string preferredName, bool nameSpecified, Dictionary<string, bool> usedNames) {
if (GetTypeSemanticsInternal(property.DeclaringTypeDefinition).Semantics.Type == TypeScriptSemantics.ImplType.NotUsableFromScript || AttributeReader.HasAttribute<NonScriptableAttribute>(property)) {
_propertySemantics[property] = PropertyScriptSemantics.NotUsableFromScript();
return;
}
else if (preferredName == "") {
if (property.IsIndexer) {
Message(Messages._7104, property);
}
else {
Message(Messages._7105, property);
}
_propertySemantics[property] = PropertyScriptSemantics.GetAndSetMethods(property.CanGet ? MethodScriptSemantics.NormalMethod("get") : null, property.CanSet ? MethodScriptSemantics.NormalMethod("set") : null);
return;
}
else if (GetTypeSemanticsInternal(property.DeclaringTypeDefinition).IsSerializable && !property.IsStatic) {
var getica = property.Getter != null ? AttributeReader.ReadAttribute<InlineCodeAttribute>(property.Getter) : null;
var setica = property.Setter != null ? AttributeReader.ReadAttribute<InlineCodeAttribute>(property.Setter) : null;
if (property.Getter != null && property.Setter != null && (getica != null) != (setica != null)) {
Message(Messages._7028, property);
}
else if (getica != null || setica != null) {
bool hasError = false;
if (property.Getter != null && !ValidateInlineCode(property.Getter, property.Getter, getica.Code, Messages._7130)) {
hasError = true;
}
if (property.Setter != null && !ValidateInlineCode(property.Setter, property.Setter, setica.Code, Messages._7130)) {
hasError = true;
}
if (!hasError) {
_propertySemantics[property] = PropertyScriptSemantics.GetAndSetMethods(getica != null ? MethodScriptSemantics.InlineCode(getica.Code) : null, setica != null ? MethodScriptSemantics.InlineCode(setica.Code) : null);
return;
}
}
usedNames[preferredName] = true;
_propertySemantics[property] = PropertyScriptSemantics.Field(preferredName);
return;
}
var saa = AttributeReader.ReadAttribute<ScriptAliasAttribute>(property);
if (saa != null) {
if (property.IsIndexer) {
Message(Messages._7106, property.Region);
}
else if (!property.IsStatic) {
Message(Messages._7107, property);
}
else {
_propertySemantics[property] = PropertyScriptSemantics.GetAndSetMethods(property.CanGet ? MethodScriptSemantics.InlineCode(saa.Alias) : null, property.CanSet ? MethodScriptSemantics.InlineCode(saa.Alias + " = {value}") : null);
return;
}
}
if (AttributeReader.HasAttribute<IntrinsicPropertyAttribute>(property)) {
if (property.DeclaringType.Kind == TypeKind.Interface) {
if (property.IsIndexer)
Message(Messages._7108, property.Region);
else
Message(Messages._7109, property);
}
else if (property.IsOverride && GetPropertySemantics((IProperty)InheritanceHelper.GetBaseMember(property).MemberDefinition).Type != PropertyScriptSemantics.ImplType.NotUsableFromScript) {
if (property.IsIndexer)
Message(Messages._7110, property.Region);
else
Message(Messages._7111, property);
}
else if (property.IsOverridable) {
if (property.IsIndexer)
Message(Messages._7112, property.Region);
else
Message(Messages._7113, property);
}
else if (property.IsExplicitInterfaceImplementation || property.ImplementedInterfaceMembers.Any(m => GetPropertySemantics((IProperty)m.MemberDefinition).Type != PropertyScriptSemantics.ImplType.NotUsableFromScript)) {
if (property.IsIndexer)
Message(Messages._7114, property.Region);
else
Message(Messages._7115, property);
}
else if (property.IsIndexer) {
if (property.Parameters.Count == 1) {
_propertySemantics[property] = PropertyScriptSemantics.GetAndSetMethods(property.CanGet ? MethodScriptSemantics.NativeIndexer() : null, property.CanSet ? MethodScriptSemantics.NativeIndexer() : null);
return;
}
else {
Message(Messages._7116, property.Region);
}
}
else {
usedNames[preferredName] = true;
_propertySemantics[property] = PropertyScriptSemantics.Field(preferredName);
return;
}
}
if (property.IsExplicitInterfaceImplementation && property.ImplementedInterfaceMembers.Any(m => GetPropertySemantics((IProperty)m.MemberDefinition).Type == PropertyScriptSemantics.ImplType.NotUsableFromScript)) {
// Inherit [NonScriptable] for explicit interface implementations.
_propertySemantics[property] = PropertyScriptSemantics.NotUsableFromScript();
return;
}
if (property.ImplementedInterfaceMembers.Count > 0) {
var bases = property.ImplementedInterfaceMembers.Where(b => GetPropertySemantics((IProperty)b).Type != PropertyScriptSemantics.ImplType.NotUsableFromScript).ToList();
var firstField = bases.FirstOrDefault(b => GetPropertySemantics((IProperty)b).Type == PropertyScriptSemantics.ImplType.Field);
if (firstField != null) {
var firstFieldSemantics = GetPropertySemantics((IProperty)firstField);
if (property.IsOverride) {
Message(Messages._7154, property, firstField.FullName);
}
else if (property.IsOverridable) {
Message(Messages._7153, property, firstField.FullName);
}
if (IsAutoProperty(property) == false) {
Message(Messages._7156, property, firstField.FullName);
}
_propertySemantics[property] = firstFieldSemantics;
return;
}
}
MethodScriptSemantics getter, setter;
if (property.CanGet) {
var getterName = DeterminePreferredMemberName(property.Getter);
if (!getterName.Item2)
getterName = Tuple.Create(!nameSpecified && _minimizeNames && property.DeclaringType.Kind != TypeKind.Interface && MetadataUtils.CanBeMinimized(property) ? null : (nameSpecified ? "get_" + preferredName : GetUniqueName("get_" + preferredName, usedNames)), false); // If the name was not specified, generate one.
ProcessMethod(property.Getter, getterName.Item1, getterName.Item2, usedNames);
getter = GetMethodSemanticsInternal(property.Getter);
}
else {
getter = null;
}
if (property.CanSet) {
var setterName = DeterminePreferredMemberName(property.Setter);
if (!setterName.Item2)
setterName = Tuple.Create(!nameSpecified && _minimizeNames && property.DeclaringType.Kind != TypeKind.Interface && MetadataUtils.CanBeMinimized(property) ? null : (nameSpecified ? "set_" + preferredName : GetUniqueName("set_" + preferredName, usedNames)), false); // If the name was not specified, generate one.
ProcessMethod(property.Setter, setterName.Item1, setterName.Item2, usedNames);
setter = GetMethodSemanticsInternal(property.Setter);
}
else {
setter = null;
}
_propertySemantics[property] = PropertyScriptSemantics.GetAndSetMethods(getter, setter);
}
private void ProcessMethod(IMethod method, string preferredName, bool nameSpecified, Dictionary<string, bool> usedNames) {
var eaa = AttributeReader.ReadAttribute<EnumerateAsArrayAttribute>(method);
var ssa = AttributeReader.ReadAttribute<ScriptSkipAttribute>(method);
var saa = AttributeReader.ReadAttribute<ScriptAliasAttribute>(method);
var ica = AttributeReader.ReadAttribute<InlineCodeAttribute>(method);
var ifa = AttributeReader.ReadAttribute<InstanceMethodOnFirstArgumentAttribute>(method);
var nsa = AttributeReader.ReadAttribute<NonScriptableAttribute>(method);
var ioa = AttributeReader.ReadAttribute<IntrinsicOperatorAttribute>(method);
var epa = AttributeReader.ReadAttribute<ExpandParamsAttribute>(method);
var asa = AttributeReader.ReadAttribute<AlternateSignatureAttribute>(method);
bool? includeGenericArguments = method.TypeParameters.Count > 0 ? MetadataUtils.ShouldGenericArgumentsBeIncluded(method) : false;
if (eaa != null && (method.Name != "GetEnumerator" || method.IsStatic || method.TypeParameters.Count > 0 || method.Parameters.Count > 0)) {
Message(Messages._7151, method);
eaa = null;
}
if (nsa != null || GetTypeSemanticsInternal(method.DeclaringTypeDefinition).Semantics.Type == TypeScriptSemantics.ImplType.NotUsableFromScript) {
_methodSemantics[method] = MethodScriptSemantics.NotUsableFromScript();
return;
}
if (ioa != null) {
if (!method.IsOperator) {
Message(Messages._7117, method);
_methodSemantics[method] = MethodScriptSemantics.NormalMethod(method.Name);
}
if (method.Name == "op_Implicit" || method.Name == "op_Explicit") {
Message(Messages._7118, method);
_methodSemantics[method] = MethodScriptSemantics.NormalMethod(method.Name);
}
else {
_methodSemantics[method] = MethodScriptSemantics.NativeOperator();
}
return;
}
else {
var interfaceImplementations = method.ImplementedInterfaceMembers.Where(m => method.IsExplicitInterfaceImplementation || _methodSemantics[(IMethod)m.MemberDefinition].Type != MethodScriptSemantics.ImplType.NotUsableFromScript).ToList();
if (ssa != null) {
// [ScriptSkip] - Skip invocation of the method entirely.
if (method.DeclaringTypeDefinition.Kind == TypeKind.Interface) {
Message(Messages._7119, method);
_methodSemantics[method] = MethodScriptSemantics.NormalMethod(method.Name);
return;
}
else if (method.IsOverride && GetMethodSemanticsInternal((IMethod)InheritanceHelper.GetBaseMember(method).MemberDefinition).Type != MethodScriptSemantics.ImplType.NotUsableFromScript) {
Message(Messages._7120, method);
_methodSemantics[method] = MethodScriptSemantics.NormalMethod(method.Name);
return;
}
else if (method.IsOverridable) {
Message(Messages._7121, method);
_methodSemantics[method] = MethodScriptSemantics.NormalMethod(method.Name);
return;
}
else if (interfaceImplementations.Count > 0) {
Message(Messages._7122, method);
_methodSemantics[method] = MethodScriptSemantics.NormalMethod(method.Name);
return;
}
else {
if (method.IsStatic) {
if (method.Parameters.Count != 1) {
Message(Messages._7123, method);
_methodSemantics[method] = MethodScriptSemantics.NormalMethod(method.Name);
return;
}
_methodSemantics[method] = MethodScriptSemantics.InlineCode("{" + method.Parameters[0].Name + "}", enumerateAsArray: eaa != null);
return;
}
else {
if (method.Parameters.Count != 0)
Message(Messages._7124, method);
_methodSemantics[method] = MethodScriptSemantics.InlineCode("{this}", enumerateAsArray: eaa != null);
return;
}
}
}
else if (saa != null) {
if (method.IsStatic) {
_methodSemantics[method] = MethodScriptSemantics.InlineCode(saa.Alias + "(" + string.Join(", ", method.Parameters.Select(p => "{" + p.Name + "}")) + ")");
return;
}
else {
Message(Messages._7125, method);
_methodSemantics[method] = MethodScriptSemantics.NormalMethod(method.Name);
return;
}
}
else if (ica != null) {
string code = ica.Code ?? "", nonVirtualCode = ica.NonVirtualCode, nonExpandedFormCode = ica.NonExpandedFormCode;
if (method.DeclaringTypeDefinition.Kind == TypeKind.Interface && string.IsNullOrEmpty(ica.GeneratedMethodName)) {
Message(Messages._7126, method);
_methodSemantics[method] = MethodScriptSemantics.NormalMethod(method.Name);
return;
}
else if (method.IsOverride && GetMethodSemanticsInternal((IMethod)InheritanceHelper.GetBaseMember(method).MemberDefinition).Type != MethodScriptSemantics.ImplType.NotUsableFromScript) {
Message(Messages._7127, method);
_methodSemantics[method] = MethodScriptSemantics.NormalMethod(method.Name);
return;
}
else if (method.IsOverridable && string.IsNullOrEmpty(ica.GeneratedMethodName)) {
Message(Messages._7128, method);
_methodSemantics[method] = MethodScriptSemantics.NormalMethod(method.Name);
return;
}
else {
if (!ValidateInlineCode(method, method, code, Messages._7130)) {
code = nonVirtualCode = nonExpandedFormCode = "X";
}
if (!string.IsNullOrEmpty(ica.NonVirtualCode) && !ValidateInlineCode(method, method, ica.NonVirtualCode, Messages._7130)) {
code = nonVirtualCode = nonExpandedFormCode = "X";
}
if (!string.IsNullOrEmpty(ica.NonExpandedFormCode)) {
if (!method.Parameters.Any(p => p.IsParams)) {
Message(Messages._7029, method.Region, "method", method.FullName);
code = nonVirtualCode = nonExpandedFormCode = "X";
}
if (!ValidateInlineCode(method, method, ica.NonExpandedFormCode, Messages._7130)) {
code = nonVirtualCode = nonExpandedFormCode = "X";
}
}
_methodSemantics[method] = MethodScriptSemantics.InlineCode(code, enumerateAsArray: eaa != null, generatedMethodName: !string.IsNullOrEmpty(ica.GeneratedMethodName) ? ica.GeneratedMethodName : null, nonVirtualInvocationLiteralCode: nonVirtualCode, nonExpandedFormLiteralCode: nonExpandedFormCode);
if (!string.IsNullOrEmpty(ica.GeneratedMethodName))
usedNames[ica.GeneratedMethodName] = true;
return;
}
}
else if (ifa != null) {
if (method.IsStatic) {
if (epa != null && !method.Parameters.Any(p => p.IsParams)) {
Message(Messages._7137, method);
}
if (method.Parameters.Count == 0) {
Message(Messages._7149, method);
_methodSemantics[method] = MethodScriptSemantics.NormalMethod(method.Name);
return;
}
else if (method.Parameters[0].IsParams) {
Message(Messages._7150, method);
_methodSemantics[method] = MethodScriptSemantics.NormalMethod(method.Name);
return;
}
else {
var sb = new StringBuilder();
sb.Append("{" + method.Parameters[0].Name + "}." + preferredName + "(");
for (int i = 1; i < method.Parameters.Count; i++) {
var p = method.Parameters[i];
if (i > 1)
sb.Append(", ");
sb.Append((epa != null && p.IsParams ? "{*" : "{") + p.Name + "}");
}
sb.Append(")");
_methodSemantics[method] = MethodScriptSemantics.InlineCode(sb.ToString());
return;
}
}
else {
Message(Messages._7131, method);
_methodSemantics[method] = MethodScriptSemantics.NormalMethod(method.Name);
return;
}
}
else {
if (method.IsOverride && GetMethodSemanticsInternal((IMethod)InheritanceHelper.GetBaseMember(method).MemberDefinition).Type != MethodScriptSemantics.ImplType.NotUsableFromScript) {
if (nameSpecified) {
Message(Messages._7132, method);
}
if (AttributeReader.HasAttribute<IncludeGenericArgumentsAttribute>(method)) {
Message(Messages._7133, method);
}
var semantics = GetMethodSemanticsInternal((IMethod)InheritanceHelper.GetBaseMember(method).MemberDefinition);
if (semantics.Type == MethodScriptSemantics.ImplType.InlineCode && semantics.GeneratedMethodName != null)
semantics = MethodScriptSemantics.NormalMethod(semantics.GeneratedMethodName, ignoreGenericArguments: semantics.IgnoreGenericArguments, expandParams: semantics.ExpandParams); // Methods derived from methods with [InlineCode(..., GeneratedMethodName = "Something")] are treated as normal methods.
if (eaa != null)
semantics = semantics.WithEnumerateAsArray();
if (semantics.Type == MethodScriptSemantics.ImplType.NormalMethod) {
var errorMethod = method.ImplementedInterfaceMembers.FirstOrDefault(im => GetMethodSemanticsInternal((IMethod)im.MemberDefinition).Name != semantics.Name);
if (errorMethod != null) {
Message(Messages._7134, method, errorMethod.FullName);
}
}
_methodSemantics[method] = semantics;
return;
}
else if (interfaceImplementations.Count > 0) {
if (nameSpecified) {
Message(Messages._7135, method);
}
var candidateNames = method.ImplementedInterfaceMembers
.Select(im => GetMethodSemanticsInternal((IMethod)im.MemberDefinition))
.Select(s => s.Type == MethodScriptSemantics.ImplType.NormalMethod ? s.Name : (s.Type == MethodScriptSemantics.ImplType.InlineCode ? s.GeneratedMethodName : null))
.Where(name => name != null)
.Distinct();
if (candidateNames.Count() > 1) {
Message(Messages._7136, method);
}
// If the method implements more than one interface member, prefer to take the implementation from one that is not unusable.
var sem = method.ImplementedInterfaceMembers.Select(im => GetMethodSemanticsInternal((IMethod)im.MemberDefinition)).FirstOrDefault(x => x.Type != MethodScriptSemantics.ImplType.NotUsableFromScript) ?? MethodScriptSemantics.NotUsableFromScript();
if (sem.Type == MethodScriptSemantics.ImplType.InlineCode && sem.GeneratedMethodName != null)
sem = MethodScriptSemantics.NormalMethod(sem.GeneratedMethodName, ignoreGenericArguments: sem.IgnoreGenericArguments, expandParams: sem.ExpandParams); // Methods implementing methods with [InlineCode(..., GeneratedMethodName = "Something")] are treated as normal methods.
if (eaa != null)
sem = sem.WithEnumerateAsArray();
_methodSemantics[method] = sem;
return;
}
else {
if (includeGenericArguments == null) {
_errorReporter.Region = method.Region;
Message(Messages._7027, method);
includeGenericArguments = true;
}
if (epa != null) {
if (!method.Parameters.Any(p => p.IsParams)) {
Message(Messages._7137, method);
}
}
if (preferredName == "") {
// Special case - Script# supports setting the name of a method to an empty string, which means that it simply removes the name (eg. "x.M(a)" becomes "x(a)"). We model this with literal code.
if (method.DeclaringTypeDefinition.Kind == TypeKind.Interface) {
Message(Messages._7138, method);
_methodSemantics[method] = MethodScriptSemantics.NormalMethod(method.Name);
return;
}
else if (method.IsOverridable) {
Message(Messages._7139, method);
_methodSemantics[method] = MethodScriptSemantics.NormalMethod(method.Name);
return;
}
else if (method.IsStatic) {
Message(Messages._7140, method);
_methodSemantics[method] = MethodScriptSemantics.NormalMethod(method.Name);
return;
}
else {
_methodSemantics[method] = MethodScriptSemantics.InlineCode("{this}(" + string.Join(", ", method.Parameters.Select(p => "{" + p.Name + "}")) + ")", enumerateAsArray: eaa != null);
return;
}
}
else {
string name = nameSpecified ? preferredName : GetUniqueName(preferredName, usedNames);
if (asa == null)
usedNames[name] = true;
if (GetTypeSemanticsInternal(method.DeclaringTypeDefinition).IsSerializable && !method.IsStatic) {
_methodSemantics[method] = MethodScriptSemantics.StaticMethodWithThisAsFirstArgument(name, generateCode: !AttributeReader.HasAttribute<AlternateSignatureAttribute>(method), ignoreGenericArguments: !includeGenericArguments.Value, expandParams: epa != null, enumerateAsArray: eaa != null);
}
else {
_methodSemantics[method] = MethodScriptSemantics.NormalMethod(name, generateCode: !AttributeReader.HasAttribute<AlternateSignatureAttribute>(method), ignoreGenericArguments: !includeGenericArguments.Value, expandParams: epa != null, enumerateAsArray: eaa != null);
}
}
}
}
}
}
private void ProcessEvent(IEvent evt, string preferredName, bool nameSpecified, Dictionary<string, bool> usedNames) {
if (GetTypeSemanticsInternal(evt.DeclaringTypeDefinition).Semantics.Type == TypeScriptSemantics.ImplType.NotUsableFromScript || AttributeReader.HasAttribute<NonScriptableAttribute>(evt)) {
_eventSemantics[evt] = EventScriptSemantics.NotUsableFromScript();
return;
}
else if (preferredName == "") {
Message(Messages._7141, evt);
_eventSemantics[evt] = EventScriptSemantics.AddAndRemoveMethods(MethodScriptSemantics.NormalMethod("add"), MethodScriptSemantics.NormalMethod("remove"));
return;
}
MethodScriptSemantics adder, remover;
if (evt.CanAdd) {
var getterName = DeterminePreferredMemberName(evt.AddAccessor);
if (!getterName.Item2)
getterName = Tuple.Create(!nameSpecified && _minimizeNames && evt.DeclaringType.Kind != TypeKind.Interface && MetadataUtils.CanBeMinimized(evt) ? null : (nameSpecified ? "add_" + preferredName : GetUniqueName("add_" + preferredName, usedNames)), false); // If the name was not specified, generate one.
ProcessMethod(evt.AddAccessor, getterName.Item1, getterName.Item2, usedNames);
adder = GetMethodSemanticsInternal(evt.AddAccessor);
}
else {
adder = null;
}
if (evt.CanRemove) {
var setterName = DeterminePreferredMemberName(evt.RemoveAccessor);
if (!setterName.Item2)
setterName = Tuple.Create(!nameSpecified && _minimizeNames && evt.DeclaringType.Kind != TypeKind.Interface && MetadataUtils.CanBeMinimized(evt) ? null : (nameSpecified ? "remove_" + preferredName : GetUniqueName("remove_" + preferredName, usedNames)), false); // If the name was not specified, generate one.
ProcessMethod(evt.RemoveAccessor, setterName.Item1, setterName.Item2, usedNames);
remover = GetMethodSemanticsInternal(evt.RemoveAccessor);
}
else {
remover = null;
}
_eventSemantics[evt] = EventScriptSemantics.AddAndRemoveMethods(adder, remover);
}
private void ProcessField(IField field, string preferredName, bool nameSpecified, Dictionary<string, bool> usedNames) {
if (GetTypeSemanticsInternal(field.DeclaringTypeDefinition).Semantics.Type == TypeScriptSemantics.ImplType.NotUsableFromScript || AttributeReader.HasAttribute<NonScriptableAttribute>(field)) {
_fieldSemantics[field] = FieldScriptSemantics.NotUsableFromScript();
}
else if (preferredName == "") {
Message(Messages._7142, field);
_fieldSemantics[field] = FieldScriptSemantics.Field("X");
}
else {
string name = (nameSpecified ? preferredName : GetUniqueName(preferredName, usedNames));
if (AttributeReader.HasAttribute<InlineConstantAttribute>(field)) {
if (field.IsConst) {
name = null;
}
else {
Message(Messages._7152, field);
}
}
else {
usedNames[name] = true;
}
if (GetTypeSemanticsInternal(field.DeclaringTypeDefinition).IsNamedValues) {
string value = preferredName;
if (!nameSpecified) { // This code handles the feature that it is possible to specify an invalid ScriptName for a member of a NamedValues enum, in which case that value has to be use as the constant value.
var sna = AttributeReader.ReadAttribute<ScriptNameAttribute>(field);
if (sna != null)
value = sna.Name;
}
_fieldSemantics[field] = FieldScriptSemantics.StringConstant(value, name);
}
else if (field.DeclaringType.Kind == TypeKind.Enum && AttributeReader.HasAttribute<ImportedAttribute>(field.DeclaringTypeDefinition) && AttributeReader.HasAttribute<ScriptNameAttribute>(field.DeclaringTypeDefinition)) {
// Fields of enums that are imported and have an explicit [ScriptName] are treated as normal fields.
_fieldSemantics[field] = FieldScriptSemantics.Field(name);
}
else if (name == null || (field.IsConst && (field.DeclaringType.Kind == TypeKind.Enum || _minimizeNames))) {
object value = Saltarelle.Compiler.JSModel.Utils.ConvertToDoubleOrStringOrBoolean(field.ConstantValue);
if (value is bool)
_fieldSemantics[field] = FieldScriptSemantics.BooleanConstant((bool)value, name);
else if (value is double)
_fieldSemantics[field] = FieldScriptSemantics.NumericConstant((double)value, name);
else if (value is string)
_fieldSemantics[field] = FieldScriptSemantics.StringConstant((string)value, name);
else
_fieldSemantics[field] = FieldScriptSemantics.NullConstant(name);
}
else {
_fieldSemantics[field] = FieldScriptSemantics.Field(name);
}
}
}
public void Prepare(ITypeDefinition type) {
try {
ProcessType(type);
ProcessTypeMembers(type);
}
catch (Exception ex) {
_errorReporter.Region = type.Region;
_errorReporter.InternalError(ex, "Error importing type " + type.FullName);
}
}
public void ReserveMemberName(ITypeDefinition type, string name, bool isStatic) {
HashSet<string> names;
if (!isStatic) {
if (!_instanceMemberNamesByType.TryGetValue(type, out names))
_instanceMemberNamesByType[type] = names = new HashSet<string>();
}
else {
if (!_staticMemberNamesByType.TryGetValue(type, out names))
_staticMemberNamesByType[type] = names = new HashSet<string>();
}
names.Add(name);
}
public bool IsMemberNameAvailable(ITypeDefinition type, string name, bool isStatic) {
if (isStatic) {
if (_unusableStaticFieldNames.Contains(name))
return false;
HashSet<string> names;
if (!_staticMemberNamesByType.TryGetValue(type, out names))
return true;
return !names.Contains(name);
}
else {
if (_unusableInstanceFieldNames.Contains(name))
return false;
if (type.DirectBaseTypes.Select(d => d.GetDefinition()).Any(t => !IsMemberNameAvailable(t, name, false)))
return false;
HashSet<string> names;
if (!_instanceMemberNamesByType.TryGetValue(type, out names))
return true;
return !names.Contains(name);
}
}
public void SetMethodSemantics(IMethod method, MethodScriptSemantics semantics) {
_methodSemantics[method] = semantics;
_ignoredMembers.Add(method);
}
public void SetConstructorSemantics(IMethod method, ConstructorScriptSemantics semantics) {
_constructorSemantics[method] = semantics;
_ignoredMembers.Add(method);
}
public void SetPropertySemantics(IProperty property, PropertyScriptSemantics semantics) {
_propertySemantics[property] = semantics;
_ignoredMembers.Add(property);
}
public void SetFieldSemantics(IField field, FieldScriptSemantics semantics) {
_fieldSemantics[field] = semantics;
_ignoredMembers.Add(field);
}
public void SetEventSemantics(IEvent evt,EventScriptSemantics semantics) {
_eventSemantics[evt] = semantics;
_ignoredMembers.Add(evt);
}
private TypeSemantics GetTypeSemanticsInternal(ITypeDefinition typeDefinition) {
TypeSemantics ts;
if (_typeSemantics.TryGetValue(typeDefinition, out ts))
return ts;
throw new ArgumentException(string.Format("Type semantics for type {0} were not correctly imported", typeDefinition.FullName));
}
public TypeScriptSemantics GetTypeSemantics(ITypeDefinition typeDefinition) {
if (typeDefinition.Kind == TypeKind.Delegate)
return TypeScriptSemantics.NormalType("Function");
else if (typeDefinition.Kind == TypeKind.Array)
return TypeScriptSemantics.NormalType("Array");
return GetTypeSemanticsInternal(typeDefinition).Semantics;
}
private MethodScriptSemantics GetMethodSemanticsInternal(IMethod method) {
switch (method.DeclaringType.Kind) {
case TypeKind.Delegate:
return MethodScriptSemantics.NotUsableFromScript();
default:
MethodScriptSemantics result;
if (!_methodSemantics.TryGetValue((IMethod)method.MemberDefinition, out result))
throw new ArgumentException(string.Format("Semantics for method " + method + " were not imported"));
return result;
}
}
public MethodScriptSemantics GetMethodSemantics(IMethod method) {
if (method.IsAccessor)
throw new ArgumentException("GetMethodSemantics should not be called for the accessor " + method);
return GetMethodSemanticsInternal(method);
}
public ConstructorScriptSemantics GetConstructorSemantics(IMethod method) {
switch (method.DeclaringType.Kind) {
case TypeKind.Anonymous:
return ConstructorScriptSemantics.Json(new IMember[0]);
case TypeKind.Delegate:
return ConstructorScriptSemantics.NotUsableFromScript();
default:
ConstructorScriptSemantics result;
if (!_constructorSemantics.TryGetValue((IMethod)method.MemberDefinition, out result))
throw new ArgumentException(string.Format("Semantics for constructor " + method + " were not imported"));
return result;
}
}
public PropertyScriptSemantics GetPropertySemantics(IProperty property) {
switch (property.DeclaringType.Kind) {
case TypeKind.Anonymous:
return PropertyScriptSemantics.Field(property.Name.Replace("<>", "$"));
case TypeKind.Delegate:
return PropertyScriptSemantics.NotUsableFromScript();
default:
PropertyScriptSemantics result;
if (!_propertySemantics.TryGetValue((IProperty)property.MemberDefinition, out result))
throw new ArgumentException(string.Format("Semantics for property " + property + " were not imported"));
return result;
}
}
public DelegateScriptSemantics GetDelegateSemantics(ITypeDefinition delegateType) {
DelegateScriptSemantics result;
if (!_delegateSemantics.TryGetValue(delegateType, out result))
throw new ArgumentException(string.Format("Semantics for delegate " + delegateType + " were not imported"));
return result;
}
private string GetBackingFieldName(ITypeDefinition declaringTypeDefinition, string memberName) {
int inheritanceDepth = declaringTypeDefinition.GetAllBaseTypes().Count(b => b.Kind != TypeKind.Interface) - 1;
if (_minimizeNames) {
int count;
_backingFieldCountPerType.TryGetValue(declaringTypeDefinition, out count);
count++;
_backingFieldCountPerType[declaringTypeDefinition] = count;
return string.Format(CultureInfo.InvariantCulture, "${0}${1}", inheritanceDepth, count);
}
else {
return string.Format(CultureInfo.InvariantCulture, "${0}${1}Field", inheritanceDepth, memberName);
}
}
public string GetAutoPropertyBackingFieldName(IProperty property) {
property = (IProperty)property.MemberDefinition;
string result;
if (_propertyBackingFieldNames.TryGetValue(property, out result))
return result;
result = GetBackingFieldName(property.DeclaringTypeDefinition, property.Name);
_propertyBackingFieldNames[property] = result;
return result;
}
public FieldScriptSemantics GetFieldSemantics(IField field) {
switch (field.DeclaringType.Kind) {
case TypeKind.Delegate:
return FieldScriptSemantics.NotUsableFromScript();
default:
FieldScriptSemantics result;
if (!_fieldSemantics.TryGetValue((IField)field.MemberDefinition, out result))
throw new ArgumentException(string.Format("Semantics for field " + field + " were not imported"));
return result;
}
}
public EventScriptSemantics GetEventSemantics(IEvent evt) {
switch (evt.DeclaringType.Kind) {
case TypeKind.Delegate:
return EventScriptSemantics.NotUsableFromScript();
default:
EventScriptSemantics result;
if (!_eventSemantics.TryGetValue((IEvent)evt.MemberDefinition, out result))
throw new ArgumentException(string.Format("Semantics for field " + evt + " were not imported"));
return result;
}
}
public string GetAutoEventBackingFieldName(IEvent evt) {
evt = (IEvent)evt.MemberDefinition;
string result;
if (_eventBackingFieldNames.TryGetValue(evt, out result))
return result;
result = GetBackingFieldName(evt.DeclaringTypeDefinition, evt.Name);
_eventBackingFieldNames[evt] = result;
return result;
}
}
}
| |
using System;
using System.Linq;
using System.Collections.Generic;
class Literals
{
int x = 0b1011;
int y = 123_456;
int z = 0b1000_0000;
}
class ExpressionBodiedMembers
{
int field = 0;
int Foo() => field;
int P => 5;
int Q
{
get => Foo();
set => field = value;
}
ExpressionBodiedMembers() : this(1) { }
ExpressionBodiedMembers(int x) => Foo();
~ExpressionBodiedMembers() => Foo();
}
class ThrowExpr
{
int Throw(int i)
{
return i > 0 ? i : throw new ArgumentException("i");
}
}
class OutVariables
{
void F(out string x)
{
x = "tainted";
}
void G(string x, out string y)
{
y = x;
}
void G()
{
F(out string t1);
F(out var t2);
var t3 = t1;
F(out t1);
t3 = t1;
t3 = t2;
G("tainted", out var t4);
var t5 = t4;
}
}
class Tuples
{
(int A, int B) F()
{
return (A: 1, B: 2);
}
void Expressions()
{
(var x, var y) = F();
var z = F();
(x, y) = F();
x = F().A;
(x, y, z.Item1) = (1, 2, 3);
(x, y) = (x, y) = (1, 2);
(var a, (var b, var c)) = (1, z);
(a, (b, c)) = (b, (c, a));
var (i, j) = ("", x);
}
string I(string x)
{
return (a: x, 2).a;
}
void TaintFlow()
{
var t1 = ("tainted", "X2");
(var t2, var t3) = t1;
var t4 = t3;
var t5 = I(t1.Item1);
}
void TupleExprNode()
{
var m1 = (1, "TupleExprNode1");
var m2 = (1, ("TupleExprNode2", 2));
}
void TupleMemberAccess()
{
var m1 = ("TupleMemberAccess1", 0).Item1;
var m2 = (0, ("TupleMemberAccess2", 1)).Item2;
}
void DefUse()
{
(var m1, var m2) = ("DefUse1", (0, 1));
string m3;
int m4, m5;
(m3, (m4, m5)) = (m1, m2);
var m6 = m4;
(var m7, (var m8, var m9)) = (m1, m2) = ("DefUse2", (0, 1));
var m10 = m9;
// Member assignment
m2.Item2 = 0;
var m11 = m2.Item1;
// Standard assignment
string m12;
string m13 = m12 = "DefUse3";
}
}
class LocalFunctions
{
int Main()
{
int f1(int x) { return x + 1; }
T f2<T, U>(T t, U u) { return t; }
Func<int> f4 = f3; // Forward reference
int f3() => 2;
Func<int, int> f5 = x => x + 1;
int f6(int x) => x > 0 ? 1 + f7(x - 1) : 0;
int f7(int x) => f6(x);
int f8()
{
int f9(int x) => f7(x);
return f9(1);
}
Action a = () =>
{
int f9() => 0;
};
return f1(2);
}
void Generics()
{
int f<T>() => 1;
T g<T>(T t) => t;
U h<T, U>(T t, U u)
{
int f2<S>(S s, T _t) => f<T>();
f<T>();
return g(u);
}
h(0, 0);
h("", true);
}
void GlobalFlow()
{
string src = "tainted";
string f(string s) => g(s) + "";
string g(string s) => s;
string h(string s) { return s; }
var sink1 = f(src);
var sink2 = g(src);
var sink3 = h(src);
}
}
class Refs
{
void F1()
{
int v1 = 2;
ref int r1 = ref v1;
var array = new int[10];
r1 = 3;
r1 = array[1];
ref int r2 = ref array[3];
ref int r3 = ref r1;
v1 = F2(ref v1);
ref int r4 = ref F2(ref r1);
F2(ref r1) = 3;
}
ref int F2(ref int p)
{
ref int F3(ref int q) { return ref q; }
return ref p;
}
delegate ref int RefFn(ref int p);
}
class Discards
{
(int, double) f(out bool x)
{
x = false;
return (0, 0.0);
}
void Test()
{
_ = f(out _);
(_, _) = f(out _);
(var x, _) = f(out _);
(_, var y) = f(out var z);
}
}
class Patterns
{
void Test()
{
object o = null;
if (o is int i1 && i1 > 0)
{
Console.WriteLine($"int {i1}");
}
else if (o is string s1)
{
Console.WriteLine($"string {s1}");
}
else if (o is double _)
{
}
else if (o is var v1)
{
}
switch (o)
{
case "xyz":
break;
case "" when 1 < 2:
break;
case "x" when o is string s4:
Console.WriteLine($"x {s4}");
break;
case int i2 when i2 > 0:
Console.WriteLine($"positive {i2}");
break;
case int i3:
Console.WriteLine($"int {i3}");
break;
case string s2:
Console.WriteLine($"string {s2}");
break;
case double _:
Console.WriteLine("Double");
break;
case var v2:
break;
default:
Console.WriteLine("Something else");
break;
}
}
}
class ForeachStatements
{
void Test()
{
var dict = new Dictionary<int, string>();
var list = dict.Select(item => (item.Key, item.Value));
foreach ((int a, string b) in list) { }
foreach ((var a, var b) in list) { }
foreach (var (a, b) in list) { }
}
}
class ForLoops
{
void Test()
{
for (int x = 0; x < 10 && x is int y; ++x)
{
Console.WriteLine(y);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.Threading;
using System.Threading.Tasks;
using Orleans.CodeGeneration;
using Orleans.GrainDirectory;
using Orleans.Providers;
using Orleans.Runtime.Configuration;
using Orleans.Runtime.GrainDirectory;
using Orleans.Runtime.Messaging;
using Orleans.Runtime.Placement;
using Orleans.Runtime.Scheduler;
using Orleans.Storage;
namespace Orleans.Runtime
{
internal class Catalog : SystemTarget, ICatalog, IPlacementContext, ISiloStatusListener
{
/// <summary>
/// Exception to indicate that the activation would have been a duplicate so messages pending for it should be redirected.
/// </summary>
[Serializable]
internal class DuplicateActivationException : Exception
{
public ActivationAddress ActivationToUse { get; private set; }
public SiloAddress PrimaryDirectoryForGrain { get; private set; } // for diagnostics only!
public DuplicateActivationException() : base("DuplicateActivationException") { }
public DuplicateActivationException(string msg) : base(msg) { }
public DuplicateActivationException(string message, Exception innerException) : base(message, innerException) { }
public DuplicateActivationException(ActivationAddress activationToUse)
: base("DuplicateActivationException")
{
ActivationToUse = activationToUse;
}
public DuplicateActivationException(ActivationAddress activationToUse, SiloAddress primaryDirectoryForGrain)
: base("DuplicateActivationException")
{
ActivationToUse = activationToUse;
PrimaryDirectoryForGrain = primaryDirectoryForGrain;
}
#if !NETSTANDARD
// Implementation of exception serialization with custom properties according to:
// http://stackoverflow.com/questions/94488/what-is-the-correct-way-to-make-a-custom-net-exception-serializable
protected DuplicateActivationException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
if (info != null)
{
ActivationToUse = (ActivationAddress) info.GetValue("ActivationToUse", typeof (ActivationAddress));
PrimaryDirectoryForGrain = (SiloAddress) info.GetValue("PrimaryDirectoryForGrain", typeof (SiloAddress));
}
}
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info != null)
{
info.AddValue("ActivationToUse", ActivationToUse, typeof (ActivationAddress));
info.AddValue("PrimaryDirectoryForGrain", PrimaryDirectoryForGrain, typeof (SiloAddress));
}
// MUST call through to the base class to let it save its own state
base.GetObjectData(info, context);
}
#endif
}
[Serializable]
internal class NonExistentActivationException : Exception
{
public ActivationAddress NonExistentActivation { get; private set; }
public bool IsStatelessWorker { get; private set; }
public NonExistentActivationException() : base("NonExistentActivationException") { }
public NonExistentActivationException(string msg) : base(msg) { }
public NonExistentActivationException(string message, Exception innerException)
: base(message, innerException) { }
public NonExistentActivationException(string msg, ActivationAddress nonExistentActivation, bool isStatelessWorker)
: base(msg)
{
NonExistentActivation = nonExistentActivation;
IsStatelessWorker = isStatelessWorker;
}
#if !NETSTANDARD
protected NonExistentActivationException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
if (info != null)
{
NonExistentActivation = (ActivationAddress)info.GetValue("NonExistentActivation", typeof(ActivationAddress));
IsStatelessWorker = (bool)info.GetValue("IsStatelessWorker", typeof(bool));
}
}
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info != null)
{
info.AddValue("NonExistentActivation", NonExistentActivation, typeof(ActivationAddress));
info.AddValue("IsStatelessWorker", IsStatelessWorker, typeof(bool));
}
// MUST call through to the base class to let it save its own state
base.GetObjectData(info, context);
}
#endif
}
public GrainTypeManager GrainTypeManager { get; private set; }
public SiloAddress LocalSilo { get; private set; }
internal ISiloStatusOracle SiloStatusOracle { get; set; }
internal readonly ActivationCollector ActivationCollector;
private readonly ILocalGrainDirectory directory;
private readonly OrleansTaskScheduler scheduler;
private readonly ActivationDirectory activations;
private IStorageProviderManager storageProviderManager;
private readonly Logger logger;
private int collectionNumber;
private int destroyActivationsNumber;
private IDisposable gcTimer;
private readonly GlobalConfiguration config;
private readonly string localSiloName;
private readonly CounterStatistic activationsCreated;
private readonly CounterStatistic activationsDestroyed;
private readonly CounterStatistic activationsFailedToActivate;
private readonly IntValueStatistic inProcessRequests;
private readonly CounterStatistic collectionCounter;
private readonly GrainCreator grainCreator;
private readonly NodeConfiguration nodeConfig;
private readonly TimeSpan maxRequestProcessingTime;
private readonly TimeSpan maxWarningRequestProcessingTime;
public Catalog(
SiloInitializationParameters siloInitializationParameters,
ILocalGrainDirectory grainDirectory,
GrainTypeManager typeManager,
OrleansTaskScheduler scheduler,
ActivationDirectory activationDirectory,
ClusterConfiguration config,
GrainCreator grainCreator,
NodeConfiguration nodeConfig,
ISiloMessageCenter messageCenter,
PlacementDirectorsManager placementDirectorsManager)
: base(Constants.CatalogId, messageCenter.MyAddress)
{
LocalSilo = siloInitializationParameters.SiloAddress;
localSiloName = siloInitializationParameters.Name;
directory = grainDirectory;
activations = activationDirectory;
this.scheduler = scheduler;
GrainTypeManager = typeManager;
collectionNumber = 0;
destroyActivationsNumber = 0;
this.grainCreator = grainCreator;
this.nodeConfig = nodeConfig;
logger = LogManager.GetLogger("Catalog", Runtime.LoggerType.Runtime);
this.config = config.Globals;
ActivationCollector = new ActivationCollector(config);
this.Dispatcher = new Dispatcher(scheduler, messageCenter, this, config, placementDirectorsManager);
GC.GetTotalMemory(true); // need to call once w/true to ensure false returns OK value
config.OnConfigChange("Globals/Activation", () => scheduler.RunOrQueueAction(Start, SchedulingContext), false);
IntValueStatistic.FindOrCreate(StatisticNames.CATALOG_ACTIVATION_COUNT, () => activations.Count);
activationsCreated = CounterStatistic.FindOrCreate(StatisticNames.CATALOG_ACTIVATION_CREATED);
activationsDestroyed = CounterStatistic.FindOrCreate(StatisticNames.CATALOG_ACTIVATION_DESTROYED);
activationsFailedToActivate = CounterStatistic.FindOrCreate(StatisticNames.CATALOG_ACTIVATION_FAILED_TO_ACTIVATE);
collectionCounter = CounterStatistic.FindOrCreate(StatisticNames.CATALOG_ACTIVATION_COLLECTION_NUMBER_OF_COLLECTIONS);
inProcessRequests = IntValueStatistic.FindOrCreate(StatisticNames.MESSAGING_PROCESSING_ACTIVATION_DATA_ALL, () =>
{
long counter = 0;
lock (activations)
{
foreach (var activation in activations)
{
ActivationData data = activation.Value;
counter += data.GetRequestCount();
}
}
return counter;
});
maxWarningRequestProcessingTime = this.config.ResponseTimeout.Multiply(5);
maxRequestProcessingTime = this.config.MaxRequestProcessingTime;
}
/// <summary>
/// Gets the dispatcher used by this instance.
/// </summary>
public Dispatcher Dispatcher { get; }
public IList<SiloAddress> GetCompatibleSiloList(GrainId grain)
{
var typeCode = grain.GetTypeCode();
var compatibleSilos = GrainTypeManager.GetSupportedSilos(typeCode).Intersect(AllActiveSilos).ToList();
if (compatibleSilos.Count == 0)
throw new OrleansException($"TypeCode ${typeCode} not supported in the cluster");
return compatibleSilos;
}
internal void SetStorageManager(IStorageProviderManager storageManager)
{
storageProviderManager = storageManager;
}
internal void Start()
{
if (gcTimer != null) gcTimer.Dispose();
var t = GrainTimer.FromTaskCallback(OnTimer, null, TimeSpan.Zero, ActivationCollector.Quantum, "Catalog.GCTimer");
t.Start();
gcTimer = t;
}
private Task OnTimer(object _)
{
return CollectActivationsImpl(true);
}
public Task CollectActivations(TimeSpan ageLimit)
{
return CollectActivationsImpl(false, ageLimit);
}
private async Task CollectActivationsImpl(bool scanStale, TimeSpan ageLimit = default(TimeSpan))
{
var watch = new Stopwatch();
watch.Start();
var number = Interlocked.Increment(ref collectionNumber);
long memBefore = GC.GetTotalMemory(false) / (1024 * 1024);
logger.Info(ErrorCode.Catalog_BeforeCollection, "Before collection#{0}: memory={1}MB, #activations={2}, collector={3}.",
number, memBefore, activations.Count, ActivationCollector.ToString());
List<ActivationData> list = scanStale ? ActivationCollector.ScanStale() : ActivationCollector.ScanAll(ageLimit);
collectionCounter.Increment();
var count = 0;
if (list != null && list.Count > 0)
{
count = list.Count;
if (logger.IsVerbose) logger.Verbose("CollectActivations{0}", list.ToStrings(d => d.Grain.ToString() + d.ActivationId));
await DeactivateActivationsFromCollector(list);
}
long memAfter = GC.GetTotalMemory(false) / (1024 * 1024);
watch.Stop();
logger.Info(ErrorCode.Catalog_AfterCollection, "After collection#{0}: memory={1}MB, #activations={2}, collected {3} activations, collector={4}, collection time={5}.",
number, memAfter, activations.Count, count, ActivationCollector.ToString(), watch.Elapsed);
}
public List<Tuple<GrainId, string, int>> GetGrainStatistics()
{
var counts = new Dictionary<string, Dictionary<GrainId, int>>();
lock (activations)
{
foreach (var activation in activations)
{
ActivationData data = activation.Value;
if (data == null || data.GrainInstance == null) continue;
// TODO: generic type expansion
var grainTypeName = TypeUtils.GetFullName(data.GrainInstanceType);
Dictionary<GrainId, int> grains;
int n;
if (!counts.TryGetValue(grainTypeName, out grains))
{
counts.Add(grainTypeName, new Dictionary<GrainId, int> { { data.Grain, 1 } });
}
else if (!grains.TryGetValue(data.Grain, out n))
grains[data.Grain] = 1;
else
grains[data.Grain] = n + 1;
}
}
return counts
.SelectMany(p => p.Value.Select(p2 => Tuple.Create(p2.Key, p.Key, p2.Value)))
.ToList();
}
public List<DetailedGrainStatistic> GetDetailedGrainStatistics(string[] types=null)
{
var stats = new List<DetailedGrainStatistic>();
lock (activations)
{
foreach (var activation in activations)
{
ActivationData data = activation.Value;
if (data == null || data.GrainInstance == null) continue;
if (types==null || types.Contains(TypeUtils.GetFullName(data.GrainInstanceType)))
{
stats.Add(new DetailedGrainStatistic()
{
GrainType = TypeUtils.GetFullName(data.GrainInstanceType),
GrainIdentity = data.Grain,
SiloAddress = data.Silo,
Category = data.Grain.Category.ToString()
});
}
}
}
return stats;
}
public IEnumerable<KeyValuePair<string, long>> GetSimpleGrainStatistics()
{
return activations.GetSimpleGrainStatistics();
}
public DetailedGrainReport GetDetailedGrainReport(GrainId grain)
{
var report = new DetailedGrainReport
{
Grain = grain,
SiloAddress = LocalSilo,
SiloName = localSiloName,
LocalCacheActivationAddresses = directory.GetLocalCacheData(grain),
LocalDirectoryActivationAddresses = directory.GetLocalDirectoryData(grain).Addresses,
PrimaryForGrain = directory.GetPrimaryForGrain(grain)
};
try
{
PlacementStrategy unused;
MultiClusterRegistrationStrategy unusedActivationStrategy;
string grainClassName;
GrainTypeManager.GetTypeInfo(grain.GetTypeCode(), out grainClassName, out unused, out unusedActivationStrategy);
report.GrainClassTypeName = grainClassName;
}
catch (Exception exc)
{
report.GrainClassTypeName = exc.ToString();
}
List<ActivationData> acts = activations.FindTargets(grain);
report.LocalActivations = acts != null ?
acts.Select(activationData => activationData.ToDetailedString()).ToList() :
new List<string>();
return report;
}
#region MessageTargets
/// <summary>
/// Register a new object to which messages can be delivered with the local lookup table and scheduler.
/// </summary>
/// <param name="activation"></param>
public void RegisterMessageTarget(ActivationData activation)
{
var context = new SchedulingContext(activation);
scheduler.RegisterWorkContext(context);
activations.RecordNewTarget(activation);
activationsCreated.Increment();
}
/// <summary>
/// Unregister message target and stop delivering messages to it
/// </summary>
/// <param name="activation"></param>
public void UnregisterMessageTarget(ActivationData activation)
{
activations.RemoveTarget(activation);
// this should be removed once we've refactored the deactivation code path. For now safe to keep.
ActivationCollector.TryCancelCollection(activation);
activationsDestroyed.Increment();
scheduler.UnregisterWorkContext(new SchedulingContext(activation));
if (activation.GrainInstance == null) return;
var grainTypeName = TypeUtils.GetFullName(activation.GrainInstanceType);
activations.DecrementGrainCounter(grainTypeName);
activation.SetGrainInstance(null);
}
/// <summary>
/// FOR TESTING PURPOSES ONLY!!
/// </summary>
/// <param name="grain"></param>
internal int UnregisterGrainForTesting(GrainId grain)
{
var acts = activations.FindTargets(grain);
if (acts == null) return 0;
int numActsBefore = acts.Count;
foreach (var act in acts)
UnregisterMessageTarget(act);
return numActsBefore;
}
#endregion
#region Grains
internal bool CanInterleave(ActivationId running, Message message)
{
ActivationData target;
GrainTypeData data;
return TryGetActivationData(running, out target) &&
target.GrainInstance != null &&
GrainTypeManager.TryGetData(TypeUtils.GetFullName(target.GrainInstanceType), out data) &&
(data.IsReentrant || data.MayInterleave((InvokeMethodRequest)message.BodyObject));
}
public void GetGrainTypeInfo(int typeCode, out string grainClass, out PlacementStrategy placement, out MultiClusterRegistrationStrategy activationStrategy, string genericArguments = null)
{
GrainTypeManager.GetTypeInfo(typeCode, out grainClass, out placement, out activationStrategy, genericArguments);
}
#endregion
#region Activations
public int ActivationCount { get { return activations.Count; } }
/// <summary>
/// If activation already exists, use it
/// Otherwise, create an activation of an existing grain by reading its state.
/// Return immediately using a dummy that will queue messages.
/// Concurrently start creating and initializing the real activation and replace it when it is ready.
/// </summary>
/// <param name="address">Grain's activation address</param>
/// <param name="newPlacement">Creation of new activation was requested by the placement director.</param>
/// <param name="grainType">The type of grain to be activated or created</param>
/// <param name="genericArguments">Specific generic type of grain to be activated or created</param>
/// <param name="requestContextData">Request context data.</param>
/// <param name="activatedPromise"></param>
/// <returns></returns>
public ActivationData GetOrCreateActivation(
ActivationAddress address,
bool newPlacement,
string grainType,
string genericArguments,
Dictionary<string, object> requestContextData,
out Task activatedPromise)
{
ActivationData result;
activatedPromise = TaskDone.Done;
PlacementStrategy placement;
lock (activations)
{
if (TryGetActivationData(address.Activation, out result))
{
return result;
}
int typeCode = address.Grain.GetTypeCode();
string actualGrainType = null;
MultiClusterRegistrationStrategy activationStrategy;
if (typeCode != 0)
{
GetGrainTypeInfo(typeCode, out actualGrainType, out placement, out activationStrategy, genericArguments);
}
else
{
// special case for Membership grain.
placement = SystemPlacement.Singleton;
activationStrategy = ClusterLocalRegistration.Singleton;
}
if (newPlacement && !SiloStatusOracle.CurrentStatus.IsTerminating())
{
// create a dummy activation that will queue up messages until the real data arrives
if (string.IsNullOrEmpty(grainType))
{
grainType = actualGrainType;
}
// We want to do this (RegisterMessageTarget) under the same lock that we tested TryGetActivationData. They both access ActivationDirectory.
result = new ActivationData(
address,
genericArguments,
placement,
activationStrategy,
ActivationCollector,
config.Application.GetCollectionAgeLimit(grainType),
this.nodeConfig,
this.maxWarningRequestProcessingTime,
this.maxRequestProcessingTime);
RegisterMessageTarget(result);
}
} // End lock
// Did not find and did not start placing new
if (result == null)
{
var msg = String.Format("Non-existent activation: {0}, grain type: {1}.",
address.ToFullString(), grainType);
if (logger.IsVerbose) logger.Verbose(ErrorCode.CatalogNonExistingActivation2, msg);
CounterStatistic.FindOrCreate(StatisticNames.CATALOG_ACTIVATION_NON_EXISTENT_ACTIVATIONS).Increment();
throw new NonExistentActivationException(msg, address, placement is StatelessWorkerPlacement);
}
SetupActivationInstance(result, grainType, genericArguments);
activatedPromise = InitActivation(result, grainType, genericArguments, requestContextData);
return result;
}
private void SetupActivationInstance(ActivationData result, string grainType, string genericArguments)
{
lock (result)
{
if (result.GrainInstance == null)
{
CreateGrainInstance(grainType, result, genericArguments);
}
}
}
private async Task InitActivation(ActivationData activation, string grainType, string genericArguments, Dictionary<string, object> requestContextData)
{
// We've created a dummy activation, which we'll eventually return, but in the meantime we'll queue up (or perform promptly)
// the operations required to turn the "dummy" activation into a real activation
ActivationAddress address = activation.Address;
int initStage = 0;
// A chain of promises that will have to complete in order to complete the activation
// Register with the grain directory, register with the store if necessary and call the Activate method on the new activation.
try
{
initStage = 1;
await RegisterActivationInGrainDirectoryAndValidate(activation);
initStage = 2;
await SetupActivationState(activation, String.IsNullOrEmpty(genericArguments) ? grainType : $"{grainType}[{genericArguments}]");
initStage = 3;
await InvokeActivate(activation, requestContextData);
ActivationCollector.ScheduleCollection(activation);
// Success!! Log the result, and start processing messages
if (logger.IsVerbose) logger.Verbose("InitActivation is done: {0}", address);
}
catch (Exception ex)
{
lock (activation)
{
activation.SetState(ActivationState.Invalid);
try
{
UnregisterMessageTarget(activation);
}
catch (Exception exc)
{
logger.Warn(ErrorCode.Catalog_UnregisterMessageTarget4, String.Format("UnregisterMessageTarget failed on {0}.", activation), exc);
}
switch (initStage)
{
case 1: // failed to RegisterActivationInGrainDirectory
ActivationAddress target = null;
Exception dupExc;
// Failure!! Could it be that this grain uses single activation placement, and there already was an activation?
if (Utils.TryFindException(ex, typeof (DuplicateActivationException), out dupExc))
{
target = ((DuplicateActivationException) dupExc).ActivationToUse;
CounterStatistic.FindOrCreate(StatisticNames.CATALOG_ACTIVATION_DUPLICATE_ACTIVATIONS)
.Increment();
}
activation.ForwardingAddress = target;
if (target != null)
{
var primary = ((DuplicateActivationException)dupExc).PrimaryDirectoryForGrain;
// If this was a duplicate, it's not an error, just a race.
// Forward on all of the pending messages, and then forget about this activation.
string logMsg = String.Format("Tried to create a duplicate activation {0}, but we'll use {1} instead. " +
"GrainInstanceType is {2}. " +
"{3}" +
"Full activation address is {4}. We have {5} messages to forward.",
address,
target,
activation.GrainInstanceType,
primary != null ? "Primary Directory partition for this grain is " + primary + ". " : String.Empty,
address.ToFullString(),
activation.WaitingCount);
if (activation.IsUsingGrainDirectory)
{
logger.Info(ErrorCode.Catalog_DuplicateActivation, logMsg);
}
else
{
if (logger.IsVerbose) logger.Verbose(ErrorCode.Catalog_DuplicateActivation, logMsg);
}
RerouteAllQueuedMessages(activation, target, "Duplicate activation", ex);
}
else
{
logger.Warn(ErrorCode.Runtime_Error_100064,
String.Format("Failed to RegisterActivationInGrainDirectory for {0}.",
activation), ex);
// Need to undo the registration we just did earlier
if (activation.IsUsingGrainDirectory)
{
scheduler.RunOrQueueTask(() => directory.UnregisterAsync(address, UnregistrationCause.Force),
SchedulingContext).Ignore();
}
RerouteAllQueuedMessages(activation, null,
"Failed RegisterActivationInGrainDirectory", ex);
}
break;
case 2: // failed to setup persistent state
logger.Warn(ErrorCode.Catalog_Failed_SetupActivationState,
String.Format("Failed to SetupActivationState for {0}.", activation), ex);
// Need to undo the registration we just did earlier
if (activation.IsUsingGrainDirectory)
{
scheduler.RunOrQueueTask(() => directory.UnregisterAsync(address, UnregistrationCause.Force),
SchedulingContext).Ignore();
}
RerouteAllQueuedMessages(activation, null, "Failed SetupActivationState", ex);
break;
case 3: // failed to InvokeActivate
logger.Warn(ErrorCode.Catalog_Failed_InvokeActivate,
String.Format("Failed to InvokeActivate for {0}.", activation), ex);
// Need to undo the registration we just did earlier
if (activation.IsUsingGrainDirectory)
{
scheduler.RunOrQueueTask(() => directory.UnregisterAsync(address, UnregistrationCause.Force),
SchedulingContext).Ignore();
}
RerouteAllQueuedMessages(activation, null, "Failed InvokeActivate", ex);
break;
}
}
throw;
}
}
/// <summary>
/// Perform just the prompt, local part of creating an activation object
/// Caller is responsible for registering locally, registering with store and calling its activate routine
/// </summary>
/// <param name="grainTypeName"></param>
/// <param name="data"></param>
/// <param name="genericArguments"></param>
/// <returns></returns>
private void CreateGrainInstance(string grainTypeName, ActivationData data, string genericArguments)
{
string grainClassName;
if (!GrainTypeManager.TryGetPrimaryImplementation(grainTypeName, out grainClassName))
{
// Lookup from grain type code
var typeCode = data.Grain.GetTypeCode();
if (typeCode != 0)
{
PlacementStrategy unused;
MultiClusterRegistrationStrategy unusedActivationStrategy;
GetGrainTypeInfo(typeCode, out grainClassName, out unused, out unusedActivationStrategy, genericArguments);
}
else
{
grainClassName = grainTypeName;
}
}
GrainTypeData grainTypeData = GrainTypeManager[grainClassName];
//Get the grain's type
Type grainType = grainTypeData.Type;
//Gets the type for the grain's state
Type stateObjectType = grainTypeData.StateObjectType;
lock (data)
{
Grain grain;
//Create a new instance of a stateless grain
if (stateObjectType == null)
{
//Create a new instance of the given grain type
grain = grainCreator.CreateGrainInstance(grainType, data.Identity);
}
//Create a new instance of a stateful grain
else
{
SetupStorageProvider(grainType, data);
grain = grainCreator.CreateGrainInstance(grainType, data.Identity, stateObjectType, data.StorageProvider);
}
grain.Data = data;
data.SetGrainInstance(grain);
}
activations.IncrementGrainCounter(grainClassName);
if (logger.IsVerbose) logger.Verbose("CreateGrainInstance {0}{1}", data.Grain, data.ActivationId);
}
private void SetupStorageProvider(Type grainType, ActivationData data)
{
var grainTypeName = grainType.FullName;
// Get the storage provider name, using the default if not specified.
var attr = grainType.GetTypeInfo().GetCustomAttributes<StorageProviderAttribute>(true).FirstOrDefault();
var storageProviderName = attr != null ? attr.ProviderName : Constants.DEFAULT_STORAGE_PROVIDER_NAME;
IStorageProvider provider;
if (storageProviderManager == null || storageProviderManager.GetNumLoadedProviders() == 0)
{
var errMsg = string.Format("No storage providers found loading grain type {0}", grainTypeName);
logger.Error(ErrorCode.Provider_CatalogNoStorageProvider_1, errMsg);
throw new BadProviderConfigException(errMsg);
}
if (string.IsNullOrWhiteSpace(storageProviderName))
{
// Use default storage provider
provider = storageProviderManager.GetDefaultProvider();
}
else
{
// Look for MemoryStore provider as special case name
bool caseInsensitive = Constants.MEMORY_STORAGE_PROVIDER_NAME.Equals(storageProviderName, StringComparison.OrdinalIgnoreCase);
storageProviderManager.TryGetProvider(storageProviderName, out provider, caseInsensitive);
if (provider == null)
{
var errMsg = string.Format(
"Cannot find storage provider with Name={0} for grain type {1}", storageProviderName,
grainTypeName);
logger.Error(ErrorCode.Provider_CatalogNoStorageProvider_2, errMsg);
throw new BadProviderConfigException(errMsg);
}
}
data.StorageProvider = provider;
if (logger.IsVerbose2)
{
string msg = string.Format("Assigned storage provider with Name={0} to grain type {1}",
storageProviderName, grainTypeName);
logger.Verbose2(ErrorCode.Provider_CatalogStorageProviderAllocated, msg);
}
}
private async Task SetupActivationState(ActivationData result, string grainType)
{
var statefulGrain = result.GrainInstance as IStatefulGrain;
if (statefulGrain == null)
{
return;
}
var state = statefulGrain.GrainState;
if (result.StorageProvider != null && state != null)
{
var sw = Stopwatch.StartNew();
var innerState = statefulGrain.GrainState.State;
// Populate state data
try
{
var grainRef = result.GrainReference;
await scheduler.RunOrQueueTask(() =>
result.StorageProvider.ReadStateAsync(grainType, grainRef, state),
new SchedulingContext(result));
sw.Stop();
StorageStatisticsGroup.OnStorageActivate(result.StorageProvider, grainType, result.GrainReference, sw.Elapsed);
}
catch (Exception ex)
{
StorageStatisticsGroup.OnStorageActivateError(result.StorageProvider, grainType, result.GrainReference);
sw.Stop();
if (!(ex.GetBaseException() is KeyNotFoundException))
throw;
statefulGrain.GrainState.State = innerState; // Just keep original empty state object
}
}
}
/// <summary>
/// Try to get runtime data for an activation
/// </summary>
/// <param name="activationId"></param>
/// <param name="data"></param>
/// <returns></returns>
public bool TryGetActivationData(ActivationId activationId, out ActivationData data)
{
data = null;
if (activationId.IsSystem) return false;
data = activations.FindTarget(activationId);
return data != null;
}
private Task DeactivateActivationsFromCollector(List<ActivationData> list)
{
logger.Info(ErrorCode.Catalog_ShutdownActivations_1, "DeactivateActivationsFromCollector: total {0} to promptly Destroy.", list.Count);
CounterStatistic.FindOrCreate(StatisticNames.CATALOG_ACTIVATION_SHUTDOWN_VIA_COLLECTION).IncrementBy(list.Count);
foreach (var activation in list)
{
lock (activation)
{
activation.PrepareForDeactivation(); // Don't accept any new messages
}
}
return DestroyActivations(list);
}
// To be called fro within Activation context.
// Cannot be awaitable, since after DestroyActivation is done the activation is in Invalid state and cannot await any Task.
internal void DeactivateActivationOnIdle(ActivationData data)
{
DeactivateActivationImpl(data, StatisticNames.CATALOG_ACTIVATION_SHUTDOWN_VIA_DEACTIVATE_ON_IDLE);
}
// To be called fro within Activation context.
// To be used only if an activation is stuck for a long time, since it can lead to a duplicate activation
internal void DeactivateStuckActivation(ActivationData activationData)
{
DeactivateActivationImpl(activationData, StatisticNames.CATALOG_ACTIVATION_SHUTDOWN_VIA_DEACTIVATE_STUCK_ACTIVATION);
// The unregistration is normally done in the regular deactivation process, but since this activation seems
// stuck (it might never run the deactivation process), we remove it from the directory directly
scheduler.RunOrQueueTask(
() => directory.UnregisterAsync(activationData.Address, UnregistrationCause.Force),
SchedulingContext)
.Ignore();
}
private void DeactivateActivationImpl(ActivationData data, StatisticName statisticName)
{
bool promptly = false;
bool alreadBeingDestroyed = false;
lock (data)
{
if (data.State == ActivationState.Valid)
{
// Change the ActivationData state here, since we're about to give up the lock.
data.PrepareForDeactivation(); // Don't accept any new messages
ActivationCollector.TryCancelCollection(data);
if (!data.IsCurrentlyExecuting)
{
promptly = true;
}
else // busy, so destroy later.
{
data.AddOnInactive(() => DestroyActivationVoid(data));
}
}
else if (data.State == ActivationState.Create)
{
throw new InvalidOperationException(String.Format(
"Activation {0} has called DeactivateOnIdle from within a constructor, which is not allowed.",
data.ToString()));
}
else if (data.State == ActivationState.Activating)
{
throw new InvalidOperationException(String.Format(
"Activation {0} has called DeactivateOnIdle from within OnActivateAsync, which is not allowed.",
data.ToString()));
}
else
{
alreadBeingDestroyed = true;
}
}
logger.Info(ErrorCode.Catalog_ShutdownActivations_2,
"DeactivateActivationOnIdle: {0} {1}.", data.ToString(), promptly ? "promptly" : (alreadBeingDestroyed ? "already being destroyed or invalid" : "later when become idle"));
CounterStatistic.FindOrCreate(statisticName).Increment();
if (promptly)
{
DestroyActivationVoid(data); // Don't await or Ignore, since we are in this activation context and it may have alraedy been destroyed!
}
}
/// <summary>
/// Gracefully deletes activations, putting it into a shutdown state to
/// complete and commit outstanding transactions before deleting it.
/// To be called not from within Activation context, so can be awaited.
/// </summary>
/// <param name="list"></param>
/// <returns></returns>
internal async Task DeactivateActivations(List<ActivationData> list)
{
if (list == null || list.Count == 0) return;
if (logger.IsVerbose) logger.Verbose("DeactivateActivations: {0} activations.", list.Count);
List<ActivationData> destroyNow = null;
List<MultiTaskCompletionSource> destroyLater = null;
int alreadyBeingDestroyed = 0;
foreach (var d in list)
{
var activationData = d; // capture
lock (activationData)
{
if (activationData.State == ActivationState.Valid)
{
// Change the ActivationData state here, since we're about to give up the lock.
activationData.PrepareForDeactivation(); // Don't accept any new messages
ActivationCollector.TryCancelCollection(activationData);
if (!activationData.IsCurrentlyExecuting)
{
if (destroyNow == null)
{
destroyNow = new List<ActivationData>();
}
destroyNow.Add(activationData);
}
else // busy, so destroy later.
{
if (destroyLater == null)
{
destroyLater = new List<MultiTaskCompletionSource>();
}
var tcs = new MultiTaskCompletionSource(1);
destroyLater.Add(tcs);
activationData.AddOnInactive(() => DestroyActivationAsync(activationData, tcs));
}
}
else
{
alreadyBeingDestroyed++;
}
}
}
int numDestroyNow = destroyNow == null ? 0 : destroyNow.Count;
int numDestroyLater = destroyLater == null ? 0 : destroyLater.Count;
logger.Info(ErrorCode.Catalog_ShutdownActivations_3,
"DeactivateActivations: total {0} to shutdown, out of them {1} promptly, {2} later when become idle and {3} are already being destroyed or invalid.",
list.Count, numDestroyNow, numDestroyLater, alreadyBeingDestroyed);
CounterStatistic.FindOrCreate(StatisticNames.CATALOG_ACTIVATION_SHUTDOWN_VIA_DIRECT_SHUTDOWN).IncrementBy(list.Count);
if (destroyNow != null && destroyNow.Count > 0)
{
await DestroyActivations(destroyNow);
}
if (destroyLater != null && destroyLater.Count > 0)
{
await Task.WhenAll(destroyLater.Select(t => t.Task).ToArray());
}
}
public Task DeactivateAllActivations()
{
logger.Info(ErrorCode.Catalog_DeactivateAllActivations, "DeactivateAllActivations.");
var activationsToShutdown = activations.Where(kv => !kv.Value.IsExemptFromCollection).Select(kv => kv.Value).ToList();
return DeactivateActivations(activationsToShutdown);
}
/// <summary>
/// Deletes activation immediately regardless of active transactions etc.
/// For use by grain delete, transaction abort, etc.
/// </summary>
/// <param name="activation"></param>
private void DestroyActivationVoid(ActivationData activation)
{
StartDestroyActivations(new List<ActivationData> { activation });
}
private void DestroyActivationAsync(ActivationData activation, MultiTaskCompletionSource tcs)
{
StartDestroyActivations(new List<ActivationData> { activation }, tcs);
}
/// <summary>
/// Forcibly deletes activations now, without waiting for any outstanding transactions to complete.
/// Deletes activation immediately regardless of active transactions etc.
/// For use by grain delete, transaction abort, etc.
/// </summary>
/// <param name="list"></param>
/// <returns></returns>
// Overall code flow:
// Deactivating state was already set before, in the correct context under lock.
// that means no more new requests will be accepted into this activation and all timer were stopped (no new ticks will be delivered or enqueued)
// Wait for all already scheduled ticks to finish
// CallGrainDeactivate
// when AsyncDeactivate promise is resolved (NOT when all Deactivate turns are done, which may be orphan tasks):
// Unregister in the directory
// when all AsyncDeactivate turns are done (Dispatcher.OnActivationCompletedRequest):
// Set Invalid state
// UnregisterMessageTarget -> no new tasks will be enqueue (if an orphan task get enqueud, it is ignored and dropped on the floor).
// InvalidateCacheEntry
// Reroute pending
private Task DestroyActivations(List<ActivationData> list)
{
var tcs = new MultiTaskCompletionSource(list.Count);
StartDestroyActivations(list, tcs);
return tcs.Task;
}
private async void StartDestroyActivations(List<ActivationData> list, MultiTaskCompletionSource tcs = null)
{
int number = destroyActivationsNumber;
destroyActivationsNumber++;
try
{
logger.Info(ErrorCode.Catalog_DestroyActivations, "Starting DestroyActivations #{0} of {1} activations", number, list.Count);
// step 1 - WaitForAllTimersToFinish
var tasks1 = new List<Task>();
foreach (var activation in list)
{
tasks1.Add(activation.WaitForAllTimersToFinish());
}
try
{
await Task.WhenAll(tasks1);
}
catch (Exception exc)
{
logger.Warn(ErrorCode.Catalog_WaitForAllTimersToFinish_Exception, String.Format("WaitForAllTimersToFinish {0} failed.", list.Count), exc);
}
// step 2 - CallGrainDeactivate
var tasks2 = new List<Tuple<Task, ActivationData>>();
foreach (var activation in list)
{
var activationData = activation; // Capture loop variable
var task = scheduler.RunOrQueueTask(() => CallGrainDeactivateAndCleanupStreams(activationData), new SchedulingContext(activationData));
tasks2.Add(new Tuple<Task, ActivationData>(task, activationData));
}
var asyncQueue = new AsyncBatchedContinuationQueue<ActivationData>();
asyncQueue.Queue(tasks2, tupleList =>
{
FinishDestroyActivations(tupleList.Select(t => t.Item2).ToList(), number, tcs);
GC.KeepAlive(asyncQueue); // not sure about GC not collecting the asyncQueue local var prematuraly, so just want to capture it here to make sure. Just to be safe.
});
}
catch (Exception exc)
{
logger.Warn(ErrorCode.Catalog_DeactivateActivation_Exception, String.Format("StartDestroyActivations #{0} failed with {1} Activations.", number, list.Count), exc);
}
}
private async void FinishDestroyActivations(List<ActivationData> list, int number, MultiTaskCompletionSource tcs)
{
try
{
//logger.Info(ErrorCode.Catalog_DestroyActivations_Done, "Starting FinishDestroyActivations #{0} - with {1} Activations.", number, list.Count);
// step 3 - UnregisterManyAsync
try
{
List<ActivationAddress> activationsToDeactivate = list.
Where((ActivationData d) => d.IsUsingGrainDirectory).
Select((ActivationData d) => ActivationAddress.GetAddress(LocalSilo, d.Grain, d.ActivationId)).ToList();
if (activationsToDeactivate.Count > 0)
{
await scheduler.RunOrQueueTask(() =>
directory.UnregisterManyAsync(activationsToDeactivate, UnregistrationCause.Force),
SchedulingContext);
}
}
catch (Exception exc)
{
logger.Warn(ErrorCode.Catalog_UnregisterManyAsync, String.Format("UnregisterManyAsync {0} failed.", list.Count), exc);
}
// step 4 - UnregisterMessageTarget and OnFinishedGrainDeactivate
foreach (var activationData in list)
{
try
{
lock (activationData)
{
activationData.SetState(ActivationState.Invalid); // Deactivate calls on this activation are finished
}
UnregisterMessageTarget(activationData);
}
catch (Exception exc)
{
logger.Warn(ErrorCode.Catalog_UnregisterMessageTarget2, String.Format("UnregisterMessageTarget failed on {0}.", activationData), exc);
}
try
{
// IMPORTANT: no more awaits and .Ignore after that point.
// Just use this opportunity to invalidate local Cache Entry as well.
// If this silo is not the grain directory partition for this grain, it may have it in its cache.
directory.InvalidateCacheEntry(activationData.Address);
RerouteAllQueuedMessages(activationData, null, "Finished Destroy Activation");
}
catch (Exception exc)
{
logger.Warn(ErrorCode.Catalog_UnregisterMessageTarget3, String.Format("Last stage of DestroyActivations failed on {0}.", activationData), exc);
}
}
// step 5 - Resolve any waiting TaskCompletionSource
if (tcs != null)
{
tcs.SetMultipleResults(list.Count);
}
logger.Info(ErrorCode.Catalog_DestroyActivations_Done, "Done FinishDestroyActivations #{0} - Destroyed {1} Activations.", number, list.Count);
}catch (Exception exc)
{
logger.Error(ErrorCode.Catalog_FinishDeactivateActivation_Exception, String.Format("FinishDestroyActivations #{0} failed with {1} Activations.", number, list.Count), exc);
}
}
private void RerouteAllQueuedMessages(ActivationData activation, ActivationAddress forwardingAddress, string failedOperation, Exception exc = null)
{
lock (activation)
{
List<Message> msgs = activation.DequeueAllWaitingMessages();
if (msgs == null || msgs.Count <= 0) return;
if (logger.IsVerbose) logger.Verbose(ErrorCode.Catalog_RerouteAllQueuedMessages, String.Format("RerouteAllQueuedMessages: {0} msgs from Invalid activation {1}.", msgs.Count(), activation));
this.Dispatcher.ProcessRequestsToInvalidActivation(msgs, activation.Address, forwardingAddress, failedOperation, exc);
}
}
private async Task CallGrainActivate(ActivationData activation, Dictionary<string, object> requestContextData)
{
var grainTypeName = activation.GrainInstanceType.FullName;
// Note: This call is being made from within Scheduler.Queue wrapper, so we are already executing on worker thread
if (logger.IsVerbose) logger.Verbose(ErrorCode.Catalog_BeforeCallingActivate, "About to call {1} grain's OnActivateAsync() method {0}", activation, grainTypeName);
// Call OnActivateAsync inline, but within try-catch wrapper to safely capture any exceptions thrown from called function
try
{
RequestContext.Import(requestContextData);
await activation.GrainInstance.OnActivateAsync();
if (logger.IsVerbose) logger.Verbose(ErrorCode.Catalog_AfterCallingActivate, "Returned from calling {1} grain's OnActivateAsync() method {0}", activation, grainTypeName);
lock (activation)
{
if (activation.State == ActivationState.Activating)
{
activation.SetState(ActivationState.Valid); // Activate calls on this activation are finished
}
if (!activation.IsCurrentlyExecuting)
{
activation.RunOnInactive();
}
// Run message pump to see if there is a new request is queued to be processed
this.Dispatcher.RunMessagePump(activation);
}
}
catch (Exception exc)
{
logger.Error(ErrorCode.Catalog_ErrorCallingActivate,
string.Format("Error calling grain's OnActivateAsync() method - Grain type = {1} Activation = {0}", activation, grainTypeName), exc);
activation.SetState(ActivationState.Invalid); // Mark this activation as unusable
activationsFailedToActivate.Increment();
throw;
}
}
private async Task<ActivationData> CallGrainDeactivateAndCleanupStreams(ActivationData activation)
{
try
{
var grainTypeName = activation.GrainInstanceType.FullName;
// Note: This call is being made from within Scheduler.Queue wrapper, so we are already executing on worker thread
if (logger.IsVerbose) logger.Verbose(ErrorCode.Catalog_BeforeCallingDeactivate, "About to call {1} grain's OnDeactivateAsync() method {0}", activation, grainTypeName);
// Call OnDeactivateAsync inline, but within try-catch wrapper to safely capture any exceptions thrown from called function
try
{
// just check in case this activation data is already Invalid or not here at all.
ActivationData ignore;
if (TryGetActivationData(activation.ActivationId, out ignore) &&
activation.State == ActivationState.Deactivating)
{
RequestContext.Clear(); // Clear any previous RC, so it does not leak into this call by mistake.
await activation.GrainInstance.OnDeactivateAsync();
}
if (logger.IsVerbose) logger.Verbose(ErrorCode.Catalog_AfterCallingDeactivate, "Returned from calling {1} grain's OnDeactivateAsync() method {0}", activation, grainTypeName);
}
catch (Exception exc)
{
logger.Error(ErrorCode.Catalog_ErrorCallingDeactivate,
string.Format("Error calling grain's OnDeactivateAsync() method - Grain type = {1} Activation = {0}", activation, grainTypeName), exc);
}
if (activation.IsUsingStreams)
{
try
{
await activation.DeactivateStreamResources();
}
catch (Exception exc)
{
logger.Warn(ErrorCode.Catalog_DeactivateStreamResources_Exception, String.Format("DeactivateStreamResources Grain type = {0} Activation = {1} failed.", grainTypeName, activation), exc);
}
}
}
catch(Exception exc)
{
logger.Error(ErrorCode.Catalog_FinishGrainDeactivateAndCleanupStreams_Exception, String.Format("CallGrainDeactivateAndCleanupStreams Activation = {0} failed.", activation), exc);
}
return activation;
}
private async Task RegisterActivationInGrainDirectoryAndValidate(ActivationData activation)
{
ActivationAddress address = activation.Address;
// Currently, the only grain type that is not registered in the Grain Directory is StatelessWorker.
// Among those that are registered in the directory, we currently do not have any multi activations.
if (activation.IsUsingGrainDirectory)
{
var result = await scheduler.RunOrQueueTask(() => directory.RegisterAsync(address, singleActivation:true), this.SchedulingContext);
if (address.Equals(result.Address)) return;
SiloAddress primaryDirectoryForGrain = directory.GetPrimaryForGrain(address.Grain);
throw new DuplicateActivationException(result.Address, primaryDirectoryForGrain);
}
else
{
StatelessWorkerPlacement stPlacement = activation.PlacedUsing as StatelessWorkerPlacement;
int maxNumLocalActivations = stPlacement.MaxLocal;
lock (activations)
{
List<ActivationData> local;
if (!LocalLookup(address.Grain, out local) || local.Count <= maxNumLocalActivations)
return;
var id = StatelessWorkerDirector.PickRandom(local).Address;
throw new DuplicateActivationException(id);
}
}
// We currently don't have any other case for multiple activations except for StatelessWorker.
}
#endregion
#region Activations - private
/// <summary>
/// Invoke the activate method on a newly created activation
/// </summary>
/// <param name="activation"></param>
/// <param name="requestContextData"></param>
/// <returns></returns>
private Task InvokeActivate(ActivationData activation, Dictionary<string, object> requestContextData)
{
// NOTE: This should only be called with the correct schedulering context for the activation to be invoked.
lock (activation)
{
activation.SetState(ActivationState.Activating);
}
return scheduler.QueueTask(() => CallGrainActivate(activation, requestContextData), new SchedulingContext(activation)); // Target grain's scheduler context);
// ActivationData will transition out of ActivationState.Activating via Dispatcher.OnActivationCompletedRequest
}
#endregion
#region IPlacementContext
public Logger Logger => logger;
public bool FastLookup(GrainId grain, out AddressesAndTag addresses)
{
return directory.LocalLookup(grain, out addresses) && addresses.Addresses != null && addresses.Addresses.Count > 0;
// NOTE: only check with the local directory cache.
// DO NOT check in the local activations TargetDirectory!!!
// The only source of truth about which activation should be legit to is the state of the ditributed directory.
// Everyone should converge to that (that is the meaning of "eventualy consistency - eventualy we converge to one truth").
// If we keep using the local activation, it may not be registered in th directory any more, but we will never know that and keep using it,
// thus volaiting the single-activation semantics and not converging even eventualy!
}
public Task<AddressesAndTag> FullLookup(GrainId grain)
{
return scheduler.RunOrQueueTask(() => directory.LookupAsync(grain), this.SchedulingContext);
}
public Task<AddressesAndTag> LookupInCluster(GrainId grain, string clusterId)
{
return scheduler.RunOrQueueTask(() => directory.LookupInCluster(grain, clusterId), this.SchedulingContext);
}
public bool LocalLookup(GrainId grain, out List<ActivationData> addresses)
{
addresses = activations.FindTargets(grain);
return addresses != null;
}
public List<SiloAddress> AllActiveSilos
{
get
{
var result = SiloStatusOracle.GetApproximateSiloStatuses(true).Select(s => s.Key).ToList();
if (result.Count > 0) return result;
logger.Warn(ErrorCode.Catalog_GetApproximateSiloStatuses, "AllActiveSilos SiloStatusOracle.GetApproximateSiloStatuses empty");
return new List<SiloAddress> { LocalSilo };
}
}
public SiloStatus LocalSiloStatus
{
get {
return SiloStatusOracle.CurrentStatus;
}
}
#endregion
#region Implementation of ICatalog
public Task CreateSystemGrain(GrainId grainId, string grainType)
{
ActivationAddress target = ActivationAddress.NewActivationAddress(LocalSilo, grainId);
Task activatedPromise;
GetOrCreateActivation(target, true, grainType, null, null, out activatedPromise);
return activatedPromise ?? TaskDone.Done;
}
public Task DeleteActivations(List<ActivationAddress> addresses)
{
return DestroyActivations(TryGetActivationDatas(addresses));
}
private List<ActivationData> TryGetActivationDatas(List<ActivationAddress> addresses)
{
var datas = new List<ActivationData>(addresses.Count);
foreach (var activationAddress in addresses)
{
ActivationData data;
if (TryGetActivationData(activationAddress.Activation, out data))
datas.Add(data);
}
return datas;
}
#endregion
#region Implementation of ISiloStatusListener
public void SiloStatusChangeNotification(SiloAddress updatedSilo, SiloStatus status)
{
// ignore joining events and also events on myself.
if (updatedSilo.Equals(LocalSilo)) return;
// We deactivate those activations when silo goes either of ShuttingDown/Stopping/Dead states,
// since this is what Directory is doing as well. Directory removes a silo based on all those 3 statuses,
// thus it will only deliver a "remove" notification for a given silo once to us. Therefore, we need to react the fist time we are notified.
// We may review the directory behaiviour in the future and treat ShuttingDown differently ("drain only") and then this code will have to change a well.
if (!status.IsTerminating()) return;
if (status == SiloStatus.Dead)
{
RuntimeClient.Current.BreakOutstandingMessagesToDeadSilo(updatedSilo);
}
var activationsToShutdown = new List<ActivationData>();
try
{
// scan all activations in activation directory and deactivate the ones that the removed silo is their primary partition owner.
lock (activations)
{
foreach (var activation in activations)
{
try
{
var activationData = activation.Value;
if (!activationData.IsUsingGrainDirectory) continue;
if (!directory.GetPrimaryForGrain(activationData.Grain).Equals(updatedSilo)) continue;
lock (activationData)
{
// adapted from InsideGarinClient.DeactivateOnIdle().
activationData.ResetKeepAliveRequest();
activationsToShutdown.Add(activationData);
}
}
catch (Exception exc)
{
logger.Error(ErrorCode.Catalog_SiloStatusChangeNotification_Exception,
String.Format("Catalog has thrown an exception while executing SiloStatusChangeNotification of silo {0}.", updatedSilo.ToStringWithHashCode()), exc);
}
}
}
logger.Info(ErrorCode.Catalog_SiloStatusChangeNotification,
String.Format("Catalog is deactivating {0} activations due to a failure of silo {1}, since it is a primary directory partiton to these grain ids.",
activationsToShutdown.Count, updatedSilo.ToStringWithHashCode()));
}
finally
{
// outside the lock.
if (activationsToShutdown.Count > 0)
{
DeactivateActivations(activationsToShutdown).Ignore();
}
}
}
#endregion
}
}
| |
namespace Mailosaur.Operations
{
using System;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Mailosaur.Models;
public class Messages : OperationBase
{
/// <summary>
/// Initializes a new instance of the Messages class.
/// </summary>
/// <param name='client'>
/// Reference to the HttpClient.
/// </param>
public Messages(HttpClient client) : base(client) { }
/// <summary>
/// Retrieve a message using search criteria
/// </summary>
/// <remarks>
/// Returns as soon as a message matching the specified search criteria is
/// found. This is the most efficient method of looking up a message.
/// </remarks>
/// <param name='server'>
/// The identifier of the server hosting the message.
/// </param>
/// <param name='criteria'>
/// The search criteria to use in order to find a match.
/// </param>
/// <param name='timeout'>
/// Specify how long to wait for a matching result (in milliseconds).
/// </param>
/// <param name='receivedAfter'>
/// Limits results to only messages received after this date/time.
/// </param>
public Message Get(string server, SearchCriteria criteria = null, int timeout = 10000, DateTime? receivedAfter = null)
=> Task.Run(async () => await GetAsync(server, criteria, timeout, receivedAfter)).UnwrapException<Message>();
/// <summary>
/// Retrieve a message using search criteria
/// </summary>
/// <remarks>
/// Returns as soon as a message matching the specified search criteria is
/// found. This is the most efficient method of looking up a message.
/// </remarks>
/// <param name='server'>
/// The identifier of the server hosting the message.
/// </param>
/// <param name='criteria'>
/// The search criteria to use in order to find a match.
/// </param>
/// <param name='timeout'>
/// Specify how long to wait for a matching result (in milliseconds).
/// </param>
/// <param name='receivedAfter'>
/// Limits results to only messages received after this date/time.
/// </param>
public async Task<Message> GetAsync(string server, SearchCriteria criteria = null, int timeout = 10000, DateTime? receivedAfter = null)
{
// Timeout defaulted to 10s, receivedAfter to 1h
receivedAfter = receivedAfter != null ? receivedAfter : DateTime.UtcNow.AddHours(-1);
criteria = criteria != null ? criteria : new SearchCriteria();
if (server.Length != 8)
throw new MailosaurException("Must provide a valid Server ID.", "invalid_request");
var result = await SearchAsync(server, criteria, 0, 1, timeout, receivedAfter);
return GetById(result.Items[0].Id);
}
/// <summary>
/// Retrieve a message
/// </summary>
/// <remarks>
/// Retrieves the detail for a single email message. Simply supply the unique
/// identifier for the required message.
/// </remarks>
/// <param name='id'>
/// The identifier of the email message to be retrieved.
/// </param>
public Message GetById(string id)
=> Task.Run(async () => await GetByIdAsync(id)).UnwrapException<Message>();
/// <summary>
/// Retrieve a message
/// </summary>
/// <remarks>
/// Retrieves the detail for a single email message. Simply supply the unique
/// identifier for the required message.
/// </remarks>
/// <param name='id'>
/// The identifier of the email message to be retrieved.
/// </param>
public Task<Message> GetByIdAsync(string id)
=> ExecuteRequest<Message>(HttpMethod.Get, $"api/messages/{id}");
/// <summary>
/// a message
/// </summary>
/// <remarks>
/// Permanently deletes a message. This operation cannot be undone. Also
/// deletes any attachments related to the message.
/// </remarks>
/// <param name='id'>
/// The identifier of the message to be deleted.
/// </param>
public void Delete(string id)
=> Task.Run(async () => await DeleteAsync(id)).WaitAndUnwrapException();
/// <summary>
/// Delete a message
/// </summary>
/// <remarks>
/// Permanently deletes a message. This operation cannot be undone. Also
/// deletes any attachments related to the message.
/// </remarks>
/// <param name='id'>
/// The identifier of the message to be deleted.
/// </param>
public Task DeleteAsync(string id)
=> ExecuteRequest(HttpMethod.Delete, $"api/messages/{id}");
/// <summary>
/// List all messages
/// </summary>
/// <remarks>
/// Returns a list of your messages in summary form. The summaries are returned
/// sorted by received date, with the most recently-received messages appearing
/// first.
/// </remarks>
/// <param name='server'>
/// The identifier of the server hosting the messages.
/// </param>
/// <param name='page'>
/// Used in conjunction with `itemsPerPage` to support pagination.
/// </param>
/// <param name='itemsPerPage'>
/// A limit on the number of results to be returned per page. Can be set
/// between 1 and 1000 items, the default is 50.
/// </param>
/// <param name='receivedAfter'>
/// Limits results to only messages received after this date/time.
/// </param>
public MessageListResult List(string server, int? page = default(int?), int? itemsPerPage = default(int?), DateTime? receivedAfter = null)
=> Task.Run(async () => await ListAsync(server, page, itemsPerPage, receivedAfter)).UnwrapException<MessageListResult>();
/// <summary>
/// List all messages
/// </summary>
/// <remarks>
/// Returns a list of your messages in summary form. The summaries are returned
/// sorted by received date, with the most recently-received messages appearing
/// first.
/// </remarks>
/// <param name='server'>
/// The identifier of the server hosting the messages.
/// </param>
/// <param name='page'>
/// Used in conjunction with `itemsPerPage` to support pagination.
/// </param>
/// <param name='itemsPerPage'>
/// A limit on the number of results to be returned per page. Can be set
/// between 1 and 1000 items, the default is 50.
/// </param>
/// <param name='receivedAfter'>
/// Limits results to only messages received after this date/time.
/// </param>
public Task<MessageListResult> ListAsync(string server, int? page = default(int?), int? itemsPerPage = default(int?), DateTime? receivedAfter = null)
=> ExecuteRequest<MessageListResult>(HttpMethod.Get, PagePath($"api/messages?server={server}", page, itemsPerPage, receivedAfter));
/// <summary>
/// Delete all messages
/// </summary>
/// <remarks>
/// Permanently deletes all messages held by the specified server. This
/// operation cannot be undone. Also deletes any attachments related to each
/// message.
/// </remarks>
/// <param name='server'>
/// The identifier of the server to be emptied.
/// </param>
public void DeleteAll(string server)
=> Task.Run(async () => await DeleteAllAsync(server)).WaitAndUnwrapException();
/// <summary>
/// Delete all messages
/// </summary>
/// <remarks>
/// Permanently deletes all messages held by the specified server. This
/// operation cannot be undone. Also deletes any attachments related to each
/// message.
/// </remarks>
/// <param name='server'>
/// The identifier of the server to be emptied.
/// </param>
public Task DeleteAllAsync(string server)
=> ExecuteRequest(HttpMethod.Delete, $"api/messages?server={server}");
/// <summary>
/// Search for messages
/// </summary>
/// <remarks>
/// Returns a list of messages matching the specified search criteria, in
/// summary form. The messages are returned sorted by received date, with the
/// most recently-received messages appearing first.
/// </remarks>
/// <param name='server'>
/// The identifier of the server hosting the messages.
/// </param>
/// <param name='criteria'>
/// The search criteria to match results against.
/// </param>
/// <param name='page'>
/// Used in conjunction with `itemsPerPage` to support pagination.
/// </param>
/// <param name='itemsPerPage'>
/// A limit on the number of results to be returned per page. Can be set
/// between 1 and 1000 items, the default is 50.
/// </param>
/// <param name='timeout'>
/// Specify how long to wait for a matching result (in milliseconds).
/// </param>
/// <param name='receivedAfter'>
/// Limits results to only messages received after this date/time.
/// </param>
/// <param name='errorOnTimeout'>
/// When set to false, an error will not be throw if timeout is reached
/// (default: true).
/// </param>
public MessageListResult Search(string server, SearchCriteria criteria, int? page = null, int? itemsPerPage = null, int? timeout = null, DateTime? receivedAfter = null, bool errorOnTimeout = true)
=> Task.Run(async () => await SearchAsync(server, criteria, page, itemsPerPage, timeout, receivedAfter, errorOnTimeout)).UnwrapException<MessageListResult>();
/// <summary>
/// Search for messages
/// </summary>
/// <remarks>
/// Returns a list of messages matching the specified search criteria, in
/// summary form. The messages are returned sorted by received date, with the
/// most recently-received messages appearing first.
/// </remarks>
/// <param name='server'>
/// The identifier of the server hosting the messages.
/// </param>
/// <param name='criteria'>
/// The search criteria to match results against.
/// </param>
/// <param name='page'>
/// Used in conjunction with `itemsPerPage` to support pagination.
/// </param>
/// <param name='itemsPerPage'>
/// A limit on the number of results to be returned per page. Can be set
/// between 1 and 1000 items, the default is 50.
/// </param>
/// <param name='timeout'>
/// Specify how long to wait for a matching result (in milliseconds).
/// </param>
/// <param name='receivedAfter'>
/// Limits results to only messages received after this date/time.
/// </param>
/// <param name='errorOnTimeout'>
/// When set to false, an error will not be throw if timeout is reached
/// (default: true).
/// </param>
public async Task<MessageListResult> SearchAsync(string server, SearchCriteria criteria, int? page = null, int? itemsPerPage = null, int? timeout = null, DateTime? receivedAfter = null, bool errorOnTimeout = true)
{
var pollCount = 0;
var startTime = DateTime.UtcNow;
while(true)
{
var result = await ExecuteRequest<MessageListResultWithHeaders>(HttpMethod.Post, PagePath($"api/messages/search?server={server}", page, itemsPerPage, receivedAfter), criteria);
if (timeout == null || timeout == 0 || result.MessageListResult.Items.Count != 0)
return result.MessageListResult;
var delayPattern = (string.IsNullOrWhiteSpace(result.DelayHeader) ? "1000" : result.DelayHeader)
.Split(',').Select(x => Int32.Parse(x)).ToArray();
var delay = pollCount >= delayPattern.Length ?
delayPattern[delayPattern.Length - 1] :
delayPattern[pollCount];
pollCount++;
// Stop if timeout will be exceeded
if (((int)(DateTime.UtcNow - startTime).TotalMilliseconds) + delay > timeout)
{
if (errorOnTimeout == false) {
return result.MessageListResult;
}
throw new MailosaurException("No matching messages found in time. By default, only messages received in the last hour are checked (use receivedAfter to override this).", "search_timeout");
}
Task.Delay(delay).Wait();
}
}
/// <summary>
/// Wait for a specific message
/// </summary>
/// <remarks>
/// Returns as soon as a message matching the specified search criteria is
/// found. This is the most efficient method of looking up a message.
/// </remarks>
/// <param name='server'>
/// The identifier of the server hosting the message.
/// </param>
/// <param name='criteria'>
/// The search criteria to use in order to find a match.
/// </param>
public Message WaitFor(string server, SearchCriteria criteria)
=> Task.Run(async () => await WaitForAsync(server, criteria)).UnwrapException<Message>();
/// <summary>
/// Wait for a specific message
/// </summary>
/// <remarks>
/// Returns as soon as a message matching the specified search criteria is
/// found. This is the most efficient method of looking up a message.
/// </remarks>
/// <param name='server'>
/// The identifier of the server hosting the message.
/// </param>
/// <param name='criteria'>
/// The search criteria to use in order to find a match.
/// </param>
public Task<Message> WaitForAsync(string server, SearchCriteria criteria)
=> ExecuteRequest<Message>(HttpMethod.Post, $"api/messages/await?server={server}", criteria);
}
}
| |
/* ====================================================================
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.HSSF.UserModel
{
using System;
using System.IO;
using System.Collections;
using System.Text;
using NPOI.HSSF.Record;
using NPOI.Util;
using NPOI.HSSF.Model;
using NPOI.HSSF.Util;
using NPOI.SS.Formula;
using NPOI.SS.Formula.PTG;
/// <summary>
/// High Level Represantion of Named Range
/// </summary>
/// <remarks>@author Libin Roman (Vista Portal LDT. Developer)</remarks>
internal class HSSFName:NPOI.SS.UserModel.IName
{
private HSSFWorkbook book;
private NameRecord _definedNameRec;
private NameCommentRecord _commentRec;
/* package */
internal HSSFName(HSSFWorkbook book, NameRecord name):this(book, name, null)
{
}
/// <summary>
/// Creates new HSSFName - called by HSSFWorkbook to Create a sheet from
/// scratch.
/// </summary>
/// <param name="book">lowlevel Workbook object associated with the sheet.</param>
/// <param name="name">the Name Record</param>
/// <param name="comment"></param>
internal HSSFName(HSSFWorkbook book, NameRecord name, NameCommentRecord comment)
{
this.book = book;
this._definedNameRec = name;
_commentRec = comment;
}
/// <summary>
/// Gets or sets the sheets name which this named range is referenced to
/// </summary>
/// <value>sheet name, which this named range refered to</value>
public String SheetName
{
get
{
String result;
int indexToExternSheet = _definedNameRec.ExternSheetNumber;
result = book.Workbook.FindSheetNameFromExternSheet(indexToExternSheet);
return result;
}
//set
//{
// int sheetNumber = book.GetSheetIndex(value);
// int externSheetNumber = book.GetExternalSheetIndex(sheetNumber);
// name.ExternSheetNumber = externSheetNumber;
//}
}
/// <summary>
/// Gets or sets the name of the named range
/// </summary>
/// <value>named range name</value>
public String NameName
{
get
{
String result = _definedNameRec.NameText;
return result;
}
set
{
ValidateName(value);
_definedNameRec.NameText = value;
InternalWorkbook wb = book.Workbook;
int sheetNumber = _definedNameRec.SheetNumber;
//Check to Ensure no other names have the same case-insensitive name
for (int i = wb.NumNames- 1; i >= 0; i--)
{
NameRecord rec = wb.GetNameRecord(i);
if (rec != _definedNameRec)
{
if (rec.NameText.Equals(NameName, StringComparison.OrdinalIgnoreCase) && sheetNumber == rec.SheetNumber)
{
String msg = "The " + (sheetNumber == 0 ? "workbook" : "sheet") + " already contains this name: " + value;
_definedNameRec.NameText = (value + "(2)");
throw new ArgumentException(msg);
}
}
}
// Update our comment, if there is one
if (_commentRec != null)
{
String oldName = _commentRec.NameText;
_commentRec.NameText=value;
book.Workbook.UpdateNameCommentRecordCache(_commentRec);
}
}
}
private void ValidateName(String name)
{
if (name.Length == 0) throw new ArgumentException("Name cannot be blank");
char c = name[0];
if (!(c == '_' || Char.IsLetter(c)) || name.IndexOf(' ') != -1)
{
throw new ArgumentException("Invalid name: '" + name + "'; Names must begin with a letter or underscore and not contain spaces");
}
}
public String RefersToFormula
{
get
{
if (_definedNameRec.IsFunctionName)
{
throw new InvalidOperationException("Only applicable to named ranges");
}
Ptg[] ptgs = _definedNameRec.NameDefinition;
if (ptgs.Length < 1)
{
// 'refersToFormula' has not been set yet
return null;
}
return HSSFFormulaParser.ToFormulaString(book, ptgs);
}
set
{
Ptg[] ptgs = HSSFFormulaParser.Parse(value, book, NPOI.SS.Formula.FormulaType.NAMEDRANGE, SheetIndex);
_definedNameRec.NameDefinition = ptgs;
}
}
/**
* Returns the sheet index this name applies to.
*
* @return the sheet index this name applies to, -1 if this name applies to the entire workbook
*/
public int SheetIndex
{
get
{
return _definedNameRec.SheetNumber - 1;
}
set
{
int lastSheetIx = book.NumberOfSheets - 1;
if (value < -1 || value > lastSheetIx)
{
throw new ArgumentException("Sheet index (" + value + ") is out of range" +
(lastSheetIx == -1 ? "" : (" (0.." + lastSheetIx + ")")));
}
_definedNameRec.SheetNumber = (value + 1);
}
}
public string Comment
{
get
{
if (_commentRec != null)
{
// Prefer the comment record if it has text in it
if (_commentRec.CommentText != null &&
_commentRec.CommentText.Length > 0)
{
return _commentRec.CommentText;
}
}
return _definedNameRec.DescriptionText;
}
set { _definedNameRec.DescriptionText = value; }
}
/// <summary>
/// Tests if this name points to a cell that no longer exists
/// </summary>
/// <value>
/// <c>true</c> if the name refers to a deleted cell; otherwise, <c>false</c>.
/// </value>
public bool IsDeleted
{
get
{
Ptg[] ptgs = _definedNameRec.NameDefinition;
return Ptg.DoesFormulaReferToDeletedCell(ptgs);
}
}
/// <summary>
/// Gets a value indicating whether this instance is function name.
/// </summary>
/// <value>
/// <c>true</c> if this instance is function name; otherwise, <c>false</c>.
/// </value>
public bool IsFunctionName
{
get
{
return _definedNameRec.IsFunctionName;
}
}
/**
* Indicates that the defined name refers to a user-defined function.
* This attribute is used when there is an add-in or other code project associated with the file.
*
* @param value <c>true</c> indicates the name refers to a function.
*/
public void SetFunction(bool value)
{
_definedNameRec.SetFunction(value);
}
/// <summary>
/// Returns a <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
/// </summary>
/// <returns>
/// A <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
/// </returns>
public override String ToString()
{
StringBuilder sb = new StringBuilder(64);
sb.Append(GetType().Name).Append(" [");
sb.Append(_definedNameRec.NameText);
sb.Append("]");
return sb.ToString();
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using Lucene.Net.Documents;
using Lucene.Net.Search;
using Lucene.Net.Search.Function;
using Lucene.Net.Spatial.Queries;
using Lucene.Net.Spatial.Util;
using Spatial4n.Core.Context;
using Spatial4n.Core.Shapes;
namespace Lucene.Net.Spatial.Vector
{
/// <summary>
/// Simple {@link SpatialStrategy} which represents Points in two numeric {@link DoubleField}s.
///
/// Note, currently only Points can be indexed by this Strategy. At query time, the bounding
/// box of the given Shape is used to create {@link NumericRangeQuery}s to efficiently
/// find Points within the Shape.
///
/// Due to the simple use of numeric fields, this Strategy provides support for sorting by
/// distance through {@link DistanceValueSource}
/// </summary>
public class PointVectorStrategy : SpatialStrategy
{
public static String SUFFIX_X = "__x";
public static String SUFFIX_Y = "__y";
private readonly String fieldNameX;
private readonly String fieldNameY;
public int precisionStep = 8; // same as solr default
public PointVectorStrategy(SpatialContext ctx, String fieldNamePrefix)
: base(ctx, fieldNamePrefix)
{
this.fieldNameX = fieldNamePrefix + SUFFIX_X;
this.fieldNameY = fieldNamePrefix + SUFFIX_Y;
}
public void SetPrecisionStep(int p)
{
precisionStep = p;
if (precisionStep <= 0 || precisionStep >= 64)
precisionStep = int.MaxValue;
}
public string GetFieldNameX()
{
return fieldNameX;
}
public string GetFieldNameY()
{
return fieldNameY;
}
public override AbstractField[] CreateIndexableFields(Shape shape)
{
var point = shape as Point;
if (point != null)
return CreateIndexableFields(point);
throw new InvalidOperationException("Can only index Point, not " + shape);
}
public AbstractField[] CreateIndexableFields(Point point)
{
var f = new AbstractField[2];
var f0 = new NumericField(fieldNameX, precisionStep, Field.Store.NO, true)
{OmitNorms = true, OmitTermFreqAndPositions = true};
f0.SetDoubleValue(point.GetX());
f[0] = f0;
var f1 = new NumericField(fieldNameY, precisionStep, Field.Store.NO, true)
{OmitNorms = true, OmitTermFreqAndPositions = true};
f1.SetDoubleValue(point.GetY());
f[1] = f1;
return f;
}
public override ValueSource MakeDistanceValueSource(Point queryPoint)
{
return new DistanceValueSource(this, queryPoint);
}
public override ConstantScoreQuery MakeQuery(SpatialArgs args)
{
if (!SpatialOperation.Is(args.Operation,
SpatialOperation.Intersects,
SpatialOperation.IsWithin))
throw new UnsupportedSpatialOperation(args.Operation);
Shape shape = args.Shape;
var bbox = shape as Rectangle;
if (bbox != null)
return new ConstantScoreQuery(new QueryWrapperFilter(MakeWithin(bbox)));
var circle = shape as Circle;
if (circle != null)
{
bbox = circle.GetBoundingBox();
var vsf = new ValueSourceFilter(
new QueryWrapperFilter(MakeWithin(bbox)),
MakeDistanceValueSource(circle.GetCenter()),
0,
circle.GetRadius());
return new ConstantScoreQuery(vsf);
}
throw new InvalidOperationException("Only Rectangles and Circles are currently supported, " +
"found [" + shape.GetType().Name + "]"); //TODO
}
//TODO this is basically old code that hasn't been verified well and should probably be removed
public Query MakeQueryDistanceScore(SpatialArgs args)
{
// For starters, just limit the bbox
var shape = args.Shape;
if (!(shape is Rectangle || shape is Circle))
throw new InvalidOperationException("Only Rectangles and Circles are currently supported, found ["
+ shape.GetType().Name + "]");//TODO
Rectangle bbox = shape.GetBoundingBox();
if (bbox.GetCrossesDateLine())
{
throw new InvalidOperationException("Crossing dateline not yet supported");
}
ValueSource valueSource = null;
Query spatial = null;
SpatialOperation op = args.Operation;
if (SpatialOperation.Is(op,
SpatialOperation.BBoxWithin,
SpatialOperation.BBoxIntersects))
{
spatial = MakeWithin(bbox);
}
else if (SpatialOperation.Is(op,
SpatialOperation.Intersects,
SpatialOperation.IsWithin))
{
spatial = MakeWithin(bbox);
var circle = args.Shape as Circle;
if (circle != null)
{
// Make the ValueSource
valueSource = MakeDistanceValueSource(shape.GetCenter());
var vsf = new ValueSourceFilter(
new QueryWrapperFilter(spatial), valueSource, 0, circle.GetRadius());
spatial = new FilteredQuery(new MatchAllDocsQuery(), vsf);
}
}
else if (op == SpatialOperation.IsDisjointTo)
{
spatial = MakeDisjoint(bbox);
}
if (spatial == null)
{
throw new UnsupportedSpatialOperation(args.Operation);
}
if (valueSource != null)
{
valueSource = new CachingDoubleValueSource(valueSource);
}
else
{
valueSource = MakeDistanceValueSource(shape.GetCenter());
}
Query spatialRankingQuery = new FunctionQuery(valueSource);
var bq = new BooleanQuery();
bq.Add(spatial, Occur.MUST);
bq.Add(spatialRankingQuery, Occur.MUST);
return bq;
}
public override Filter MakeFilter(SpatialArgs args)
{
//unwrap the CSQ from makeQuery
ConstantScoreQuery csq = MakeQuery(args);
Filter filter = csq.Filter;
if (filter != null)
return filter;
else
return new QueryWrapperFilter(csq);
}
/// <summary>
/// Constructs a query to retrieve documents that fully contain the input envelope.
/// </summary>
/// <param name="bbox"></param>
private Query MakeWithin(Rectangle bbox)
{
var bq = new BooleanQuery();
const Occur MUST = Occur.MUST;
if (bbox.GetCrossesDateLine())
{
//use null as performance trick since no data will be beyond the world bounds
bq.Add(RangeQuery(fieldNameX, null /*-180*/, bbox.GetMaxX()), Occur.SHOULD);
bq.Add(RangeQuery(fieldNameX, bbox.GetMinX(), null /*+180*/), Occur.SHOULD);
bq.MinimumNumberShouldMatch = 1; //must match at least one of the SHOULD
}
else
{
bq.Add(RangeQuery(fieldNameX, bbox.GetMinX(), bbox.GetMaxX()), MUST);
}
bq.Add(RangeQuery(fieldNameY, bbox.GetMinY(), bbox.GetMaxY()), MUST);
return bq;
}
private NumericRangeQuery<Double> RangeQuery(String fieldName, double? min, double? max)
{
return NumericRangeQuery.NewDoubleRange(
fieldName,
precisionStep,
min,
max,
true,
true); //inclusive
}
/// <summary>
/// Constructs a query to retrieve documents that fully contain the input envelope.
/// </summary>
/// <param name="bbox"></param>
private Query MakeDisjoint(Rectangle bbox)
{
if (bbox.GetCrossesDateLine())
throw new InvalidOperationException("MakeDisjoint doesn't handle dateline cross");
Query qX = RangeQuery(fieldNameX, bbox.GetMinX(), bbox.GetMaxX());
Query qY = RangeQuery(fieldNameY, bbox.GetMinY(), bbox.GetMaxY());
var bq = new BooleanQuery {{qX, Occur.MUST_NOT}, {qY, Occur.MUST_NOT}};
return bq;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Diagnostics;
using System.Net.Quic;
using System.Runtime.ExceptionServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Connections;
using Microsoft.AspNetCore.Connections.Features;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.Extensions.Logging;
namespace Microsoft.AspNetCore.Server.Kestrel.Transport.Quic.Internal
{
internal partial class QuicConnectionContext : TransportMultiplexedConnection
{
// Internal for testing.
internal PooledStreamStack<QuicStreamContext> StreamPool;
private bool _streamPoolHeartbeatInitialized;
// Ticks updated once per-second in heartbeat event.
private long _heartbeatTicks;
private readonly object _poolLock = new object();
private readonly object _shutdownLock = new object();
private readonly QuicConnection _connection;
private readonly QuicTransportContext _context;
private readonly ILogger _log;
private readonly CancellationTokenSource _connectionClosedTokenSource = new CancellationTokenSource();
private Task? _closeTask;
private ExceptionDispatchInfo? _abortReason;
internal const int InitialStreamPoolSize = 5;
internal const int MaxStreamPoolSize = 100;
internal const long StreamPoolExpiryTicks = TimeSpan.TicksPerSecond * 5;
public QuicConnectionContext(QuicConnection connection, QuicTransportContext context)
{
_log = context.Log;
_context = context;
_connection = connection;
ConnectionClosed = _connectionClosedTokenSource.Token;
StreamPool = new PooledStreamStack<QuicStreamContext>(InitialStreamPoolSize);
RemoteEndPoint = connection.RemoteEndPoint;
LocalEndPoint = connection.LocalEndPoint;
InitializeFeatures();
}
public override async ValueTask DisposeAsync()
{
try
{
lock (_shutdownLock)
{
_closeTask ??= _connection.CloseAsync(errorCode: 0).AsTask();
}
await _closeTask;
}
catch (Exception ex)
{
_log.LogWarning(ex, "Failed to gracefully shutdown connection.");
}
_connection.Dispose();
}
public override void Abort() => Abort(new ConnectionAbortedException("The connection was aborted by the application via MultiplexedConnectionContext.Abort()."));
public override void Abort(ConnectionAbortedException abortReason)
{
lock (_shutdownLock)
{
// Check if connection has already been already aborted.
if (_abortReason != null)
{
return;
}
var resolvedErrorCode = _error ?? 0;
_abortReason = ExceptionDispatchInfo.Capture(abortReason);
QuicLog.ConnectionAbort(_log, this, resolvedErrorCode, abortReason.Message);
_closeTask = _connection.CloseAsync(errorCode: resolvedErrorCode).AsTask();
}
}
public override async ValueTask<ConnectionContext?> AcceptAsync(CancellationToken cancellationToken = default)
{
try
{
var stream = await _connection.AcceptStreamAsync(cancellationToken);
QuicStreamContext? context = null;
// Only use pool for bidirectional streams. Just a handful of unidirecitonal
// streams are created for a connection and they live for the lifetime of the connection.
if (stream.CanRead && stream.CanWrite)
{
lock (_poolLock)
{
StreamPool.TryPop(out context);
}
}
if (context == null)
{
context = new QuicStreamContext(this, _context);
}
else
{
context.ResetFeatureCollection();
context.ResetItems();
}
context.Initialize(stream);
context.Start();
QuicLog.AcceptedStream(_log, context);
return context;
}
catch (QuicConnectionAbortedException ex)
{
// Shutdown initiated by peer, abortive.
_error = ex.ErrorCode;
QuicLog.ConnectionAborted(_log, this, ex.ErrorCode, ex);
ThreadPool.UnsafeQueueUserWorkItem(state =>
{
state.CancelConnectionClosedToken();
},
this,
preferLocal: false);
// Throw error so consumer sees the connection is aborted by peer.
throw new ConnectionResetException(ex.Message, ex);
}
catch (QuicOperationAbortedException ex)
{
lock (_shutdownLock)
{
// This error should only happen when shutdown has been initiated by the server.
// If there is no abort reason and we have this error then the connection is in an
// unexpected state. Abort connection and throw reason error.
if (_abortReason == null)
{
Abort(new ConnectionAbortedException("Unexpected error when accepting stream.", ex));
}
_abortReason!.Throw();
}
}
catch (OperationCanceledException)
{
Debug.Assert(cancellationToken.IsCancellationRequested, "Error requires cancellation is requested.");
lock (_shutdownLock)
{
// Connection has been aborted. Throw reason exception.
_abortReason?.Throw();
}
}
catch (Exception ex)
{
Debug.Fail($"Unexpected exception in {nameof(QuicConnectionContext)}.{nameof(AcceptAsync)}: {ex}");
throw;
}
// Return null for graceful closure or cancellation.
return null;
}
private void CancelConnectionClosedToken()
{
try
{
_connectionClosedTokenSource.Cancel();
}
catch (Exception ex)
{
_log.LogError(0, ex, $"Unexpected exception in {nameof(QuicConnectionContext)}.{nameof(CancelConnectionClosedToken)}.");
}
}
public override ValueTask<ConnectionContext> ConnectAsync(IFeatureCollection? features = null, CancellationToken cancellationToken = default)
{
QuicStream quicStream;
var streamDirectionFeature = features?.Get<IStreamDirectionFeature>();
if (streamDirectionFeature != null)
{
if (streamDirectionFeature.CanRead)
{
quicStream = _connection.OpenBidirectionalStream();
}
else
{
quicStream = _connection.OpenUnidirectionalStream();
}
}
else
{
quicStream = _connection.OpenBidirectionalStream();
}
// Only a handful of control streams are created by the server and they last for the
// lifetime of the connection. No value in pooling them.
QuicStreamContext? context = new QuicStreamContext(this, _context);
context.Initialize(quicStream);
context.Start();
QuicLog.ConnectedStream(_log, context);
return new ValueTask<ConnectionContext>(context);
}
internal bool TryReturnStream(QuicStreamContext stream)
{
lock (_poolLock)
{
if (!_streamPoolHeartbeatInitialized)
{
// Heartbeat feature is added to connection features by Kestrel.
// No event is on the context is raised between feature being added and serving
// connections so initialize heartbeat the first time a stream is added to
// the connection's stream pool.
var heartbeatFeature = Features.Get<IConnectionHeartbeatFeature>();
if (heartbeatFeature == null)
{
throw new InvalidOperationException($"Required {nameof(IConnectionHeartbeatFeature)} not found in connection features.");
}
heartbeatFeature.OnHeartbeat(static state => ((QuicConnectionContext)state).RemoveExpiredStreams(), this);
// Set ticks for the first time. Ticks are then updated in heartbeat.
var now = _context.Options.SystemClock.UtcNow.Ticks;
Volatile.Write(ref _heartbeatTicks, now);
_streamPoolHeartbeatInitialized = true;
}
if (stream.CanReuse && StreamPool.Count < MaxStreamPoolSize)
{
stream.PoolExpirationTicks = Volatile.Read(ref _heartbeatTicks) + StreamPoolExpiryTicks;
StreamPool.Push(stream);
return true;
}
}
return false;
}
private void RemoveExpiredStreams()
{
lock (_poolLock)
{
// Update ticks on heartbeat. A precise value isn't necessary.
var now = _context.Options.SystemClock.UtcNow.Ticks;
Volatile.Write(ref _heartbeatTicks, now);
StreamPool.RemoveExpired(now);
}
}
}
}
| |
// This code was written for the OpenTK library and has been released
// to the Public Domain.
// It is provided "as is" without express or implied warranty of any kind.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Threading;
using OpenTK;
using OpenTK.Graphics;
using OpenTK.Graphics.OpenGL;
using OpenTK.Input;
namespace Examples.Tutorial
{
/// <summary>
/// Demonstrates how to decouple rendering from the main thread.
/// Note that all OpenGL function calls should take place at the rendering thread -
/// OpenGL will not be available on the main thread at all!
/// </summary>
[Example("GameWindow Threaded", ExampleCategory.OpenTK, "GameWindow", 3, Documentation = "GameWindowThreaded")]
public class ThreadedRendering : GameWindow
{
bool viewport_changed = true;
int viewport_width, viewport_height;
bool position_changed = true;
int position_x, position_y;
float position_dx, position_dy;
bool exit = false;
Thread rendering_thread;
object update_lock = new object();
const float GravityAccel = -9.81f;
struct Particle
{
public Vector2 Position;
public Vector2 Velocity;
public Color4 Color;
}
List<Particle> Particles = new List<Particle>();
Random rand = new Random();
public ThreadedRendering()
: base(800, 600)
{
Keyboard.KeyDown += delegate(object sender, KeyboardKeyEventArgs e)
{
if (e.Key == Key.Escape)
this.Exit();
};
Keyboard.KeyUp += delegate(object sender, KeyboardKeyEventArgs e)
{
if (e.Key == Key.F11)
if (this.WindowState == WindowState.Fullscreen)
this.WindowState = WindowState.Normal;
else
this.WindowState = WindowState.Fullscreen;
};
Resize += delegate(object sender, EventArgs e)
{
// Note that we cannot call any OpenGL methods directly. What we can do is set
// a flag and respond to it from the rendering thread.
lock (update_lock)
{
viewport_changed = true;
viewport_width = Width;
viewport_height = Height;
}
};
Move += delegate(object sender, EventArgs e)
{
// Note that we cannot call any OpenGL methods directly. What we can do is set
// a flag and respond to it from the rendering thread.
lock (update_lock)
{
position_changed = true;
position_dx = (position_x - X) / (float)Width;
position_dy = (position_y - Y) / (float)Height;
position_x = X;
position_y = Y;
}
};
// Make sure initial position are correct, otherwise we'll give a huge
// initial velocity to the balls.
position_x = X;
position_y = Y;
}
#region OnLoad
/// <summary>
/// Setup OpenGL and load resources here.
/// </summary>
/// <param name="e">Not used.</param>
protected override void OnLoad(EventArgs e)
{
Context.MakeCurrent(null); // Release the OpenGL context so it can be used on the new thread.
rendering_thread = new Thread(RenderLoop);
rendering_thread.IsBackground = true;
rendering_thread.Start();
}
#endregion
#region OnUnload
/// <summary>
/// Release resources here.
/// </summary>
/// <param name="e">Not used.</param>
protected override void OnUnload(EventArgs e)
{
exit = true; // Set a flag that the rendering thread should stop running.
rendering_thread.Join();
base.OnUnload(e);
}
#endregion
#region OnUpdateFrame
/// <summary>
/// Add your game logic here.
/// </summary>
/// <param name="e">Contains timing information.</param>
/// <remarks>There is no need to call the base implementation.</remarks>
protected override void OnUpdateFrame(FrameEventArgs e)
{
// Nothing to do!
}
#endregion
#region OnRenderFrame
/// <summary>
/// Ignored. All rendering is performed on our own rendering function.
/// </summary>
/// <param name="e">Contains timing information.</param>
/// <remarks>There is no need to call the base implementation.</remarks>
protected override void OnRenderFrame(FrameEventArgs e)
{
// Nothing to do. Release the CPU to other threads.
Thread.Sleep(1);
}
#endregion
#region RenderLoop
void RenderLoop()
{
MakeCurrent(); // The context now belongs to this thread. No other thread may use it!
VSync = VSyncMode.On;
for (int i = 0; i < 64; i++)
{
Particle p = new Particle();
p.Position = new Vector2((float)rand.NextDouble() * 2 - 1, (float)rand.NextDouble() * 2 - 1);
p.Color.R = (float)rand.NextDouble();
p.Color.G = (float)rand.NextDouble();
p.Color.B = (float)rand.NextDouble();
Particles.Add(p);
}
// Since we don't use OpenTK's timing mechanism, we need to keep time ourselves;
Stopwatch render_watch = new Stopwatch();
Stopwatch update_watch = new Stopwatch();
update_watch.Start();
render_watch.Start();
GL.ClearColor(Color.MidnightBlue);
GL.Enable(EnableCap.DepthTest);
GL.Enable(EnableCap.PointSmooth);
GL.PointSize(16);
while (!exit)
{
Update(update_watch.Elapsed.TotalSeconds);
update_watch.Reset();
update_watch.Start();
Render(render_watch.Elapsed.TotalSeconds);
render_watch.Reset(); // Stopwatch may be inaccurate over larger intervals.
render_watch.Start(); // Plus, timekeeping is easier if we always start counting from 0.
SwapBuffers();
}
Context.MakeCurrent(null);
}
#endregion
#region Update
void Update(double time)
{
lock (update_lock)
{
// When the user moves the window we make the particles react to
// this movement. The reaction is semi-random and not physically
// correct. It looks quite good, however.
if (position_changed)
{
for (int i = 0; i < Particles.Count; i++)
{
Particle p = Particles[i];
p.Velocity += new Vector2(
16 * (position_dx + 0.05f * (float)(rand.NextDouble() - 0.5)),
32 * (position_dy + 0.05f * (float)(rand.NextDouble() - 0.5)));
Particles[i] = p;
}
position_changed = false;
}
}
// For simplicity, we use simple Euler integration to simulate particle movement.
// This is not accurate, especially under varying timesteps (as is the case here).
// A better solution would have been time-corrected Verlet integration, as
// described here:
// http://www.gamedev.net/reference/programming/features/verlet/
for (int i = 0; i < Particles.Count; i++)
{
Particle p = Particles[i];
p.Velocity.X = Math.Abs(p.Position.X) >= 1 ?-p.Velocity.X * 0.92f : p.Velocity.X * 0.97f;
p.Velocity.Y = Math.Abs(p.Position.Y) >= 1 ? -p.Velocity.Y * 0.92f : p.Velocity.Y * 0.97f;
if (p.Position.Y > -0.99)
{
p.Velocity.Y += (float)(GravityAccel * time);
}
else
{
if (Math.Abs(p.Velocity.Y) < 0.02)
{
p.Velocity.Y = 0;
p.Position.Y = -1;
}
else
{
p.Velocity.Y *= 0.9f;
}
}
p.Position += p.Velocity * (float)time;
if (p.Position.Y <= -1)
p.Position.Y = -1;
Particles[i] = p;
}
}
#endregion
#region Render
/// <summary>
/// This is our main rendering function, which executes on the rendering thread.
/// </summary>
public void Render(double time)
{
lock (update_lock)
{
if (viewport_changed)
{
GL.Viewport(0, 0, viewport_width, viewport_height);
viewport_changed = false;
}
}
Matrix4 perspective =
Matrix4.CreateOrthographic(2, 2, -1, 1);
GL.MatrixMode(MatrixMode.Projection);
GL.LoadMatrix(ref perspective);
GL.MatrixMode(MatrixMode.Modelview);
GL.LoadIdentity();
GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);
GL.Begin(BeginMode.Points);
foreach (Particle p in Particles)
{
GL.Color4(p.Color);
GL.Vertex2(p.Position);
}
GL.End();
}
#endregion
#region public static void Main()
/// <summary>
/// Entry point of this example.
/// </summary>
[STAThread]
public static void Main()
{
using (GameWindow example = new ThreadedRendering())
{
// Get the title and category of this example using reflection.
Utilities.SetWindowTitle(example);
example.Run();
}
}
#endregion
}
}
| |
/*
* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using Newtonsoft.Json;
namespace XenAPI
{
/// <summary>
/// A placeholder for a binary blob
/// First published in XenServer 5.0.
/// </summary>
public partial class Blob : XenObject<Blob>
{
#region Constructors
public Blob()
{
}
public Blob(string uuid,
string name_label,
string name_description,
long size,
bool pubblic,
DateTime last_updated,
string mime_type)
{
this.uuid = uuid;
this.name_label = name_label;
this.name_description = name_description;
this.size = size;
this.pubblic = pubblic;
this.last_updated = last_updated;
this.mime_type = mime_type;
}
/// <summary>
/// Creates a new Blob from a Hashtable.
/// Note that the fields not contained in the Hashtable
/// will be created with their default values.
/// </summary>
/// <param name="table"></param>
public Blob(Hashtable table)
: this()
{
UpdateFrom(table);
}
/// <summary>
/// Creates a new Blob from a Proxy_Blob.
/// </summary>
/// <param name="proxy"></param>
public Blob(Proxy_Blob proxy)
{
UpdateFrom(proxy);
}
#endregion
/// <summary>
/// Updates each field of this instance with the value of
/// the corresponding field of a given Blob.
/// </summary>
public override void UpdateFrom(Blob update)
{
uuid = update.uuid;
name_label = update.name_label;
name_description = update.name_description;
size = update.size;
pubblic = update.pubblic;
last_updated = update.last_updated;
mime_type = update.mime_type;
}
internal void UpdateFrom(Proxy_Blob proxy)
{
uuid = proxy.uuid == null ? null : proxy.uuid;
name_label = proxy.name_label == null ? null : proxy.name_label;
name_description = proxy.name_description == null ? null : proxy.name_description;
size = proxy.size == null ? 0 : long.Parse(proxy.size);
pubblic = (bool)proxy.pubblic;
last_updated = proxy.last_updated;
mime_type = proxy.mime_type == null ? null : proxy.mime_type;
}
public Proxy_Blob ToProxy()
{
Proxy_Blob result_ = new Proxy_Blob();
result_.uuid = uuid ?? "";
result_.name_label = name_label ?? "";
result_.name_description = name_description ?? "";
result_.size = size.ToString();
result_.pubblic = pubblic;
result_.last_updated = last_updated;
result_.mime_type = mime_type ?? "";
return result_;
}
/// <summary>
/// Given a Hashtable with field-value pairs, it updates the fields of this Blob
/// with the values listed in the Hashtable. Note that only the fields contained
/// in the Hashtable will be updated and the rest will remain the same.
/// </summary>
/// <param name="table"></param>
public void UpdateFrom(Hashtable table)
{
if (table.ContainsKey("uuid"))
uuid = Marshalling.ParseString(table, "uuid");
if (table.ContainsKey("name_label"))
name_label = Marshalling.ParseString(table, "name_label");
if (table.ContainsKey("name_description"))
name_description = Marshalling.ParseString(table, "name_description");
if (table.ContainsKey("size"))
size = Marshalling.ParseLong(table, "size");
if (table.ContainsKey("pubblic"))
pubblic = Marshalling.ParseBool(table, "pubblic");
if (table.ContainsKey("last_updated"))
last_updated = Marshalling.ParseDateTime(table, "last_updated");
if (table.ContainsKey("mime_type"))
mime_type = Marshalling.ParseString(table, "mime_type");
}
public bool DeepEquals(Blob other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
return Helper.AreEqual2(this._uuid, other._uuid) &&
Helper.AreEqual2(this._name_label, other._name_label) &&
Helper.AreEqual2(this._name_description, other._name_description) &&
Helper.AreEqual2(this._size, other._size) &&
Helper.AreEqual2(this._pubblic, other._pubblic) &&
Helper.AreEqual2(this._last_updated, other._last_updated) &&
Helper.AreEqual2(this._mime_type, other._mime_type);
}
internal static List<Blob> ProxyArrayToObjectList(Proxy_Blob[] input)
{
var result = new List<Blob>();
foreach (var item in input)
result.Add(new Blob(item));
return result;
}
public override string SaveChanges(Session session, string opaqueRef, Blob server)
{
if (opaqueRef == null)
{
System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server");
return "";
}
else
{
if (!Helper.AreEqual2(_name_label, server._name_label))
{
Blob.set_name_label(session, opaqueRef, _name_label);
}
if (!Helper.AreEqual2(_name_description, server._name_description))
{
Blob.set_name_description(session, opaqueRef, _name_description);
}
return null;
}
}
/// <summary>
/// Get a record containing the current state of the given blob.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_blob">The opaque_ref of the given blob</param>
public static Blob get_record(Session session, string _blob)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.blob_get_record(session.opaque_ref, _blob);
else
return new Blob(session.XmlRpcProxy.blob_get_record(session.opaque_ref, _blob ?? "").parse());
}
/// <summary>
/// Get a reference to the blob instance with the specified UUID.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_uuid">UUID of object to return</param>
public static XenRef<Blob> get_by_uuid(Session session, string _uuid)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.blob_get_by_uuid(session.opaque_ref, _uuid);
else
return XenRef<Blob>.Create(session.XmlRpcProxy.blob_get_by_uuid(session.opaque_ref, _uuid ?? "").parse());
}
/// <summary>
/// Get all the blob instances with the given label.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_label">label of object to return</param>
public static List<XenRef<Blob>> get_by_name_label(Session session, string _label)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.blob_get_by_name_label(session.opaque_ref, _label);
else
return XenRef<Blob>.Create(session.XmlRpcProxy.blob_get_by_name_label(session.opaque_ref, _label ?? "").parse());
}
/// <summary>
/// Get the uuid field of the given blob.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_blob">The opaque_ref of the given blob</param>
public static string get_uuid(Session session, string _blob)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.blob_get_uuid(session.opaque_ref, _blob);
else
return session.XmlRpcProxy.blob_get_uuid(session.opaque_ref, _blob ?? "").parse();
}
/// <summary>
/// Get the name/label field of the given blob.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_blob">The opaque_ref of the given blob</param>
public static string get_name_label(Session session, string _blob)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.blob_get_name_label(session.opaque_ref, _blob);
else
return session.XmlRpcProxy.blob_get_name_label(session.opaque_ref, _blob ?? "").parse();
}
/// <summary>
/// Get the name/description field of the given blob.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_blob">The opaque_ref of the given blob</param>
public static string get_name_description(Session session, string _blob)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.blob_get_name_description(session.opaque_ref, _blob);
else
return session.XmlRpcProxy.blob_get_name_description(session.opaque_ref, _blob ?? "").parse();
}
/// <summary>
/// Get the size field of the given blob.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_blob">The opaque_ref of the given blob</param>
public static long get_size(Session session, string _blob)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.blob_get_size(session.opaque_ref, _blob);
else
return long.Parse(session.XmlRpcProxy.blob_get_size(session.opaque_ref, _blob ?? "").parse());
}
/// <summary>
/// Get the public field of the given blob.
/// First published in XenServer 6.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_blob">The opaque_ref of the given blob</param>
public static bool get_public(Session session, string _blob)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.blob_get_public(session.opaque_ref, _blob);
else
return (bool)session.XmlRpcProxy.blob_get_public(session.opaque_ref, _blob ?? "").parse();
}
/// <summary>
/// Get the last_updated field of the given blob.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_blob">The opaque_ref of the given blob</param>
public static DateTime get_last_updated(Session session, string _blob)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.blob_get_last_updated(session.opaque_ref, _blob);
else
return session.XmlRpcProxy.blob_get_last_updated(session.opaque_ref, _blob ?? "").parse();
}
/// <summary>
/// Get the mime_type field of the given blob.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_blob">The opaque_ref of the given blob</param>
public static string get_mime_type(Session session, string _blob)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.blob_get_mime_type(session.opaque_ref, _blob);
else
return session.XmlRpcProxy.blob_get_mime_type(session.opaque_ref, _blob ?? "").parse();
}
/// <summary>
/// Set the name/label field of the given blob.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_blob">The opaque_ref of the given blob</param>
/// <param name="_label">New value to set</param>
public static void set_name_label(Session session, string _blob, string _label)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.blob_set_name_label(session.opaque_ref, _blob, _label);
else
session.XmlRpcProxy.blob_set_name_label(session.opaque_ref, _blob ?? "", _label ?? "").parse();
}
/// <summary>
/// Set the name/description field of the given blob.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_blob">The opaque_ref of the given blob</param>
/// <param name="_description">New value to set</param>
public static void set_name_description(Session session, string _blob, string _description)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.blob_set_name_description(session.opaque_ref, _blob, _description);
else
session.XmlRpcProxy.blob_set_name_description(session.opaque_ref, _blob ?? "", _description ?? "").parse();
}
/// <summary>
/// Set the public field of the given blob.
/// First published in XenServer 6.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_blob">The opaque_ref of the given blob</param>
/// <param name="_public">New value to set</param>
public static void set_public(Session session, string _blob, bool _public)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.blob_set_public(session.opaque_ref, _blob, _public);
else
session.XmlRpcProxy.blob_set_public(session.opaque_ref, _blob ?? "", _public).parse();
}
/// <summary>
/// Create a placeholder for a binary blob
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_mime_type">The mime-type of the blob. Defaults to 'application/octet-stream' if the empty string is supplied</param>
public static XenRef<Blob> create(Session session, string _mime_type)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.blob_create(session.opaque_ref, _mime_type);
else
return XenRef<Blob>.Create(session.XmlRpcProxy.blob_create(session.opaque_ref, _mime_type ?? "").parse());
}
/// <summary>
/// Create a placeholder for a binary blob
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_mime_type">The mime-type of the blob. Defaults to 'application/octet-stream' if the empty string is supplied</param>
/// <param name="_public">True if the blob should be publicly available First published in XenServer 6.1.</param>
public static XenRef<Blob> create(Session session, string _mime_type, bool _public)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.blob_create(session.opaque_ref, _mime_type, _public);
else
return XenRef<Blob>.Create(session.XmlRpcProxy.blob_create(session.opaque_ref, _mime_type ?? "", _public).parse());
}
/// <summary>
///
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_blob">The opaque_ref of the given blob</param>
public static void destroy(Session session, string _blob)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.blob_destroy(session.opaque_ref, _blob);
else
session.XmlRpcProxy.blob_destroy(session.opaque_ref, _blob ?? "").parse();
}
/// <summary>
/// Return a list of all the blobs known to the system.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
public static List<XenRef<Blob>> get_all(Session session)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.blob_get_all(session.opaque_ref);
else
return XenRef<Blob>.Create(session.XmlRpcProxy.blob_get_all(session.opaque_ref).parse());
}
/// <summary>
/// Get all the blob Records at once, in a single XML RPC call
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
public static Dictionary<XenRef<Blob>, Blob> get_all_records(Session session)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.blob_get_all_records(session.opaque_ref);
else
return XenRef<Blob>.Create<Proxy_Blob>(session.XmlRpcProxy.blob_get_all_records(session.opaque_ref).parse());
}
/// <summary>
/// Unique identifier/object reference
/// </summary>
public virtual string uuid
{
get { return _uuid; }
set
{
if (!Helper.AreEqual(value, _uuid))
{
_uuid = value;
NotifyPropertyChanged("uuid");
}
}
}
private string _uuid = "";
/// <summary>
/// a human-readable name
/// </summary>
public virtual string name_label
{
get { return _name_label; }
set
{
if (!Helper.AreEqual(value, _name_label))
{
_name_label = value;
NotifyPropertyChanged("name_label");
}
}
}
private string _name_label = "";
/// <summary>
/// a notes field containing human-readable description
/// </summary>
public virtual string name_description
{
get { return _name_description; }
set
{
if (!Helper.AreEqual(value, _name_description))
{
_name_description = value;
NotifyPropertyChanged("name_description");
}
}
}
private string _name_description = "";
/// <summary>
/// Size of the binary data, in bytes
/// </summary>
public virtual long size
{
get { return _size; }
set
{
if (!Helper.AreEqual(value, _size))
{
_size = value;
NotifyPropertyChanged("size");
}
}
}
private long _size;
/// <summary>
/// True if the blob is publicly accessible
/// First published in XenServer 6.1.
/// </summary>
public virtual bool pubblic
{
get { return _pubblic; }
set
{
if (!Helper.AreEqual(value, _pubblic))
{
_pubblic = value;
NotifyPropertyChanged("pubblic");
}
}
}
private bool _pubblic = false;
/// <summary>
/// Time at which the data in the blob was last updated
/// </summary>
[JsonConverter(typeof(XenDateTimeConverter))]
public virtual DateTime last_updated
{
get { return _last_updated; }
set
{
if (!Helper.AreEqual(value, _last_updated))
{
_last_updated = value;
NotifyPropertyChanged("last_updated");
}
}
}
private DateTime _last_updated;
/// <summary>
/// The mime type associated with this object. Defaults to 'application/octet-stream' if the empty string is supplied
/// </summary>
public virtual string mime_type
{
get { return _mime_type; }
set
{
if (!Helper.AreEqual(value, _mime_type))
{
_mime_type = value;
NotifyPropertyChanged("mime_type");
}
}
}
private string _mime_type = "";
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.Arm;
namespace JIT.HardwareIntrinsics.Arm
{
public static partial class Program
{
private static void AbsByte()
{
var test = new SimpleUnaryOpTest__AbsByte();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (AdvSimd.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleUnaryOpTest__AbsByte
{
private struct DataTable
{
private byte[] inArray1;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle outHandle;
private ulong alignment;
public DataTable(SByte[] inArray1, Byte[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<SByte>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Byte>();
if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<SByte, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<SByte> _fld1;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (sbyte)-TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref testStruct._fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>());
return testStruct;
}
public void RunStructFldScenario(SimpleUnaryOpTest__AbsByte testClass)
{
var result = AdvSimd.Abs(_fld1);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleUnaryOpTest__AbsByte testClass)
{
fixed (Vector128<SByte>* pFld1 = &_fld1)
{
var result = AdvSimd.Abs(
AdvSimd.LoadVector128((SByte*)(pFld1))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<SByte>>() / sizeof(SByte);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte);
private static SByte[] _data1 = new SByte[Op1ElementCount];
private static Vector128<SByte> _clsVar1;
private Vector128<SByte> _fld1;
private DataTable _dataTable;
static SimpleUnaryOpTest__AbsByte()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (sbyte)-TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _clsVar1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>());
}
public SimpleUnaryOpTest__AbsByte()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (sbyte)-TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (sbyte)-TestLibrary.Generator.GetSByte(); }
_dataTable = new DataTable(_data1, new Byte[RetElementCount], LargestVectorSize);
}
public bool IsSupported => AdvSimd.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = AdvSimd.Abs(
Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = AdvSimd.Abs(
AdvSimd.LoadVector128((SByte*)(_dataTable.inArray1Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.Abs), new Type[] { typeof(Vector128<SByte>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.Abs), new Type[] { typeof(Vector128<SByte>) })
.Invoke(null, new object[] {
AdvSimd.LoadVector128((SByte*)(_dataTable.inArray1Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = AdvSimd.Abs(
_clsVar1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<SByte>* pClsVar1 = &_clsVar1)
{
var result = AdvSimd.Abs(
AdvSimd.LoadVector128((SByte*)(pClsVar1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr);
var result = AdvSimd.Abs(op1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = AdvSimd.LoadVector128((SByte*)(_dataTable.inArray1Ptr));
var result = AdvSimd.Abs(op1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleUnaryOpTest__AbsByte();
var result = AdvSimd.Abs(test._fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleUnaryOpTest__AbsByte();
fixed (Vector128<SByte>* pFld1 = &test._fld1)
{
var result = AdvSimd.Abs(
AdvSimd.LoadVector128((SByte*)(pFld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = AdvSimd.Abs(_fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<SByte>* pFld1 = &_fld1)
{
var result = AdvSimd.Abs(
AdvSimd.LoadVector128((SByte*)(pFld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = AdvSimd.Abs(test._fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = AdvSimd.Abs(
AdvSimd.LoadVector128((SByte*)(&test._fld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<SByte> op1, void* result, [CallerMemberName] string method = "")
{
SByte[] inArray1 = new SByte[Op1ElementCount];
Byte[] outArray = new Byte[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), op1);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Byte>>());
ValidateResult(inArray1, outArray, method);
}
private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "")
{
SByte[] inArray1 = new SByte[Op1ElementCount];
Byte[] outArray = new Byte[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<SByte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Byte>>());
ValidateResult(inArray1, outArray, method);
}
private void ValidateResult(SByte[] firstOp, Byte[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (result[0] != (byte)Math.Abs(firstOp[0]))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != (byte)Math.Abs(firstOp[i]))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.Abs)}<Byte>(Vector128<SByte>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Symbology.dll
// Description: Contains the business logic for symbology layers and symbol categories.
// ********************************************************************************************************
//
// The Original Code is from MapWindow.dll version 6.0
//
// The Initial Developer of this Original Code is Ted Dunsford. Created 11/5/2009 9:37:56 AM
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
//
// ********************************************************************************************************
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using DotSpatial.Data;
using DotSpatial.NTSExtension;
using GeoAPI.Geometries;
namespace DotSpatial.Symbology
{
public class IndexSelection : Changeable, IIndexSelection
{
#region IIndexSelection Members
/// <summary>
/// Adds all of the specified index values to the selection
/// </summary>
/// <param name="indices">The indices to add</param>
public void AddRange(IEnumerable<int> indices)
{
foreach (int index in indices)
{
_layer.DrawnStates[index].Selected = SelectionState;
}
OnChanged();
}
/// <summary>
/// Add REgion
/// </summary>
/// <param name="region"></param>
/// <param name="affectedArea"></param>
/// <returns></returns>
public bool AddRegion(Envelope region, out Envelope affectedArea)
{
bool added = false;
SuspendChanges();
Extent affected = new Extent();
IPolygon reg = region.ToPolygon();
for (int shp = 0; shp < _layer.DrawnStates.Length; shp++)
{
if (RegionCategory != null && _layer.DrawnStates[shp].Category != RegionCategory) continue;
bool doAdd = false;
ShapeRange shape = _shapes[shp];
if (SelectionMode == SelectionMode.Intersects)
{
// Prevent geometry creation (which is slow) and use ShapeRange instead
ShapeRange env = new ShapeRange(region);
if (env.Intersects(shape))
{
_layer.DrawnStates[shp].Selected = SelectionState;
affected.ExpandToInclude(shape.Extent);
added = true;
OnChanged();
}
}
else if (SelectionMode == SelectionMode.IntersectsExtent)
{
if (shape.Extent.Intersects(region))
{
_layer.DrawnStates[shp].Selected = SelectionState;
affected.ExpandToInclude(shape.Extent);
added = true;
OnChanged();
}
}
else if (SelectionMode == SelectionMode.ContainsExtent)
{
if (shape.Extent.Within(region))
{
_layer.DrawnStates[shp].Selected = SelectionState;
affected.ExpandToInclude(shape.Extent);
added = true;
OnChanged();
}
}
else if (SelectionMode == SelectionMode.Disjoint)
{
if (shape.Extent.Intersects(region))
{
IGeometry g = _layer.DataSet.GetFeature(shp).Geometry;
if (reg.Disjoint(g)) doAdd = true;
}
else
{
doAdd = true;
}
}
else
{
if (!shape.Extent.Intersects(region)) continue;
IGeometry geom = _layer.DataSet.GetFeature(shp).Geometry;
switch (SelectionMode)
{
case SelectionMode.Contains:
if (shape.Extent.Within(region))
{
doAdd = true;
}
else if (shape.Extent.Intersects(region))
{
if (reg.Contains(geom)) doAdd = true;
}
break;
case SelectionMode.CoveredBy:
if (reg.CoveredBy(geom)) doAdd = true;
break;
case SelectionMode.Covers:
if (reg.Covers(geom)) doAdd = true;
break;
case SelectionMode.Intersects:
if (shape.Extent.Within(region))
{
doAdd = true;
}
else if (shape.Extent.Intersects(region))
{
if (reg.Intersects(geom)) doAdd = true;
}
break;
case SelectionMode.Overlaps:
if (reg.Overlaps(geom)) doAdd = true;
break;
case SelectionMode.Touches:
if (reg.Touches(geom)) doAdd = true;
break;
case SelectionMode.Within:
if (reg.Within(geom)) doAdd = true;
break;
}
}
if (!doAdd) continue;
OnChanged();
_layer.DrawnStates[shp].Selected = SelectionState;
affected.ExpandToInclude(shape.Extent);
added = true;
}
ResumeChanges();
affectedArea = affected.ToEnvelope();
return added;
}
/// <summary>
///
/// </summary>
/// <param name="region"></param>
/// <param name="affectedArea"></param>
/// <returns></returns>
public bool InvertSelection(Envelope region, out Envelope affectedArea)
{
SuspendChanges();
bool flipped = false;
Extent affected = new Extent();
IPolygon reg = region.ToPolygon();
for (int shp = 0; shp < _layer.DrawnStates.Length; shp++)
{
if (RegionCategory != null && _layer.DrawnStates[shp].Category != RegionCategory) continue;
bool doFlip = false;
ShapeRange shape = _shapes[shp];
if (SelectionMode == SelectionMode.Intersects)
{
// Prevent geometry creation (which is slow) and use ShapeRange instead
ShapeRange env = new ShapeRange(region);
if (env.Intersects(shape))
{
_layer.DrawnStates[shp].Selected = !_layer.DrawnStates[shp].Selected;
affected.ExpandToInclude(shape.Extent);
flipped = true;
OnChanged();
}
}
else if (SelectionMode == SelectionMode.IntersectsExtent)
{
if (shape.Extent.Intersects(region))
{
_layer.DrawnStates[shp].Selected = !_layer.DrawnStates[shp].Selected;
affected.ExpandToInclude(shape.Extent);
flipped = true;
OnChanged();
}
}
else if (SelectionMode == SelectionMode.ContainsExtent)
{
if (shape.Extent.Within(region))
{
_layer.DrawnStates[shp].Selected = !_layer.DrawnStates[shp].Selected;
affected.ExpandToInclude(shape.Extent);
flipped = true;
OnChanged();
}
}
else if (SelectionMode == SelectionMode.Disjoint)
{
if (shape.Extent.Intersects(region))
{
IGeometry g = _layer.DataSet.GetFeature(shp).Geometry;
if (reg.Disjoint(g)) doFlip = true;
}
else
{
doFlip = true;
}
}
else
{
if (!shape.Extent.Intersects(region)) continue;
IGeometry geom = _layer.DataSet.GetFeature(shp).Geometry; // only get this if envelopes intersect
switch (SelectionMode)
{
case SelectionMode.Contains:
if (region.Intersects(geom.EnvelopeInternal))
{
if (reg.Contains(geom)) doFlip = true;
}
break;
case SelectionMode.CoveredBy:
if (reg.CoveredBy(geom)) doFlip = true;
break;
case SelectionMode.Covers:
if (reg.Covers(geom)) doFlip = true;
break;
case SelectionMode.Intersects:
if (region.Intersects(geom.EnvelopeInternal))
{
if (reg.Intersects(geom)) doFlip = true;
}
break;
case SelectionMode.Overlaps:
if (reg.Overlaps(geom)) doFlip = true;
break;
case SelectionMode.Touches:
if (reg.Touches(geom)) doFlip = true;
break;
case SelectionMode.Within:
if (reg.Within(geom)) doFlip = true;
break;
}
}
if (!doFlip) continue;
flipped = true;
OnChanged();
_layer.DrawnStates[shp].Selected = !_layer.DrawnStates[shp].Selected;
affected.ExpandToInclude(shape.Extent);
}
affectedArea = affected.ToEnvelope();
ResumeChanges();
return flipped;
}
/// <summary>
/// Attempts to remove all the members from the collection. If
/// one of the specified indices is outside the range of possible
/// values, this returns false, even if others were successfully removed.
/// This will also return false if none of the states were changed.
/// </summary>
/// <param name="indices">The indices to remove</param>
/// <returns></returns>
public bool RemoveRange(IEnumerable<int> indices)
{
bool problem = false;
bool changed = false;
FastDrawnState[] drawnStates = _layer.DrawnStates;
foreach (int index in indices)
{
if (index < 0 || index > drawnStates.Length)
{
problem = true;
}
else
{
if (drawnStates[index].Selected != !SelectionState) changed = true;
drawnStates[index].Selected = !SelectionState;
}
}
return !problem && changed;
}
/// <summary>
///
/// </summary>
/// <param name="region"></param>
/// <param name="affectedArea"></param>
/// <returns></returns>
public bool RemoveRegion(Envelope region, out Envelope affectedArea)
{
bool removed = false;
SuspendChanges();
Extent affected = new Extent();
IPolygon reg = region.ToPolygon();
for (int shp = 0; shp < _layer.DrawnStates.Length; shp++)
{
if (RegionCategory != null && _layer.DrawnStates[shp].Category != RegionCategory) continue;
bool doRemove = false;
ShapeRange shape = _shapes[shp];
if (SelectionMode == SelectionMode.Intersects)
{
// Prevent geometry creation (which is slow) and use ShapeRange instead
ShapeRange env = new ShapeRange(region);
if (env.Intersects(shape))
{
_layer.DrawnStates[shp].Selected = !SelectionState;
affected.ExpandToInclude(shape.Extent);
removed = true;
}
}
else if (SelectionMode == SelectionMode.IntersectsExtent)
{
if (shape.Extent.Intersects(region))
{
_layer.DrawnStates[shp].Selected = !SelectionState;
affected.ExpandToInclude(shape.Extent);
removed = true;
}
}
else if (SelectionMode == SelectionMode.ContainsExtent)
{
if (shape.Extent.Within(region))
{
_layer.DrawnStates[shp].Selected = !SelectionState;
affected.ExpandToInclude(shape.Extent);
removed = true;
}
}
else if (SelectionMode == SelectionMode.Disjoint)
{
if (shape.Extent.Intersects(region))
{
IGeometry g = _layer.DataSet.Features[shp].Geometry;
if (reg.Disjoint(g)) doRemove = true;
}
else
{
doRemove = true;
}
}
else
{
if (!shape.Extent.Intersects(region)) continue;
IGeometry geom = _layer.DataSet.Features[shp].Geometry;
switch (SelectionMode)
{
case SelectionMode.Contains:
if (shape.Extent.Within(region))
{
doRemove = true;
}
else if (shape.Extent.Intersects(region))
{
if (reg.Contains(geom)) doRemove = true;
}
break;
case SelectionMode.CoveredBy:
if (reg.CoveredBy(geom)) doRemove = true;
break;
case SelectionMode.Covers:
if (reg.Covers(geom)) doRemove = true;
break;
case SelectionMode.Intersects:
if (shape.Extent.Within(region))
{
doRemove = true;
}
else if (shape.Extent.Intersects(region))
{
if (reg.Intersects(geom)) doRemove = true;
}
break;
case SelectionMode.Overlaps:
if (reg.Overlaps(geom)) doRemove = true;
break;
case SelectionMode.Touches:
if (reg.Touches(geom)) doRemove = true;
break;
case SelectionMode.Within:
if (reg.Within(geom)) doRemove = true;
break;
}
}
if (!doRemove) continue;
OnChanged();
_layer.DrawnStates[shp].Selected = !SelectionState;
affected.ExpandToInclude(shape.Extent);
removed = true;
}
affectedArea = affected.ToEnvelope();
ResumeChanges();
return removed;
}
/// <summary>
/// Returns a new featureset based on the features in this collection
/// </summary>
/// <returns></returns>
public FeatureSet ToFeatureSet()
{
FeatureSet fs = new FeatureSet(ToFeatureList());
fs.Projection = _layer.DataSet.Projection;
return fs;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public List<IFeature> ToFeatureList()
{
List<IFeature> result = new List<IFeature>();
FastDrawnState[] drawnStates = _layer.DrawnStates;
for (int shp = 0; shp < drawnStates.Length; shp++)
{
if (drawnStates[shp].Selected == SelectionState)
{
result.Add(_layer.DataSet.GetFeature(shp));
}
}
return result;
}
/// <summary>
/// Calculates the envelope of this collection
/// </summary>
public Envelope Envelope
{
get
{
if (!_layer.DrawnStatesNeeded) return new Envelope();
Extent ext = new Extent();
FastDrawnState[] drawnStates = _layer.DrawnStates;
for (int shp = 0; shp < drawnStates.Length; shp++)
{
if (drawnStates[shp].Selected == SelectionState)
{
ext.ExpandToInclude(_shapes[shp].Extent);
}
}
return ext.ToEnvelope();
}
}
/// <summary>
/// Selection Mode controls how envelopes are treated when working with geometries.
/// </summary>
public SelectionMode SelectionMode { get; set; }
/// <summary>
/// Gets or sets whether this should work as "Selected" indices (true) or
/// "UnSelected" indices (false).
/// </summary>
public bool SelectionState { get; set; }
/// <inheritdoc />
public DataTable GetAttributes(int startIndex, int numRows)
{
return GetAttributes(startIndex, numRows, _layer.DataSet.GetColumns().Select(d => d.ColumnName));
}
/// <inheritdoc />
public DataTable GetAttributes(int startIndex, int numRows, IEnumerable<string> fieldNames)
{
var c = new AttributeCache(_layer.DataSet, numRows);
var fn = new HashSet<string>(fieldNames);
var result = new DataTable();
foreach (DataColumn col in _layer.DataSet.GetColumns())
{
if (fn.Contains(col.ColumnName))
{
result.Columns.Add(col);
}
}
int i = 0;
FastDrawnState[] drawnStates = _layer.DrawnStates;
for (int fid = 0; fid < drawnStates.Length; fid++)
{
if (drawnStates[fid].Selected)
{
i++;
if (i < startIndex) continue;
DataRow dr = result.NewRow();
Dictionary<string, object> vals = c.RetrieveElement(fid);
foreach (KeyValuePair<string, object> pair in vals)
{
if (fn.Contains(pair.Key))
dr[pair.Key] = pair.Value;
}
result.Rows.Add(dr);
if (i > startIndex + numRows) break;
}
}
return result;
}
/// <inheritdoc />
public void SetAttributes(int startIndex, DataTable values)
{
FastDrawnState[] drawnStates = _layer.DrawnStates;
int sind = -1;
for (int fid = 0; fid < drawnStates.Length; fid++)
{
if (drawnStates[fid].Selected)
{
sind++;
if (sind > startIndex + values.Rows.Count)
{
break;
}
if (sind >= startIndex)
{
_layer.DataSet.Edit(fid, values.Rows[sind]);
}
}
}
}
/// <inheritdoc />
public int NumRows()
{
return Count;
}
/// <inheritdoc />
public DataColumn[] GetColumns()
{
{ return _layer.DataSet.GetColumns(); }
}
/// <inheritdoc />
public DataColumn GetColumn(string name)
{
return _layer.DataSet.GetColumn(name);
}
/// <summary>
/// Gets or sets the handler to use for progress messages during selection.
/// </summary>
public IProgressHandler ProgressHandler { get; set; }
/// <inheritdoc />
public void Add(int index)
{
if (index < 0 || index >= _layer.DrawnStates.Length) return;
if (_layer.DrawnStates[index].Selected == SelectionState) return;
_layer.DrawnStates[index].Selected = SelectionState;
OnChanged();
}
/// <inheritdoc />
public void Clear()
{
for (int shp = 0; shp < _layer.DrawnStates.Length; shp++)
{
_layer.DrawnStates[shp].Selected = !SelectionState;
}
OnChanged();
}
/// <inheritdoc />
public bool Contains(int index)
{
return _layer.DrawnStates[index].Selected == SelectionState;
}
/// <inheritdoc />
public void CopyTo(int[] array, int arrayIndex)
{
int index = arrayIndex;
foreach (int i in this)
{
array[index] = i;
index++;
}
}
/// <inheritdoc />
public int Count
{
get
{
int count = 0;
if (_layer.DrawnStates == null) return 0;
for (int i = 0; i < _layer.DrawnStates.Length; i++)
{
if (_layer.DrawnStates[i].Selected == SelectionState) count++;
}
return count;
}
}
/// <inheritdoc />
public bool IsReadOnly
{
get { return false; }
}
/// <inheritdoc />
public bool Remove(int index)
{
if (index < 0 || index >= _layer.DrawnStates.Length) return false;
if (_layer.DrawnStates[index].Selected != SelectionState) return false;
_layer.DrawnStates[index].Selected = !SelectionState;
OnChanged();
return true;
}
/// <summary>
/// Setting this to a specific category will only allow selection by
/// region to affect the features that are within the specified category.
/// </summary>
public IFeatureCategory RegionCategory { get; set; }
/// <inheritdoc />
public IEnumerator<int> GetEnumerator()
{
return new IndexSelectionEnumerator(_layer.DrawnStates, SelectionState);
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
/// <inheritdoc />
public void AddRow(Dictionary<string, object> values)
{
// Don't worry about the index in this case.
_layer.DataSet.AddRow(values);
}
/// <inheritdoc />
public void AddRow(DataRow values)
{
// Don't worry about the index in this case.
_layer.DataSet.AddRow(values);
}
/// <inheritdoc />
public void Edit(int index, Dictionary<string, object> values)
{
int sourceIndex = GetSourceIndex(index);
_layer.DataSet.Edit(sourceIndex, values);
}
/// <inheritdoc />
public void Edit(int index, DataRow values)
{
int sourceIndex = GetSourceIndex(index);
_layer.DataSet.Edit(sourceIndex, values);
}
/// <inheritdoc />
public int[] GetCounts(string[] expressions, ICancelProgressHandler progressHandler, int maxSampleSize)
{
int numSelected = Count;
int[] counts = new int[expressions.Length];
bool requiresRun = false;
for (int ie = 0; ie < expressions.Length; ie++)
{
if (string.IsNullOrEmpty(expressions[ie]))
{
counts[ie] = numSelected;
}
else
{
requiresRun = true;
}
}
if (!requiresRun) return counts;
AttributePager ap = new AttributePager(_layer.DataSet, 100000);
int numinTable = 0;
DataTable result = new DataTable();
result.Columns.AddRange(_layer.DataSet.GetColumns());
FastDrawnState[] drawnStates = _layer.DrawnStates;
for (int shp = 0; shp < drawnStates.Length; shp++)
{
if (drawnStates[shp].Selected)
{
result.Rows.Add(ap.Row(shp).ItemArray);
numinTable++;
if (numinTable > 100000)
{
for (int ie = 0; ie < expressions.Length; ie++)
{
if (string.IsNullOrEmpty(expressions[ie])) continue;
counts[ie] += result.Select(expressions[ie]).Length;
}
result.Clear();
}
}
}
for (int ie = 0; ie < expressions.Length; ie++)
{
if (string.IsNullOrEmpty(expressions[ie])) continue;
counts[ie] += result.Select(expressions[ie]).Length;
}
result.Clear();
return counts;
}
#endregion
private int GetSourceIndex(int selectedIndex)
{
// For instance, the 0 index member of the selection might in fact
// be the 10th member of the featureset. But we want to edit the 10th member
// and not the 0 member.
int count = 0;
foreach (int i in this)
{
if (count == selectedIndex) return i;
count++;
}
throw new IndexOutOfRangeException("Index requested was: " + selectedIndex + " but the selection only has " + count + " members");
}
#region Nested type: IndexSelectionEnumerator
/// <summary>
/// This class cycles through the members
/// </summary>
public class IndexSelectionEnumerator : IEnumerator<int>
{
private readonly bool _selectionState;
private readonly FastDrawnState[] _states;
private int _current;
/// <summary>
/// Creates a new instance of IndexSelectionEnumerator
/// </summary>
/// <param name="states"></param>
/// <param name="selectionState"></param>
public IndexSelectionEnumerator(FastDrawnState[] states, bool selectionState)
{
_states = states;
_selectionState = selectionState;
_current = -1;
}
#region IEnumerator<int> Members
/// <inheritdoc />
public int Current
{
get { return _current; }
}
/// <inheritdoc />
public void Dispose()
{
}
object IEnumerator.Current
{
get { return _current; }
}
/// <inheritdoc />
public bool MoveNext()
{
do
{
_current++;
} while (_current < _states.Length && _states[_current].Selected != _selectionState);
return _current != _states.Length;
}
/// <inheritdoc />
public void Reset()
{
_current = -1;
}
#endregion
}
#endregion
#region Private Variables
private readonly IFeatureLayer _layer;
private readonly List<ShapeRange> _shapes;
#endregion
#region Constructors
/// <summary>
/// Creates a new instance of IndexSelection
/// </summary>
public IndexSelection(IFeatureLayer layer)
{
_layer = layer;
_shapes = layer.DataSet.ShapeIndices;
SelectionMode = SelectionMode.IntersectsExtent;
SelectionState = true;
}
#endregion
}
}
| |
/*
* Copyright (c) Contributors, http://aurora-sim.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Aurora-Sim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
namespace Aurora.Framework
{
public static class AuroraModuleLoader
{
private static bool ALLOW_CACHE = true;
private static List<string> dllBlackList;
private static readonly List<string> firstLoad = new List<string>();
private static readonly Dictionary<string, List<Type>> LoadedDlls = new Dictionary<string, List<Type>>();
private static readonly Dictionary<string, Assembly> LoadedAssemblys = new Dictionary<string, Assembly>();
#region Module Loaders
/// <summary>
/// Find all T modules in the current directory
/// </summary>
/// <typeparam name = "T"></typeparam>
/// <returns></returns>
public static List<T> PickupModules<T>()
{
return LoadModules<T>(Util.BasePathCombine(""));
}
/// <summary>
/// Gets all modules found in the given directory.
/// Identifier is the name of the interface.
/// </summary>
/// <typeparam name = "T"></typeparam>
/// <param name = "moduleDir"></param>
/// <param name = "identifier"></param>
/// <returns></returns>
public static List<T> LoadModules<T>(string moduleDir)
{
if (moduleDir == "")
moduleDir = Util.BasePathCombine("");
List<T> modules = new List<T>();
lock (firstLoad)
{
if (!firstLoad.Contains(moduleDir))
{
DirectoryInfo dir = new DirectoryInfo(moduleDir);
#region blacklist
if (dllBlackList == null || dllBlackList.Count == 0)
{
dllBlackList = new List<string>
{
Path.Combine(dir.FullName, "AsyncCtpLibrary.dll"),
Path.Combine(dir.FullName, "NHibernate.ByteCode.Castle.dll"),
Path.Combine(dir.FullName, "Antlr3.Runtime.dll"),
Path.Combine(dir.FullName, "AprSharp.dll"),
Path.Combine(dir.FullName, "Axiom.MathLib.dll"),
Path.Combine(dir.FullName, "BclExtras35.dll"),
Path.Combine(dir.FullName, "BulletSim.dll"),
Path.Combine(dir.FullName, "BulletSim-x86_64.dll"),
Path.Combine(dir.FullName, "BulletDotNET.dll"),
Path.Combine(dir.FullName, "C5.dll"),
Path.Combine(dir.FullName, "Castle.Core.dll"),
Path.Combine(dir.FullName, "Castle.DynamicProxy.dll"),
Path.Combine(dir.FullName, "Castle.DynamicProxy2.dll"),
Path.Combine(dir.FullName, "Community.CsharpSqlite.dll"),
Path.Combine(dir.FullName, "Community.CsharpSqlite.Sqlite.dll"),
Path.Combine(dir.FullName, "CookComputing.XmlRpcV2.dll"),
Path.Combine(dir.FullName, "CSJ2K.dll"),
Path.Combine(dir.FullName, "DotNetOpenId.dll"),
Path.Combine(dir.FullName, "DotNetOpenMail.dll"),
Path.Combine(dir.FullName, "DotSets.dll"),
Path.Combine(dir.FullName, "Fadd.dll"),
Path.Combine(dir.FullName, "Fadd.Globalization.Yaml.dll"),
Path.Combine(dir.FullName, "FluentNHibernate.dll"),
Path.Combine(dir.FullName, "Glacier2.dll"),
Path.Combine(dir.FullName, "GlynnTucker.Cache.dll"),
Path.Combine(dir.FullName, "Google.ProtocolBuffers.dll"),
Path.Combine(dir.FullName, "GoogleTranslateAPI.dll"),
Path.Combine(dir.FullName, "HttpServer.dll"),
Path.Combine(dir.FullName, "HttpServer_OpenSim.dll"),
Path.Combine(dir.FullName, "Ice.dll"),
Path.Combine(dir.FullName, "Iesi.Collections.dll"),
Path.Combine(dir.FullName, "intl3_svn.dll"),
Path.Combine(dir.FullName, "Kds.Serialization.dll"),
Path.Combine(dir.FullName, "libapr.dll"),
Path.Combine(dir.FullName, "libapriconv.dll"),
Path.Combine(dir.FullName, "libaprutil.dll"),
Path.Combine(dir.FullName, "libbulletnet.dll"),
Path.Combine(dir.FullName, "libdb44d.dll"),
Path.Combine(dir.FullName, "libdb_dotNET43.dll"),
Path.Combine(dir.FullName, "libeay32.dll"),
Path.Combine(dir.FullName, "log4net.dll"),
Path.Combine(dir.FullName, "Modified.XnaDevRu.BulletX.dll"),
Path.Combine(dir.FullName, "Mono.Addins.CecilReflector.dll"),
Path.Combine(dir.FullName, "Mono.Addins.dll"),
Path.Combine(dir.FullName, "Mono.Addins.Setup.dll"),
Path.Combine(dir.FullName, "Mono.Data.Sqlite.dll"),
Path.Combine(dir.FullName, "Mono.Data.SqliteClient.dll"),
Path.Combine(dir.FullName, "Mono.GetOptions.dll"),
Path.Combine(dir.FullName, "Mono.PEToolkit.dll"),
Path.Combine(dir.FullName, "Mono.Security.dll"),
Path.Combine(dir.FullName, "MonoXnaCompactMaths.dll"),
Path.Combine(dir.FullName, "MXP.dll"),
Path.Combine(dir.FullName, "MySql.Data.dll"),
Path.Combine(dir.FullName, "NDesk.Options.dll"),
Path.Combine(dir.FullName, "Newtonsoft.Json.dll"),
Path.Combine(dir.FullName, "Newtonsoft.Json.Net20.dll"),
Path.Combine(dir.FullName, "NHibernate.ByteCode.Castle.dll"),
Path.Combine(dir.FullName, "NHibernate.dll"),
Path.Combine(dir.FullName, "HttpServer_OpenSim.dll"),
Path.Combine(dir.FullName, "Nini.dll"),
Path.Combine(dir.FullName, "Npgsql.dll"),
Path.Combine(dir.FullName, "nunit.framework.dll"),
Path.Combine(dir.FullName, "ode.dll"),
Path.Combine(dir.FullName, "odex86.dll"),
Path.Combine(dir.FullName, "odex64.dll"),
Path.Combine(dir.FullName, "odeNoSSE.dll"),
Path.Combine(dir.FullName, "odeSSE1.dll"),
Path.Combine(dir.FullName, "ode10.dll"),
Path.Combine(dir.FullName, "ode11.dll"),
Path.Combine(dir.FullName, "Ode.NET.dll"),
Path.Combine(dir.FullName, "Ode.NET.Single.dll"),
Path.Combine(dir.FullName, "Ode.NET.Double.dll"),
Path.Combine(dir.FullName, "openjpeg-dotnet-x86_64.dll"),
Path.Combine(dir.FullName, "openjpeg-dotnet.dll"),
Path.Combine(dir.FullName, "openjpeg.dll"),
Path.Combine(dir.FullName, "OpenMetaverse.dll"),
Path.Combine(dir.FullName, "OpenMetaverse.GUI.dll"),
Path.Combine(dir.FullName, "OpenMetaverse.Rendering.Simple.dll"),
Path.Combine(dir.FullName, "OpenMetaverse.Rendering.Meshmerizer.dll"),
Path.Combine(dir.FullName, "OpenMetaverse.Http.dll"),
Path.Combine(dir.FullName, "OpenMetaverse.StructuredData.dll"),
Path.Combine(dir.FullName, "OpenMetaverse.Utilities.dll"),
Path.Combine(dir.FullName, "OpenMetaverseTypes.dll"),
Path.Combine(dir.FullName, "OpenMetaverse.Tests.dll"),
Path.Combine(dir.FullName, "PhysX-wrapper.dll"),
Path.Combine(dir.FullName, "PhysX_Wrapper_Dotnet.dll"),
Path.Combine(dir.FullName, "PrimMesher.dll"),
Path.Combine(dir.FullName, "protobuf-net.dll"),
Path.Combine(dir.FullName, "PumaCode.SvnDotNet.dll"),
Path.Combine(dir.FullName, "RAIL.dll"),
Path.Combine(dir.FullName, "SmartThreadPool.dll"),
Path.Combine(dir.FullName, "sqlite3.dll"),
Path.Combine(dir.FullName, "ssleay32.dll"),
Path.Combine(dir.FullName, "SubversionSharp.dll"),
Path.Combine(dir.FullName, "svn_client-1.dll"),
Path.Combine(dir.FullName, "System.Data.SQLite.dll"),
Path.Combine(dir.FullName, "System.Data.SQLitex64.dll"),
Path.Combine(dir.FullName, "System.Data.SQLitex86.dll"),
Path.Combine(dir.FullName, "Tools.dll"),
Path.Combine(dir.FullName, "xunit.dll"),
Path.Combine(dir.FullName, "XMLRPC.dll"),
Path.Combine(dir.FullName, "Warp3D.dll"),
Path.Combine(dir.FullName, "zlib.net.dll")
};
}
#endregion
if (ALLOW_CACHE)
LoadedDlls.Add(moduleDir, new List<Type>());
foreach (FileInfo fileInfo in dir.GetFiles("*.dll"))
{
modules.AddRange(LoadModulesFromDLL<T>(moduleDir, fileInfo.FullName));
}
if (ALLOW_CACHE)
firstLoad.Add(moduleDir);
}
else
{
try
{
List<Type> loadedDllModules;
LoadedDlls.TryGetValue(moduleDir, out loadedDllModules);
foreach (Type pluginType in loadedDllModules)
{
try
{
if (pluginType.IsPublic)
{
if (!pluginType.IsAbstract)
{
if (pluginType.GetInterface(typeof(T).Name) != null)
{
modules.Add((T)Activator.CreateInstance(pluginType));
}
}
}
}
catch (Exception)
{
}
}
}
catch (Exception)
{
}
}
}
return modules;
}
public static void ClearCache()
{
LoadedDlls.Clear();
firstLoad.Clear();
}
/// <summary>
/// Load all T modules from dllname
/// </summary>
/// <typeparam name = "T"></typeparam>
/// <param name = "dllName"></param>
/// <returns></returns>
private static List<T> LoadModulesFromDLL<T>(string moduleDir, string dllName)
{
List<T> modules = new List<T>();
if (dllBlackList.Contains(dllName))
return modules;
//MainConsole.Instance.Info ("[ModuleLoader]: Loading " + dllName);
Assembly pluginAssembly;
if (!LoadedAssemblys.TryGetValue(dllName, out pluginAssembly))
{
try
{
pluginAssembly = Assembly.LoadFrom(dllName);
LoadedAssemblys.Add(dllName, pluginAssembly);
}
catch (BadImageFormatException)
{
}
}
if (pluginAssembly != null)
{
try
{
List<Type> loadedTypes = new List<Type>();
foreach (Type pluginType in pluginAssembly.GetTypes())
{
try
{
if (pluginType.IsPublic)
{
if (!pluginType.IsAbstract)
{
if (ALLOW_CACHE)
{
if (!firstLoad.Contains(moduleDir))
{
//Only add on the first load
if (!loadedTypes.Contains(pluginType))
loadedTypes.Add(pluginType);
}
}
if (pluginType.GetInterface(typeof (T).Name, true) != null)
{
modules.Add((T) Activator.CreateInstance(pluginType));
}
}
}
}
catch (Exception ex)
{
MainConsole.Instance.Warn("[MODULELOADER]: Error loading module " + pluginType.Name + " in file " + dllName +
" : " + ex);
}
}
if (ALLOW_CACHE)
LoadedDlls[moduleDir].AddRange(loadedTypes);
}
catch (Exception)
{
}
}
return modules;
}
#endregion
/// <summary>
/// Load all plugins from the given .dll file with the interface 'type'
/// </summary>
/// <typeparam name = "T"></typeparam>
/// <param name = "dllName"></param>
/// <param name = "type"></param>
/// <returns></returns>
public static T LoadPlugin<T>(string dllName)
{
string type = typeof (T).ToString();
try
{
Assembly pluginAssembly = Assembly.LoadFrom(dllName);
#if (!ISWIN)
foreach (Type pluginType in pluginAssembly.GetTypes())
{
if (pluginType.IsPublic)
{
try
{
Type typeInterface = pluginType.GetInterface(type, true);
if (typeInterface != null)
{
return (T)Activator.CreateInstance(pluginType);
}
}
catch (Exception)
{
}
}
}
#else
foreach (Type pluginType in pluginAssembly.GetTypes().Where(pluginType => pluginType.IsPublic))
{
try
{
Type typeInterface = pluginType.GetInterface(type, true);
if (typeInterface != null)
{
return (T) Activator.CreateInstance(pluginType);
}
}
catch (Exception)
{
}
}
#endif
}
catch (ReflectionTypeLoadException e)
{
foreach (Exception e2 in e.LoaderExceptions)
{
MainConsole.Instance.Error(e2.ToString());
}
throw e;
}
return default(T);
}
/// <summary>
/// Load all plugins from the given .dll file with the interface 'type'
/// </summary>
/// <typeparam name = "T"></typeparam>
/// <param name = "dllName"></param>
/// <param name = "type"></param>
/// <returns></returns>
public static List<T> LoadPlugins<T>(string dllName)
{
List<T> plugins = new List<T>();
string type = typeof (T).ToString();
try
{
Assembly pluginAssembly = Assembly.LoadFrom(dllName);
#if (!ISWIN)
foreach (Type pluginType in pluginAssembly.GetTypes())
{
if (pluginType.IsPublic)
{
try
{
Type typeInterface = pluginType.GetInterface(type, true);
if (typeInterface != null)
{
plugins.Add((T)Activator.CreateInstance(pluginType));
}
}
catch (Exception)
{
}
}
}
#else
foreach (Type pluginType in pluginAssembly.GetTypes().Where(pluginType => pluginType.IsPublic))
{
try
{
Type typeInterface = pluginType.GetInterface(type, true);
if (typeInterface != null)
{
plugins.Add((T) Activator.CreateInstance(pluginType));
}
}
catch (Exception)
{
}
}
#endif
}
catch (ReflectionTypeLoadException e)
{
foreach (Exception e2 in e.LoaderExceptions)
{
MainConsole.Instance.Error(e2.ToString());
}
throw e;
}
return plugins;
}
/// <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
{
string[] parts = dllName.Split(new[] {':'});
dllName = parts[0];
string className = String.Empty;
if (parts.Length > 1)
className = parts[1];
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, true);
if (typeInterface != null)
{
T plug = null;
try
{
plug = (T) Activator.CreateInstance(pluginType,
args);
}
catch (Exception e)
{
if (!(e is MissingMethodException))
MainConsole.Instance.ErrorFormat("Error loading plugin from {0}, exception {1}", dllName,
e.InnerException);
return null;
}
return plug;
}
}
}
return null;
}
catch (Exception e)
{
MainConsole.Instance.Error(string.Format("Error loading plugin from {0}", dllName), e);
return null;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void BlendInt324()
{
var test = new ImmBinaryOpTest__BlendInt324();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class ImmBinaryOpTest__BlendInt324
{
private struct TestStruct
{
public Vector128<Int32> _fld1;
public Vector128<Int32> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
return testStruct;
}
public void RunStructFldScenario(ImmBinaryOpTest__BlendInt324 testClass)
{
var result = Avx2.Blend(_fld1, _fld2, 4);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32);
private static Int32[] _data1 = new Int32[Op1ElementCount];
private static Int32[] _data2 = new Int32[Op2ElementCount];
private static Vector128<Int32> _clsVar1;
private static Vector128<Int32> _clsVar2;
private Vector128<Int32> _fld1;
private Vector128<Int32> _fld2;
private SimpleBinaryOpTest__DataTable<Int32, Int32, Int32> _dataTable;
static ImmBinaryOpTest__BlendInt324()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
}
public ImmBinaryOpTest__BlendInt324()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
_dataTable = new SimpleBinaryOpTest__DataTable<Int32, Int32, Int32>(_data1, _data2, new Int32[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Avx2.Blend(
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr),
4
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Avx2.Blend(
Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr)),
4
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Avx2.Blend(
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr)),
4
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Avx2).GetMethod(nameof(Avx2.Blend), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr),
(byte)4
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx2).GetMethod(nameof(Avx2.Blend), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>), typeof(byte) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr)),
(byte)4
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx2).GetMethod(nameof(Avx2.Blend), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>), typeof(byte) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr)),
(byte)4
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx2.Blend(
_clsVar1,
_clsVar2,
4
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var left = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr);
var result = Avx2.Blend(left, right, 4);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var left = Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr));
var result = Avx2.Blend(left, right, 4);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var left = Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr));
var result = Avx2.Blend(left, right, 4);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new ImmBinaryOpTest__BlendInt324();
var result = Avx2.Blend(test._fld1, test._fld2, 4);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx2.Blend(_fld1, _fld2, 4);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Avx2.Blend(test._fld1, test._fld2, 4);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<Int32> left, Vector128<Int32> right, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray1 = new Int32[Op1ElementCount];
Int32[] inArray2 = new Int32[Op2ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), left);
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray1 = new Int32[Op1ElementCount];
Int32[] inArray2 = new Int32[Op2ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), (uint)Unsafe.SizeOf<Vector128<Int32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), (uint)Unsafe.SizeOf<Vector128<Int32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Int32[] left, Int32[] right, Int32[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (result[0] != (((4 & (1 << 0)) == 0) ? left[0] : right[0]))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != (((4 & (1 << i)) == 0) ? left[i] : right[i]))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.Blend)}<Int32>(Vector128<Int32>.4, Vector128<Int32>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
using NetCoreEx.BinaryExtensions;
using System;
using System.Drawing;
using System.Text;
using WinApi.User32;
namespace WinApi.Windows
{
internal interface INativeAttachable
{
void Attach(IntPtr handle);
IntPtr Detach();
}
/// <summary>
/// A simple wrapper around the Win32 window. It has nothing except
/// the handle of the window. All functions here are direct api calls.
/// </summary>
internal class NativeWindow : INativeAttachable
{
IntPtr handle;
public IntPtr Handle
{
get
{
return handle;
}
protected set
{
handle = value;
OnHandleChange();
}
}
/// <summary>
/// This method is invoked when the value of the Handle property has changed.
/// </summary>
protected virtual void OnHandleChange() { }
void INativeAttachable.Attach(IntPtr handle)
{
this.Handle = handle;
}
IntPtr INativeAttachable.Detach()
{
var h = this.Handle;
this.Handle = IntPtr.Zero;
return h;
}
public bool SetText(string text)
{
return User32Methods.SetWindowText(this.Handle, text);
}
public string GetText()
{
var size = User32Methods.GetWindowTextLength(this.Handle);
if (size > 0)
{
var len = size + 1;
var sb = new StringBuilder(len);
return User32Methods.GetWindowText(this.Handle, sb, len) > 0 ? sb.ToString() : string.Empty;
}
return string.Empty;
}
public bool SetSize(Size size)
{
return this.SetSize(ref size);
}
public bool SetSize(ref Size size)
{
return this.SetSize(size.Width, size.Height);
}
public bool SetSize(int width, int height)
{
return User32Methods.SetWindowPos(this.Handle, IntPtr.Zero, -1, -1, width, height,
WindowPositionFlags.SWP_NOACTIVATE | WindowPositionFlags.SWP_NOMOVE | WindowPositionFlags.SWP_NOZORDER);
}
public bool SetPosition(int x, int y)
{
return User32Methods.SetWindowPos(this.Handle, IntPtr.Zero, x, y, -1, -1,
WindowPositionFlags.SWP_NOACTIVATE | WindowPositionFlags.SWP_NOSIZE | WindowPositionFlags.SWP_NOZORDER);
}
public bool SetPosition(int x, int y, int width, int height)
{
return User32Methods.SetWindowPos(this.Handle, IntPtr.Zero, x, y, width, height,
WindowPositionFlags.SWP_NOACTIVATE | WindowPositionFlags.SWP_NOZORDER);
}
public bool SetPosition(int x, int y, int width, int height, WindowPositionFlags flags)
{
return User32Methods.SetWindowPos(this.Handle, IntPtr.Zero, x, y, width, height, flags);
}
public bool SetPosition(HwndZOrder order, int x, int y, int width, int height, WindowPositionFlags flags)
{
return User32Helpers.SetWindowPos(this.Handle, order, x, y, width, height, flags);
}
public bool SetPosition(IntPtr hWndInsertAfter, int x, int y, int width, int height, WindowPositionFlags flags)
{
return User32Methods.SetWindowPos(this.Handle, hWndInsertAfter, x, y, width, height, flags);
}
public bool SetPosition(Rectangle rect)
{
return this.SetPosition(ref rect);
}
public bool SetPosition(Rectangle rect, WindowPositionFlags flags)
{
return this.SetPosition(ref rect, flags);
}
public bool SetPosition(ref Rectangle rect)
{
return this.SetPosition(rect.Left, rect.Top, rect.Width, rect.Height,
WindowPositionFlags.SWP_NOACTIVATE | WindowPositionFlags.SWP_NOZORDER);
}
public bool SetPosition(ref Rectangle rect, WindowPositionFlags flags)
{
return this.SetPosition(rect.Left, rect.Top, rect.Width, rect.Height, flags);
}
public bool GetWindowRect(out Rectangle rectangle)
{
return User32Methods.GetWindowRect(this.Handle, out rectangle);
}
public Rectangle GetWindowRect()
{
Rectangle rectangle;
User32Methods.GetWindowRect(this.Handle, out rectangle);
return rectangle;
}
public bool GetClientRect(out Rectangle rectangle)
{
return User32Methods.GetClientRect(this.Handle, out rectangle);
}
public Rectangle GetClientRect()
{
Rectangle rectangle;
User32Methods.GetClientRect(this.Handle, out rectangle);
return rectangle;
}
public Size GetClientSize()
{
Rectangle rect;
this.GetClientRect(out rect);
return new Size {Width = rect.Width, Height = rect.Height};
}
public Size GetWindowSize()
{
Rectangle rect;
this.GetWindowRect(out rect);
return new Size {Width = rect.Width, Height = rect.Height};
}
public bool IsVisible()
{
return User32Methods.IsWindowVisible(this.Handle);
}
public bool IsEnabled()
{
return User32Methods.IsWindowEnabled(this.Handle);
}
public IntPtr SetParam(WindowLongFlags index, IntPtr value)
{
return User32Methods.SetWindowLongPtr(this.Handle, (int) index, value);
}
public IntPtr GetParam(WindowLongFlags index)
{
return User32Methods.GetWindowLongPtr(this.Handle, (int) index);
}
public WindowStyles GetStyles()
{
return (WindowStyles) this.GetParam(WindowLongFlags.GWL_STYLE).ToSafeInt32();
}
public WindowExStyles GetExStyles()
{
return (WindowExStyles) this.GetParam(WindowLongFlags.GWL_EXSTYLE).ToSafeInt32();
}
public WindowStyles SetStyle(WindowStyles styles)
{
return (WindowStyles) this.SetParam(WindowLongFlags.GWL_STYLE, new IntPtr((int) styles));
}
public WindowExStyles SetExStyles(WindowExStyles exStyles)
{
return (WindowExStyles) this.SetParam(WindowLongFlags.GWL_EXSTYLE, new IntPtr((int) exStyles));
}
public bool Show()
{
return User32Methods.ShowWindow(this.Handle, ShowWindowCommands.SW_SHOW);
}
public bool Hide()
{
return User32Methods.ShowWindow(this.Handle, ShowWindowCommands.SW_HIDE);
}
public IntPtr BeginPaint(out PaintStruct ps)
{
return User32Methods.BeginPaint(this.Handle, out ps);
}
public void EndPaint(ref PaintStruct ps)
{
User32Methods.EndPaint(this.Handle, ref ps);
}
public void RedrawFrame()
{
this.SetPosition(new Rectangle(),
WindowPositionFlags.SWP_FRAMECHANGED | WindowPositionFlags.SWP_NOMOVE |
WindowPositionFlags.SWP_NOSIZE);
}
public IntPtr GetDc()
{
return User32Methods.GetDC(this.Handle);
}
public IntPtr GetWindowDc()
{
return User32Methods.GetWindowDC(this.Handle);
}
public bool ReleaseDc(IntPtr hdc)
{
return User32Methods.ReleaseDC(this.Handle, hdc);
}
public bool SetState(ShowWindowCommands flags)
{
return User32Methods.ShowWindow(this.Handle, flags);
}
public bool Validate(ref Rectangle rect)
{
return User32Methods.ValidateRect(this.Handle, ref rect);
}
public bool Validate()
{
return User32Methods.ValidateRect(this.Handle, IntPtr.Zero);
}
public bool Invalidate(ref Rectangle rect, bool shouldErase = false)
{
return User32Methods.InvalidateRect(this.Handle, ref rect, shouldErase);
}
public bool Invalidate(bool shouldErase = false)
{
return User32Methods.InvalidateRect(this.Handle, IntPtr.Zero, shouldErase);
}
public void SetFocus()
{
User32Methods.SetFocus(this.Handle);
}
public Rectangle ClientToScreen(ref Rectangle clientRect)
{
Rectangle rect;
this.ClientToScreen(ref clientRect, out rect);
return rect;
}
public virtual void ClientToScreen(ref Rectangle clientRect, out Rectangle screenRect)
{
screenRect = clientRect;
User32Helpers.MapWindowPoints(this.Handle, IntPtr.Zero, ref screenRect);
User32Methods.AdjustWindowRectEx(ref screenRect, this.GetStyles(),
User32Methods.GetMenu(this.Handle) != IntPtr.Zero, this.GetExStyles());
}
public Rectangle ScreenToClient(ref Rectangle screenRect)
{
Rectangle rect;
this.ScreenToClient(ref screenRect, out rect);
return rect;
}
public virtual void ScreenToClient(ref Rectangle screenRect, out Rectangle clientRect)
{
clientRect = screenRect;
User32Helpers.MapWindowPoints(IntPtr.Zero, this.Handle, ref clientRect);
User32Helpers.InverseAdjustWindowRectEx(ref clientRect, this.GetStyles(),
User32Methods.GetMenu(this.Handle) != IntPtr.Zero, this.GetExStyles());
}
public void CenterToScreen(bool useWorkArea = true)
{
var monitor = User32Methods.MonitorFromWindow(this.Handle,
MonitorFlag.MONITOR_DEFAULTTONEAREST);
MonitorInfo monitorInfo;
User32Helpers.GetMonitorInfo(monitor, out monitorInfo);
var screenRect = useWorkArea ? monitorInfo.WorkRect : monitorInfo.MonitorRect;
var midX = screenRect.Width/2;
var midY = screenRect.Height/2;
var size = this.GetWindowSize();
this.SetPosition(midX - size.Width/2, midY - size.Height/2);
}
public bool Destroy()
{
if (User32Methods.DestroyWindow(this.Handle))
{
this.Handle = IntPtr.Zero;
return true;
}
return false;
}
}
}
| |
#region File Description
//-----------------------------------------------------------------------------
// PathfindingGame.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
#region Using Statements
using System;
using System.Collections.Generic;
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.Input.Touch;
#endregion
namespace Pathfinding
{
/// <summary>
/// This is the main type for your game
/// </summary>
public class Pathfinding : Microsoft.Xna.Framework.Game
{
#region Constants
const int bottomUIHeight = 80;
const int sliderButtonWidth = 20;
#endregion
#region Fields
private KeyboardState currentKeyboardState;
private GamePadState currentGamePadState;
private Texture2D ButtonA;
private Texture2D ButtonB;
private Texture2D ButtonX;
private Texture2D ButtonY;
private Texture2D onePixelWhite;
private Rectangle buttonStartStop = new Rectangle(5, 405, 110, 30);
private Rectangle buttonReset = new Rectangle(125, 405, 110, 30);
private Rectangle buttonNextMap = new Rectangle(245, 405, 110, 30);
private Rectangle buttonPathfinding = new Rectangle(365, 405, 270, 30);
private Rectangle barTimeStep = new Rectangle(125, 450, 200, 20);
private Vector2 pathStatusPosition;
private Vector2 searchStepsPosition;
private Rectangle gameplayArea;
private SpriteFont HUDFont;
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
Map map;
Tank tank;
PathFinder pathFinder;
#endregion
public Pathfinding()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
#if WINDOWS_PHONE
// Frame rate is 30 fps by default for Windows Phone.
TargetElapsedTime = TimeSpan.FromTicks(333333);
graphics.IsFullScreen = true;
#endif
map = new Map();
tank = new Tank();
pathFinder = new PathFinder();
}
/// <summary>
/// Allows the game to perform any initialization it needs to before starting to run.
/// This is where it can query for any required services and load any non-graphic
/// related content. Calling base.Initialize will enumerate through any components
/// and initialize them as well.
/// </summary>
protected override void Initialize()
{
base.Initialize();
// TODO: Add your initialization logic here
gameplayArea = GraphicsDevice.Viewport.TitleSafeArea;
// The bottom part of the screen houses controls for the buttons
gameplayArea.Height -= bottomUIHeight;
pathStatusPosition = new Vector2(645, 425);
searchStepsPosition = new Vector2(645, 445);
TouchPanel.EnabledGestures = GestureType.Tap;
map.UpdateMapViewport(gameplayArea);
tank.Initialize(map);
pathFinder.Initialize(map);
}
/// <summary>
/// LoadContent will be called once per game and is the place to load
/// all of your content.
/// </summary>
protected override void LoadContent()
{
ButtonA = Content.Load<Texture2D>("xboxControllerButtonA");
ButtonB = Content.Load<Texture2D>("xboxControllerButtonB");
ButtonX = Content.Load<Texture2D>("xboxControllerButtonX");
ButtonY = Content.Load<Texture2D>("xboxControllerButtonY");
HUDFont = Content.Load<SpriteFont>("HUDFont");
onePixelWhite = new Texture2D(GraphicsDevice,1,1);
onePixelWhite.SetData<Color>(new Color[] { Color.White });
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
map.LoadContent(Content);
tank.LoadContent(Content);
pathFinder.LoadContent(Content);
// TODO: use this.Content to load your game content here
base.LoadContent();
}
/// <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
}
#region Update
/// <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)
{
HandleInput();
if (map.MapReload)
{
map.ReloadMap();
map.UpdateMapViewport(gameplayArea);
tank.Reset();
pathFinder.Reset();
}
if (pathFinder.SearchStatus == SearchStatus.PathFound && !tank.Moving)
{
foreach (Point point in pathFinder.FinalPath())
{
tank.Waypoints.Enqueue(map.MapToWorld(point, true));
}
tank.Moving = true;
}
pathFinder.Update(gameTime);
tank.Update(gameTime);
base.Update(gameTime);
}
#endregion
#region Draw
/// <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.Black);
map.Draw(spriteBatch);
pathFinder.Draw(spriteBatch);
tank.Draw(spriteBatch);
DrawHUD(spriteBatch);
DrawPathStatus(spriteBatch);
base.Draw(gameTime);
}
/// <summary>
/// Helper function used by Draw. It is used to draw the slider bars
/// </summary>
private void DrawBar(Rectangle bar, float barWidthNormalized, string label)
{
// Calculate how wide the bar should be, and then draw it.
bar.Height /= 2;
spriteBatch.Draw(onePixelWhite, bar, Color.White);
// Draw the slider
spriteBatch.Draw(onePixelWhite, new Rectangle(bar.X + (int)(bar.Width * barWidthNormalized),
bar.Y - bar.Height / 2, sliderButtonWidth, bar.Height * 2), Color.Orange);
// Finally, draw the label to the left of the bar.
Vector2 labelSize = HUDFont.MeasureString(label);
Vector2 labelPosition = new Vector2(bar.X - 10 - labelSize.X, bar.Y - bar.Height / 2);
spriteBatch.DrawString(HUDFont, label, labelPosition, Color.White);
}
/// <summary>
/// Helper function used to draw the buttons
/// </summary>
/// <param name="button"></param>
/// <param name="label"></param>
private void DrawButton(Rectangle button, string label)
{
spriteBatch.Draw(onePixelWhite, button, Color.Orange);
spriteBatch.DrawString(HUDFont, label, new Vector2(button.Left + 10, button.Top + 5), Color.Black);
}
/// <summary>
/// Helper function used to draw the HUD
/// </summary>
/// <param name="spriteBatch"></param>
private void DrawHUD(SpriteBatch spriteBatch)
{
spriteBatch.Begin();
DrawBar(barTimeStep, pathFinder.TimeStep, "Time Step:");
#if WINDOWS_PHONE
DrawButton(buttonStartStop, "Start/Stop");
DrawButton(buttonReset, "Reset");
DrawButton(buttonPathfinding, "Pathfinding mode: " + pathFinder.SearchMethod.ToString());
DrawButton(buttonNextMap, "Next Map");
#else
float textureWidth = ButtonA.Width;
spriteBatch.Draw(ButtonA, new Vector2(10, 400), Color.White);
spriteBatch.DrawString(
HUDFont, " Start/Stop",
new Vector2(10 + textureWidth, 400), Color.White);
spriteBatch.Draw(ButtonB, new Vector2(150, 400), Color.White);
spriteBatch.DrawString(
HUDFont, " Reset",
new Vector2(150 + textureWidth, 400), Color.White);
spriteBatch.Draw(ButtonY, new Vector2(250, 400), Color.White);
spriteBatch.DrawString(
HUDFont, " Next map",
new Vector2(250 + textureWidth, 400), Color.White);
spriteBatch.Draw(ButtonX, new Vector2(400, 400), Color.White);
spriteBatch.DrawString(
HUDFont, " Pathfinding mode: " + pathFinder.SearchMethod.ToString(),
new Vector2(400 + textureWidth, 400), Color.White);
#endif
spriteBatch.End();
}
/// <summary>
/// Helper function used to draw the path status of the tank
/// </summary>
/// <param name="spriteBatch"></param>
private void DrawPathStatus(SpriteBatch spriteBatch)
{
spriteBatch.Begin();
string stepString = string.Format("Search Steps: {0}",
pathFinder.TotalSearchSteps);
spriteBatch.DrawString(HUDFont, stepString, searchStepsPosition,
Color.White);
switch (pathFinder.SearchStatus)
{
case SearchStatus.Stopped:
spriteBatch.DrawString(
HUDFont, "Not Searching", pathStatusPosition, Color.White);
break;
case SearchStatus.Searching:
spriteBatch.DrawString(
HUDFont, "Searching...", pathStatusPosition, Color.White);
break;
case SearchStatus.PathFound:
spriteBatch.DrawString(
HUDFont, "Path Found!", pathStatusPosition, Color.Green);
break;
case SearchStatus.NoPath:
spriteBatch.DrawString(
HUDFont, "No Path Found!", pathStatusPosition, Color.Red);
break;
default:
break;
}
spriteBatch.End();
}
#endregion
#region Handle Input
/// <summary>
/// Handle input for the sample
/// </summary>
void HandleInput()
{
KeyboardState previousKeyboardState = currentKeyboardState;
GamePadState previousGamePadState = currentGamePadState;
currentGamePadState = GamePad.GetState(PlayerIndex.One);
currentKeyboardState = Keyboard.GetState();
// Allows the game to exit
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();
if (previousGamePadState.Buttons.A == ButtonState.Released &&
currentGamePadState.Buttons.A == ButtonState.Pressed ||
previousKeyboardState.IsKeyUp(Keys.A) &&
currentKeyboardState.IsKeyDown(Keys.A))
{
pathFinder.IsSearching = !pathFinder.IsSearching;
}
if (previousGamePadState.Buttons.B == ButtonState.Released &&
currentGamePadState.Buttons.B == ButtonState.Pressed ||
previousKeyboardState.IsKeyUp(Keys.B) &&
currentKeyboardState.IsKeyDown(Keys.B))
{
map.MapReload = true;
}
if (previousGamePadState.Buttons.X == ButtonState.Released &&
currentGamePadState.Buttons.X == ButtonState.Pressed ||
previousKeyboardState.IsKeyUp(Keys.X) &&
currentKeyboardState.IsKeyDown(Keys.X))
{
pathFinder.NextSearchType();
}
if (previousGamePadState.Buttons.Y == ButtonState.Released &&
currentGamePadState.Buttons.Y == ButtonState.Pressed ||
previousKeyboardState.IsKeyUp(Keys.Y) &&
currentKeyboardState.IsKeyDown(Keys.Y))
{
map.CycleMap();
}
if (previousGamePadState.DPad.Right == ButtonState.Released &&
currentGamePadState.DPad.Right == ButtonState.Pressed ||
previousKeyboardState.IsKeyUp(Keys.Right) &&
currentKeyboardState.IsKeyDown(Keys.Right))
{
pathFinder.TimeStep += .1f;
}
if (previousGamePadState.DPad.Left == ButtonState.Released &&
currentGamePadState.DPad.Left == ButtonState.Pressed ||
previousKeyboardState.IsKeyUp(Keys.Left) &&
currentKeyboardState.IsKeyDown(Keys.Left))
{
pathFinder.TimeStep -= .1f;
}
pathFinder.TimeStep = MathHelper.Clamp(pathFinder.TimeStep, 0f, 1f);
TouchCollection rawTouch = TouchPanel.GetState();
// Use raw touch for the sliders
if (rawTouch.Count > 0)
{
// Only grab the first one
TouchLocation touchLocation = rawTouch[0];
// Create a collidable rectangle to determine if we touched the controls
Rectangle touchRectangle = new Rectangle((int)touchLocation.Position.X,
(int)touchLocation.Position.Y, 10, 10);
// Have the sliders rely on the raw touch to function properly
if (barTimeStep.Intersects(touchRectangle))
{
pathFinder.TimeStep = (float)(touchRectangle.X - barTimeStep.X) / (float)barTimeStep.Width;
}
}
// Next we handle all of the gestures. since we may have multiple gestures available,
// we use a loop to read in all of the gestures. this is important to make sure the
// TouchPanel's queue doesn't get backed up with old data
while (TouchPanel.IsGestureAvailable)
{
// Read the next gesture from the queue
GestureSample gesture = TouchPanel.ReadGesture();
// Create a collidable rectangle to determine if we touched the controls
Rectangle touch = new Rectangle((int)gesture.Position.X, (int)gesture.Position.Y, 20, 20);
// We can use the type of gesture to determine our behavior
switch (gesture.GestureType)
{
case GestureType.Tap:
if (buttonStartStop.Intersects(touch))
{
pathFinder.IsSearching = !pathFinder.IsSearching;
}
else if (buttonReset.Intersects(touch))
{
map.MapReload = true;
}
else if (buttonPathfinding.Intersects(touch))
{
pathFinder.NextSearchType();
}
else if (buttonNextMap.Intersects(touch))
{
map.CycleMap();
}
break;
}
}
}
#endregion
}
}
| |
/*
***********************************************************************************************************************
*
* Copyright (c) 2022 Advanced Micro Devices, Inc. All Rights Reserved.
*
* 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.
*
**********************************************************************************************************************/
[CsIl]
il_cs_2_0
dcl_global_flags refactoringAllowed
; UAV0 - DST MSAA Image 2/4/8x
; UAV1 - SRC MSAA Image 2/4/8x
dcl_typed_uav_id(0)_type(2dmsaa)_fmtx(uint)
dcl_typed_uav_id(1)_type(2dmsaa)_fmtx(uint)
; cb0[0] = (source X offset, source Y offset, copy width, copy height)
; cb0[1] = (dest X offset, dest Y offset, src sample count, dst sample count)
dcl_cb cb0[2]
dcl_num_thread_per_group 8, 8, 1
dcl_literal l0, 0, 1, 2, 3
dcl_literal l1, 4, 5, 6, 7
; Check if the absolute thread ID is outside the bounds of the image copy extents
ult r0.__zw, vAbsTid0.xxxy, cb0[0].zzzw
iand r0.__z_, r0.w, r0.z
if_logicalnz r0.z
; Add source copy offsets to the thread ID to compute texture location.
iadd r0.xyz, vAbsTid0.xyz, cb0[0].xy0
; Add dest copy offsets to the thread ID to compute texture location.
iadd r9.xyz, vAbsTid0.xyz, cb0[1].xy0
switch cb0[1].z
case 2
mov r0.w, l0.x
uav_load_id(1) r1, r0
mov r0.w, l0.y
uav_load_id(1) r2, r0
switch cb0[1].w
case 4
mov r9.w, l0.x
uav_store_id(0) r9, r1
mov r9.w, l0.y
uav_store_id(0) r9, r1
mov r9.w, l0.z
uav_store_id(0) r9, r2
mov r9.w, l0.w
uav_store_id(0) r9, r2
break
case 8
mov r9.w, l0.x
uav_store_id(0) r9, r1
mov r9.w, l0.y
uav_store_id(0) r9, r1
mov r9.w, l0.z
uav_store_id(0) r9, r1
mov r9.w, l0.w
uav_store_id(0) r9, r1
mov r9.w, l1.x
uav_store_id(0) r9, r2
mov r9.w, l1.y
uav_store_id(0) r9, r2
mov r9.w, l1.z
uav_store_id(0) r9, r2
mov r9.w, l1.w
uav_store_id(0) r9, r2
break
default
break
endswitch
break
case 4
mov r0.w, l0.x
uav_load_id(1) r1, r0
mov r0.w, l0.y
uav_load_id(1) r2, r0
mov r0.w, l0.z
uav_load_id(1) r3, r0
mov r0.w, l0.w
uav_load_id(1) r4, r0
switch cb0[1].w
case 2
add_d2 r1, r1, r2
add_d2 r3, r3, r4
mov r9.w, l0.x
uav_store_id(0) r9, r1
mov r9.w, l0.y
uav_store_id(0) r9, r3
break
case 8
mov r9.w, l0.x
uav_store_id(0) r9, r1
mov r9.w, l0.y
uav_store_id(0) r9, r1
mov r9.w, l0.z
uav_store_id(0) r9, r2
mov r9.w, l0.w
uav_store_id(0) r9, r2
mov r9.w, l1.x
uav_store_id(0) r9, r3
mov r9.w, l1.y
uav_store_id(0) r9, r3
mov r9.w, l1.z
uav_store_id(0) r9, r4
mov r9.w, l1.w
uav_store_id(0) r9, r4
break
default
break
endswitch
break
case 8
mov r0.w, l0.x
uav_load_id(1) r1, r0
mov r0.w, l0.y
uav_load_id(1) r2, r0
mov r0.w, l0.z
uav_load_id(1) r3, r0
mov r0.w, l0.w
uav_load_id(1) r4, r0
mov r0.w, l1.x
uav_load_id(1) r5, r0
mov r0.w, l1.y
uav_load_id(1) r6, r0
mov r0.w, l1.z
uav_load_id(1) r7, r0
mov r0.w, l1.w
uav_load_id(1) r8, r0
switch cb0[1].w
case 2
add_d2 r1, r1, r2
add_d2 r3, r3, r4
add_d2 r5, r5, r6
add_d2 r7, r7, r8
add_d2 r1, r1, r3
add_d2 r5, r5, r7
mov r9.w, l0.x
uav_store_id(0) r9, r1
mov r9.w, l0.y
uav_store_id(0) r9, r5
break
case 4
add_d2 r1, r1, r2
add_d2 r3, r3, r4
add_d2 r5, r5, r6
add_d2 r7, r7, r8
mov r9.w, l0.x
uav_store_id(0) r9, r1
mov r9.w, l0.y
uav_store_id(0) r9, r3
mov r9.w, l0.z
uav_store_id(0) r9, r5
mov r9.w, l0.w
uav_store_id(0) r9, r7
break
default
break
endswitch
break
default
break
endswitch
endif
end
[ResourceMappingNodes]
rsrcInfo:
- type: Uav
sizeInDwords: 8
id: 0
- type: Uav
sizeInDwords: 8
id: 1
- type: InlineConst
sizeInDwords: 4
id: 0
slot: 0
- type: InlineConst
sizeInDwords: 4
id: 0
slot: 1
[ResourceMappingRootNodes]
- type: DescriptorTableVaPtr
visibility: cs
sizeInDwords: 1
pNext: rsrcInfo
| |
using System;
using System.Globalization;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Text;
using System.IO;
using System.Xml.Serialization;
using CsDO.Lib;
using CsDO.Lib.Configuration;
namespace CsDO.Lib.MockDriver
{
internal class ResultCache
{
#region Factory
public static readonly ResultCache Instance = new ResultCache( );
#endregion
#region Enums
public enum CacheEntryType
{
ExecuteDbDataReader = 0,
ExecuteScalar = 1,
ExecuteNonQuery = 2
}
#endregion
#region Constants
private const string CacheKeySeparator = "|";
#endregion
#region Private vars
private Dictionary<int, ResultCacheEntry> _cache = new Dictionary<int, ResultCacheEntry>( );
private object syncRoot = new object( );
#endregion
#region Properties
public ResultCacheEntry this[ int hashedKey ]
{
get
{
return Get( hashedKey );
}
}
#endregion
#region Constructors
private ResultCache( )
{
Load( );
}
#endregion
#region Public Methods
public ResultCacheEntry Get( int hashedKey )
{
if ( !ConfigurationHelper.Instance.TestMode )
return null;
if ( _cache.ContainsKey( hashedKey ) )
return _cache[ hashedKey ];
else
return new ResultCacheEntry(hashedKey, 1, ((MockDriver)Conf.Driver).ds);
}
public void Add( int hashedKey, object scalarResult )
{
if ( ConfigurationHelper.Instance.TestMode )
return;
if ( !_cache.ContainsKey( hashedKey ) )
_cache.Add( hashedKey, new ResultCacheEntry( hashedKey, scalarResult ) );
else
_cache[ hashedKey ] = new ResultCacheEntry( hashedKey, scalarResult );
Save( );
}
public void Add( int hashedKey, object scalarResult, DataSet dataSetResult )
{
if ( ConfigurationHelper.Instance.TestMode )
return;
if ( !_cache.ContainsKey( hashedKey ) )
_cache.Add( hashedKey, new ResultCacheEntry( hashedKey, scalarResult, dataSetResult ) );
else
_cache[ hashedKey ] = new ResultCacheEntry( hashedKey, scalarResult, dataSetResult );
Save( );
}
public static int GetHashedKey( string cacheEntryType, DbCommand command )
{
StringBuilder sb = new StringBuilder( );
GetParameterDataString( sb, command );
return ( String.Format( CultureInfo.InvariantCulture, "{0}{1}", cacheEntryType, sb.ToString( ) ) ).GetHashCode( );
}
#endregion
#region Private Methods
private void Load( )
{
lock ( syncRoot )
{
TextReader reader = null;
try
{
if ( File.Exists( ConfigurationHelper.Instance.CacheFile ) )
{
reader = new StreamReader( ConfigurationHelper.Instance.CacheFile );
XmlSerializer serializer = new XmlSerializer( typeof( ResultCacheEntry[ ] ) );
ResultCacheEntry[ ] cacheEntrys = ( ResultCacheEntry[ ] )serializer.Deserialize( reader );
reader.Close( );
_cache.Clear( );
foreach ( ResultCacheEntry entry in cacheEntrys )
_cache.Add( entry.HashedKey, entry );
}
}
catch
{
if ( reader != null )
reader.Close( );
if ( File.Exists( ConfigurationHelper.Instance.CacheFile ) )
File.Delete( ConfigurationHelper.Instance.CacheFile );
}
}
}
private void Save( )
{
ResultCacheEntry[ ] cacheEntrys = new ResultCacheEntry[ _cache.Count ];
int i = 0;
foreach ( KeyValuePair<int, ResultCacheEntry> kvp in _cache )
{
cacheEntrys[ i ] = kvp.Value;
i++;
}
lock ( syncRoot )
{
TextWriter writer = new StreamWriter( ConfigurationHelper.Instance.CacheFile, false );
XmlSerializer serializer = new XmlSerializer( typeof( ResultCacheEntry[ ] ) );
serializer.Serialize( writer, cacheEntrys );
writer.Close( );
}
}
private static void GetParameterDataString( StringBuilder sb, DbCommand parameter )
{
if ( parameter != null && !String.IsNullOrEmpty( parameter.CommandText ) )
{
sb.Append( CacheKeySeparator );
sb.Append( parameter.CommandText );
if ( parameter.Parameters != null && parameter.Parameters.Count != 0 )
{
foreach ( DbParameter param in parameter.Parameters )
{
if ( param.Direction == ParameterDirection.Input || param.Direction == ParameterDirection.InputOutput )
{
if ( !String.IsNullOrEmpty( param.ParameterName ) )
{
sb.Append( CacheKeySeparator );
sb.Append( param.ParameterName );
}
try
{
if ( param.Value != null )
{
sb.Append( CacheKeySeparator );
sb.Append( param.Value.ToString( ) );
}
}
catch { }
}
}
}
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Description;
using IDoTodos.Areas.HelpPage.Models;
namespace IDoTodos.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 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 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)
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
model = GenerateApiModel(apiDescription, sampleGenerator);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HelpPageSampleGenerator sampleGenerator)
{
HelpPageApiModel apiModel = new HelpPageApiModel();
apiModel.ApiDescription = apiDescription;
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(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}", e.Message));
}
return apiModel;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Xml;
using System.IO;
using System.Xml.Schema;
using System.Xml.Serialization;
using System.ComponentModel;
using System.Text;
using System.Web.Services.Configuration;
namespace System.Web.Services.Description {
[XmlFormatExtension("binding", Namespace, typeof(Binding))]
[XmlFormatExtensionPrefix("soap", Namespace)]
[XmlFormatExtensionPrefix("soapenc", "http://schemas.xmlsoap.org/soap/encoding/")]
public class SoapBinding : ServiceDescriptionFormatExtension {
private string _transport;
private static XmlSchema s_schema = null;
public const string Namespace = "http://schemas.xmlsoap.org/wsdl/soap/";
public const string HttpTransport = "http://schemas.xmlsoap.org/soap/http";
[XmlAttribute("transport")]
public string Transport {
get { return _transport == null ? string.Empty : _transport; }
set { _transport = value; }
}
[XmlAttribute("style"), DefaultValue(SoapBindingStyle.Document)]
public SoapBindingStyle Style { get; set; } = SoapBindingStyle.Document;
public static XmlSchema Schema {
get {
if (s_schema == null) {
using (XmlTextReader reader = new XmlTextReader(new StringReader(Schemas.Soap)))
{
reader.DtdProcessing = DtdProcessing.Ignore;
s_schema = XmlSchema.Read(reader, null);
}
}
return s_schema;
}
}
}
public enum SoapBindingStyle {
[XmlIgnore]
Default,
[XmlEnum("document")]
Document,
[XmlEnum("rpc")]
Rpc,
}
[XmlFormatExtension("operation", SoapBinding.Namespace, typeof(OperationBinding))]
public class SoapOperationBinding : ServiceDescriptionFormatExtension {
private string _soapAction;
[XmlAttribute("soapAction")]
public string SoapAction {
get { return _soapAction == null ? string.Empty : _soapAction; }
set { _soapAction = value; }
}
[XmlAttribute("style"), DefaultValue(SoapBindingStyle.Default)]
public SoapBindingStyle Style { get; set; }
}
[XmlFormatExtension("body", SoapBinding.Namespace, typeof(InputBinding), typeof(OutputBinding), typeof(MimePart))]
public class SoapBodyBinding : ServiceDescriptionFormatExtension {
private string _ns;
private string _encoding;
[XmlAttribute("use"), DefaultValue(SoapBindingUse.Default)]
public SoapBindingUse Use { get; set; }
[XmlAttribute("namespace"), DefaultValue("")]
public string Namespace {
get { return _ns == null ? string.Empty : _ns; }
set { _ns = value; }
}
[XmlAttribute("encodingStyle"), DefaultValue("")]
public string Encoding {
get { return _encoding == null ? string.Empty : _encoding; }
set { _encoding = value; }
}
[XmlAttribute("parts")]
public string PartsString {
get {
if (Parts == null)
{
return null;
}
StringBuilder builder = new StringBuilder();
for (int i = 0; i < Parts.Length; i++) {
if (i > 0)
{
builder.Append(' ');
}
builder.Append(Parts[i]);
}
return builder.ToString();
}
set {
if (value == null)
{
Parts = null;
}
else
{
Parts = value.Split(new char[] { ' ' });
}
}
}
[XmlIgnore]
public string[] Parts { get; set; }
}
public enum SoapBindingUse {
[XmlIgnore]
Default,
[XmlEnum("encoded")]
Encoded,
[XmlEnum("literal")]
Literal,
}
[XmlFormatExtension("fault", SoapBinding.Namespace, typeof(FaultBinding))]
public class SoapFaultBinding : ServiceDescriptionFormatExtension {
private string _ns;
private string _encoding;
[XmlAttribute("use"), DefaultValue(SoapBindingUse.Default)]
public SoapBindingUse Use { get; set; }
[XmlAttribute("name")]
public string Name { get; set; }
[XmlAttribute("namespace")]
public string Namespace {
get { return _ns == null ? string.Empty : _ns; }
set { _ns = value; }
}
[XmlAttribute("encodingStyle"), DefaultValue("")]
public string Encoding {
get { return _encoding == null ? string.Empty : _encoding; }
set { _encoding = value; }
}
}
[XmlFormatExtension("header", SoapBinding.Namespace, typeof(InputBinding), typeof(OutputBinding))]
public class SoapHeaderBinding : ServiceDescriptionFormatExtension {
private string _encoding;
private string _ns;
[XmlIgnore]
public bool MapToProperty { get; set; }
[XmlAttribute("message")]
public XmlQualifiedName Message { get; set; } = XmlQualifiedName.Empty;
[XmlAttribute("part")]
public string Part { get; set; }
[XmlAttribute("use"), DefaultValue(SoapBindingUse.Default)]
public SoapBindingUse Use { get; set; }
[XmlAttribute("encodingStyle"), DefaultValue("")]
public string Encoding {
get { return _encoding == null ? string.Empty : _encoding; }
set { _encoding = value; }
}
[XmlAttribute("namespace"), DefaultValue("")]
public string Namespace {
get { return _ns == null ? string.Empty : _ns; }
set { _ns = value; }
}
[XmlElement("headerfault")]
public SoapHeaderFaultBinding Fault { get; set; }
}
public class SoapHeaderFaultBinding : ServiceDescriptionFormatExtension {
private string _encoding;
private string _ns;
[XmlAttribute("message")]
public XmlQualifiedName Message { get; set; } = XmlQualifiedName.Empty;
[XmlAttribute("part")]
public string Part { get; set; }
[XmlAttribute("use"), DefaultValue(SoapBindingUse.Default)]
public SoapBindingUse Use { get; set; }
[XmlAttribute("encodingStyle"), DefaultValue("")]
public string Encoding {
get { return _encoding == null ? string.Empty : _encoding; }
set { _encoding = value; }
}
[XmlAttribute("namespace"), DefaultValue("")]
public string Namespace {
get { return _ns == null ? string.Empty : _ns; }
set { _ns = value; }
}
}
[XmlFormatExtension("address", SoapBinding.Namespace, typeof(Port))]
public class SoapAddressBinding : ServiceDescriptionFormatExtension {
private string _location;
[XmlAttribute("location")]
public string Location {
get { return _location == null ? string.Empty : _location; }
set { _location = value; }
}
}
}
| |
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Tencent is pleased to support the open source community by making behaviac available.
//
// Copyright (C) 2015-2017 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at http://opensource.org/licenses/BSD-3-Clause
//
// Unless required by applicable law or agreed to in writing, software distributed under the License is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and limitations under the License.
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
using System.Collections.Generic;
namespace behaviac
{
// ============================================================================
public class State : BehaviorNode
{
protected override void load(int version, string agentType, List<property_t> properties)
{
base.load(version, agentType, properties);
for (int i = 0; i < properties.Count; ++i)
{
property_t p = properties[i];
if (p.name == "Method")
{
this.m_method = AgentMeta.ParseMethod(p.value);
}
else if (p.name == "IsEndState")
{
this.m_bIsEndState = (p.value == "true");
}
}
}
public override void Attach(BehaviorNode pAttachment, bool bIsPrecondition, bool bIsEffector, bool bIsTransition)
{
if (bIsTransition)
{
Debug.Check(!bIsEffector && !bIsPrecondition);
if (this.m_transitions == null)
{
this.m_transitions = new List<Transition>();
}
Transition pTransition = pAttachment as Transition;
Debug.Check(pTransition != null);
this.m_transitions.Add(pTransition);
return;
}
Debug.Check(bIsTransition == false);
base.Attach(pAttachment, bIsPrecondition, bIsEffector, bIsTransition);
}
public override bool IsValid(Agent pAgent, BehaviorTask pTask)
{
if (!(pTask.GetNode() is State))
{
return false;
}
return base.IsValid(pAgent, pTask);
}
public bool IsEndState
{
get
{
return this.m_bIsEndState;
}
}
public EBTStatus Execute(Agent pAgent)
{
EBTStatus result = EBTStatus.BT_RUNNING;
if (this.m_method != null)
{
this.m_method.Run(pAgent);
}
else
{
result = this.update_impl(pAgent, EBTStatus.BT_RUNNING);
}
return result;
}
protected override BehaviorTask createTask()
{
StateTask pTask = new StateTask();
return pTask;
}
//nextStateId holds the next state id if it returns running when a certain transition is satisfied
//otherwise, it returns success or failure if it ends
public EBTStatus Update(Agent pAgent, out int nextStateId)
{
nextStateId = -1;
//when no method is specified(m_method == null),
//'update_impl' is used to return the configured result status for both xml/bson and c#
EBTStatus result = this.Execute(pAgent);
if (this.m_bIsEndState)
{
result = EBTStatus.BT_SUCCESS;
}
else
{
bool bTransitioned = UpdateTransitions(pAgent, this, this.m_transitions, ref nextStateId, result);
if (bTransitioned)
{
result = EBTStatus.BT_SUCCESS;
}
}
return result;
}
public static bool UpdateTransitions(Agent pAgent, BehaviorNode node, List<Transition> transitions, ref int nextStateId, EBTStatus result)
{
bool bTransitioned = false;
if (transitions != null)
{
for (int i = 0; i < transitions.Count; ++i)
{
Transition transition = transitions[i];
if (transition.Evaluate(pAgent, result))
{
nextStateId = transition.TargetStateId;
Debug.Check(nextStateId != -1);
//transition actions
transition.ApplyEffects(pAgent, Effector.EPhase.E_BOTH);
#if !BEHAVIAC_RELEASE
if (Config.IsLoggingOrSocketing)
{
BehaviorTask.CHECK_BREAKPOINT(pAgent, node, "transition", EActionResult.EAR_none);
}
#endif
bTransitioned = true;
break;
}
}
}
return bTransitioned;
}
protected bool m_bIsEndState;
protected IMethod m_method;
protected List<Transition> m_transitions;
public class StateTask : LeafTask
{
public override void copyto(BehaviorTask target)
{
base.copyto(target);
}
public override void save(ISerializableNode node)
{
base.save(node);
}
public override void load(ISerializableNode node)
{
base.load(node);
}
protected int m_nextStateId = -1;
public override int GetNextStateId()
{
return m_nextStateId;
}
public bool IsEndState
{
get
{
Debug.Check(this.GetNode() is State, "node is not an State");
State pStateNode = (State)(this.GetNode());
return pStateNode.IsEndState;
}
}
protected override bool onenter(Agent pAgent)
{
this.m_nextStateId = -1;
return true;
}
protected override void onexit(Agent pAgent, EBTStatus s)
{
}
protected override EBTStatus update(Agent pAgent, EBTStatus childStatus)
{
Debug.Check(childStatus == EBTStatus.BT_RUNNING);
Debug.Check(this.GetNode() is State, "node is not an State");
State pStateNode = (State)(this.GetNode());
EBTStatus result = pStateNode.Update(pAgent, out this.m_nextStateId);
return result;
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.Linq;
using MbUnit.Framework;
using Moq;
using Subtext.Framework;
using Subtext.Framework.Components;
using Subtext.Framework.Data;
namespace UnitTests.Subtext.Framework.Data
{
/// <summary>
/// Summary description for DataHelperTests.
/// </summary>
[TestFixture]
public class DataHelperTests
{
[Test]
public void ReadFeedbackItem_ReadsParentEntrySyndicated_AsUTC()
{
// arrange
var reader = new Mock<IDataReader>();
DateTime dateSyndicated = DateTime.ParseExact("2009/08/15 11:00 PM", "yyyy/MM/dd hh:mm tt", CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal);
reader.SetupGet(r => r["Id"]).Returns(1);
reader.SetupGet(r => r["Title"]).Returns("Test");
reader.SetupGet(r => r["Body"]).Returns("Foo");
reader.SetupGet(r => r["EntryId"]).Returns(99);
reader.SetupGet(r => r["Author"]).Returns("Author");
reader.SetupGet(r => r["IsBlogAuthor"]).Returns(false);
reader.SetupGet(r => r["Email"]).Returns("Foo");
reader.SetupGet(r => r["Url"]).Returns("http://subtextproject.com/");
reader.SetupGet(r => r["FeedbackType"]).Returns(1);
reader.SetupGet(r => r["StatusFlag"]).Returns(1);
reader.SetupGet(r => r["CommentAPI"]).Returns(false);
reader.SetupGet(r => r["Referrer"]).Returns("Foo");
reader.SetupGet(r => r["IpAddress"]).Returns("127.0.0.1");
reader.SetupGet(r => r["UserAgent"]).Returns("Foo");
reader.SetupGet(r => r["FeedbackChecksumHash"]).Returns("Foo");
reader.SetupGet(r => r["DateCreatedUtc"]).Returns(dateSyndicated.AddDays(-2));
reader.SetupGet(r => r["DateModifiedUtc"]).Returns(dateSyndicated.AddHours(-1));
reader.SetupGet(r => r["ParentEntryName"]).Returns("FooBarParent");
reader.SetupGet(r => r["ParentEntryCreateDateUtc"]).Returns(dateSyndicated.AddDays(-5));
reader.SetupGet(r => r["ParentEntryDatePublishedUtc"]).Returns(dateSyndicated.AddDays(-4));
// act
var feedback = reader.Object.ReadFeedbackItem();
// assert
Assert.AreEqual(dateSyndicated.AddDays(-4), feedback.ParentDatePublishedUtc);
Assert.AreEqual(DateTimeKind.Utc, feedback.DateCreatedUtc.Kind);
Assert.AreEqual(DateTimeKind.Utc, feedback.DateModifiedUtc.Kind);
Assert.AreEqual(DateTimeKind.Utc, feedback.ParentDateCreatedUtc.Kind);
Assert.AreEqual(DateTimeKind.Utc, feedback.ParentDatePublishedUtc.Kind);
}
[Test]
public void ReadValue_WithValueMatchingType_ReturnsValueAsType()
{
//arrange
var reader = new Mock<IDataReader>();
reader.SetupGet(r => r["column"]).Returns(98008);
//act
var result = reader.Object.ReadValue<int>("column");
//assert
Assert.AreEqual(98008, result);
}
[Test]
public void ReadValue_WithValueReturningDbNull_ReturnsDefaultValue()
{
//arrange
var reader = new Mock<IDataReader>();
reader.SetupGet(r => r["column"]).Returns(DBNull.Value);
//act
var result = reader.Object.ReadValue("column", 8675309);
//assert
Assert.AreEqual(8675309, result);
}
[Test]
public void ReadValue_WithValueReturningNull_ReturnsDefaultValue()
{
//arrange
var reader = new Mock<IDataReader>();
reader.SetupGet(r => r["column"]).Returns(null);
//act
var result = reader.Object.ReadValue("column", 8675309);
//assert
Assert.AreEqual(8675309, result);
}
[Test]
public void ReadValue_WithValueFuncThrowingFormatException_ReturnsDefaultValue()
{
//arrange
var reader = new Mock<IDataReader>();
reader.SetupGet(r => r["column"]).Returns(null);
//act
var result = reader.Object.ReadValue("column", value => { throw new FormatException(); }, 8675309);
//assert
Assert.AreEqual(8675309, result);
}
[Test]
public void ReadValue_WithValueFuncThrowingIndexOutOfRangeException_ReturnsDefaultValue()
{
//arrange
var reader = new Mock<IDataReader>();
reader.SetupGet(r => r["column"]).Returns(null);
//act
var result = reader.Object.ReadValue("column", value => { throw new IndexOutOfRangeException(); }, 8675309);
//assert
Assert.AreEqual(8675309, result);
}
[Test]
public void AsEnumerable_WithMultipleRows_ReturnsEnumerationOfRows()
{
//arrange
var reader = new Mock<IDataReader>();
reader.Setup(r => r.Read()).Returns(new Queue<bool>(new[] { true, true, false }).Dequeue);
reader.SetupGet(r => r["column"]).Returns(new Queue<object>(new object[] { 123, 456 }).Dequeue);
//act
var result = reader.Object.ReadEnumerable(r => r.ReadValue<Int32>("column")).ToList();
//assert
Assert.AreEqual(123, result[0]);
Assert.AreEqual(456, result[1]);
}
[Test]
public void AsPagedCollection_WithMultipleRows_ReturnsPagedCollection()
{
//arrange
var reader = new Mock<IDataReader>();
reader.Setup(r => r.Read()).Returns(new Queue<bool>(new[] { true, true, false, true }).Dequeue);
reader.SetupGet(r => r["column"]).Returns(new Queue<object>(new object[] { 123, 456 }).Dequeue);
reader.SetupGet(r => r["TotalRecords"]).Returns(2);
reader.Setup(r => r.NextResult()).Returns(true);
//act
var result = reader.Object.ReadPagedCollection(r => r.ReadValue<int>("column"));
//assert
Assert.AreEqual(123, result[0]);
Assert.AreEqual(456, result[1]);
Assert.AreEqual(2, result.MaxItems);
}
[Test]
public void ReadObject_WithUriProperty_TriesAndParsesUrlAndSetsIt()
{
//arrange
var reader = new Mock<IDataReader>();
reader.Setup(r => r.Read()).Returns(true).AtMostOnce();
reader.SetupGet(r => r["Url"]).Returns("http://subtextproject.com/");
reader.Setup(r => r.Read()).Returns(false);
//act
var result = reader.Object.ReadObject<ObjectWithProperties>();
//assert
Assert.AreEqual("http://subtextproject.com/", result.Url.ToString());
}
[Test]
public void ReadObject_WithComplexProperty_DoesNotTryAndSetIt()
{
//arrange
var reader = new Mock<IDataReader>();
reader.Setup(r => r.Read()).Returns(true).AtMostOnce();
reader.SetupGet(r => r["ComplexObject"]).Throws(new IndexOutOfRangeException());
reader.Setup(r => r.Read()).Returns(false);
//act
var result = reader.Object.ReadObject<ObjectWithProperties>();
//assert
Assert.AreEqual(null, result.ComplexObject);
}
[Test]
public void ReadObject_WithReadOnlyProperty_DoesNotTryAndSetIt()
{
//arrange
var reader = new Mock<IDataReader>();
reader.Setup(r => r.Read()).Returns(true).AtMostOnce();
reader.SetupGet(r => r["ReadOnlyBoolean"]).Throws(new IndexOutOfRangeException());
reader.Setup(r => r.Read()).Returns(false);
//act
var result = reader.Object.ReadObject<ObjectWithProperties>();
//assert
Assert.AreEqual(false, result.ReadOnlyBoolean);
}
[Test]
public void IDataReader_WithIntColumnHavingSameNameAsProperty_PopulatesObjectWithPropertySetCorrectly()
{
//arrange
var reader = new Mock<IDataReader>();
reader.Setup(r => r.Read()).Returns(true).AtMostOnce();
reader.SetupGet(r => r["IntProperty"]).Returns(42);
reader.Setup(r => r.Read()).Returns(false);
//act
var result = reader.Object.ReadObject<ObjectWithProperties>();
//assert
Assert.AreEqual(42, result.IntProperty);
}
[Test]
public void IDataReader_WithStringColumnHavingSameNameAsProperty_PopulatesObjectWithPropertySetCorrectly()
{
//arrange
var reader = new Mock<IDataReader>();
reader.Setup(r => r.Read()).Returns(true).AtMostOnce();
reader.SetupGet(r => r["StringProperty"]).Returns("Hello world");
reader.Setup(r => r.Read()).Returns(false);
//act
var result = reader.Object.ReadObject<ObjectWithProperties>();
//assert
Assert.AreEqual("Hello world", result.StringProperty);
}
[Test]
public void IDataReader_WithDateTimeColumnHavingSameNameAsDateTimeProperty_PopulatesObjectWithPropertySetCorrectly()
{
//arrange
DateTime now = DateTime.UtcNow;
var reader = new Mock<IDataReader>();
reader.Setup(r => r.Read()).Returns(true).AtMostOnce();
reader.SetupGet(r => r["DateProperty"]).Returns(now);
reader.Setup(r => r.Read()).Returns(false);
//act
var result = reader.Object.ReadObject<ObjectWithProperties>();
//assert
Assert.AreEqual(now, result.DateProperty);
}
[Test]
public void IDataReader_WithNullColumn_DoesNotSetProperty()
{
//arrange
var reader = new Mock<IDataReader>();
reader.Setup(r => r.Read()).Returns(true).AtMostOnce();
reader.SetupGet(r => r["NullableIntProperty"]).Returns(DBNull.Value);
reader.Setup(r => r.Read()).Returns(false);
//act
var result = reader.Object.ReadObject<ObjectWithProperties>();
//assert
Assert.AreEqual(null, result.NullableIntProperty);
}
[Test]
public void IDataReader_WithNullableIntColumnHavingSameNameAsProperty_PopulatesObjectWithNullablePropertySetCorrectly()
{
//arrange
var reader = new Mock<IDataReader>();
reader.Setup(r => r.Read()).Returns(true).AtMostOnce();
reader.SetupGet(r => r["NullableIntProperty"]).Returns(23);
reader.Setup(r => r.Read()).Returns(false);
//act
var result = reader.Object.ReadObject<ObjectWithProperties>();
//assert
Assert.AreEqual(23, result.NullableIntProperty);
}
/// <summary>
/// Makes sure that we parse the date correctly.
/// </summary>
[Test]
public void LoadArchiveCountParsesDateCorrectly()
{
// Arrange
var reader = new TestDataReader();
reader.AddRecord(1, 2, 2005, 23);
reader.AddRecord(1, 23, 2005, 23);
// Act
ICollection<ArchiveCount> archive = DataHelper.ReadArchiveCount(reader);
// Assert
Assert.AreEqual(2, archive.Count, "Should only have two records.");
ArchiveCount first = null;
ArchiveCount second = null;
foreach (ArchiveCount count in archive)
{
if (first == null)
{
first = count;
continue;
}
if (second == null)
{
second = count;
continue;
}
}
Assert.AreEqual(DateTime.ParseExact("01/02/2005", "MM/dd/yyyy", CultureInfo.InvariantCulture), first.Date,
"Something happened to the date parsing.");
Assert.AreEqual(DateTime.ParseExact("01/23/2005", "MM/dd/yyyy", CultureInfo.InvariantCulture), second.Date,
"Something happened to the date parsing.");
}
#region Test class that implements IDataReader
#region Nested type: DataReaderRecord
internal struct DataReaderRecord
{
public int Count;
public int Day;
public int Month;
public int Year;
public DataReaderRecord(int month, int day, int year, int count)
{
Month = month;
Day = day;
Year = year;
Count = count;
}
}
#endregion
#region Nested type: TestDataReader
internal class TestDataReader : IDataReader
{
readonly ArrayList _records = new ArrayList();
int _currentIndex = -1;
#region IDataReader Members
public string GetName(int i)
{
throw new NotImplementedException();
}
public string GetDataTypeName(int i)
{
throw new NotImplementedException();
}
public Type GetFieldType(int i)
{
throw new NotImplementedException();
}
public object GetValue(int i)
{
throw new NotImplementedException();
}
public int GetValues(object[] values)
{
throw new NotImplementedException();
}
public int GetOrdinal(string name)
{
throw new NotImplementedException();
}
public bool GetBoolean(int i)
{
throw new NotImplementedException();
}
public byte GetByte(int i)
{
throw new NotImplementedException();
}
public long GetBytes(int i, long fieldOffset, byte[] buffer, int bufferoffset, int length)
{
throw new NotImplementedException();
}
public char GetChar(int i)
{
throw new NotImplementedException();
}
public long GetChars(int i, long fieldoffset, char[] buffer, int bufferoffset, int length)
{
throw new NotImplementedException();
}
public Guid GetGuid(int i)
{
throw new NotImplementedException();
}
public short GetInt16(int i)
{
throw new NotImplementedException();
}
public int GetInt32(int i)
{
throw new NotImplementedException();
}
public long GetInt64(int i)
{
throw new NotImplementedException();
}
public float GetFloat(int i)
{
throw new NotImplementedException();
}
public double GetDouble(int i)
{
throw new NotImplementedException();
}
public string GetString(int i)
{
throw new NotImplementedException();
}
public decimal GetDecimal(int i)
{
throw new NotImplementedException();
}
public DateTime GetDateTime(int i)
{
throw new NotImplementedException();
}
public IDataReader GetData(int i)
{
throw new NotImplementedException();
}
public bool IsDBNull(int i)
{
throw new NotImplementedException();
}
public int FieldCount
{
get { throw new NotImplementedException(); }
}
public object this[int i]
{
get { throw new NotImplementedException(); }
}
public void Close()
{
throw new NotImplementedException();
}
public bool NextResult()
{
throw new NotImplementedException();
}
public bool Read()
{
return ++_currentIndex < _records.Count;
}
public DataTable GetSchemaTable()
{
throw new NotImplementedException();
}
public int Depth
{
get { throw new NotImplementedException(); }
}
public bool IsClosed
{
get { throw new NotImplementedException(); }
}
public int RecordsAffected
{
get { throw new NotImplementedException(); }
}
public void Dispose()
{
throw new NotImplementedException();
}
public object this[string name]
{
get
{
if (_records.Count == 0)
{
throw new InvalidOperationException("No records in this reader.");
}
var record = (DataReaderRecord)_records[_currentIndex];
switch (name)
{
case "Month":
return record.Month;
case "Day":
return record.Day;
case "Year":
return record.Year;
case "Count":
return record.Count;
}
throw new InvalidOperationException("Unexpected column '" + name + "'");
}
}
#endregion
public void AddRecord(int month, int day, int year, int count)
{
_records.Add(new DataReaderRecord(month, day, year, count));
}
public void AddRecord(DataReaderRecord record)
{
_records.Add(record);
}
}
#endregion
#endregion
#region Nested type: ObjectWithProperties
public class ObjectWithProperties
{
public int IntProperty { get; set; }
public int? NullableIntProperty { get; set; }
public string StringProperty { get; set; }
public bool ReadOnlyBoolean { get; private set; }
public Blog ComplexObject { get; set; }
public DateTime DateProperty { get; set; }
public Uri Url { get; set; }
}
#endregion
}
}
| |
// Generated by SharpKit.QooxDoo.Generator
using System;
using System.Collections.Generic;
using SharpKit.Html;
using SharpKit.JavaScript;
namespace qx.ui.control
{
/// <summary>
/// <para>A typical color selector as known from native applications.</para>
/// <para>Includes support for RGB and HSB color areas.</para>
/// </summary>
[JsType(JsMode.Prototype, Name = "qx.ui.control.ColorSelector", OmitOptionalParameters = true, Export = false)]
public partial class ColorSelector : qx.ui.core.Widget, qx.ui.form.IColorForm
{
#region Events
/// <summary>
/// <para>Fired when the value was modified</para>
/// </summary>
public event Action<qx.eventx.type.Data> OnChangeValue;
/// <summary>
/// <para>Fired when the “Cancel” button is clicked.</para>
/// </summary>
public event Action<qx.eventx.type.Event> OnDialogcancel;
/// <summary>
/// <para>Fired when the “OK” button is clicked.</para>
/// </summary>
public event Action<qx.eventx.type.Event> OnDialogok;
#endregion Events
#region Properties
/// <summary>
/// <para>The appearance ID. This ID is used to identify the appearance theme
/// entry to use for this widget. This controls the styling of the element.</para>
/// </summary>
[JsProperty(Name = "appearance", NativeField = true)]
public string Appearance { get; set; }
/// <summary>
/// <para>The numeric blue value of the selected color.</para>
/// </summary>
[JsProperty(Name = "blue", NativeField = true)]
public double Blue { get; set; }
/// <summary>
/// <para>The numeric brightness value.</para>
/// </summary>
[JsProperty(Name = "brightness", NativeField = true)]
public double Brightness { get; set; }
/// <summary>
/// <para>The numeric green value of the selected color.</para>
/// </summary>
[JsProperty(Name = "green", NativeField = true)]
public double Green { get; set; }
/// <summary>
/// <para>The numeric hue value.</para>
/// </summary>
[JsProperty(Name = "hue", NativeField = true)]
public double Hue { get; set; }
/// <summary>
/// <para>The numeric red value of the selected color.</para>
/// </summary>
[JsProperty(Name = "red", NativeField = true)]
public double Red { get; set; }
/// <summary>
/// <para>The numeric saturation value.</para>
/// </summary>
[JsProperty(Name = "saturation", NativeField = true)]
public double Saturation { get; set; }
#endregion Properties
#region Methods
/// <summary>
/// <para>Creates a ColorSelector.</para>
/// </summary>
public ColorSelector() { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the (computed) value of the property blue.</para>
/// </summary>
[JsMethod(Name = "getBlue")]
public double GetBlue() { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the (computed) value of the property brightness.</para>
/// </summary>
[JsMethod(Name = "getBrightness")]
public double GetBrightness() { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the (computed) value of the property green.</para>
/// </summary>
[JsMethod(Name = "getGreen")]
public double GetGreen() { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the (computed) value of the property hue.</para>
/// </summary>
[JsMethod(Name = "getHue")]
public double GetHue() { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the (computed) value of the property red.</para>
/// </summary>
[JsMethod(Name = "getRed")]
public double GetRed() { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the (computed) value of the property saturation.</para>
/// </summary>
[JsMethod(Name = "getSaturation")]
public double GetSaturation() { throw new NotImplementedException(); }
/// <summary>
/// <para>The element’s user set value.</para>
/// </summary>
/// <returns>The value.</returns>
[JsMethod(Name = "getValue")]
public string GetValue() { throw new NotImplementedException(); }
/// <summary>
/// <para>Calls the apply method and dispatches the change event of the property blue
/// with the default value defined by the class developer. This function can
/// only be called from the constructor of a class.</para>
/// </summary>
/// <param name="value">Initial value for property blue.</param>
[JsMethod(Name = "initBlue")]
public void InitBlue(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Calls the apply method and dispatches the change event of the property brightness
/// with the default value defined by the class developer. This function can
/// only be called from the constructor of a class.</para>
/// </summary>
/// <param name="value">Initial value for property brightness.</param>
[JsMethod(Name = "initBrightness")]
public void InitBrightness(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Calls the apply method and dispatches the change event of the property green
/// with the default value defined by the class developer. This function can
/// only be called from the constructor of a class.</para>
/// </summary>
/// <param name="value">Initial value for property green.</param>
[JsMethod(Name = "initGreen")]
public void InitGreen(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Calls the apply method and dispatches the change event of the property hue
/// with the default value defined by the class developer. This function can
/// only be called from the constructor of a class.</para>
/// </summary>
/// <param name="value">Initial value for property hue.</param>
[JsMethod(Name = "initHue")]
public void InitHue(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Calls the apply method and dispatches the change event of the property red
/// with the default value defined by the class developer. This function can
/// only be called from the constructor of a class.</para>
/// </summary>
/// <param name="value">Initial value for property red.</param>
[JsMethod(Name = "initRed")]
public void InitRed(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Calls the apply method and dispatches the change event of the property saturation
/// with the default value defined by the class developer. This function can
/// only be called from the constructor of a class.</para>
/// </summary>
/// <param name="value">Initial value for property saturation.</param>
[JsMethod(Name = "initSaturation")]
public void InitSaturation(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property blue.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetBlue")]
public void ResetBlue() { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property brightness.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetBrightness")]
public void ResetBrightness() { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property green.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetGreen")]
public void ResetGreen() { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property hue.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetHue")]
public void ResetHue() { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property red.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetRed")]
public void ResetRed() { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property saturation.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetSaturation")]
public void ResetSaturation() { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the element’s value to its initial value.</para>
/// </summary>
[JsMethod(Name = "resetValue")]
public void ResetValue() { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the user value of the property blue.</para>
/// </summary>
/// <param name="value">New value for property blue.</param>
[JsMethod(Name = "setBlue")]
public void SetBlue(double value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the user value of the property brightness.</para>
/// </summary>
/// <param name="value">New value for property brightness.</param>
[JsMethod(Name = "setBrightness")]
public void SetBrightness(double value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the user value of the property green.</para>
/// </summary>
/// <param name="value">New value for property green.</param>
[JsMethod(Name = "setGreen")]
public void SetGreen(double value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the user value of the property hue.</para>
/// </summary>
/// <param name="value">New value for property hue.</param>
[JsMethod(Name = "setHue")]
public void SetHue(double value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets previous color’s to given values.</para>
/// </summary>
/// <param name="red">Red color value.</param>
/// <param name="green">Green color value.</param>
/// <param name="blue">Blue color value.</param>
[JsMethod(Name = "setPreviousColor")]
public void SetPreviousColor(double red, double green, double blue) { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the user value of the property red.</para>
/// </summary>
/// <param name="value">New value for property red.</param>
[JsMethod(Name = "setRed")]
public void SetRed(double value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the user value of the property saturation.</para>
/// </summary>
/// <param name="value">New value for property saturation.</param>
[JsMethod(Name = "setSaturation")]
public void SetSaturation(double value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the element’s value.</para>
/// </summary>
/// <param name="value">The new value of the element.</param>
[JsMethod(Name = "setValue")]
public void SetValue(string value) { throw new NotImplementedException(); }
#endregion Methods
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Xunit;
namespace System.Runtime.CompilerServices
{
public class UnsafeTests
{
[Fact]
public static unsafe void ReadInt32()
{
int expected = 10;
void* address = Unsafe.AsPointer(ref expected);
int ret = Unsafe.Read<int>(address);
Assert.Equal(expected, ret);
}
[Fact]
public static unsafe void WriteInt32()
{
int value = 10;
int* address = (int*)Unsafe.AsPointer(ref value);
int expected = 20;
Unsafe.Write(address, expected);
Assert.Equal(expected, value);
Assert.Equal(expected, *address);
Assert.Equal(expected, Unsafe.Read<int>(address));
}
[Fact]
public static unsafe void WriteBytesIntoInt32()
{
int value = 20;
int* intAddress = (int*)Unsafe.AsPointer(ref value);
byte* byteAddress = (byte*)intAddress;
for (int i = 0; i < 4; i++)
{
Unsafe.Write(byteAddress + i, (byte)i);
}
Assert.Equal(0, Unsafe.Read<byte>(byteAddress));
Assert.Equal(1, Unsafe.Read<byte>(byteAddress + 1));
Assert.Equal(2, Unsafe.Read<byte>(byteAddress + 2));
Assert.Equal(3, Unsafe.Read<byte>(byteAddress + 3));
Byte4 b4 = Unsafe.Read<Byte4>(byteAddress);
Assert.Equal(0, b4.B0);
Assert.Equal(1, b4.B1);
Assert.Equal(2, b4.B2);
Assert.Equal(3, b4.B3);
int expected = (b4.B3 << 24) + (b4.B2 << 16) + (b4.B1 << 8) + (b4.B0);
Assert.Equal(expected, value);
}
[Fact]
public static unsafe void LongIntoCompoundStruct()
{
long value = 1234567891011121314L;
long* longAddress = (long*)Unsafe.AsPointer(ref value);
Byte4Short2 b4s2 = Unsafe.Read<Byte4Short2>(longAddress);
Assert.Equal(162, b4s2.B0);
Assert.Equal(48, b4s2.B1);
Assert.Equal(210, b4s2.B2);
Assert.Equal(178, b4s2.B3);
Assert.Equal(4340, b4s2.S4);
Assert.Equal(4386, b4s2.S6);
b4s2.B0 = 1;
b4s2.B1 = 1;
b4s2.B2 = 1;
b4s2.B3 = 1;
b4s2.S4 = 1;
b4s2.S6 = 1;
Unsafe.Write(longAddress, b4s2);
long expected = 281479288520961;
Assert.Equal(expected, value);
Assert.Equal(expected, Unsafe.Read<long>(longAddress));
}
[Fact]
public static unsafe void ReadWriteDoublePointer()
{
int value1 = 10;
int value2 = 20;
int* valueAddress = (int*)Unsafe.AsPointer(ref value1);
int** valueAddressPtr = &valueAddress;
Unsafe.Write(valueAddressPtr, new IntPtr(&value2));
Assert.Equal(20, *(*valueAddressPtr));
Assert.Equal(20, Unsafe.Read<int>(valueAddress));
Assert.Equal(new IntPtr(valueAddress), Unsafe.Read<IntPtr>(valueAddressPtr));
Assert.Equal(20, Unsafe.Read<int>(Unsafe.Read<IntPtr>(valueAddressPtr).ToPointer()));
}
[Fact]
public static unsafe void CopyToRef()
{
int value = 10;
int destination = -1;
Unsafe.Copy(ref destination, Unsafe.AsPointer(ref value));
Assert.Equal(10, destination);
Assert.Equal(10, value);
int destination2 = -1;
Unsafe.Copy(ref destination2, &value);
Assert.Equal(10, destination2);
Assert.Equal(10, value);
}
[Fact]
public static unsafe void CopyToVoidPtr()
{
int value = 10;
int destination = -1;
Unsafe.Copy(Unsafe.AsPointer(ref destination), ref value);
Assert.Equal(10, destination);
Assert.Equal(10, value);
int destination2 = -1;
Unsafe.Copy(&destination2, ref value);
Assert.Equal(10, destination2);
Assert.Equal(10, value);
}
[Theory]
[MemberData(nameof(SizeOfData))]
public static unsafe void SizeOf<T>(int expected, T valueUnused)
{
// valueUnused is only present to enable Xunit to call the correct generic overload.
Assert.Equal(expected, Unsafe.SizeOf<T>());
}
public static IEnumerable<object[]> SizeOfData()
{
yield return new object[] { 1, new sbyte() };
yield return new object[] { 1, new byte() };
yield return new object[] { 2, new short() };
yield return new object[] { 2, new ushort() };
yield return new object[] { 4, new int() };
yield return new object[] { 4, new uint() };
yield return new object[] { 8, new long() };
yield return new object[] { 8, new ulong() };
yield return new object[] { 4, new float() };
yield return new object[] { 8, new double() };
yield return new object[] { 4, new Byte4() };
yield return new object[] { 8, new Byte4Short2() };
yield return new object[] { 512, new Byte512() };
}
[Theory]
[MemberData(nameof(InitBlockData))]
public static unsafe void InitBlockStack(int numBytes, byte value)
{
byte* stackPtr = stackalloc byte[numBytes];
Unsafe.InitBlock(stackPtr, value, (uint)numBytes);
for (int i = 0; i < numBytes; i++)
{
Assert.Equal(stackPtr[i], value);
}
}
[Theory]
[MemberData(nameof(InitBlockData))]
public static unsafe void InitBlockUnmanaged(int numBytes, byte value)
{
IntPtr allocatedMemory = Marshal.AllocCoTaskMem(numBytes);
byte* bytePtr = (byte*)allocatedMemory.ToPointer();
Unsafe.InitBlock(bytePtr, value, (uint)numBytes);
for (int i = 0; i < numBytes; i++)
{
Assert.Equal(bytePtr[i], value);
}
}
[Theory]
[MemberData(nameof(InitBlockData))]
public static unsafe void InitBlockRefStack(int numBytes, byte value)
{
byte* stackPtr = stackalloc byte[numBytes];
Unsafe.InitBlock(ref *stackPtr, value, (uint)numBytes);
for (int i = 0; i < numBytes; i++)
{
Assert.Equal(stackPtr[i], value);
}
}
[Theory]
[MemberData(nameof(InitBlockData))]
public static unsafe void InitBlockRefUnmanaged(int numBytes, byte value)
{
IntPtr allocatedMemory = Marshal.AllocCoTaskMem(numBytes);
byte* bytePtr = (byte*)allocatedMemory.ToPointer();
Unsafe.InitBlock(ref *bytePtr, value, (uint)numBytes);
for (int i = 0; i < numBytes; i++)
{
Assert.Equal(bytePtr[i], value);
}
}
[Theory]
[MemberData(nameof(InitBlockData))]
public static unsafe void InitBlockUnalignedStack(int numBytes, byte value)
{
byte* stackPtr = stackalloc byte[numBytes + 1];
stackPtr += 1; // +1 = make unaligned
Unsafe.InitBlockUnaligned(stackPtr, value, (uint)numBytes);
for (int i = 0; i < numBytes; i++)
{
Assert.Equal(stackPtr[i], value);
}
}
[Theory]
[MemberData(nameof(InitBlockData))]
public static unsafe void InitBlockUnalignedUnmanaged(int numBytes, byte value)
{
IntPtr allocatedMemory = Marshal.AllocCoTaskMem(numBytes + 1);
byte* bytePtr = (byte*)allocatedMemory.ToPointer() + 1; // +1 = make unaligned
Unsafe.InitBlockUnaligned(bytePtr, value, (uint)numBytes);
for (int i = 0; i < numBytes; i++)
{
Assert.Equal(bytePtr[i], value);
}
}
[Theory]
[MemberData(nameof(InitBlockData))]
public static unsafe void InitBlockUnalignedRefStack(int numBytes, byte value)
{
byte* stackPtr = stackalloc byte[numBytes + 1];
stackPtr += 1; // +1 = make unaligned
Unsafe.InitBlockUnaligned(ref *stackPtr, value, (uint)numBytes);
for (int i = 0; i < numBytes; i++)
{
Assert.Equal(stackPtr[i], value);
}
}
[Theory]
[MemberData(nameof(InitBlockData))]
public static unsafe void InitBlockUnalignedRefUnmanaged(int numBytes, byte value)
{
IntPtr allocatedMemory = Marshal.AllocCoTaskMem(numBytes + 1);
byte* bytePtr = (byte*)allocatedMemory.ToPointer() + 1; // +1 = make unaligned
Unsafe.InitBlockUnaligned(ref *bytePtr, value, (uint)numBytes);
for (int i = 0; i < numBytes; i++)
{
Assert.Equal(bytePtr[i], value);
}
}
public static IEnumerable<object[]> InitBlockData()
{
yield return new object[] { 0, 1 };
yield return new object[] { 1, 1 };
yield return new object[] { 10, 0 };
yield return new object[] { 10, 2 };
yield return new object[] { 10, 255 };
yield return new object[] { 10000, 255 };
}
[Theory]
[MemberData(nameof(CopyBlockData))]
public static unsafe void CopyBlock(int numBytes)
{
byte* source = stackalloc byte[numBytes];
byte* destination = stackalloc byte[numBytes];
for (int i = 0; i < numBytes; i++)
{
byte value = (byte)(i % 255);
source[i] = value;
}
Unsafe.CopyBlock(destination, source, (uint)numBytes);
for (int i = 0; i < numBytes; i++)
{
byte value = (byte)(i % 255);
Assert.Equal(value, destination[i]);
Assert.Equal(source[i], destination[i]);
}
}
[Theory]
[MemberData(nameof(CopyBlockData))]
public static unsafe void CopyBlockRef(int numBytes)
{
byte* source = stackalloc byte[numBytes];
byte* destination = stackalloc byte[numBytes];
for (int i = 0; i < numBytes; i++)
{
byte value = (byte)(i % 255);
source[i] = value;
}
Unsafe.CopyBlock(ref destination[0], ref source[0], (uint)numBytes);
for (int i = 0; i < numBytes; i++)
{
byte value = (byte)(i % 255);
Assert.Equal(value, destination[i]);
Assert.Equal(source[i], destination[i]);
}
}
[Theory]
[MemberData(nameof(CopyBlockData))]
public static unsafe void CopyBlockUnaligned(int numBytes)
{
byte* source = stackalloc byte[numBytes + 1];
byte* destination = stackalloc byte[numBytes + 1];
source += 1; // +1 = make unaligned
destination += 1; // +1 = make unaligned
for (int i = 0; i < numBytes; i++)
{
byte value = (byte)(i % 255);
source[i] = value;
}
Unsafe.CopyBlockUnaligned(destination, source, (uint)numBytes);
for (int i = 0; i < numBytes; i++)
{
byte value = (byte)(i % 255);
Assert.Equal(value, destination[i]);
Assert.Equal(source[i], destination[i]);
}
}
[Theory]
[MemberData(nameof(CopyBlockData))]
public static unsafe void CopyBlockUnalignedRef(int numBytes)
{
byte* source = stackalloc byte[numBytes + 1];
byte* destination = stackalloc byte[numBytes + 1];
source += 1; // +1 = make unaligned
destination += 1; // +1 = make unaligned
for (int i = 0; i < numBytes; i++)
{
byte value = (byte)(i % 255);
source[i] = value;
}
Unsafe.CopyBlockUnaligned(ref destination[0], ref source[0], (uint)numBytes);
for (int i = 0; i < numBytes; i++)
{
byte value = (byte)(i % 255);
Assert.Equal(value, destination[i]);
Assert.Equal(source[i], destination[i]);
}
}
public static IEnumerable<object[]> CopyBlockData()
{
yield return new object[] { 0 };
yield return new object[] { 1 };
yield return new object[] { 10 };
yield return new object[] { 100 };
yield return new object[] { 100000 };
}
[Fact]
public static void As()
{
object o = "Hello";
Assert.Equal("Hello", Unsafe.As<string>(o));
}
[Fact]
public static void DangerousAs()
{
// Verify that As does not perform type checks
object o = new Object();
Assert.IsType(typeof(Object), Unsafe.As<string>(o));
}
[Fact]
public static void ByteOffsetArray()
{
var a = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7 };
Assert.Equal(new IntPtr(0), Unsafe.ByteOffset(ref a[0], ref a[0]));
Assert.Equal(new IntPtr(1), Unsafe.ByteOffset(ref a[0], ref a[1]));
Assert.Equal(new IntPtr(-1), Unsafe.ByteOffset(ref a[1], ref a[0]));
Assert.Equal(new IntPtr(2), Unsafe.ByteOffset(ref a[0], ref a[2]));
Assert.Equal(new IntPtr(-2), Unsafe.ByteOffset(ref a[2], ref a[0]));
Assert.Equal(new IntPtr(3), Unsafe.ByteOffset(ref a[0], ref a[3]));
Assert.Equal(new IntPtr(4), Unsafe.ByteOffset(ref a[0], ref a[4]));
Assert.Equal(new IntPtr(5), Unsafe.ByteOffset(ref a[0], ref a[5]));
Assert.Equal(new IntPtr(6), Unsafe.ByteOffset(ref a[0], ref a[6]));
Assert.Equal(new IntPtr(7), Unsafe.ByteOffset(ref a[0], ref a[7]));
}
[Fact]
public static void ByteOffsetStackByte4()
{
var byte4 = new Byte4();
Assert.Equal(new IntPtr(0), Unsafe.ByteOffset(ref byte4.B0, ref byte4.B0));
Assert.Equal(new IntPtr(1), Unsafe.ByteOffset(ref byte4.B0, ref byte4.B1));
Assert.Equal(new IntPtr(-1), Unsafe.ByteOffset(ref byte4.B1, ref byte4.B0));
Assert.Equal(new IntPtr(2), Unsafe.ByteOffset(ref byte4.B0, ref byte4.B2));
Assert.Equal(new IntPtr(-2), Unsafe.ByteOffset(ref byte4.B2, ref byte4.B0));
Assert.Equal(new IntPtr(3), Unsafe.ByteOffset(ref byte4.B0, ref byte4.B3));
Assert.Equal(new IntPtr(-3), Unsafe.ByteOffset(ref byte4.B3, ref byte4.B0));
}
[Fact]
public static unsafe void AsRef()
{
byte[] b = new byte[4] { 0x42, 0x42, 0x42, 0x42 };
fixed (byte * p = b)
{
ref int r = ref Unsafe.AsRef<int>(p);
Assert.Equal(0x42424242, r);
r = 0x0EF00EF0;
Assert.Equal(0xFE, b[0] | b[1] | b[2] | b[3]);
}
}
[Fact]
public static void RefAs()
{
byte[] b = new byte[4] { 0x42, 0x42, 0x42, 0x42 };
ref int r = ref Unsafe.As<byte, int>(ref b[0]);
Assert.Equal(0x42424242, r);
r = 0x0EF00EF0;
Assert.Equal(0xFE, b[0] | b[1] | b[2] | b[3]);
}
[Fact]
public static void RefAdd()
{
int[] a = new int[] { 0x123, 0x234, 0x345, 0x456 };
ref int r1 = ref Unsafe.Add(ref a[0], 1);
Assert.Equal(0x234, r1);
ref int r2 = ref Unsafe.Add(ref r1, 2);
Assert.Equal(0x456, r2);
ref int r3 = ref Unsafe.Add(ref r2, -3);
Assert.Equal(0x123, r3);
}
[Fact]
public static void RefAddIntPtr()
{
int[] a = new int[] { 0x123, 0x234, 0x345, 0x456 };
ref int r1 = ref Unsafe.Add(ref a[0], (IntPtr)1);
Assert.Equal(0x234, r1);
ref int r2 = ref Unsafe.Add(ref r1, (IntPtr)2);
Assert.Equal(0x456, r2);
ref int r3 = ref Unsafe.Add(ref r2, (IntPtr)(-3));
Assert.Equal(0x123, r3);
}
[Fact]
public static void RefAddByteOffset()
{
byte[] a = new byte[] { 0x12, 0x34, 0x56, 0x78 };
ref byte r1 = ref Unsafe.AddByteOffset(ref a[0], (IntPtr)1);
Assert.Equal(0x34, r1);
ref byte r2 = ref Unsafe.AddByteOffset(ref r1, (IntPtr)2);
Assert.Equal(0x78, r2);
ref byte r3 = ref Unsafe.AddByteOffset(ref r2, (IntPtr)(-3));
Assert.Equal(0x12, r3);
}
[Fact]
public static void RefSubtract()
{
string[] a = new string[] { "abc", "def", "ghi", "jkl" };
ref string r1 = ref Unsafe.Subtract(ref a[0], -2);
Assert.Equal("ghi", r1);
ref string r2 = ref Unsafe.Subtract(ref r1, -1);
Assert.Equal("jkl", r2);
ref string r3 = ref Unsafe.Subtract(ref r2, 3);
Assert.Equal("abc", r3);
}
[Fact]
public static void RefSubtractIntPtr()
{
string[] a = new string[] { "abc", "def", "ghi", "jkl" };
ref string r1 = ref Unsafe.Subtract(ref a[0], (IntPtr)(-2));
Assert.Equal("ghi", r1);
ref string r2 = ref Unsafe.Subtract(ref r1, (IntPtr)(-1));
Assert.Equal("jkl", r2);
ref string r3 = ref Unsafe.Subtract(ref r2, (IntPtr)3);
Assert.Equal("abc", r3);
}
[Fact]
public static void RefSubtractByteOffset()
{
byte[] a = new byte[] { 0x12, 0x34, 0x56, 0x78 };
ref byte r1 = ref Unsafe.SubtractByteOffset(ref a[0], (IntPtr)(-1));
Assert.Equal(0x34, r1);
ref byte r2 = ref Unsafe.SubtractByteOffset(ref r1, (IntPtr)(-2));
Assert.Equal(0x78, r2);
ref byte r3 = ref Unsafe.SubtractByteOffset(ref r2, (IntPtr)3);
Assert.Equal(0x12, r3);
}
[Fact]
public static void RefAreSame()
{
long[] a = new long[2];
Assert.True(Unsafe.AreSame(ref a[0], ref a[0]));
Assert.False(Unsafe.AreSame(ref a[0], ref a[1]));
}
[Fact]
public static unsafe void ReadUnaligned_ByRef_Int32()
{
byte[] unaligned = Int32Double.Unaligned(123456789, 3.42);
int actual = Unsafe.ReadUnaligned<int>(ref unaligned[1]);
Assert.Equal(123456789, actual);
}
[Fact]
public static unsafe void ReadUnaligned_ByRef_Double()
{
byte[] unaligned = Int32Double.Unaligned(123456789, 3.42);
double actual = Unsafe.ReadUnaligned<double>(ref unaligned[9]);
Assert.Equal(3.42, actual);
}
[Fact]
public static unsafe void ReadUnaligned_ByRef_Struct()
{
byte[] unaligned = Int32Double.Unaligned(123456789, 3.42);
Int32Double actual = Unsafe.ReadUnaligned<Int32Double>(ref unaligned[1]);
Assert.Equal(123456789, actual.Int32);
Assert.Equal(3.42, actual.Double);
}
[Fact]
public static unsafe void ReadUnaligned_Ptr_Int32()
{
byte[] unaligned = Int32Double.Unaligned(123456789, 3.42);
fixed (byte* p = unaligned)
{
int actual = Unsafe.ReadUnaligned<int>(p + 1);
Assert.Equal(123456789, actual);
}
}
[Fact]
public static unsafe void ReadUnaligned_Ptr_Double()
{
byte[] unaligned = Int32Double.Unaligned(123456789, 3.42);
fixed (byte* p = unaligned)
{
double actual = Unsafe.ReadUnaligned<double>(p + 9);
Assert.Equal(3.42, actual);
}
}
[Fact]
public static unsafe void ReadUnaligned_Ptr_Struct()
{
byte[] unaligned = Int32Double.Unaligned(123456789, 3.42);
fixed (byte* p = unaligned)
{
Int32Double actual = Unsafe.ReadUnaligned<Int32Double>(p + 1);
Assert.Equal(123456789, actual.Int32);
Assert.Equal(3.42, actual.Double);
}
}
[Fact]
public static unsafe void WriteUnaligned_ByRef_Int32()
{
byte[] unaligned = new byte[sizeof(Int32Double) + 1];
Unsafe.WriteUnaligned(ref unaligned[1], 123456789);
int actual = Int32Double.Aligned(unaligned).Int32;
Assert.Equal(123456789, actual);
}
[Fact]
public static unsafe void WriteUnaligned_ByRef_Double()
{
byte[] unaligned = new byte[sizeof(Int32Double) + 1];
Unsafe.WriteUnaligned(ref unaligned[9], 3.42);
double actual = Int32Double.Aligned(unaligned).Double;
Assert.Equal(3.42, actual);
}
[Fact]
public static unsafe void WriteUnaligned_ByRef_Struct()
{
byte[] unaligned = new byte[sizeof(Int32Double) + 1];
Unsafe.WriteUnaligned(ref unaligned[1], new Int32Double { Int32 = 123456789, Double = 3.42 });
Int32Double actual = Int32Double.Aligned(unaligned);
Assert.Equal(123456789, actual.Int32);
Assert.Equal(3.42, actual.Double);
}
[Fact]
public static unsafe void WriteUnaligned_Ptr_Int32()
{
byte[] unaligned = new byte[sizeof(Int32Double) + 1];
fixed (byte* p = unaligned)
{
Unsafe.WriteUnaligned(p + 1, 123456789);
}
int actual = Int32Double.Aligned(unaligned).Int32;
Assert.Equal(123456789, actual);
}
[Fact]
public static unsafe void WriteUnaligned_Ptr_Double()
{
byte[] unaligned = new byte[sizeof(Int32Double) + 1];
fixed (byte* p = unaligned)
{
Unsafe.WriteUnaligned(p + 9, 3.42);
}
double actual = Int32Double.Aligned(unaligned).Double;
Assert.Equal(3.42, actual);
}
[Fact]
public static unsafe void WriteUnaligned_Ptr_Struct()
{
byte[] unaligned = new byte[sizeof(Int32Double) + 1];
fixed (byte* p = unaligned)
{
Unsafe.WriteUnaligned(p + 1, new Int32Double { Int32 = 123456789, Double = 3.42 });
}
Int32Double actual = Int32Double.Aligned(unaligned);
Assert.Equal(123456789, actual.Int32);
Assert.Equal(3.42, actual.Double);
}
}
[StructLayout(LayoutKind.Explicit)]
public struct Byte4
{
[FieldOffset(0)]
public byte B0;
[FieldOffset(1)]
public byte B1;
[FieldOffset(2)]
public byte B2;
[FieldOffset(3)]
public byte B3;
}
[StructLayout(LayoutKind.Explicit)]
public struct Byte4Short2
{
[FieldOffset(0)]
public byte B0;
[FieldOffset(1)]
public byte B1;
[FieldOffset(2)]
public byte B2;
[FieldOffset(3)]
public byte B3;
[FieldOffset(4)]
public short S4;
[FieldOffset(6)]
public short S6;
}
public unsafe struct Byte512
{
public fixed byte Bytes[512];
}
public unsafe struct Int32Double
{
public int Int32;
public double Double;
public static unsafe byte[] Unaligned(int i, double d)
{
var aligned = new Int32Double { Int32 = i, Double = d };
var unaligned = new byte[sizeof(Int32Double) + 1];
fixed (byte* p = unaligned)
{
Buffer.MemoryCopy(&aligned, p + 1, sizeof(Int32Double), sizeof(Int32Double));
}
return unaligned;
}
public static unsafe Int32Double Aligned(byte[] unaligned)
{
var aligned = new Int32Double();
fixed (byte* p = unaligned)
{
Buffer.MemoryCopy(p + 1, &aligned, sizeof(Int32Double), sizeof(Int32Double));
}
return aligned;
}
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public interface DepthSensorInterface
{
// returns the depth sensor platform
KinectInterop.DepthSensorPlatform GetSensorPlatform();
// initializes libraries and resources needed by this sensor interface
// returns true if the resources are successfully initialized, false otherwise
bool InitSensorInterface(bool bCopyLibs, ref bool bNeedRestart);
// releases the resources and libraries used by this interface
void FreeSensorInterface(bool bDeleteLibs);
// checks if there is available sensor on this interface
// returns true if there are available sensors on this interface, false otherwise
bool IsSensorAvailable();
// returns the number of available sensors, controlled by this interface
int GetSensorsCount();
// opens the default sensor and inits needed resources. returns new sensor-data object
KinectInterop.SensorData OpenDefaultSensor(KinectInterop.FrameSource dwFlags, float sensorAngle, bool bUseMultiSource);
// closes the sensor and frees used resources
void CloseSensor(KinectInterop.SensorData sensorData);
// this method is invoked periodically to update sensor data, if needed
// returns true if update is successful, false otherwise
bool UpdateSensorData(KinectInterop.SensorData sensorData);
// gets next multi source frame, if one is available
// returns true if there is a new multi-source frame, false otherwise
bool GetMultiSourceFrame(KinectInterop.SensorData sensorData);
// frees the resources taken by the last multi-source frame
void FreeMultiSourceFrame(KinectInterop.SensorData sensorData);
// polls for new body/skeleton frame. must fill in all needed body and joints' elements (tracking state and position)
// returns true if new body frame is available, false otherwise
bool PollBodyFrame(KinectInterop.SensorData sensorData, ref KinectInterop.BodyFrameData bodyFrame, ref Matrix4x4 kinectToWorld);
// polls for new color frame data
// returns true if new color frame is available, false otherwise
bool PollColorFrame(KinectInterop.SensorData sensorData);
// polls for new depth and body index frame data
// returns true if new depth or body index frame is available, false otherwise
bool PollDepthFrame(KinectInterop.SensorData sensorData);
// polls for new infrared frame data
// returns true if new infrared frame is available, false otherwise
bool PollInfraredFrame(KinectInterop.SensorData sensorData);
// performs sensor-specific fixes of joint positions and orientations
void FixJointOrientations(KinectInterop.SensorData sensorData, ref KinectInterop.BodyData bodyData);
// checks if the given body is turned around or not
bool IsBodyTurned(ref KinectInterop.BodyData bodyData);
// returns depth frame coordinates for the given 3d space point
Vector2 MapSpacePointToDepthCoords(KinectInterop.SensorData sensorData, Vector3 spacePos);
// returns 3d Kinect-space coordinates for the given depth frame point
Vector3 MapDepthPointToSpaceCoords(KinectInterop.SensorData sensorData, Vector2 depthPos, ushort depthVal);
// returns color-space coordinates for the given depth point
Vector2 MapDepthPointToColorCoords(KinectInterop.SensorData sensorData, Vector2 depthPos, ushort depthVal);
// estimates all color-space coordinates for the current depth frame
// returns true on success, false otherwise
bool MapDepthFrameToColorCoords(KinectInterop.SensorData sensorData, ref Vector2[] vColorCoords);
// estimates all depth-space coordinates for the current color frame
// returns true on success, false otherwise
bool MapColorFrameToDepthCoords (KinectInterop.SensorData sensorData, ref Vector2[] vDepthCoords);
// returns the index of the given joint in joint's array
int GetJointIndex(KinectInterop.JointType joint);
// // returns the joint at given index
// KinectInterop.JointType GetJointAtIndex(int index);
// returns the parent joint of the given joint
KinectInterop.JointType GetParentJoint(KinectInterop.JointType joint);
// returns the next joint in the hierarchy, as to the given joint
KinectInterop.JointType GetNextJoint(KinectInterop.JointType joint);
// returns true if the face tracking is supported by this interface, false otherwise
bool IsFaceTrackingAvailable(ref bool bNeedRestart);
// initializes libraries and resources needed by the face tracking subsystem
bool InitFaceTracking(bool bUseFaceModel, bool bDrawFaceRect);
// releases the resources and libraries used by the face tracking subsystem
void FinishFaceTracking();
// this method gets invoked periodically to update the face tracking state
// returns true if update is successful, false otherwise
bool UpdateFaceTracking();
// returns true if face tracking is initialized, false otherwise
bool IsFaceTrackingActive();
// returns true if face rectangle(s) must be drawn in color map, false otherwise
bool IsDrawFaceRect();
// returns true if the face of the specified user is being tracked at the moment, false otherwise
bool IsFaceTracked(long userId);
// gets the face rectangle in color coordinates. returns true on success, false otherwise
bool GetFaceRect(long userId, ref Rect faceRect);
// visualizes face tracker debug information
void VisualizeFaceTrackerOnColorTex(Texture2D texColor);
// gets the head position of the specified user. returns true on success, false otherwise
bool GetHeadPosition(long userId, ref Vector3 headPos);
// gets the head rotation of the specified user. returns true on success, false otherwise
bool GetHeadRotation(long userId, ref Quaternion headRot);
// gets the AU values for the specified user. returns true on success, false otherwise
bool GetAnimUnits(long userId, ref Dictionary<KinectInterop.FaceShapeAnimations, float> afAU);
// gets the SU values for the specified user. returns true on success, false otherwise
bool GetShapeUnits(long userId, ref Dictionary<KinectInterop.FaceShapeDeformations, float> afSU);
// returns the length of model's vertices array for the specified user
int GetFaceModelVerticesCount(long userId);
// gets the model vertices for the specified user. returns true on success, false otherwise
bool GetFaceModelVertices(long userId, ref Vector3[] avVertices);
// returns the length of model's triangles array
int GetFaceModelTrianglesCount();
// gets the model triangle indices. returns true on success, false otherwise
bool GetFaceModelTriangles(bool bMirrored, ref int[] avTriangles);
// returns true if the face tracking is supported by this interface, false otherwise
bool IsSpeechRecognitionAvailable(ref bool bNeedRestart);
// initializes libraries and resources needed by the speech recognition subsystem
int InitSpeechRecognition(string sRecoCriteria, bool bUseKinect, bool bAdaptationOff);
// releases the resources and libraries used by the speech recognition subsystem
void FinishSpeechRecognition();
// this method gets invoked periodically to update the speech recognition state
// returns true if update is successful, false otherwise
int UpdateSpeechRecognition();
// loads new grammar file with the specified language code
int LoadSpeechGrammar(string sFileName, short iLangCode, bool bDynamic);
// adds a phrase to the from-rule in dynamic grammar. if the to-rule is empty, this means end of the phrase recognition
int AddGrammarPhrase(string sFromRule, string sToRule, string sPhrase, bool bClearRulePhrases, bool bCommitGrammar);
// sets the required confidence of the recognized phrases (must be between 0.0f and 1.0f)
void SetSpeechConfidence(float fConfidence);
// returns true if speech start has been detected, false otherwise
bool IsSpeechStarted();
// returns true if speech end has been detected, false otherwise
bool IsSpeechEnded();
// returns true if a grammar phrase has been recognized, false otherwise
bool IsPhraseRecognized();
// returns the confidence of the currently recognized phrase, in range [0, 1]
float GetPhraseConfidence();
// returns the tag of the recognized grammar phrase, empty string if no phrase is recognized at the moment
string GetRecognizedPhraseTag();
// clears the currently recognized grammar phrase (prepares SR system for next phrase recognition)
void ClearRecognizedPhrase();
// returns true if the background removal is supported by this interface, false otherwise
bool IsBackgroundRemovalAvailable(ref bool bNeedRestart);
// initializes libraries and resources needed by the background removal subsystem
bool InitBackgroundRemoval(KinectInterop.SensorData sensorData, bool isHiResPrefered);
// releases the resources and libraries used by the background removal subsystem
void FinishBackgroundRemoval(KinectInterop.SensorData sensorData);
// this method gets invoked periodically to update the background removal
// returns true if update is successful, false otherwise
bool UpdateBackgroundRemoval(KinectInterop.SensorData sensorData, bool isHiResPrefered, Color32 defaultColor);
// returns true if background removal is initialized, false otherwise
bool IsBackgroundRemovalActive();
// returns true if BR-manager supports high resolution background removal
bool IsBRHiResSupported();
// returns the rectange of the foreground frame
Rect GetForegroundFrameRect(KinectInterop.SensorData sensorData, bool isHiResPrefered);
// returns the length of the foreground frame in bytes
int GetForegroundFrameLength(KinectInterop.SensorData sensorData, bool isHiResPrefered);
// polls for new foreground frame data
// returns true if foreground frame is available, false otherwise
bool PollForegroundFrame(KinectInterop.SensorData sensorData, bool isHiResPrefered, Color32 defaultColor, ref byte[] foregroundImage);
}
| |
/*
* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace XenAPI
{
/// <summary>
/// The physical block devices through which hosts access SRs
/// First published in XenServer 4.0.
/// </summary>
public partial class PBD : XenObject<PBD>
{
public PBD()
{
}
public PBD(string uuid,
XenRef<Host> host,
XenRef<SR> SR,
Dictionary<string, string> device_config,
bool currently_attached,
Dictionary<string, string> other_config)
{
this.uuid = uuid;
this.host = host;
this.SR = SR;
this.device_config = device_config;
this.currently_attached = currently_attached;
this.other_config = other_config;
}
/// <summary>
/// Creates a new PBD from a Proxy_PBD.
/// </summary>
/// <param name="proxy"></param>
public PBD(Proxy_PBD proxy)
{
this.UpdateFromProxy(proxy);
}
/// <summary>
/// Updates each field of this instance with the value of
/// the corresponding field of a given PBD.
/// </summary>
public override void UpdateFrom(PBD update)
{
uuid = update.uuid;
host = update.host;
SR = update.SR;
device_config = update.device_config;
currently_attached = update.currently_attached;
other_config = update.other_config;
}
internal void UpdateFromProxy(Proxy_PBD proxy)
{
uuid = proxy.uuid == null ? null : (string)proxy.uuid;
host = proxy.host == null ? null : XenRef<Host>.Create(proxy.host);
SR = proxy.SR == null ? null : XenRef<SR>.Create(proxy.SR);
device_config = proxy.device_config == null ? null : Maps.convert_from_proxy_string_string(proxy.device_config);
currently_attached = (bool)proxy.currently_attached;
other_config = proxy.other_config == null ? null : Maps.convert_from_proxy_string_string(proxy.other_config);
}
public Proxy_PBD ToProxy()
{
Proxy_PBD result_ = new Proxy_PBD();
result_.uuid = uuid ?? "";
result_.host = host ?? "";
result_.SR = SR ?? "";
result_.device_config = Maps.convert_to_proxy_string_string(device_config);
result_.currently_attached = currently_attached;
result_.other_config = Maps.convert_to_proxy_string_string(other_config);
return result_;
}
/// <summary>
/// Creates a new PBD from a Hashtable.
/// Note that the fields not contained in the Hashtable
/// will be created with their default values.
/// </summary>
/// <param name="table"></param>
public PBD(Hashtable table) : this()
{
UpdateFrom(table);
}
/// <summary>
/// Given a Hashtable with field-value pairs, it updates the fields of this PBD
/// with the values listed in the Hashtable. Note that only the fields contained
/// in the Hashtable will be updated and the rest will remain the same.
/// </summary>
/// <param name="table"></param>
public void UpdateFrom(Hashtable table)
{
if (table.ContainsKey("uuid"))
uuid = Marshalling.ParseString(table, "uuid");
if (table.ContainsKey("host"))
host = Marshalling.ParseRef<Host>(table, "host");
if (table.ContainsKey("SR"))
SR = Marshalling.ParseRef<SR>(table, "SR");
if (table.ContainsKey("device_config"))
device_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "device_config"));
if (table.ContainsKey("currently_attached"))
currently_attached = Marshalling.ParseBool(table, "currently_attached");
if (table.ContainsKey("other_config"))
other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config"));
}
public bool DeepEquals(PBD other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
return Helper.AreEqual2(this._uuid, other._uuid) &&
Helper.AreEqual2(this._host, other._host) &&
Helper.AreEqual2(this._SR, other._SR) &&
Helper.AreEqual2(this._device_config, other._device_config) &&
Helper.AreEqual2(this._currently_attached, other._currently_attached) &&
Helper.AreEqual2(this._other_config, other._other_config);
}
internal static List<PBD> ProxyArrayToObjectList(Proxy_PBD[] input)
{
var result = new List<PBD>();
foreach (var item in input)
result.Add(new PBD(item));
return result;
}
public override string SaveChanges(Session session, string opaqueRef, PBD server)
{
if (opaqueRef == null)
{
var reference = create(session, this);
return reference == null ? null : reference.opaque_ref;
}
else
{
if (!Helper.AreEqual2(_other_config, server._other_config))
{
PBD.set_other_config(session, opaqueRef, _other_config);
}
if (!Helper.AreEqual2(_device_config, server._device_config))
{
PBD.set_device_config(session, opaqueRef, _device_config);
}
return null;
}
}
/// <summary>
/// Get a record containing the current state of the given PBD.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pbd">The opaque_ref of the given pbd</param>
public static PBD get_record(Session session, string _pbd)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pbd_get_record(session.opaque_ref, _pbd);
else
return new PBD((Proxy_PBD)session.proxy.pbd_get_record(session.opaque_ref, _pbd ?? "").parse());
}
/// <summary>
/// Get a reference to the PBD instance with the specified UUID.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_uuid">UUID of object to return</param>
public static XenRef<PBD> get_by_uuid(Session session, string _uuid)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pbd_get_by_uuid(session.opaque_ref, _uuid);
else
return XenRef<PBD>.Create(session.proxy.pbd_get_by_uuid(session.opaque_ref, _uuid ?? "").parse());
}
/// <summary>
/// Create a new PBD instance, and return its handle.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_record">All constructor arguments</param>
public static XenRef<PBD> create(Session session, PBD _record)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pbd_create(session.opaque_ref, _record);
else
return XenRef<PBD>.Create(session.proxy.pbd_create(session.opaque_ref, _record.ToProxy()).parse());
}
/// <summary>
/// Create a new PBD instance, and return its handle.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_record">All constructor arguments</param>
public static XenRef<Task> async_create(Session session, PBD _record)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_pbd_create(session.opaque_ref, _record);
else
return XenRef<Task>.Create(session.proxy.async_pbd_create(session.opaque_ref, _record.ToProxy()).parse());
}
/// <summary>
/// Destroy the specified PBD instance.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pbd">The opaque_ref of the given pbd</param>
public static void destroy(Session session, string _pbd)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.pbd_destroy(session.opaque_ref, _pbd);
else
session.proxy.pbd_destroy(session.opaque_ref, _pbd ?? "").parse();
}
/// <summary>
/// Destroy the specified PBD instance.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pbd">The opaque_ref of the given pbd</param>
public static XenRef<Task> async_destroy(Session session, string _pbd)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_pbd_destroy(session.opaque_ref, _pbd);
else
return XenRef<Task>.Create(session.proxy.async_pbd_destroy(session.opaque_ref, _pbd ?? "").parse());
}
/// <summary>
/// Get the uuid field of the given PBD.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pbd">The opaque_ref of the given pbd</param>
public static string get_uuid(Session session, string _pbd)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pbd_get_uuid(session.opaque_ref, _pbd);
else
return (string)session.proxy.pbd_get_uuid(session.opaque_ref, _pbd ?? "").parse();
}
/// <summary>
/// Get the host field of the given PBD.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pbd">The opaque_ref of the given pbd</param>
public static XenRef<Host> get_host(Session session, string _pbd)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pbd_get_host(session.opaque_ref, _pbd);
else
return XenRef<Host>.Create(session.proxy.pbd_get_host(session.opaque_ref, _pbd ?? "").parse());
}
/// <summary>
/// Get the SR field of the given PBD.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pbd">The opaque_ref of the given pbd</param>
public static XenRef<SR> get_SR(Session session, string _pbd)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pbd_get_sr(session.opaque_ref, _pbd);
else
return XenRef<SR>.Create(session.proxy.pbd_get_sr(session.opaque_ref, _pbd ?? "").parse());
}
/// <summary>
/// Get the device_config field of the given PBD.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pbd">The opaque_ref of the given pbd</param>
public static Dictionary<string, string> get_device_config(Session session, string _pbd)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pbd_get_device_config(session.opaque_ref, _pbd);
else
return Maps.convert_from_proxy_string_string(session.proxy.pbd_get_device_config(session.opaque_ref, _pbd ?? "").parse());
}
/// <summary>
/// Get the currently_attached field of the given PBD.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pbd">The opaque_ref of the given pbd</param>
public static bool get_currently_attached(Session session, string _pbd)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pbd_get_currently_attached(session.opaque_ref, _pbd);
else
return (bool)session.proxy.pbd_get_currently_attached(session.opaque_ref, _pbd ?? "").parse();
}
/// <summary>
/// Get the other_config field of the given PBD.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pbd">The opaque_ref of the given pbd</param>
public static Dictionary<string, string> get_other_config(Session session, string _pbd)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pbd_get_other_config(session.opaque_ref, _pbd);
else
return Maps.convert_from_proxy_string_string(session.proxy.pbd_get_other_config(session.opaque_ref, _pbd ?? "").parse());
}
/// <summary>
/// Set the other_config field of the given PBD.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pbd">The opaque_ref of the given pbd</param>
/// <param name="_other_config">New value to set</param>
public static void set_other_config(Session session, string _pbd, Dictionary<string, string> _other_config)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.pbd_set_other_config(session.opaque_ref, _pbd, _other_config);
else
session.proxy.pbd_set_other_config(session.opaque_ref, _pbd ?? "", Maps.convert_to_proxy_string_string(_other_config)).parse();
}
/// <summary>
/// Add the given key-value pair to the other_config field of the given PBD.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pbd">The opaque_ref of the given pbd</param>
/// <param name="_key">Key to add</param>
/// <param name="_value">Value to add</param>
public static void add_to_other_config(Session session, string _pbd, string _key, string _value)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.pbd_add_to_other_config(session.opaque_ref, _pbd, _key, _value);
else
session.proxy.pbd_add_to_other_config(session.opaque_ref, _pbd ?? "", _key ?? "", _value ?? "").parse();
}
/// <summary>
/// Remove the given key and its corresponding value from the other_config field of the given PBD. If the key is not in that Map, then do nothing.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pbd">The opaque_ref of the given pbd</param>
/// <param name="_key">Key to remove</param>
public static void remove_from_other_config(Session session, string _pbd, string _key)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.pbd_remove_from_other_config(session.opaque_ref, _pbd, _key);
else
session.proxy.pbd_remove_from_other_config(session.opaque_ref, _pbd ?? "", _key ?? "").parse();
}
/// <summary>
/// Activate the specified PBD, causing the referenced SR to be attached and scanned
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pbd">The opaque_ref of the given pbd</param>
public static void plug(Session session, string _pbd)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.pbd_plug(session.opaque_ref, _pbd);
else
session.proxy.pbd_plug(session.opaque_ref, _pbd ?? "").parse();
}
/// <summary>
/// Activate the specified PBD, causing the referenced SR to be attached and scanned
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pbd">The opaque_ref of the given pbd</param>
public static XenRef<Task> async_plug(Session session, string _pbd)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_pbd_plug(session.opaque_ref, _pbd);
else
return XenRef<Task>.Create(session.proxy.async_pbd_plug(session.opaque_ref, _pbd ?? "").parse());
}
/// <summary>
/// Deactivate the specified PBD, causing the referenced SR to be detached and nolonger scanned
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pbd">The opaque_ref of the given pbd</param>
public static void unplug(Session session, string _pbd)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.pbd_unplug(session.opaque_ref, _pbd);
else
session.proxy.pbd_unplug(session.opaque_ref, _pbd ?? "").parse();
}
/// <summary>
/// Deactivate the specified PBD, causing the referenced SR to be detached and nolonger scanned
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pbd">The opaque_ref of the given pbd</param>
public static XenRef<Task> async_unplug(Session session, string _pbd)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_pbd_unplug(session.opaque_ref, _pbd);
else
return XenRef<Task>.Create(session.proxy.async_pbd_unplug(session.opaque_ref, _pbd ?? "").parse());
}
/// <summary>
/// Sets the PBD's device_config field
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pbd">The opaque_ref of the given pbd</param>
/// <param name="_value">The new value of the PBD's device_config</param>
public static void set_device_config(Session session, string _pbd, Dictionary<string, string> _value)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.pbd_set_device_config(session.opaque_ref, _pbd, _value);
else
session.proxy.pbd_set_device_config(session.opaque_ref, _pbd ?? "", Maps.convert_to_proxy_string_string(_value)).parse();
}
/// <summary>
/// Sets the PBD's device_config field
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pbd">The opaque_ref of the given pbd</param>
/// <param name="_value">The new value of the PBD's device_config</param>
public static XenRef<Task> async_set_device_config(Session session, string _pbd, Dictionary<string, string> _value)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_pbd_set_device_config(session.opaque_ref, _pbd, _value);
else
return XenRef<Task>.Create(session.proxy.async_pbd_set_device_config(session.opaque_ref, _pbd ?? "", Maps.convert_to_proxy_string_string(_value)).parse());
}
/// <summary>
/// Return a list of all the PBDs known to the system.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
public static List<XenRef<PBD>> get_all(Session session)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pbd_get_all(session.opaque_ref);
else
return XenRef<PBD>.Create(session.proxy.pbd_get_all(session.opaque_ref).parse());
}
/// <summary>
/// Get all the PBD Records at once, in a single XML RPC call
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
public static Dictionary<XenRef<PBD>, PBD> get_all_records(Session session)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pbd_get_all_records(session.opaque_ref);
else
return XenRef<PBD>.Create<Proxy_PBD>(session.proxy.pbd_get_all_records(session.opaque_ref).parse());
}
/// <summary>
/// Unique identifier/object reference
/// </summary>
public virtual string uuid
{
get { return _uuid; }
set
{
if (!Helper.AreEqual(value, _uuid))
{
_uuid = value;
Changed = true;
NotifyPropertyChanged("uuid");
}
}
}
private string _uuid = "";
/// <summary>
/// physical machine on which the pbd is available
/// </summary>
[JsonConverter(typeof(XenRefConverter<Host>))]
public virtual XenRef<Host> host
{
get { return _host; }
set
{
if (!Helper.AreEqual(value, _host))
{
_host = value;
Changed = true;
NotifyPropertyChanged("host");
}
}
}
private XenRef<Host> _host = new XenRef<Host>(Helper.NullOpaqueRef);
/// <summary>
/// the storage repository that the pbd realises
/// </summary>
[JsonConverter(typeof(XenRefConverter<SR>))]
public virtual XenRef<SR> SR
{
get { return _SR; }
set
{
if (!Helper.AreEqual(value, _SR))
{
_SR = value;
Changed = true;
NotifyPropertyChanged("SR");
}
}
}
private XenRef<SR> _SR = new XenRef<SR>(Helper.NullOpaqueRef);
/// <summary>
/// a config string to string map that is provided to the host's SR-backend-driver
/// </summary>
[JsonConverter(typeof(StringStringMapConverter))]
public virtual Dictionary<string, string> device_config
{
get { return _device_config; }
set
{
if (!Helper.AreEqual(value, _device_config))
{
_device_config = value;
Changed = true;
NotifyPropertyChanged("device_config");
}
}
}
private Dictionary<string, string> _device_config = new Dictionary<string, string>() {};
/// <summary>
/// is the SR currently attached on this host?
/// </summary>
public virtual bool currently_attached
{
get { return _currently_attached; }
set
{
if (!Helper.AreEqual(value, _currently_attached))
{
_currently_attached = value;
Changed = true;
NotifyPropertyChanged("currently_attached");
}
}
}
private bool _currently_attached;
/// <summary>
/// additional configuration
/// First published in XenServer 4.1.
/// </summary>
[JsonConverter(typeof(StringStringMapConverter))]
public virtual Dictionary<string, string> other_config
{
get { return _other_config; }
set
{
if (!Helper.AreEqual(value, _other_config))
{
_other_config = value;
Changed = true;
NotifyPropertyChanged("other_config");
}
}
}
private Dictionary<string, string> _other_config = new Dictionary<string, string>() {};
}
}
| |
using System;
using System.IO;
using System.Net;
using System.Xml;
using System.Globalization;
namespace SharpVectors.Dom.Svg
{
public sealed class SvgImageElement : SvgTransformableElement, ISvgImageElement
{
#region Private Fields
private ISvgAnimatedLength x;
private ISvgAnimatedLength y;
private ISvgAnimatedLength width;
private ISvgAnimatedLength height;
private SvgTests svgTests;
private SvgUriReference svgURIReference;
private SvgFitToViewBox svgFitToViewBox;
private SvgExternalResourcesRequired svgExternalResourcesRequired;
#endregion
#region Constructors and Destructor
public SvgImageElement(string prefix, string localname, string ns, SvgDocument doc)
: base(prefix, localname, ns, doc)
{
svgExternalResourcesRequired = new SvgExternalResourcesRequired(this);
svgTests = new SvgTests(this);
svgURIReference = new SvgUriReference(this);
svgFitToViewBox = new SvgFitToViewBox(this);
}
#endregion
#region Public properties
//public SvgRect CalculatedViewbox
//{
// get
// {
// SvgRect viewBox = null;
// if (IsSvgImage)
// {
// SvgDocument doc = GetImageDocument();
// SvgSvgElement outerSvg = (SvgSvgElement)doc.DocumentElement;
// if (outerSvg.HasAttribute("viewBox"))
// {
// viewBox = (SvgRect)outerSvg.ViewBox.AnimVal;
// }
// else
// {
// viewBox = SvgRect.Empty;
// }
// }
// else
// {
// viewBox = new SvgRect(0, 0, Bitmap.Size.Width, Bitmap.Size.Height);
// }
// return viewBox;
// }
//}
public bool IsSvgImage
{
get
{
if (!Href.AnimVal.StartsWith("data:"))
{
try
{
string absoluteUri = svgURIReference.AbsoluteUri;
if (!String.IsNullOrEmpty(absoluteUri))
{
Uri svgUri = new Uri(absoluteUri, UriKind.Absolute);
if (svgUri.IsFile)
{
return absoluteUri.EndsWith(".svg",
StringComparison.OrdinalIgnoreCase) ||
absoluteUri.EndsWith(".svgz", StringComparison.OrdinalIgnoreCase);
}
}
WebResponse resource = svgURIReference.ReferencedResource;
if (resource == null)
{
return false;
}
// local files are returning as binary/octet-stream
// this "fix" tests the file extension for .svg and .svgz
string name = resource.ResponseUri.ToString().ToLower(CultureInfo.InvariantCulture);
return (resource.ContentType.StartsWith("image/svg+xml") ||
name.EndsWith(".svg", StringComparison.OrdinalIgnoreCase) ||
name.EndsWith(".svgz", StringComparison.OrdinalIgnoreCase));
}
catch (WebException)
{
return false;
}
catch (IOException)
{
return false;
}
}
return false;
}
}
public SvgWindow SvgWindow
{
get
{
if (this.IsSvgImage)
{
SvgWindow parentWindow = (SvgWindow)OwnerDocument.Window;
if (parentWindow != null)
{
SvgWindow wnd = parentWindow.CreateOwnedWindow(
(long)Width.AnimVal.Value, (long)Height.AnimVal.Value);
SvgDocument doc = new SvgDocument(wnd);
wnd.Document = doc;
string absoluteUri = svgURIReference.AbsoluteUri;
Uri svgUri = new Uri(absoluteUri, UriKind.Absolute);
if (svgUri.IsFile)
{
Stream resStream = File.OpenRead(svgUri.LocalPath);
doc.Load(absoluteUri, resStream);
}
else
{
Stream resStream = svgURIReference.ReferencedResource.GetResponseStream();
doc.Load(absoluteUri, resStream);
}
return wnd;
}
}
return null;
}
}
#endregion
#region ISvgElement Members
/// <summary>
/// Gets a value providing a hint on the rendering defined by this element.
/// </summary>
/// <value>
/// An enumeration of the <see cref="SvgRenderingHint"/> specifying the rendering hint.
/// This will always return <see cref="SvgRenderingHint.Image"/>
/// </value>
public override SvgRenderingHint RenderingHint
{
get
{
return SvgRenderingHint.Image;
}
}
#endregion
#region ISvgImageElement Members
public ISvgAnimatedLength Width
{
get
{
if (width == null)
{
width = new SvgAnimatedLength(this, "width", SvgLengthDirection.Horizontal, "0");
}
return width;
}
}
public ISvgAnimatedLength Height
{
get
{
if (height == null)
{
height = new SvgAnimatedLength(this, "height", SvgLengthDirection.Vertical, "0");
}
return height;
}
}
public ISvgAnimatedLength X
{
get
{
if (x == null)
{
x = new SvgAnimatedLength(this, "x", SvgLengthDirection.Horizontal, "0");
}
return x;
}
}
public ISvgAnimatedLength Y
{
get
{
if (y == null)
{
y = new SvgAnimatedLength(this, "y", SvgLengthDirection.Vertical, "0");
}
return y;
}
}
public ISvgColorProfileElement ColorProfile
{
get
{
string colorProfile = this.GetAttribute("color-profile");
if (String.IsNullOrEmpty(colorProfile))
{
return null;
}
XmlElement profileElement = this.OwnerDocument.GetElementById(colorProfile);
if (profileElement == null)
{
XmlElement root = this.OwnerDocument.DocumentElement;
XmlNodeList elemList = root.GetElementsByTagName("color-profile");
if (elemList != null && elemList.Count != 0)
{
for (int i = 0; i < elemList.Count; i++)
{
XmlElement elementNode = elemList[i] as XmlElement;
if (elementNode != null && String.Equals(colorProfile,
elementNode.GetAttribute("id")))
{
profileElement = elementNode;
break;
}
}
}
}
return profileElement as SvgColorProfileElement;
}
}
#endregion
#region ISvgURIReference Members
public ISvgAnimatedString Href
{
get
{
return svgURIReference.Href;
}
}
public SvgUriReference UriReference
{
get
{
return svgURIReference;
}
}
public XmlElement ReferencedElement
{
get
{
return svgURIReference.ReferencedNode as XmlElement;
}
}
#endregion
#region ISvgFitToViewBox Members
public ISvgAnimatedPreserveAspectRatio PreserveAspectRatio
{
get
{
return svgFitToViewBox.PreserveAspectRatio;
}
}
#endregion
#region ISvgImageElement Members from SVG 1.2
public SvgDocument GetImageDocument()
{
SvgWindow window = this.SvgWindow;
if (window == null)
{
return null;
}
else
{
return (SvgDocument)window.Document;
}
}
#endregion
#region Update handling
public override void HandleAttributeChange(XmlAttribute attribute)
{
if (attribute.NamespaceURI.Length == 0)
{
// This list may be too long to be useful...
switch (attribute.LocalName)
{
// Additional attributes
case "x":
x = null;
return;
case "y":
y = null;
return;
case "width":
width = null;
return;
case "height":
height = null;
return;
}
base.HandleAttributeChange(attribute);
}
}
#endregion
#region ISvgExternalResourcesRequired Members
public ISvgAnimatedBoolean ExternalResourcesRequired
{
get
{
return svgExternalResourcesRequired.ExternalResourcesRequired;
}
}
#endregion
#region ISvgTests Members
public ISvgStringList RequiredFeatures
{
get { return svgTests.RequiredFeatures; }
}
public ISvgStringList RequiredExtensions
{
get { return svgTests.RequiredExtensions; }
}
public ISvgStringList SystemLanguage
{
get { return svgTests.SystemLanguage; }
}
public bool HasExtension(string extension)
{
return svgTests.HasExtension(extension);
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using CodeFirstWebFramework;
namespace AccountServer {
[Auth(AccessLevel.Admin)]
[Implementation(typeof(AdminHelper))]
public class AdminModule : AppModule {
protected override void Init() {
base.Init();
InsertMenuOptions(
new MenuOption("Settings", "/admin/editsettings.html"),
new MenuOption("Users", "/admin/users"),
new MenuOption("Integrity Check", "/admin/integritycheck.html"),
new MenuOption("Import", "/admin/import.html"),
new MenuOption("Backup", "/admin/backup.html"),
new MenuOption("Restore", "/admin/restore.html")
);
if (SecurityOn) {
if (Session.User != null)
InsertMenuOption(new MenuOption("Change password", "/admin/changepassword"));
InsertMenuOption(new MenuOption(Session.User == null ? "Login" : "Logout", "/admin/login"));
}
}
[Auth(AccessLevel.Any)]
public override void Default() {
if (UserAccessLevel < AccessLevel.Admin)
Redirect("/admin/login");
}
public void EditSettings() {
Form form = new AdminHelper(this).EditSettings();
JObject header = (JObject)form.Data;
header.Add("YearStart", Settings.YearStart(Utils.Today));
header.Add("YearEnd", Settings.YearEnd(Utils.Today));
Record = new JObject().AddRange("header", header,
"BankAccounts", SelectBankAccounts(),
"Skins", form["Skin"].Options["selectOptions"]
);
}
public AjaxReturn EditSettingsSave(JObject json) {
if (!SecurityOn)
json["RequireAuthorisation"] = false;
return new AdminHelper(this).EditSettingsSave(json);
}
public AjaxReturn EditUserSave(JObject json) {
AdminHelper helper = new AdminHelper(this);
User user = (User)((JObject)json["header"]).To(typeof(User));
JObject old = null;
string oldPassword = null;
if (user.idUser > 0) {
// Existing record
User header = Database.Get<User>((int)user.idUser);
oldPassword = header.Password;
header.Password = "";
old = new JObject().AddRange("header", header);
old["detail"] = user.ModulePermissions ? helper.permissions((int)user.idUser).ToJToken() : new JArray();
}
AjaxReturn result = helper.EditUserSave(json);
if (result.error == null) {
JObject header = (JObject)json["header"];
header["Password"] = oldPassword != null && header.AsString("Password") != oldPassword ? "(changed)" : "";
if (!header.AsBool("ModulePermissions"))
json["detail"] = new JArray();
Database.AuditUpdate("User", header.AsInt("idUser"), old, json);
}
return result;
}
public void Import() {
}
public void ImportFile(UploadedFile file, string dateFormat, bool allowImbalancedTransactions) {
Method = "import";
Stream s = null;
try {
s = file.Stream();
if (Path.GetExtension(file.Name).ToLower() == ".qif") {
QifImporter qif = new QifImporter();
new ImportBatchJob(this, qif, delegate() {
try {
Batch.Records = file.Content.Length;
Batch.Status = "Importing file " + file.Name + " as QIF";
Database.BeginTransaction();
qif.DateFormat = dateFormat;
qif.AllowImbalancedTransactions = allowImbalancedTransactions;
qif.Import(new StreamReader(s), this);
Database.Commit();
} catch (Exception ex) {
throw new CheckException(ex, "Error at line {0}\r\n{1}", qif.Line, ex.Message);
} finally {
s.Dispose();
}
Message = "File " + file.Name + " imported successfully as QIF";
});
} else {
CsvParser csv = new CsvParser(new StreamReader(s));
Importer importer = Importer.ImporterFor(csv);
Utils.Check(importer != null, "No importer for file {0}", file.Name);
new ImportBatchJob(this, csv, delegate() {
try {
Batch.Records = file.Content.Length;
Batch.Status = "Importing file " + file.Name + " as " + importer.Name + " to ";
Database.BeginTransaction();
importer.DateFormat = dateFormat;
importer.Import(csv, this);
Database.Commit();
} catch (Exception ex) {
throw new CheckException(ex, "Error at line {0}\r\n{1}", csv.Line, ex.Message);
} finally {
s.Dispose();
}
Message = "File " + file.Name + " imported successfully as " + importer.Name + " to " + importer.TableName;
});
}
} catch (Exception ex) {
Log(ex.ToString());
Message = ex.Message;
if (s != null)
s.Dispose();
}
}
class ImportBatchJob : BatchJob {
FileProcessor _file;
bool _recordReset;
public ImportBatchJob(CodeFirstWebFramework.AppModule module, FileProcessor file, Action action)
: base(module, action) {
_file = file;
}
public override int Record {
get {
return _recordReset ? base.Record : _file.Character;
}
set {
base.Record = value;
_recordReset = true;
}
}
}
public void IntegrityCheck() {
List<string> errors = new List<string>();
foreach (JObject r in Database.Query(@"SELECT * FROM
(SELECT DocumentId, SUM(Amount) AS Amount
FROM Journal
GROUP BY DocumentId) AS r
LEFT JOIN Document ON idDocument = DocumentId
LEFT JOIN DocumentType ON idDocumentType = DocumentTypeId
WHERE Amount <> 0"))
errors.Add(string.Format("{0} {1} {2} {3:d} does not balance {4:0.00}", r.AsString("DocType"),
r.AsString("DocumentId"), r.AsString("DocumentIdentifier"), r.AsDate("DocumentDate"), r.AsDecimal("Amount")));
foreach (JObject r in Database.Query(@"SELECT * FROM
(SELECT NameAddressId, SUM(Amount) AS Amount, Sum(Outstanding) As Outstanding
FROM Journal
WHERE AccountId IN (1, 2)
GROUP BY NameAddressId) AS r
LEFT JOIN NameAddress ON idNameAddress = NameAddressId
WHERE Amount <> Outstanding "))
errors.Add(string.Format("Name {0} {1} {2} amount {3:0.00} does not equal outstanding {4:0.00} ",
r.AsString("NameAddressId"), r.AsString("Type"), r.AsString("Name"), r.AsDecimal("Amount"), r.AsDecimal("Outstanding")));
foreach (JObject r in Database.Query(@"SELECT * FROM
(SELECT DocumentId, COUNT(idJournal) AS JCount, MAX(JournalNum) AS MaxJournal, COUNT(idLine) AS LCount
FROM Journal
LEFT JOIN Line ON idLine = idJournal
GROUP BY DocumentId) AS r
LEFT JOIN Document ON idDocument = DocumentId
LEFT JOIN DocumentType ON idDocumentType = DocumentTypeId
WHERE JCount < LCount + 1
OR JCount > LCount + 2
OR JCount != MaxJournal"))
errors.Add(string.Format("{0} {1} {2} {3:d} Journals={4} Lines={5} Max journal num={6}", r.AsString("DocType"),
r.AsString("DocumentId"), r.AsString("DocumentIdentifier"), r.AsDate("DocumentDate"), r.AsInt("JCount"),
r.AsInt("LCount"), r.AsInt("MaxJournal")));
foreach (JObject r in Database.Query(@"SELECT NameAddress.* FROM NameAddress
LEFT JOIN Member ON NameAddressId = idNameAddress
WHERE Type = 'M'
AND idMember IS NULL"))
errors.Add(string.Format("{0} {1} member address is not associated with a member", r.AsString("idNameAddress"),
r.AsString("Name")));
if (errors.Count == 0)
errors.Add("No errors");
Record = errors;
}
}
/// <summary>
/// Additional access level.
/// </summary>
public class AccessLevel : CodeFirstWebFramework.AccessLevel {
public const int Authorise = 30;
}
}
| |
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Windows.Forms;
using DpSdkEngLib;
using DPSDKOPSLib;
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
using System.Linq;
using System.Xml.Linq;
// ERROR: Not supported in C#: OptionDeclaration
using Microsoft.VisualBasic.PowerPacks;
namespace _4PosBackOffice.NET
{
internal partial class frmMainHOParam : System.Windows.Forms.Form
{
private ADODB.Recordset withEventsField_adoPrimaryRS;
public ADODB.Recordset adoPrimaryRS {
get { return withEventsField_adoPrimaryRS; }
set {
if (withEventsField_adoPrimaryRS != null) {
withEventsField_adoPrimaryRS.MoveComplete -= adoPrimaryRS_MoveComplete;
withEventsField_adoPrimaryRS.WillChangeRecord -= adoPrimaryRS_WillChangeRecord;
}
withEventsField_adoPrimaryRS = value;
if (withEventsField_adoPrimaryRS != null) {
withEventsField_adoPrimaryRS.MoveComplete += adoPrimaryRS_MoveComplete;
withEventsField_adoPrimaryRS.WillChangeRecord += adoPrimaryRS_WillChangeRecord;
}
}
}
int gID;
int mvBookMark;
bool mbChangedByCode;
bool mbEditFlag;
bool mbAddNewFlag;
bool mbDataChanged;
bool loading;
bool g_Emails;
public void loadItem()
{
ADODB.Recordset rj = default(ADODB.Recordset);
System.Windows.Forms.CheckBox oCheck = null;
adoPrimaryRS = modRecordSet.getRS(ref "SELECT Company_HOParamBit FROM Company");
const short gReOrderLvl = 1;
const short gEmployeePer = 2;
const short gWaitronCount = 4;
const short gActualCost = 8;
const short gPromotion = 16;
const short gRecipe = 32;
// ERROR: Not supported in C#: OnErrorStatement
//Bind the check boxes to the data provider
this._chkBit_1.CheckState = System.Math.Abs(Convert.ToInt32(Convert.ToBoolean(adoPrimaryRS.Fields("Company_HOParamBit").Value & gReOrderLvl)));
this._chkBit_2.CheckState = System.Math.Abs(Convert.ToInt32(Convert.ToBoolean(adoPrimaryRS.Fields("Company_HOParamBit").Value & gEmployeePer)));
this._chkBit_3.CheckState = System.Math.Abs(Convert.ToInt32(Convert.ToBoolean(adoPrimaryRS.Fields("Company_HOParamBit").Value & gWaitronCount)));
this._chkBit_4.CheckState = System.Math.Abs(Convert.ToInt32(Convert.ToBoolean(adoPrimaryRS.Fields("Company_HOParamBit").Value & gActualCost)));
this._chkBit_5.CheckState = System.Math.Abs(Convert.ToInt32(Convert.ToBoolean(adoPrimaryRS.Fields("Company_HOParamBit").Value & gPromotion)));
this._chkBit_6.CheckState = System.Math.Abs(Convert.ToInt32(Convert.ToBoolean(adoPrimaryRS.Fields("Company_HOParamBit").Value & gRecipe)));
ShowDialog();
}
private void cmdClose_Click(System.Object eventSender, System.EventArgs eventArgs)
{
cmdClose.Focus();
System.Windows.Forms.Application.DoEvents();
if (update_Renamed()) {
this.Close();
}
}
private void frmMainHOParam_KeyPress(System.Object eventSender, System.Windows.Forms.KeyPressEventArgs eventArgs)
{
short KeyAscii = Strings.Asc(eventArgs.KeyChar);
switch (KeyAscii) {
case System.Windows.Forms.Keys.Escape:
KeyAscii = 0;
System.Windows.Forms.Application.DoEvents();
adoPrimaryRS.Move(0);
cmdClose_Click(cmdClose, new System.EventArgs());
break;
}
eventArgs.KeyChar = Strings.Chr(KeyAscii);
if (KeyAscii == 0) {
eventArgs.Handled = true;
}
}
private void frmMainHOParam_FormClosed(System.Object eventSender, System.Windows.Forms.FormClosedEventArgs eventArgs)
{
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default;
}
private void adoPrimaryRS_MoveComplete(ADODB.EventReasonEnum adReason, ADODB.Error pError, ref ADODB.EventStatusEnum adStatus, ADODB.Recordset pRecordset)
{
//This will display the current record position for this recordset
}
private void adoPrimaryRS_WillChangeRecord(ADODB.EventReasonEnum adReason, int cRecords, ref ADODB.EventStatusEnum adStatus, ADODB.Recordset pRecordset)
{
//This is where you put validation code
//This event gets called when the following actions occur
bool bCancel = false;
switch (adReason) {
case ADODB.EventReasonEnum.adRsnAddNew:
break;
case ADODB.EventReasonEnum.adRsnClose:
break;
case ADODB.EventReasonEnum.adRsnDelete:
break;
case ADODB.EventReasonEnum.adRsnFirstChange:
break;
case ADODB.EventReasonEnum.adRsnMove:
break;
case ADODB.EventReasonEnum.adRsnRequery:
break;
case ADODB.EventReasonEnum.adRsnResynch:
break;
case ADODB.EventReasonEnum.adRsnUndoAddNew:
break;
case ADODB.EventReasonEnum.adRsnUndoDelete:
break;
case ADODB.EventReasonEnum.adRsnUndoUpdate:
break;
case ADODB.EventReasonEnum.adRsnUpdate:
break;
}
if (bCancel)
adStatus = ADODB.EventStatusEnum.adStatusCancel;
}
private void cmdCancel_Click(System.Object eventSender, System.EventArgs eventArgs)
{
// ERROR: Not supported in C#: OnErrorStatement
if (mbAddNewFlag) {
this.Close();
} else {
mbEditFlag = false;
mbAddNewFlag = false;
adoPrimaryRS.CancelUpdate();
if (mvBookMark > 0) {
adoPrimaryRS.Bookmark = mvBookMark;
} else {
adoPrimaryRS.MoveFirst();
}
mbDataChanged = false;
}
}
private bool update_Renamed()
{
bool functionReturnValue = false;
// ERROR: Not supported in C#: OnErrorStatement
bool lDirty = false;
short x = 0;
short lBit = 0;
const short gReOrderLvl = 1;
const short gEmployeePer = 2;
const short gWaitronCount = 4;
const short gActualCost = 8;
const short gPromotion = 16;
const short gRecipe = 32;
lDirty = false;
functionReturnValue = true;
if (this._chkBit_1.CheckState)
lBit = lBit + gReOrderLvl;
if (this._chkBit_2.CheckState)
lBit = lBit + gEmployeePer;
if (this._chkBit_3.CheckState)
lBit = lBit + gWaitronCount;
if (this._chkBit_4.CheckState)
lBit = lBit + gActualCost;
if (this._chkBit_5.CheckState)
lBit = lBit + gPromotion;
if (this._chkBit_6.CheckState)
lBit = lBit + gRecipe;
adoPrimaryRS.Fields("Company_HOParamBit").Value = lBit;
if (mbAddNewFlag) {
adoPrimaryRS.UpdateBatch(ADODB.AffectEnum.adAffectAll);
adoPrimaryRS.MoveLast();
//move to the new record
} else {
adoPrimaryRS.UpdateBatch(ADODB.AffectEnum.adAffectAll);
}
mbEditFlag = false;
mbAddNewFlag = false;
mbDataChanged = false;
return functionReturnValue;
UpdateErr:
Interaction.MsgBox(Err().Description);
functionReturnValue = false;
return functionReturnValue;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// See the LICENSE file in the project root for more information.
//
// System.Drawing.gdipFunctions.cs
//
// Authors:
// Alexandre Pigolkine (pigolkine@gmx.de)
// Jordi Mas i Hernandez (jordi@ximian.com)
// Sanjay Gupta (gsanjay@novell.com)
// Ravindra (rkumar@novell.com)
// Peter Dennis Bartok (pbartok@novell.com)
// Sebastien Pouliot <sebastien@ximian.com>
//
// Copyright (C) 2004 - 2007 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.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Drawing.Text;
using System.Globalization;
using System.Security;
using System.Runtime.InteropServices.ComTypes;
namespace System.Drawing
{
/// <summary>
/// GDI+ API Functions
/// </summary>
internal static class GDIPlus
{
public const int FACESIZE = 32;
public const int LANG_NEUTRAL = 0;
public static IntPtr Display = IntPtr.Zero;
public static bool UseX11Drawable = false;
public static bool UseCarbonDrawable = false;
public static bool UseCocoaDrawable = false;
private const string GdiPlus = "gdiplus";
#region gdiplus.dll functions
internal static ulong GdiPlusToken = 0;
static void ProcessExit(object sender, EventArgs e)
{
// Called all pending objects and claim any pending handle before
// shutting down
GC.Collect();
GC.WaitForPendingFinalizers();
#if false
GdiPlusToken = 0;
// This causes crashes in because this call occurs before all
// managed GDI+ objects are finalized. When they are finalized
// they call into a shutdown GDI+ and we crash.
GdiplusShutdown (ref GdiPlusToken);
// This causes crashes in Mono libgdiplus because this call
// occurs before all managed GDI objects are finalized
// When they are finalized they use the closed display and
// crash
if (UseX11Drawable && Display != IntPtr.Zero) {
XCloseDisplay (Display);
}
#endif
}
static GDIPlus()
{
#if NETSTANDARD1_6
bool isUnix = !RuntimeInformation.IsOSPlatform (OSPlatform.Windows);
#else
int platform = (int)Environment.OSVersion.Platform;
bool isUnix = (platform == 4) || (platform == 6) || (platform == 128);
#endif
if (isUnix)
{
if (Environment.GetEnvironmentVariable("not_supported_MONO_MWF_USE_NEW_X11_BACKEND") != null || Environment.GetEnvironmentVariable("MONO_MWF_MAC_FORCE_X11") != null)
{
UseX11Drawable = true;
}
else
{
IntPtr buf = Marshal.AllocHGlobal(8192);
// This is kind of a hack but gets us sysname from uname (struct utsname *name) on
// linux and darwin
if (uname(buf) != 0)
{
// WTH: We couldn't detect the OS; lets default to X11
UseX11Drawable = true;
}
else
{
string os = Marshal.PtrToStringAnsi(buf);
if (os == "Darwin")
UseCarbonDrawable = true;
else
UseX11Drawable = true;
}
Marshal.FreeHGlobal(buf);
}
}
// under MS 1.x this event is raised only for the default application domain
#if !NETSTANDARD1_6
AppDomain.CurrentDomain.ProcessExit += new EventHandler(ProcessExit);
#endif
}
static public bool RunningOnWindows()
{
return !UseX11Drawable && !UseCarbonDrawable && !UseCocoaDrawable;
}
static public bool RunningOnUnix()
{
return UseX11Drawable || UseCarbonDrawable || UseCocoaDrawable;
}
// Copies a Ptr to an array of Points and releases the memory
static public void FromUnManagedMemoryToPointI(IntPtr prt, Point[] pts)
{
int nPointSize = Marshal.SizeOf(pts[0]);
IntPtr pos = prt;
for (int i = 0; i < pts.Length; i++, pos = new IntPtr(pos.ToInt64() + nPointSize))
pts[i] = (Point)Marshal.PtrToStructure(pos, typeof(Point));
Marshal.FreeHGlobal(prt);
}
// Copies a Ptr to an array of Points and releases the memory
static public void FromUnManagedMemoryToPoint(IntPtr prt, PointF[] pts)
{
int nPointSize = Marshal.SizeOf(pts[0]);
IntPtr pos = prt;
for (int i = 0; i < pts.Length; i++, pos = new IntPtr(pos.ToInt64() + nPointSize))
pts[i] = (PointF)Marshal.PtrToStructure(pos, typeof(PointF));
Marshal.FreeHGlobal(prt);
}
// Copies an array of Points to unmanaged memory
static public IntPtr FromPointToUnManagedMemoryI(Point[] pts)
{
int nPointSize = Marshal.SizeOf(pts[0]);
IntPtr dest = Marshal.AllocHGlobal(nPointSize * pts.Length);
IntPtr pos = dest;
for (int i = 0; i < pts.Length; i++, pos = new IntPtr(pos.ToInt64() + nPointSize))
Marshal.StructureToPtr(pts[i], pos, false);
return dest;
}
// Copies a Ptr to an array of v and releases the memory
static public void FromUnManagedMemoryToRectangles(IntPtr prt, RectangleF[] pts)
{
int nPointSize = Marshal.SizeOf(pts[0]);
IntPtr pos = prt;
for (int i = 0; i < pts.Length; i++, pos = new IntPtr(pos.ToInt64() + nPointSize))
pts[i] = (RectangleF)Marshal.PtrToStructure(pos, typeof(RectangleF));
Marshal.FreeHGlobal(prt);
}
// Copies an array of Points to unmanaged memory
static public IntPtr FromPointToUnManagedMemory(PointF[] pts)
{
int nPointSize = Marshal.SizeOf(pts[0]);
IntPtr dest = Marshal.AllocHGlobal(nPointSize * pts.Length);
IntPtr pos = dest;
for (int i = 0; i < pts.Length; i++, pos = new IntPtr(pos.ToInt64() + nPointSize))
Marshal.StructureToPtr(pts[i], pos, false);
return dest;
}
// Converts a status into exception
// TODO: Add more status code mappings here
static internal void CheckStatus(Status status)
{
string msg;
switch (status)
{
case Status.Ok:
return;
case Status.GenericError:
msg = string.Format("Generic Error [GDI+ status: {0}]", status);
throw new Exception(msg);
case Status.InvalidParameter:
msg = string.Format("A null reference or invalid value was found [GDI+ status: {0}]", status);
throw new ArgumentException(msg);
case Status.OutOfMemory:
msg = string.Format("Not enough memory to complete operation [GDI+ status: {0}]", status);
throw new OutOfMemoryException(msg);
case Status.ObjectBusy:
msg = string.Format("Object is busy and cannot state allow this operation [GDI+ status: {0}]", status);
throw new MemberAccessException(msg);
case Status.InsufficientBuffer:
msg = string.Format("Insufficient buffer provided to complete operation [GDI+ status: {0}]", status);
#if NETCORE
throw new Exception(msg);
#else
throw new InternalBufferOverflowException (msg);
#endif
case Status.PropertyNotSupported:
msg = string.Format("Property not supported [GDI+ status: {0}]", status);
throw new NotSupportedException(msg);
case Status.FileNotFound:
msg = string.Format("Requested file was not found [GDI+ status: {0}]", status);
throw new FileNotFoundException(msg);
case Status.AccessDenied:
msg = string.Format("Access to resource was denied [GDI+ status: {0}]", status);
throw new UnauthorizedAccessException(msg);
case Status.UnknownImageFormat:
msg = string.Format("Either the image format is unknown or you don't have the required libraries to decode this format [GDI+ status: {0}]", status);
throw new NotSupportedException(msg);
case Status.NotImplemented:
msg = string.Format("The requested feature is not implemented [GDI+ status: {0}]", status);
throw new NotImplementedException(msg);
case Status.WrongState:
msg = string.Format("Object is not in a state that can allow this operation [GDI+ status: {0}]", status);
throw new ArgumentException(msg);
case Status.FontFamilyNotFound:
msg = string.Format("The requested FontFamily could not be found [GDI+ status: {0}]", status);
throw new ArgumentException(msg);
case Status.ValueOverflow:
msg = string.Format("Argument is out of range [GDI+ status: {0}]", status);
throw new OverflowException(msg);
case Status.Win32Error:
msg = string.Format("The operation is invalid [GDI+ status: {0}]", status);
throw new InvalidOperationException(msg);
default:
msg = string.Format("Unknown Error [GDI+ status: {0}]", status);
throw new Exception(msg);
}
}
// This is win32/gdi, not gdiplus, but it's easier to keep in here, also see above comment
[DllImport("gdi32.dll", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Auto)]
internal static extern IntPtr CreateFontIndirect(ref LOGFONT logfont);
[DllImport("user32.dll", EntryPoint = "GetDC", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi)]
internal static extern IntPtr GetDC(IntPtr hwnd);
[DllImport("user32.dll", EntryPoint = "ReleaseDC", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi)]
internal static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC);
[DllImport("gdi32.dll", EntryPoint = "SelectObject", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi)]
internal static extern IntPtr SelectObject(IntPtr hdc, IntPtr obj);
[DllImport("user32.dll", SetLastError = true)]
internal static extern bool GetIconInfo(IntPtr hIcon, out IconInfo iconinfo);
[DllImport("user32.dll", CallingConvention = CallingConvention.StdCall, SetLastError = true)]
internal static extern IntPtr CreateIconIndirect([In] ref IconInfo piconinfo);
[DllImport("user32.dll", CallingConvention = CallingConvention.StdCall, SetLastError = true)]
internal static extern bool DestroyIcon(IntPtr hIcon);
[DllImport("gdi32.dll")]
internal static extern bool DeleteObject(IntPtr hObject);
[DllImport("user32.dll")]
internal static extern IntPtr GetDesktopWindow();
[DllImport("gdi32.dll", SetLastError = true)]
public static extern int BitBlt(IntPtr hdcDest, int nXDest, int nYDest,
int nWidth, int nHeight, IntPtr hdcSrc, int nXSrc, int nYSrc, int dwRop);
[DllImport("user32.dll", EntryPoint = "GetSysColor", CallingConvention = CallingConvention.StdCall)]
public static extern uint Win32GetSysColor(GetSysColorIndex index);
// Some special X11 stuff
[DllImport("libX11", EntryPoint = "XOpenDisplay")]
internal extern static IntPtr XOpenDisplay(IntPtr display);
[DllImport("libX11", EntryPoint = "XCloseDisplay")]
internal extern static int XCloseDisplay(IntPtr display);
[DllImport("libX11", EntryPoint = "XRootWindow")]
internal extern static IntPtr XRootWindow(IntPtr display, int screen);
[DllImport("libX11", EntryPoint = "XDefaultScreen")]
internal extern static int XDefaultScreen(IntPtr display);
[DllImport("libX11", EntryPoint = "XDefaultDepth")]
internal extern static uint XDefaultDepth(IntPtr display, int screen);
[DllImport("libX11", EntryPoint = "XGetImage")]
internal extern static IntPtr XGetImage(IntPtr display, IntPtr drawable, int src_x, int src_y, int width, int height, int pane, int format);
[DllImport("libX11", EntryPoint = "XGetPixel")]
internal extern static int XGetPixel(IntPtr image, int x, int y);
[DllImport("libX11", EntryPoint = "XDestroyImage")]
internal extern static int XDestroyImage(IntPtr image);
[DllImport("libX11", EntryPoint = "XDefaultVisual")]
internal extern static IntPtr XDefaultVisual(IntPtr display, int screen);
[DllImport("libX11", EntryPoint = "XGetVisualInfo")]
internal extern static IntPtr XGetVisualInfo(IntPtr display, int vinfo_mask, ref XVisualInfo vinfo_template, ref int nitems);
[DllImport("libX11", EntryPoint = "XVisualIDFromVisual")]
internal extern static IntPtr XVisualIDFromVisual(IntPtr visual);
[DllImport("libX11", EntryPoint = "XFree")]
internal extern static void XFree(IntPtr data);
internal sealed class GdiPlusStreamHelper
{
public Stream stream;
private StreamGetHeaderDelegate sghd = null;
private StreamGetBytesDelegate sgbd = null;
private StreamSeekDelegate skd = null;
private StreamPutBytesDelegate spbd = null;
private StreamCloseDelegate scd = null;
private StreamSizeDelegate ssd = null;
private byte[] start_buf;
private int start_buf_pos;
private int start_buf_len;
private byte[] managedBuf;
private const int default_bufsize = 4096;
public GdiPlusStreamHelper(Stream s, bool seekToOrigin)
{
managedBuf = new byte[default_bufsize];
stream = s;
if (stream != null && stream.CanSeek && seekToOrigin)
{
stream.Seek(0, SeekOrigin.Begin);
}
}
public int StreamGetHeaderImpl(IntPtr buf, int bufsz)
{
int bytesRead;
start_buf = new byte[bufsz];
try
{
bytesRead = stream.Read(start_buf, 0, bufsz);
}
catch (IOException)
{
return -1;
}
if (bytesRead > 0 && buf != IntPtr.Zero)
{
Marshal.Copy(start_buf, 0, (IntPtr)(buf.ToInt64()), bytesRead);
}
start_buf_pos = 0;
start_buf_len = bytesRead;
return bytesRead;
}
public StreamGetHeaderDelegate GetHeaderDelegate
{
get
{
if (stream != null && stream.CanRead)
{
if (sghd == null)
{
sghd = new StreamGetHeaderDelegate(StreamGetHeaderImpl);
}
return sghd;
}
return null;
}
}
public int StreamGetBytesImpl(IntPtr buf, int bufsz, bool peek)
{
if (buf == IntPtr.Zero && peek)
{
return -1;
}
if (bufsz > managedBuf.Length)
managedBuf = new byte[bufsz];
int bytesRead = 0;
long streamPosition = 0;
if (bufsz > 0)
{
if (stream.CanSeek)
{
streamPosition = stream.Position;
}
if (start_buf_len > 0)
{
if (start_buf_len > bufsz)
{
Array.Copy(start_buf, start_buf_pos, managedBuf, 0, bufsz);
start_buf_pos += bufsz;
start_buf_len -= bufsz;
bytesRead = bufsz;
bufsz = 0;
}
else
{
// this is easy
Array.Copy(start_buf, start_buf_pos, managedBuf, 0, start_buf_len);
bufsz -= start_buf_len;
bytesRead = start_buf_len;
start_buf_len = 0;
}
}
if (bufsz > 0)
{
try
{
bytesRead += stream.Read(managedBuf, bytesRead, bufsz);
}
catch (IOException)
{
return -1;
}
}
if (bytesRead > 0 && buf != IntPtr.Zero)
{
Marshal.Copy(managedBuf, 0, (IntPtr)(buf.ToInt64()), bytesRead);
}
if (!stream.CanSeek && (bufsz == 10) && peek)
{
// Special 'hack' to support peeking of the type for gdi+ on non-seekable streams
}
if (peek)
{
if (stream.CanSeek)
{
// If we are peeking bytes, then go back to original position before peeking
stream.Seek(streamPosition, SeekOrigin.Begin);
}
else
{
throw new NotSupportedException();
}
}
}
return bytesRead;
}
public StreamGetBytesDelegate GetBytesDelegate
{
get
{
if (stream != null && stream.CanRead)
{
if (sgbd == null)
{
sgbd = new StreamGetBytesDelegate(StreamGetBytesImpl);
}
return sgbd;
}
return null;
}
}
public long StreamSeekImpl(int offset, int whence)
{
// Make sure we have a valid 'whence'.
if ((whence < 0) || (whence > 2))
return -1;
// Invalidate the start_buf if we're actually going to call a Seek method.
start_buf_pos += start_buf_len;
start_buf_len = 0;
SeekOrigin origin;
// Translate 'whence' into a SeekOrigin enum member.
switch (whence)
{
case 0:
origin = SeekOrigin.Begin;
break;
case 1:
origin = SeekOrigin.Current;
break;
case 2:
origin = SeekOrigin.End;
break;
// The following line is redundant but necessary to avoid a
// "Use of unassigned local variable" error without actually
// initializing 'origin' to a dummy value.
default:
return -1;
}
// Do the actual seek operation and return its result.
return stream.Seek((long)offset, origin);
}
public StreamSeekDelegate SeekDelegate
{
get
{
if (stream != null && stream.CanSeek)
{
if (skd == null)
{
skd = new StreamSeekDelegate(StreamSeekImpl);
}
return skd;
}
return null;
}
}
public int StreamPutBytesImpl(IntPtr buf, int bufsz)
{
if (bufsz > managedBuf.Length)
managedBuf = new byte[bufsz];
Marshal.Copy(buf, managedBuf, 0, bufsz);
stream.Write(managedBuf, 0, bufsz);
return bufsz;
}
public StreamPutBytesDelegate PutBytesDelegate
{
get
{
if (stream != null && stream.CanWrite)
{
if (spbd == null)
{
spbd = new StreamPutBytesDelegate(StreamPutBytesImpl);
}
return spbd;
}
return null;
}
}
public void StreamCloseImpl()
{
stream.Dispose();
}
public StreamCloseDelegate CloseDelegate
{
get
{
if (stream != null)
{
if (scd == null)
{
scd = new StreamCloseDelegate(StreamCloseImpl);
}
return scd;
}
return null;
}
}
public long StreamSizeImpl()
{
try
{
return stream.Length;
}
catch
{
return -1;
}
}
public StreamSizeDelegate SizeDelegate
{
get
{
if (stream != null)
{
if (ssd == null)
{
ssd = new StreamSizeDelegate(StreamSizeImpl);
}
return ssd;
}
return null;
}
}
}
[DllImport("libc")]
static extern int uname(IntPtr buf);
#endregion
}
}
| |
//
// Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.UnitTests.Targets.Wrappers
{
using System;
using System.Collections.Generic;
using NLog.Targets;
using NLog.Targets.Wrappers;
using Xunit;
public class PostFilteringTargetWrapperTests : NLogTestBase
{
[Fact]
public void PostFilteringTargetWrapperUsingDefaultFilterTest()
{
var target = new MyTarget();
var wrapper = new PostFilteringTargetWrapper()
{
WrappedTarget = target,
Rules =
{
// if we had any warnings, log debug too
new FilteringRule("level >= LogLevel.Warn", "level >= LogLevel.Debug"),
// when there is an error, emit everything
new FilteringRule
{
Exists = "level >= LogLevel.Error",
Filter = "true",
},
},
// by default log info and above
DefaultFilter = "level >= LogLevel.Info",
};
wrapper.Initialize(null);
target.Initialize(null);
var exceptions = new List<Exception>();
var events = new []
{
new LogEventInfo(LogLevel.Debug, "Logger1", "Hello").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Info, "Logger1", "Hello").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Info, "Logger2", "Hello").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Debug, "Logger1", "Hello").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Trace, "Logger1", "Hello").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Info, "Logger3", "Hello").WithContinuation(exceptions.Add),
};
wrapper.WriteAsyncLogEvents(events);
// make sure all Info events went through
Assert.Equal(3, target.Events.Count);
Assert.Same(events[1].LogEvent, target.Events[0]);
Assert.Same(events[2].LogEvent, target.Events[1]);
Assert.Same(events[5].LogEvent, target.Events[2]);
Assert.Equal(events.Length, exceptions.Count);
}
[Fact]
public void PostFilteringTargetWrapperUsingDefaultNonFilterTest()
{
var target = new MyTarget();
var wrapper = new PostFilteringTargetWrapper()
{
WrappedTarget = target,
Rules =
{
// if we had any warnings, log debug too
new FilteringRule("level >= LogLevel.Warn", "level >= LogLevel.Debug"),
// when there is an error, emit everything
new FilteringRule("level >= LogLevel.Error", "true"),
},
// by default log info and above
DefaultFilter = "level >= LogLevel.Info",
};
wrapper.Initialize(null);
target.Initialize(null);
var exceptions = new List<Exception>();
var events = new[]
{
new LogEventInfo(LogLevel.Debug, "Logger1", "Hello").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Info, "Logger1", "Hello").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Info, "Logger2", "Hello").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Debug, "Logger1", "Hello").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Trace, "Logger1", "Hello").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Info, "Logger3", "Hello").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Warn, "Logger1", "Hello").WithContinuation(exceptions.Add),
};
string result = RunAndCaptureInternalLog(() => wrapper.WriteAsyncLogEvents(events), LogLevel.Trace);
Assert.True(result.IndexOf("Running on 7 events") != -1);
Assert.True(result.IndexOf("Rule matched: (level >= Warn)") != -1);
Assert.True(result.IndexOf("Filter to apply: (level >= Debug)") != -1);
Assert.True(result.IndexOf("After filtering: 6 events.") != -1);
Assert.True(result.IndexOf("Sending to MyTarget") != -1);
// make sure all Debug,Info,Warn events went through
Assert.Equal(6, target.Events.Count);
Assert.Same(events[0].LogEvent, target.Events[0]);
Assert.Same(events[1].LogEvent, target.Events[1]);
Assert.Same(events[2].LogEvent, target.Events[2]);
Assert.Same(events[3].LogEvent, target.Events[3]);
Assert.Same(events[5].LogEvent, target.Events[4]);
Assert.Same(events[6].LogEvent, target.Events[5]);
Assert.Equal(events.Length, exceptions.Count);
}
[Fact]
public void PostFilteringTargetWrapperUsingDefaultNonFilterTest2()
{
// in this case both rules would match, but first one is picked
var target = new MyTarget();
var wrapper = new PostFilteringTargetWrapper()
{
WrappedTarget = target,
Rules =
{
// when there is an error, emit everything
new FilteringRule("level >= LogLevel.Error", "true"),
// if we had any warnings, log debug too
new FilteringRule("level >= LogLevel.Warn", "level >= LogLevel.Debug"),
},
// by default log info and above
DefaultFilter = "level >= LogLevel.Info",
};
wrapper.Initialize(null);
target.Initialize(null);
var exceptions = new List<Exception>();
var events = new []
{
new LogEventInfo(LogLevel.Debug, "Logger1", "Hello").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Info, "Logger1", "Hello").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Info, "Logger2", "Hello").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Debug, "Logger1", "Hello").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Trace, "Logger1", "Hello").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Info, "Logger3", "Hello").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Error, "Logger1", "Hello").WithContinuation(exceptions.Add),
};
var result = RunAndCaptureInternalLog(() => wrapper.WriteAsyncLogEvents(events), LogLevel.Trace);
Assert.True(result.IndexOf("Running on 7 events") != -1);
Assert.True(result.IndexOf("Rule matched: (level >= Error)") != -1);
Assert.True(result.IndexOf("Filter to apply: True") != -1);
Assert.True(result.IndexOf("After filtering: 7 events.") != -1);
Assert.True(result.IndexOf("Sending to MyTarget") != -1);
// make sure all events went through
Assert.Equal(7, target.Events.Count);
Assert.Same(events[0].LogEvent, target.Events[0]);
Assert.Same(events[1].LogEvent, target.Events[1]);
Assert.Same(events[2].LogEvent, target.Events[2]);
Assert.Same(events[3].LogEvent, target.Events[3]);
Assert.Same(events[4].LogEvent, target.Events[4]);
Assert.Same(events[5].LogEvent, target.Events[5]);
Assert.Same(events[6].LogEvent, target.Events[6]);
Assert.Equal(events.Length, exceptions.Count);
}
[Fact]
public void PostFilteringTargetWrapperOnlyDefaultFilter()
{
var target = new MyTarget() { OptimizeBufferReuse = true };
var wrapper = new PostFilteringTargetWrapper()
{
WrappedTarget = target,
DefaultFilter = "level >= LogLevel.Info", // by default log info and above
};
wrapper.Initialize(null);
target.Initialize(null);
var exceptions = new List<Exception>();
wrapper.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "Logger1", "Hello").WithContinuation(exceptions.Add));
Assert.Single(target.Events);
wrapper.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Debug, "Logger1", "Hello").WithContinuation(exceptions.Add));
Assert.Single(target.Events);
}
[Fact]
public void PostFilteringTargetWrapperNoFiltersDefined()
{
var target = new MyTarget();
var wrapper = new PostFilteringTargetWrapper()
{
WrappedTarget = target,
};
wrapper.Initialize(null);
target.Initialize(null);
var exceptions = new List<Exception>();
var events = new[]
{
new LogEventInfo(LogLevel.Debug, "Logger1", "Hello").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Info, "Logger1", "Hello").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Info, "Logger2", "Hello").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Debug, "Logger1", "Hello").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Trace, "Logger1", "Hello").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Info, "Logger3", "Hello").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Error, "Logger1", "Hello").WithContinuation(exceptions.Add),
};
wrapper.WriteAsyncLogEvents(events);
// make sure all events went through
Assert.Equal(7, target.Events.Count);
Assert.Same(events[0].LogEvent, target.Events[0]);
Assert.Same(events[1].LogEvent, target.Events[1]);
Assert.Same(events[2].LogEvent, target.Events[2]);
Assert.Same(events[3].LogEvent, target.Events[3]);
Assert.Same(events[4].LogEvent, target.Events[4]);
Assert.Same(events[5].LogEvent, target.Events[5]);
Assert.Same(events[6].LogEvent, target.Events[6]);
Assert.Equal(events.Length, exceptions.Count);
}
public class MyTarget : Target
{
public MyTarget()
{
Events = new List<LogEventInfo>();
}
public MyTarget(string name) : this()
{
Name = name;
}
public List<LogEventInfo> Events { get; set; }
protected override void Write(LogEventInfo logEvent)
{
Events.Add(logEvent);
}
}
}
}
| |
#region Copyright notice and license
// Copyright 2015 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;
using Grpc.Core;
using Grpc.Core.Utils;
using Grpc.Core.Profiling;
namespace Grpc.Core.Internal
{
/// <summary>
/// grpc_call from <c>grpc/grpc.h</c>
/// </summary>
internal class CallSafeHandle : SafeHandleZeroIsInvalid, INativeCall
{
public static readonly CallSafeHandle NullInstance = new CallSafeHandle();
static readonly NativeMethods Native = NativeMethods.Get();
const uint GRPC_WRITE_BUFFER_HINT = 1;
CompletionQueueSafeHandle completionQueue;
private CallSafeHandle()
{
}
public void Initialize(CompletionQueueSafeHandle completionQueue)
{
this.completionQueue = completionQueue;
}
public void SetCredentials(CallCredentialsSafeHandle credentials)
{
Native.grpcsharp_call_set_credentials(this, credentials).CheckOk();
}
public void StartUnary(UnaryResponseClientHandler callback, byte[] payload, WriteFlags writeFlags, MetadataArraySafeHandle metadataArray, CallFlags callFlags)
{
using (completionQueue.NewScope())
{
var ctx = BatchContextSafeHandle.Create();
completionQueue.CompletionRegistry.RegisterBatchCompletion(ctx, (success, context) => callback(success, context.GetReceivedStatusOnClient(), context.GetReceivedMessage(), context.GetReceivedInitialMetadata()));
Native.grpcsharp_call_start_unary(this, ctx, payload, new UIntPtr((ulong)payload.Length), writeFlags, metadataArray, callFlags)
.CheckOk();
}
}
public void StartUnary(BatchContextSafeHandle ctx, byte[] payload, WriteFlags writeFlags, MetadataArraySafeHandle metadataArray, CallFlags callFlags)
{
Native.grpcsharp_call_start_unary(this, ctx, payload, new UIntPtr((ulong)payload.Length), writeFlags, metadataArray, callFlags)
.CheckOk();
}
public void StartClientStreaming(UnaryResponseClientHandler callback, MetadataArraySafeHandle metadataArray, CallFlags callFlags)
{
using (completionQueue.NewScope())
{
var ctx = BatchContextSafeHandle.Create();
completionQueue.CompletionRegistry.RegisterBatchCompletion(ctx, (success, context) => callback(success, context.GetReceivedStatusOnClient(), context.GetReceivedMessage(), context.GetReceivedInitialMetadata()));
Native.grpcsharp_call_start_client_streaming(this, ctx, metadataArray, callFlags).CheckOk();
}
}
public void StartServerStreaming(ReceivedStatusOnClientHandler callback, byte[] payload, WriteFlags writeFlags, MetadataArraySafeHandle metadataArray, CallFlags callFlags)
{
using (completionQueue.NewScope())
{
var ctx = BatchContextSafeHandle.Create();
completionQueue.CompletionRegistry.RegisterBatchCompletion(ctx, (success, context) => callback(success, context.GetReceivedStatusOnClient()));
Native.grpcsharp_call_start_server_streaming(this, ctx, payload, new UIntPtr((ulong)payload.Length), writeFlags, metadataArray, callFlags).CheckOk();
}
}
public void StartDuplexStreaming(ReceivedStatusOnClientHandler callback, MetadataArraySafeHandle metadataArray, CallFlags callFlags)
{
using (completionQueue.NewScope())
{
var ctx = BatchContextSafeHandle.Create();
completionQueue.CompletionRegistry.RegisterBatchCompletion(ctx, (success, context) => callback(success, context.GetReceivedStatusOnClient()));
Native.grpcsharp_call_start_duplex_streaming(this, ctx, metadataArray, callFlags).CheckOk();
}
}
public void StartSendMessage(SendCompletionHandler callback, byte[] payload, WriteFlags writeFlags, bool sendEmptyInitialMetadata)
{
using (completionQueue.NewScope())
{
var ctx = BatchContextSafeHandle.Create();
completionQueue.CompletionRegistry.RegisterBatchCompletion(ctx, (success, context) => callback(success));
Native.grpcsharp_call_send_message(this, ctx, payload, new UIntPtr((ulong)payload.Length), writeFlags, sendEmptyInitialMetadata ? 1 : 0).CheckOk();
}
}
public void StartSendCloseFromClient(SendCompletionHandler callback)
{
using (completionQueue.NewScope())
{
var ctx = BatchContextSafeHandle.Create();
completionQueue.CompletionRegistry.RegisterBatchCompletion(ctx, (success, context) => callback(success));
Native.grpcsharp_call_send_close_from_client(this, ctx).CheckOk();
}
}
public void StartSendStatusFromServer(SendCompletionHandler callback, Status status, MetadataArraySafeHandle metadataArray, bool sendEmptyInitialMetadata,
byte[] optionalPayload, WriteFlags writeFlags)
{
using (completionQueue.NewScope())
{
var ctx = BatchContextSafeHandle.Create();
var optionalPayloadLength = optionalPayload != null ? new UIntPtr((ulong)optionalPayload.Length) : UIntPtr.Zero;
completionQueue.CompletionRegistry.RegisterBatchCompletion(ctx, (success, context) => callback(success));
var statusDetailBytes = MarshalUtils.GetBytesUTF8(status.Detail);
Native.grpcsharp_call_send_status_from_server(this, ctx, status.StatusCode, statusDetailBytes, new UIntPtr((ulong)statusDetailBytes.Length), metadataArray, sendEmptyInitialMetadata ? 1 : 0,
optionalPayload, optionalPayloadLength, writeFlags).CheckOk();
}
}
public void StartReceiveMessage(ReceivedMessageHandler callback)
{
using (completionQueue.NewScope())
{
var ctx = BatchContextSafeHandle.Create();
completionQueue.CompletionRegistry.RegisterBatchCompletion(ctx, (success, context) => callback(success, context.GetReceivedMessage()));
Native.grpcsharp_call_recv_message(this, ctx).CheckOk();
}
}
public void StartReceiveInitialMetadata(ReceivedResponseHeadersHandler callback)
{
using (completionQueue.NewScope())
{
var ctx = BatchContextSafeHandle.Create();
completionQueue.CompletionRegistry.RegisterBatchCompletion(ctx, (success, context) => callback(success, context.GetReceivedInitialMetadata()));
Native.grpcsharp_call_recv_initial_metadata(this, ctx).CheckOk();
}
}
public void StartServerSide(ReceivedCloseOnServerHandler callback)
{
using (completionQueue.NewScope())
{
var ctx = BatchContextSafeHandle.Create();
completionQueue.CompletionRegistry.RegisterBatchCompletion(ctx, (success, context) => callback(success, context.GetReceivedCloseOnServerCancelled()));
Native.grpcsharp_call_start_serverside(this, ctx).CheckOk();
}
}
public void StartSendInitialMetadata(SendCompletionHandler callback, MetadataArraySafeHandle metadataArray)
{
using (completionQueue.NewScope())
{
var ctx = BatchContextSafeHandle.Create();
completionQueue.CompletionRegistry.RegisterBatchCompletion(ctx, (success, context) => callback(success));
Native.grpcsharp_call_send_initial_metadata(this, ctx, metadataArray).CheckOk();
}
}
public void Cancel()
{
Native.grpcsharp_call_cancel(this).CheckOk();
}
public void CancelWithStatus(Status status)
{
Native.grpcsharp_call_cancel_with_status(this, status.StatusCode, status.Detail).CheckOk();
}
public string GetPeer()
{
using (var cstring = Native.grpcsharp_call_get_peer(this))
{
return cstring.GetValue();
}
}
public AuthContextSafeHandle GetAuthContext()
{
return Native.grpcsharp_call_auth_context(this);
}
protected override bool ReleaseHandle()
{
Native.grpcsharp_call_destroy(handle);
return true;
}
private static uint GetFlags(bool buffered)
{
return buffered ? 0 : GRPC_WRITE_BUFFER_HINT;
}
/// <summary>
/// Only for testing.
/// </summary>
public static CallSafeHandle CreateFake(IntPtr ptr, CompletionQueueSafeHandle cq)
{
var call = new CallSafeHandle();
call.SetHandle(ptr);
call.Initialize(cq);
return call;
}
}
}
| |
#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;
/// <summary>
/// Visitor implementation that avoids the overhead of cloning collections
/// before visiting them.
///
/// Avoid mutating collections when using this implementation.
/// </summary>
public partial class FastDepthFirstVisitor : IAstVisitor
{
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnCompileUnit(Boo.Lang.Compiler.Ast.CompileUnit node)
{
{
var modules = node.Modules;
if (modules != null)
{
var innerList = modules.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnTypeMemberStatement(Boo.Lang.Compiler.Ast.TypeMemberStatement node)
{
{
var modifier = node.Modifier;
if (modifier != null)
modifier.Accept(this);
}
{
var typeMember = node.TypeMember;
if (typeMember != null)
typeMember.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnExplicitMemberInfo(Boo.Lang.Compiler.Ast.ExplicitMemberInfo node)
{
{
var interfaceType = node.InterfaceType;
if (interfaceType != null)
interfaceType.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnSimpleTypeReference(Boo.Lang.Compiler.Ast.SimpleTypeReference node)
{
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnArrayTypeReference(Boo.Lang.Compiler.Ast.ArrayTypeReference node)
{
{
var elementType = node.ElementType;
if (elementType != null)
elementType.Accept(this);
}
{
var rank = node.Rank;
if (rank != null)
rank.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnCallableTypeReference(Boo.Lang.Compiler.Ast.CallableTypeReference node)
{
{
var parameters = node.Parameters;
if (parameters != null)
{
var innerList = parameters.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var returnType = node.ReturnType;
if (returnType != null)
returnType.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnGenericTypeReference(Boo.Lang.Compiler.Ast.GenericTypeReference node)
{
{
var genericArguments = node.GenericArguments;
if (genericArguments != null)
{
var innerList = genericArguments.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnGenericTypeDefinitionReference(Boo.Lang.Compiler.Ast.GenericTypeDefinitionReference node)
{
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnCallableDefinition(Boo.Lang.Compiler.Ast.CallableDefinition node)
{
{
var attributes = node.Attributes;
if (attributes != null)
{
var innerList = attributes.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var parameters = node.Parameters;
if (parameters != null)
{
var innerList = parameters.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var genericParameters = node.GenericParameters;
if (genericParameters != null)
{
var innerList = genericParameters.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var returnType = node.ReturnType;
if (returnType != null)
returnType.Accept(this);
}
{
var returnTypeAttributes = node.ReturnTypeAttributes;
if (returnTypeAttributes != null)
{
var innerList = returnTypeAttributes.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnNamespaceDeclaration(Boo.Lang.Compiler.Ast.NamespaceDeclaration node)
{
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnImport(Boo.Lang.Compiler.Ast.Import node)
{
{
var expression = node.Expression;
if (expression != null)
expression.Accept(this);
}
{
var assemblyReference = node.AssemblyReference;
if (assemblyReference != null)
assemblyReference.Accept(this);
}
{
var alias = node.Alias;
if (alias != null)
alias.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnModule(Boo.Lang.Compiler.Ast.Module node)
{
{
var attributes = node.Attributes;
if (attributes != null)
{
var innerList = attributes.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var members = node.Members;
if (members != null)
{
var innerList = members.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var baseTypes = node.BaseTypes;
if (baseTypes != null)
{
var innerList = baseTypes.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var genericParameters = node.GenericParameters;
if (genericParameters != null)
{
var innerList = genericParameters.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var @namespace = node.Namespace;
if (@namespace != null)
@namespace.Accept(this);
}
{
var imports = node.Imports;
if (imports != null)
{
var innerList = imports.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var globals = node.Globals;
if (globals != null)
globals.Accept(this);
}
{
var assemblyAttributes = node.AssemblyAttributes;
if (assemblyAttributes != null)
{
var innerList = assemblyAttributes.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnClassDefinition(Boo.Lang.Compiler.Ast.ClassDefinition node)
{
{
var attributes = node.Attributes;
if (attributes != null)
{
var innerList = attributes.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var members = node.Members;
if (members != null)
{
var innerList = members.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var baseTypes = node.BaseTypes;
if (baseTypes != null)
{
var innerList = baseTypes.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var genericParameters = node.GenericParameters;
if (genericParameters != null)
{
var innerList = genericParameters.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnStructDefinition(Boo.Lang.Compiler.Ast.StructDefinition node)
{
{
var attributes = node.Attributes;
if (attributes != null)
{
var innerList = attributes.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var members = node.Members;
if (members != null)
{
var innerList = members.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var baseTypes = node.BaseTypes;
if (baseTypes != null)
{
var innerList = baseTypes.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var genericParameters = node.GenericParameters;
if (genericParameters != null)
{
var innerList = genericParameters.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnInterfaceDefinition(Boo.Lang.Compiler.Ast.InterfaceDefinition node)
{
{
var attributes = node.Attributes;
if (attributes != null)
{
var innerList = attributes.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var members = node.Members;
if (members != null)
{
var innerList = members.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var baseTypes = node.BaseTypes;
if (baseTypes != null)
{
var innerList = baseTypes.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var genericParameters = node.GenericParameters;
if (genericParameters != null)
{
var innerList = genericParameters.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnEnumDefinition(Boo.Lang.Compiler.Ast.EnumDefinition node)
{
{
var attributes = node.Attributes;
if (attributes != null)
{
var innerList = attributes.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var members = node.Members;
if (members != null)
{
var innerList = members.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var baseTypes = node.BaseTypes;
if (baseTypes != null)
{
var innerList = baseTypes.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var genericParameters = node.GenericParameters;
if (genericParameters != null)
{
var innerList = genericParameters.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnEnumMember(Boo.Lang.Compiler.Ast.EnumMember node)
{
{
var attributes = node.Attributes;
if (attributes != null)
{
var innerList = attributes.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var initializer = node.Initializer;
if (initializer != null)
initializer.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnField(Boo.Lang.Compiler.Ast.Field node)
{
{
var attributes = node.Attributes;
if (attributes != null)
{
var innerList = attributes.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var type = node.Type;
if (type != null)
type.Accept(this);
}
{
var initializer = node.Initializer;
if (initializer != null)
initializer.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnProperty(Boo.Lang.Compiler.Ast.Property node)
{
{
var attributes = node.Attributes;
if (attributes != null)
{
var innerList = attributes.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var parameters = node.Parameters;
if (parameters != null)
{
var innerList = parameters.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var getter = node.Getter;
if (getter != null)
getter.Accept(this);
}
{
var setter = node.Setter;
if (setter != null)
setter.Accept(this);
}
{
var type = node.Type;
if (type != null)
type.Accept(this);
}
{
var explicitInfo = node.ExplicitInfo;
if (explicitInfo != null)
explicitInfo.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnEvent(Boo.Lang.Compiler.Ast.Event node)
{
{
var attributes = node.Attributes;
if (attributes != null)
{
var innerList = attributes.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var add = node.Add;
if (add != null)
add.Accept(this);
}
{
var remove = node.Remove;
if (remove != null)
remove.Accept(this);
}
{
var raise = node.Raise;
if (raise != null)
raise.Accept(this);
}
{
var type = node.Type;
if (type != null)
type.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnLocal(Boo.Lang.Compiler.Ast.Local node)
{
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnBlockExpression(Boo.Lang.Compiler.Ast.BlockExpression node)
{
{
var parameters = node.Parameters;
if (parameters != null)
{
var innerList = parameters.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var returnType = node.ReturnType;
if (returnType != null)
returnType.Accept(this);
}
{
var body = node.Body;
if (body != null)
body.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnMethod(Boo.Lang.Compiler.Ast.Method node)
{
{
var attributes = node.Attributes;
if (attributes != null)
{
var innerList = attributes.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var parameters = node.Parameters;
if (parameters != null)
{
var innerList = parameters.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var genericParameters = node.GenericParameters;
if (genericParameters != null)
{
var innerList = genericParameters.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var returnType = node.ReturnType;
if (returnType != null)
returnType.Accept(this);
}
{
var returnTypeAttributes = node.ReturnTypeAttributes;
if (returnTypeAttributes != null)
{
var innerList = returnTypeAttributes.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var body = node.Body;
if (body != null)
body.Accept(this);
}
{
var locals = node.Locals;
if (locals != null)
{
var innerList = locals.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var explicitInfo = node.ExplicitInfo;
if (explicitInfo != null)
explicitInfo.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnConstructor(Boo.Lang.Compiler.Ast.Constructor node)
{
{
var attributes = node.Attributes;
if (attributes != null)
{
var innerList = attributes.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var parameters = node.Parameters;
if (parameters != null)
{
var innerList = parameters.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var genericParameters = node.GenericParameters;
if (genericParameters != null)
{
var innerList = genericParameters.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var returnType = node.ReturnType;
if (returnType != null)
returnType.Accept(this);
}
{
var returnTypeAttributes = node.ReturnTypeAttributes;
if (returnTypeAttributes != null)
{
var innerList = returnTypeAttributes.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var body = node.Body;
if (body != null)
body.Accept(this);
}
{
var locals = node.Locals;
if (locals != null)
{
var innerList = locals.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var explicitInfo = node.ExplicitInfo;
if (explicitInfo != null)
explicitInfo.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnDestructor(Boo.Lang.Compiler.Ast.Destructor node)
{
{
var attributes = node.Attributes;
if (attributes != null)
{
var innerList = attributes.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var parameters = node.Parameters;
if (parameters != null)
{
var innerList = parameters.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var genericParameters = node.GenericParameters;
if (genericParameters != null)
{
var innerList = genericParameters.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var returnType = node.ReturnType;
if (returnType != null)
returnType.Accept(this);
}
{
var returnTypeAttributes = node.ReturnTypeAttributes;
if (returnTypeAttributes != null)
{
var innerList = returnTypeAttributes.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var body = node.Body;
if (body != null)
body.Accept(this);
}
{
var locals = node.Locals;
if (locals != null)
{
var innerList = locals.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var explicitInfo = node.ExplicitInfo;
if (explicitInfo != null)
explicitInfo.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnParameterDeclaration(Boo.Lang.Compiler.Ast.ParameterDeclaration node)
{
{
var type = node.Type;
if (type != null)
type.Accept(this);
}
{
var attributes = node.Attributes;
if (attributes != null)
{
var innerList = attributes.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnGenericParameterDeclaration(Boo.Lang.Compiler.Ast.GenericParameterDeclaration node)
{
{
var baseTypes = node.BaseTypes;
if (baseTypes != null)
{
var innerList = baseTypes.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnDeclaration(Boo.Lang.Compiler.Ast.Declaration node)
{
{
var type = node.Type;
if (type != null)
type.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnAttribute(Boo.Lang.Compiler.Ast.Attribute node)
{
{
var arguments = node.Arguments;
if (arguments != null)
{
var innerList = arguments.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var namedArguments = node.NamedArguments;
if (namedArguments != null)
{
var innerList = namedArguments.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnStatementModifier(Boo.Lang.Compiler.Ast.StatementModifier node)
{
{
var condition = node.Condition;
if (condition != null)
condition.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnGotoStatement(Boo.Lang.Compiler.Ast.GotoStatement node)
{
{
var modifier = node.Modifier;
if (modifier != null)
modifier.Accept(this);
}
{
var label = node.Label;
if (label != null)
label.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnLabelStatement(Boo.Lang.Compiler.Ast.LabelStatement node)
{
{
var modifier = node.Modifier;
if (modifier != null)
modifier.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnBlock(Boo.Lang.Compiler.Ast.Block node)
{
{
var modifier = node.Modifier;
if (modifier != null)
modifier.Accept(this);
}
{
var statements = node.Statements;
if (statements != null)
{
var innerList = statements.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnDeclarationStatement(Boo.Lang.Compiler.Ast.DeclarationStatement node)
{
{
var modifier = node.Modifier;
if (modifier != null)
modifier.Accept(this);
}
{
var declaration = node.Declaration;
if (declaration != null)
declaration.Accept(this);
}
{
var initializer = node.Initializer;
if (initializer != null)
initializer.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnMacroStatement(Boo.Lang.Compiler.Ast.MacroStatement node)
{
{
var modifier = node.Modifier;
if (modifier != null)
modifier.Accept(this);
}
{
var arguments = node.Arguments;
if (arguments != null)
{
var innerList = arguments.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var body = node.Body;
if (body != null)
body.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnTryStatement(Boo.Lang.Compiler.Ast.TryStatement node)
{
{
var modifier = node.Modifier;
if (modifier != null)
modifier.Accept(this);
}
{
var protectedBlock = node.ProtectedBlock;
if (protectedBlock != null)
protectedBlock.Accept(this);
}
{
var exceptionHandlers = node.ExceptionHandlers;
if (exceptionHandlers != null)
{
var innerList = exceptionHandlers.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var failureBlock = node.FailureBlock;
if (failureBlock != null)
failureBlock.Accept(this);
}
{
var ensureBlock = node.EnsureBlock;
if (ensureBlock != null)
ensureBlock.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnExceptionHandler(Boo.Lang.Compiler.Ast.ExceptionHandler node)
{
{
var declaration = node.Declaration;
if (declaration != null)
declaration.Accept(this);
}
{
var filterCondition = node.FilterCondition;
if (filterCondition != null)
filterCondition.Accept(this);
}
{
var block = node.Block;
if (block != null)
block.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnIfStatement(Boo.Lang.Compiler.Ast.IfStatement node)
{
{
var modifier = node.Modifier;
if (modifier != null)
modifier.Accept(this);
}
{
var condition = node.Condition;
if (condition != null)
condition.Accept(this);
}
{
var trueBlock = node.TrueBlock;
if (trueBlock != null)
trueBlock.Accept(this);
}
{
var falseBlock = node.FalseBlock;
if (falseBlock != null)
falseBlock.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnUnlessStatement(Boo.Lang.Compiler.Ast.UnlessStatement node)
{
{
var modifier = node.Modifier;
if (modifier != null)
modifier.Accept(this);
}
{
var condition = node.Condition;
if (condition != null)
condition.Accept(this);
}
{
var block = node.Block;
if (block != null)
block.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnForStatement(Boo.Lang.Compiler.Ast.ForStatement node)
{
{
var modifier = node.Modifier;
if (modifier != null)
modifier.Accept(this);
}
{
var declarations = node.Declarations;
if (declarations != null)
{
var innerList = declarations.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var iterator = node.Iterator;
if (iterator != null)
iterator.Accept(this);
}
{
var block = node.Block;
if (block != null)
block.Accept(this);
}
{
var orBlock = node.OrBlock;
if (orBlock != null)
orBlock.Accept(this);
}
{
var thenBlock = node.ThenBlock;
if (thenBlock != null)
thenBlock.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnWhileStatement(Boo.Lang.Compiler.Ast.WhileStatement node)
{
{
var modifier = node.Modifier;
if (modifier != null)
modifier.Accept(this);
}
{
var condition = node.Condition;
if (condition != null)
condition.Accept(this);
}
{
var block = node.Block;
if (block != null)
block.Accept(this);
}
{
var orBlock = node.OrBlock;
if (orBlock != null)
orBlock.Accept(this);
}
{
var thenBlock = node.ThenBlock;
if (thenBlock != null)
thenBlock.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnBreakStatement(Boo.Lang.Compiler.Ast.BreakStatement node)
{
{
var modifier = node.Modifier;
if (modifier != null)
modifier.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnContinueStatement(Boo.Lang.Compiler.Ast.ContinueStatement node)
{
{
var modifier = node.Modifier;
if (modifier != null)
modifier.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnReturnStatement(Boo.Lang.Compiler.Ast.ReturnStatement node)
{
{
var modifier = node.Modifier;
if (modifier != null)
modifier.Accept(this);
}
{
var expression = node.Expression;
if (expression != null)
expression.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnYieldStatement(Boo.Lang.Compiler.Ast.YieldStatement node)
{
{
var modifier = node.Modifier;
if (modifier != null)
modifier.Accept(this);
}
{
var expression = node.Expression;
if (expression != null)
expression.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnRaiseStatement(Boo.Lang.Compiler.Ast.RaiseStatement node)
{
{
var modifier = node.Modifier;
if (modifier != null)
modifier.Accept(this);
}
{
var exception = node.Exception;
if (exception != null)
exception.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnUnpackStatement(Boo.Lang.Compiler.Ast.UnpackStatement node)
{
{
var modifier = node.Modifier;
if (modifier != null)
modifier.Accept(this);
}
{
var declarations = node.Declarations;
if (declarations != null)
{
var innerList = declarations.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var expression = node.Expression;
if (expression != null)
expression.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnExpressionStatement(Boo.Lang.Compiler.Ast.ExpressionStatement node)
{
{
var modifier = node.Modifier;
if (modifier != null)
modifier.Accept(this);
}
{
var expression = node.Expression;
if (expression != null)
expression.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnOmittedExpression(Boo.Lang.Compiler.Ast.OmittedExpression node)
{
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnExpressionPair(Boo.Lang.Compiler.Ast.ExpressionPair node)
{
{
var first = node.First;
if (first != null)
first.Accept(this);
}
{
var second = node.Second;
if (second != null)
second.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnMethodInvocationExpression(Boo.Lang.Compiler.Ast.MethodInvocationExpression node)
{
{
var target = node.Target;
if (target != null)
target.Accept(this);
}
{
var arguments = node.Arguments;
if (arguments != null)
{
var innerList = arguments.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var namedArguments = node.NamedArguments;
if (namedArguments != null)
{
var innerList = namedArguments.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnUnaryExpression(Boo.Lang.Compiler.Ast.UnaryExpression node)
{
{
var operand = node.Operand;
if (operand != null)
operand.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnBinaryExpression(Boo.Lang.Compiler.Ast.BinaryExpression node)
{
{
var left = node.Left;
if (left != null)
left.Accept(this);
}
{
var right = node.Right;
if (right != null)
right.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnConditionalExpression(Boo.Lang.Compiler.Ast.ConditionalExpression node)
{
{
var condition = node.Condition;
if (condition != null)
condition.Accept(this);
}
{
var trueValue = node.TrueValue;
if (trueValue != null)
trueValue.Accept(this);
}
{
var falseValue = node.FalseValue;
if (falseValue != null)
falseValue.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnReferenceExpression(Boo.Lang.Compiler.Ast.ReferenceExpression node)
{
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnMemberReferenceExpression(Boo.Lang.Compiler.Ast.MemberReferenceExpression node)
{
{
var target = node.Target;
if (target != null)
target.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnGenericReferenceExpression(Boo.Lang.Compiler.Ast.GenericReferenceExpression node)
{
{
var target = node.Target;
if (target != null)
target.Accept(this);
}
{
var genericArguments = node.GenericArguments;
if (genericArguments != null)
{
var innerList = genericArguments.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnQuasiquoteExpression(Boo.Lang.Compiler.Ast.QuasiquoteExpression node)
{
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnStringLiteralExpression(Boo.Lang.Compiler.Ast.StringLiteralExpression node)
{
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnCharLiteralExpression(Boo.Lang.Compiler.Ast.CharLiteralExpression node)
{
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnTimeSpanLiteralExpression(Boo.Lang.Compiler.Ast.TimeSpanLiteralExpression node)
{
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnIntegerLiteralExpression(Boo.Lang.Compiler.Ast.IntegerLiteralExpression node)
{
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnDecimalLiteralExpression(Boo.Lang.Compiler.Ast.DecimalLiteralExpression node)
{
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnDoubleLiteralExpression(Boo.Lang.Compiler.Ast.DoubleLiteralExpression node)
{
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnNullLiteralExpression(Boo.Lang.Compiler.Ast.NullLiteralExpression node)
{
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnSelfLiteralExpression(Boo.Lang.Compiler.Ast.SelfLiteralExpression node)
{
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnSuperLiteralExpression(Boo.Lang.Compiler.Ast.SuperLiteralExpression node)
{
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnBoolLiteralExpression(Boo.Lang.Compiler.Ast.BoolLiteralExpression node)
{
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnRELiteralExpression(Boo.Lang.Compiler.Ast.RELiteralExpression node)
{
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnSpliceExpression(Boo.Lang.Compiler.Ast.SpliceExpression node)
{
{
var expression = node.Expression;
if (expression != null)
expression.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnSpliceTypeReference(Boo.Lang.Compiler.Ast.SpliceTypeReference node)
{
{
var expression = node.Expression;
if (expression != null)
expression.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnSpliceMemberReferenceExpression(Boo.Lang.Compiler.Ast.SpliceMemberReferenceExpression node)
{
{
var target = node.Target;
if (target != null)
target.Accept(this);
}
{
var nameExpression = node.NameExpression;
if (nameExpression != null)
nameExpression.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnSpliceTypeMember(Boo.Lang.Compiler.Ast.SpliceTypeMember node)
{
{
var attributes = node.Attributes;
if (attributes != null)
{
var innerList = attributes.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var typeMember = node.TypeMember;
if (typeMember != null)
typeMember.Accept(this);
}
{
var nameExpression = node.NameExpression;
if (nameExpression != null)
nameExpression.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnSpliceTypeDefinitionBody(Boo.Lang.Compiler.Ast.SpliceTypeDefinitionBody node)
{
{
var attributes = node.Attributes;
if (attributes != null)
{
var innerList = attributes.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var expression = node.Expression;
if (expression != null)
expression.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnSpliceParameterDeclaration(Boo.Lang.Compiler.Ast.SpliceParameterDeclaration node)
{
{
var type = node.Type;
if (type != null)
type.Accept(this);
}
{
var attributes = node.Attributes;
if (attributes != null)
{
var innerList = attributes.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var parameterDeclaration = node.ParameterDeclaration;
if (parameterDeclaration != null)
parameterDeclaration.Accept(this);
}
{
var nameExpression = node.NameExpression;
if (nameExpression != null)
nameExpression.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnExpressionInterpolationExpression(Boo.Lang.Compiler.Ast.ExpressionInterpolationExpression node)
{
{
var expressions = node.Expressions;
if (expressions != null)
{
var innerList = expressions.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnHashLiteralExpression(Boo.Lang.Compiler.Ast.HashLiteralExpression node)
{
{
var items = node.Items;
if (items != null)
{
var innerList = items.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnListLiteralExpression(Boo.Lang.Compiler.Ast.ListLiteralExpression node)
{
{
var items = node.Items;
if (items != null)
{
var innerList = items.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnCollectionInitializationExpression(Boo.Lang.Compiler.Ast.CollectionInitializationExpression node)
{
{
var collection = node.Collection;
if (collection != null)
collection.Accept(this);
}
{
var initializer = node.Initializer;
if (initializer != null)
initializer.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnArrayLiteralExpression(Boo.Lang.Compiler.Ast.ArrayLiteralExpression node)
{
{
var items = node.Items;
if (items != null)
{
var innerList = items.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var type = node.Type;
if (type != null)
type.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnGeneratorExpression(Boo.Lang.Compiler.Ast.GeneratorExpression node)
{
{
var expression = node.Expression;
if (expression != null)
expression.Accept(this);
}
{
var declarations = node.Declarations;
if (declarations != null)
{
var innerList = declarations.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var iterator = node.Iterator;
if (iterator != null)
iterator.Accept(this);
}
{
var filter = node.Filter;
if (filter != null)
filter.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnExtendedGeneratorExpression(Boo.Lang.Compiler.Ast.ExtendedGeneratorExpression node)
{
{
var items = node.Items;
if (items != null)
{
var innerList = items.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnSlice(Boo.Lang.Compiler.Ast.Slice node)
{
{
var begin = node.Begin;
if (begin != null)
begin.Accept(this);
}
{
var end = node.End;
if (end != null)
end.Accept(this);
}
{
var step = node.Step;
if (step != null)
step.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnSlicingExpression(Boo.Lang.Compiler.Ast.SlicingExpression node)
{
{
var target = node.Target;
if (target != null)
target.Accept(this);
}
{
var indices = node.Indices;
if (indices != null)
{
var innerList = indices.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnTryCastExpression(Boo.Lang.Compiler.Ast.TryCastExpression node)
{
{
var target = node.Target;
if (target != null)
target.Accept(this);
}
{
var type = node.Type;
if (type != null)
type.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnCastExpression(Boo.Lang.Compiler.Ast.CastExpression node)
{
{
var target = node.Target;
if (target != null)
target.Accept(this);
}
{
var type = node.Type;
if (type != null)
type.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnTypeofExpression(Boo.Lang.Compiler.Ast.TypeofExpression node)
{
{
var type = node.Type;
if (type != null)
type.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnCustomStatement(Boo.Lang.Compiler.Ast.CustomStatement node)
{
{
var modifier = node.Modifier;
if (modifier != null)
modifier.Accept(this);
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnCustomExpression(Boo.Lang.Compiler.Ast.CustomExpression node)
{
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public virtual void OnStatementTypeMember(Boo.Lang.Compiler.Ast.StatementTypeMember node)
{
{
var attributes = node.Attributes;
if (attributes != null)
{
var innerList = attributes.InnerList;
var count = innerList.Count;
for (var i=0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
{
var statement = node.Statement;
if (statement != null)
statement.Accept(this);
}
}
protected virtual void Visit(Node node)
{
if (node == null)
return;
node.Accept(this);
}
protected virtual void Visit<T>(NodeCollection<T> nodes) where T: Node
{
if (nodes == null)
return;
var innerList = nodes.InnerList;
var count = innerList.Count;
for (var i = 0; i<count; ++i)
innerList.FastAt(i).Accept(this);
}
}
}
| |
// 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.Diagnostics.CodeAnalysis;
using System.Globalization;
namespace System.ComponentModel.Design
{
/// <summary>
/// Provides access to get and set option values for a designer.
/// </summary>
public abstract class DesignerOptionService : IDesignerOptionService
{
private DesignerOptionCollection _options;
private static readonly char[] s_slash = {'\\'};
/// <summary>
/// Returns the options collection for this service. There is
/// always a global options collection that contains child collections.
/// </summary>
public DesignerOptionCollection Options
{
get => _options ?? (_options = new DesignerOptionCollection(this, null, string.Empty, null));
}
/// <summary>
/// Creates a new DesignerOptionCollection with the given name, and adds it to
/// the given parent. The "value" parameter specifies an object whose public
/// properties will be used in the Properties collection of the option collection.
/// The value parameter can be null if this options collection does not offer
/// any properties. Properties will be wrapped in such a way that passing
/// anything into the component parameter of the property descriptor will be
/// ignored and the value object will be substituted.
/// </summary>
protected DesignerOptionCollection CreateOptionCollection(DesignerOptionCollection parent, string name, object value)
{
if (parent == null)
{
throw new ArgumentNullException(nameof(parent));
}
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
if (name.Length == 0)
{
throw new ArgumentException(SR.Format(SR.InvalidArgumentValue, name.Length.ToString(), "0"), "name.Length");
}
return new DesignerOptionCollection(this, parent, name, value);
}
/// <summary>
/// Retrieves the property descriptor for the given page / value name. Returns
/// null if the property couldn't be found.
/// </summary>
private PropertyDescriptor GetOptionProperty(string pageName, string valueName)
{
if (pageName == null)
{
throw new ArgumentNullException(nameof(pageName));
}
if (valueName == null)
{
throw new ArgumentNullException(nameof(valueName));
}
string[] optionNames = pageName.Split(s_slash);
DesignerOptionCollection options = Options;
foreach (string optionName in optionNames)
{
options = options[optionName];
if (options == null)
{
return null;
}
}
return options.Properties[valueName];
}
/// <summary>
/// This method is called on demand the first time a user asks for child
/// options or properties of an options collection.
/// </summary>
protected virtual void PopulateOptionCollection(DesignerOptionCollection options)
{
}
/// <summary>
/// This method must be implemented to show the options dialog UI for the given object.
/// </summary>
protected virtual bool ShowDialog(DesignerOptionCollection options, object optionObject) => false;
/// <summary>
/// Gets the value of an option defined in this package.
/// </summary>
object IDesignerOptionService.GetOptionValue(string pageName, string valueName)
{
PropertyDescriptor optionProp = GetOptionProperty(pageName, valueName);
return optionProp?.GetValue(null);
}
/// <summary>
/// Sets the value of an option defined in this package.
/// </summary>
void IDesignerOptionService.SetOptionValue(string pageName, string valueName, object value)
{
PropertyDescriptor optionProp = GetOptionProperty(pageName, valueName);
optionProp?.SetValue(null, value);
}
/// <summary>
/// The DesignerOptionCollection class is a collection that contains
/// other DesignerOptionCollection objects. This forms a tree of options,
/// with each branch of the tree having a name and a possible collection of
/// properties. Each parent branch of the tree contains a union of the
/// properties if all the branch's children.
/// </summary>
[TypeConverter(typeof(DesignerOptionConverter))]
public sealed class DesignerOptionCollection : IList
{
private DesignerOptionService _service;
private object _value;
private ArrayList _children;
private PropertyDescriptorCollection _properties;
/// <summary>
/// Creates a new DesignerOptionCollection.
/// </summary>
internal DesignerOptionCollection(DesignerOptionService service, DesignerOptionCollection parent, string name, object value)
{
_service = service;
Parent = parent;
Name = name;
_value = value;
if (Parent != null)
{
parent._properties = null;
if (Parent._children == null)
{
Parent._children = new ArrayList(1);
}
Parent._children.Add(this);
}
}
/// <summary>
/// The count of child options collections this collection contains.
/// </summary>
public int Count
{
get
{
EnsurePopulated();
return _children.Count;
}
}
/// <summary>
/// The name of this collection. Names are programmatic names and are not
/// localized. A name search is case insensitive.
/// </summary>
public string Name { get; }
/// <summary>
/// Returns the parent collection object, or null if there is no parent.
/// </summary>
public DesignerOptionCollection Parent { get; }
/// <summary>
/// The collection of properties that this OptionCollection, along with all of
/// its children, offers. PropertyDescriptors are taken directly from the
/// value passed to CreateObjectCollection and wrapped in an additional property
/// descriptor that hides the value object from the user. This means that any
/// value may be passed into the "component" parameter of the various
/// PropertyDescriptor methods. The value is ignored and is replaced with
/// the correct value internally.
/// </summary>
public PropertyDescriptorCollection Properties
{
get
{
if (_properties == null)
{
ArrayList propList;
if (_value != null)
{
PropertyDescriptorCollection props = TypeDescriptor.GetProperties(_value);
propList = new ArrayList(props.Count);
foreach (PropertyDescriptor prop in props)
{
propList.Add(new WrappedPropertyDescriptor(prop, _value));
}
}
else
{
propList = new ArrayList(1);
}
EnsurePopulated();
foreach (DesignerOptionCollection child in _children)
{
propList.AddRange(child.Properties);
}
PropertyDescriptor[] propArray = (PropertyDescriptor[])propList.ToArray(typeof(PropertyDescriptor));
_properties = new PropertyDescriptorCollection(propArray, true);
}
return _properties;
}
}
/// <summary>
/// Retrieves the child collection at the given index.
/// </summary>
public DesignerOptionCollection this[int index]
{
[SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters")]
get
{
EnsurePopulated();
if (index < 0 || index >= _children.Count)
{
throw new IndexOutOfRangeException(nameof(index));
}
return (DesignerOptionCollection)_children[index];
}
}
/// <summary>
/// Retrieves the child collection at the given name. The name search is case
/// insensitive.
/// </summary>
public DesignerOptionCollection this[string name]
{
get
{
EnsurePopulated();
foreach (DesignerOptionCollection child in _children)
{
if (string.Compare(child.Name, name, true, CultureInfo.InvariantCulture) == 0)
{
return child;
}
}
return null;
}
}
/// <summary>
/// Copies this collection to an array.
/// </summary>
public void CopyTo(Array array, int index)
{
EnsurePopulated();
_children.CopyTo(array, index);
}
/// <summary>
/// Called before any access to our collection to force it to become populated.
/// </summary>
private void EnsurePopulated()
{
if (_children == null)
{
_service.PopulateOptionCollection(this);
if (_children == null)
{
_children = new ArrayList(1);
}
}
}
/// <summary>
/// Returns an enumerator that can be used to iterate this collection.
/// </summary>
public IEnumerator GetEnumerator()
{
EnsurePopulated();
return _children.GetEnumerator();
}
/// <summary>
/// Returns the numerical index of the given value.
/// </summary>
public int IndexOf(DesignerOptionCollection value)
{
EnsurePopulated();
return _children.IndexOf(value);
}
/// <summary>
/// Locates the value object to use for getting or setting a property.
/// </summary>
private static object RecurseFindValue(DesignerOptionCollection options)
{
if (options._value != null)
{
return options._value;
}
foreach (DesignerOptionCollection child in options)
{
object value = RecurseFindValue(child);
if (value != null)
{
return value;
}
}
return null;
}
/// <summary>
/// Displays a dialog-based user interface that allows the user to
/// configure the various options.
/// </summary>
public bool ShowDialog()
{
object value = RecurseFindValue(this);
if (value == null)
{
return false;
}
return _service.ShowDialog(this, value);
}
/// <summary>
/// Private ICollection implementation.
/// </summary>
bool ICollection.IsSynchronized => false;
/// <summary>
/// Private ICollection implementation.
/// </summary>
object ICollection.SyncRoot => this;
/// <summary>
/// Private IList implementation.
/// </summary>
bool IList.IsFixedSize => true;
/// <summary>
/// Private IList implementation.
/// </summary>
bool IList.IsReadOnly => true;
/// <summary>
/// Private IList implementation.
/// </summary>
object IList.this[int index]
{
get => this[index];
set => throw new NotSupportedException();
}
/// <summary>
/// Private IList implementation.
/// </summary>
int IList.Add(object value) => throw new NotSupportedException();
/// <summary>
/// Private IList implementation.
/// </summary>
void IList.Clear() => throw new NotSupportedException();
/// <summary>
/// Private IList implementation.
/// </summary>
bool IList.Contains(object value)
{
EnsurePopulated();
return _children.Contains(value);
}
/// <summary>
/// Private IList implementation.
/// </summary>
int IList.IndexOf(object value)
{
EnsurePopulated();
return _children.IndexOf(value);
}
/// <summary>
/// Private IList implementation.
/// </summary>
void IList.Insert(int index, object value) => throw new NotSupportedException();
/// <summary>
/// Private IList implementation.
/// </summary>
void IList.Remove(object value) => throw new NotSupportedException();
/// <summary>
/// Private IList implementation.
/// </summary>
void IList.RemoveAt(int index) => throw new NotSupportedException();
/// <summary>
/// A special property descriptor that forwards onto a base
/// property descriptor but allows any value to be used for the
/// "component" parameter.
/// </summary>
private sealed class WrappedPropertyDescriptor : PropertyDescriptor
{
private readonly object _target;
private PropertyDescriptor _property;
internal WrappedPropertyDescriptor(PropertyDescriptor property, object target) : base(property.Name, null)
{
_property = property;
_target = target;
}
public override AttributeCollection Attributes => _property.Attributes;
public override Type ComponentType => _property.ComponentType;
public override bool IsReadOnly => _property.IsReadOnly;
public override Type PropertyType => _property.PropertyType;
public override bool CanResetValue(object component) => _property.CanResetValue(_target);
public override object GetValue(object component) => _property.GetValue(_target);
public override void ResetValue(object component) => _property.ResetValue(_target);
public override void SetValue(object component, object value) => _property.SetValue(_target, value);
public override bool ShouldSerializeValue(object component) => _property.ShouldSerializeValue(_target);
}
}
/// <summary>
/// The type converter for the designer option collection.
/// </summary>
internal sealed class DesignerOptionConverter : TypeConverter
{
public override bool GetPropertiesSupported(ITypeDescriptorContext cxt) => true;
public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext cxt, object value, Attribute[] attributes)
{
PropertyDescriptorCollection props = new PropertyDescriptorCollection(null);
if (!(value is DesignerOptionCollection options))
{
return props;
}
foreach (DesignerOptionCollection option in options)
{
props.Add(new OptionPropertyDescriptor(option));
}
foreach (PropertyDescriptor p in options.Properties)
{
props.Add(p);
}
return props;
}
public override object ConvertTo(ITypeDescriptorContext cxt, CultureInfo culture, object value, Type destinationType)
{
if (destinationType == typeof(string))
{
return SR.CollectionConverterText;
}
return base.ConvertTo(cxt, culture, value, destinationType);
}
private class OptionPropertyDescriptor : PropertyDescriptor
{
private DesignerOptionCollection _option;
internal OptionPropertyDescriptor(DesignerOptionCollection option) : base(option.Name, null)
{
_option = option;
}
public override Type ComponentType => _option.GetType();
public override bool IsReadOnly => true;
public override Type PropertyType => _option.GetType();
public override bool CanResetValue(object component) => false;
public override object GetValue(object component) => _option;
public override void ResetValue(object component)
{
}
public override void SetValue(object component, object value)
{
}
public override bool ShouldSerializeValue(object component) => false;
}
}
}
}
| |
//Copyright (C) 2005 Richard J. Northedge
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//This file is based on the EnglishNameFinder.java source file found in the
//original java implementation of OpenNLP. That source file contains the following header:
//Copyright (C) 2003 Thomas Morton
//
//This library is free software; you can redistribute it and/or
//modify it under the terms of the GNU Lesser General Public
//License as published by the Free Software Foundation; either
//version 2.1 of the License, or (at your option) any later version.
//
//This library is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU Lesser General Public License for more details.
//
//You should have received a copy of the GNU Lesser General Public
//License along with this program; if not, write to the Free Software
//Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
using System;
using System.Collections.Generic;
using OpenNLP.Tools.Trees;
using OpenNLP.Tools.Util;
using OpenNLP.Tools.Parser;
namespace OpenNLP.Tools.NameFind
{
/// <summary> Class is used to create a name finder for English.</summary>
public class EnglishNameFinder
{
private readonly Dictionary<string, MaximumEntropyNameFinder> mFinders;
private readonly string mModelPath;
public static string[] NameTypes = { "person", "organization", "location", "date", "time", "percentage", "money" };
public EnglishNameFinder(string modelPath)
{
mModelPath = modelPath;
mFinders = new Dictionary<string, MaximumEntropyNameFinder>();
}
private Span[] TokenizeToSpans(string input)
{
var charType = CharacterEnum.Whitespace;
CharacterEnum state = charType;
var tokens = new List<Span>();
int inputLength = input.Length;
int start = - 1;
var previousChar = (char) (0);
for (int characterIndex = 0; characterIndex < inputLength; characterIndex++)
{
char c = input[characterIndex];
if (char.IsWhiteSpace(c))
{
charType = CharacterEnum.Whitespace;
}
else if (char.IsLetter(c))
{
charType = CharacterEnum.Alphabetic;
}
else if (char.IsDigit(c))
{
charType = CharacterEnum.Numeric;
}
else
{
charType = CharacterEnum.Other;
}
if (state == CharacterEnum.Whitespace)
{
if (charType != CharacterEnum.Whitespace)
{
start = characterIndex;
}
}
else
{
if (charType != state || (charType == CharacterEnum.Other && c != previousChar))
{
tokens.Add(new Span(start, characterIndex));
start = characterIndex;
}
}
state = charType;
previousChar = c;
}
if (charType != CharacterEnum.Whitespace)
{
tokens.Add(new Span(start, inputLength));
}
return tokens.ToArray();
}
private string[] SpansToStrings(Span[] spans, string input)
{
var tokens = new string[spans.Length];
for (int currentSpan = 0, spanCount = spans.Length; currentSpan < spanCount; currentSpan++)
{
tokens[currentSpan] = input.Substring(spans[currentSpan].Start, (spans[currentSpan].End) - (spans[currentSpan].Start));
}
return tokens;
}
private string[] Tokenize(string input)
{
return SpansToStrings(TokenizeToSpans(input), input);
}
private void AddNames(string tag, List<Span>names, Parse[] tokens, Parse lineParse)
{
for (int currentName = 0, nameCount = names.Count; currentName < nameCount; currentName++)
{
Span nameTokenSpan = names[currentName];
Parse startToken = tokens[nameTokenSpan.Start];
Parse endToken = tokens[nameTokenSpan.End];
Parse commonParent = startToken.GetCommonParent(endToken);
if (commonParent != null)
{
var nameSpan = new Span(startToken.Span.Start, endToken.Span.End);
if (nameSpan.Equals(commonParent.Span))
{
commonParent.Insert(new Parse(commonParent.Text, nameSpan, tag, 1.0));
}
else
{
Parse[] kids = commonParent.GetChildren();
bool crossingKids = false;
for (int currentKid = 0, kidCount = kids.Length; currentKid < kidCount; currentKid++)
{
if (nameSpan.Crosses(kids[currentKid].Span))
{
crossingKids = true;
}
}
if (!crossingKids)
{
commonParent.Insert(new Parse(commonParent.Text, nameSpan, tag, 1.0));
}
else
{
if (commonParent.Type == CoordinationTransformer.Noun)
{
Parse[] grandKids = kids[0].GetChildren();
if (grandKids.Length > 1 && nameSpan.Contains(grandKids[grandKids.Length - 1].Span))
{
commonParent.Insert(new Parse(commonParent.Text, commonParent.Span, tag, 1.0));
}
}
}
}
}
}
}
private Dictionary<string, string>[] CreatePreviousTokenMaps(string[] finders)
{
var previousTokenMaps = new Dictionary<string, string>[finders.Length];
for (int currentFinder = 0, finderCount = finders.Length; currentFinder < finderCount; currentFinder++)
{
previousTokenMaps[currentFinder] = new Dictionary<string, string>();
}
return previousTokenMaps;
}
private void ClearPreviousTokenMaps(Dictionary<string, string>[] previousTokenMaps)
{
for (int currentMap = 0, mapCount = previousTokenMaps.Length; currentMap < mapCount; currentMap++)
{
previousTokenMaps[currentMap].Clear();
}
}
private void UpdatePreviousTokenMaps(Dictionary<string, string>[] previousTokenMaps, string[] tokens, string[][] finderTags)
{
for (int currentMap = 0, mapCount = previousTokenMaps.Length; currentMap < mapCount; currentMap++)
{
for (int currentToken = 0, tokenCount = tokens.Length; currentToken < tokenCount; currentToken++)
{
previousTokenMaps[currentMap][tokens[currentToken]] = finderTags[currentMap][currentToken];
}
}
}
private string ProcessParse(string[] models, Parse lineParse)
{
var output = new System.Text.StringBuilder();
var finderTags = new string[models.Length][];
Dictionary<string, string>[] previousTokenMaps = CreatePreviousTokenMaps(models);
Parse[] tokenParses = lineParse.GetTagNodes();
var tokens = new string[tokenParses.Length];
for (int currentToken = 0; currentToken < tokens.Length; currentToken++)
{
tokens[currentToken] = tokenParses[currentToken].ToString();
}
for (int currentFinder = 0, finderCount = models.Length; currentFinder < finderCount; currentFinder++)
{
MaximumEntropyNameFinder finder = mFinders[models[currentFinder]];
finderTags[currentFinder] = finder.Find(tokens, previousTokenMaps[currentFinder]);
}
UpdatePreviousTokenMaps(previousTokenMaps, tokens, finderTags);
for (int currentFinder = 0, finderCount = models.Length; currentFinder < finderCount; currentFinder++)
{
int start = -1;
var names = new List<Span>(5);
for (int currentToken = 0, tokenCount = tokens.Length; currentToken < tokenCount; currentToken++)
{
if ((finderTags[currentFinder][currentToken] == MaximumEntropyNameFinder.Start) || (finderTags[currentFinder][currentToken] == MaximumEntropyNameFinder.Other))
{
if (start != -1)
{
names.Add(new Span(start, currentToken - 1));
}
start = -1;
}
if (finderTags[currentFinder][currentToken] == MaximumEntropyNameFinder.Start)
{
start = currentToken;
}
}
if (start != - 1)
{
names.Add(new Span(start, tokens.Length - 1));
}
AddNames(models[currentFinder], names, tokenParses, lineParse);
}
output.Append(lineParse.Show());
//output.Append("\r\n");
return output.ToString();
}
/// <summary>Adds sgml style name tags to the specified input string and outputs this information</summary>
/// <param name="models">The model names for the name finders to be used</param>
/// <param name="line">The input</param>
private string ProcessText(string[] models, string line)
{
var output = new System.Text.StringBuilder();
var finderTags = new string[models.Length][];
Dictionary<string, string>[] previousTokenMaps = CreatePreviousTokenMaps(models);
if (line.Length == 0)
{
ClearPreviousTokenMaps(previousTokenMaps);
output.Append("\r\n");
}
else
{
Span[] spans = TokenizeToSpans(line);
string[] tokens = SpansToStrings(spans, line);
for (int currentFinder = 0, finderCount = models.Length; currentFinder < finderCount; currentFinder++)
{
MaximumEntropyNameFinder finder = mFinders[models[currentFinder]];
finderTags[currentFinder] = finder.Find(tokens, previousTokenMaps[currentFinder]);
}
UpdatePreviousTokenMaps(previousTokenMaps, tokens, finderTags);
for (int currentToken = 0, tokenCount = tokens.Length; currentToken < tokenCount; currentToken++)
{
for (int currentFinder = 0, finderCount = models.Length; currentFinder < finderCount; currentFinder++)
{
//check for end tags
if (currentToken != 0)
{
if ((finderTags[currentFinder][currentToken] == MaximumEntropyNameFinder.Start || finderTags[currentFinder][currentToken] == MaximumEntropyNameFinder.Other) && (finderTags[currentFinder][currentToken - 1] == MaximumEntropyNameFinder.Start || finderTags[currentFinder][currentToken - 1] == MaximumEntropyNameFinder.Continue))
{
output.Append("</" + models[currentFinder] + ">");
}
}
}
if (currentToken > 0 && spans[currentToken - 1].End < spans[currentToken].Start)
{
output.Append(line.Substring(spans[currentToken - 1].End, (spans[currentToken].Start) - (spans[currentToken - 1].End)));
}
//check for start tags
for (int currentFinder = 0, finderCount = models.Length; currentFinder < finderCount; currentFinder++)
{
if (finderTags[currentFinder][currentToken] == MaximumEntropyNameFinder.Start)
{
output.Append("<" + models[currentFinder] + ">");
}
}
output.Append(tokens[currentToken]);
}
//final end tags
if (tokens.Length != 0)
{
for (int currentFinder = 0, finderCount = models.Length; currentFinder < finderCount; currentFinder++)
{
if (finderTags[currentFinder][tokens.Length - 1] == MaximumEntropyNameFinder.Start || finderTags[currentFinder][tokens.Length - 1] == MaximumEntropyNameFinder.Continue)
{
output.Append("</" + models[currentFinder] + ">");
}
}
}
if (tokens.Length != 0)
{
if (spans[tokens.Length - 1].End < line.Length)
{
output.Append(line.Substring(spans[tokens.Length - 1].End));
}
}
output.Append("\r\n");
}
return output.ToString();
}
public string GetNames(string[] models, string data)
{
CreateModels(models);
return ProcessText(models, data);
}
public string GetNames(string[] models, Parse data)
{
CreateModels(models);
return ProcessParse(models, data);
}
private void CreateModels(IEnumerable<string> models)
{
foreach (string mod in models)
{
if (!mFinders.ContainsKey(mod))
{
string modelName = mModelPath + mod + ".nbin";
SharpEntropy.IMaximumEntropyModel model = new SharpEntropy.GisModel(new SharpEntropy.IO.BinaryGisModelReader(modelName));
var finder = new MaximumEntropyNameFinder(model);
mFinders.Add(mod, finder);
}
}
}
}
internal enum CharacterEnum
{
Whitespace,
Alphabetic,
Numeric,
Other
}
}
| |
// ***********************************************************************
// Copyright (c) 2007 Charlie Poole
//
// 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.Collections;
using NUnit.Framework.Internal;
namespace NUnit.Framework.Constraints
{
/// <summary>
/// Delegate used to delay evaluation of the actual value
/// to be used in evaluating a constraint
/// </summary>
#if CLR_2_0 || CLR_4_0
public delegate T ActualValueDelegate<T>();
#else
public delegate object ActualValueDelegate();
#endif
/// <summary>
/// The Constraint class is the base of all built-in constraints
/// within NUnit. It provides the operator overloads used to combine
/// constraints.
/// </summary>
public abstract class Constraint : IResolveConstraint
{
#region UnsetObject Class
/// <summary>
/// Class used to detect any derived constraints
/// that fail to set the actual value in their
/// Matches override.
/// </summary>
private class UnsetObject
{
public override string ToString()
{
return "UNSET";
}
}
#endregion
#region Static and Instance Fields
/// <summary>
/// Static UnsetObject used to detect derived constraints
/// failing to set the actual value.
/// </summary>
protected static object UNSET = new UnsetObject();
/// <summary>
/// The actual value being tested against a constraint
/// </summary>
protected object actual = UNSET;
/// <summary>
/// The display name of this Constraint for use by ToString()
/// </summary>
private string displayName;
/// <summary>
/// Argument fields used by ToString();
/// </summary>
private readonly int argcnt;
private readonly object arg1;
private readonly object arg2;
/// <summary>
/// The builder holding this constraint
/// </summary>
private ConstraintBuilder builder;
#endregion
#region Constructors
/// <summary>
/// Construct a constraint with no arguments
/// </summary>
protected Constraint()
{
argcnt = 0;
}
/// <summary>
/// Construct a constraint with one argument
/// </summary>
protected Constraint(object arg)
{
argcnt = 1;
this.arg1 = arg;
}
/// <summary>
/// Construct a constraint with two arguments
/// </summary>
protected Constraint(object arg1, object arg2)
{
argcnt = 2;
this.arg1 = arg1;
this.arg2 = arg2;
}
#endregion
#region Set Containing ConstraintBuilder
/// <summary>
/// Sets the ConstraintBuilder holding this constraint
/// </summary>
internal void SetBuilder(ConstraintBuilder builder)
{
this.builder = builder;
}
#endregion
#region Properties
/// <summary>
/// The display name of this Constraint for use by ToString().
/// The default value is the name of the constraint with
/// trailing "Constraint" removed. Derived classes may set
/// this to another name in their constructors.
/// </summary>
protected string DisplayName
{
get
{
if (displayName == null)
{
displayName = this.GetType().Name.ToLower();
if (displayName.EndsWith("`1") || displayName.EndsWith("`2"))
displayName = displayName.Substring(0, displayName.Length - 2);
if (displayName.EndsWith("constraint"))
displayName = displayName.Substring(0, displayName.Length - 10);
}
return displayName;
}
set { displayName = value; }
}
#endregion
#region Abstract and Virtual Methods
/// <summary>
/// Write the failure message to the MessageWriter provided
/// as an argument. The default implementation simply passes
/// the constraint and the actual value to the writer, which
/// then displays the constraint description and the value.
///
/// Constraints that need to provide additional details,
/// such as where the error occured can override this.
/// </summary>
/// <param name="writer">The MessageWriter on which to display the message</param>
public virtual void WriteMessageTo(MessageWriter writer)
{
writer.DisplayDifferences(this);
}
/// <summary>
/// Test whether the constraint is satisfied by a given value
/// </summary>
/// <param name="actual">The value to be tested</param>
/// <returns>True for success, false for failure</returns>
public abstract bool Matches(object actual);
#if CLR_2_0 || CLR_4_0
/// <summary>
/// Test whether the constraint is satisfied by an
/// ActualValueDelegate that returns the value to be tested.
/// The default implementation simply evaluates the delegate
/// but derived classes may override it to provide for delayed
/// processing.
/// </summary>
/// <param name="del">An <see cref="ActualValueDelegate{T}" /></param>
/// <returns>True for success, false for failure</returns>
public virtual bool Matches<T>(ActualValueDelegate<T> del)
{
#if NET_4_5
if (AsyncInvocationRegion.IsAsyncOperation(del))
using (var region = AsyncInvocationRegion.Create(del))
return Matches(region.WaitForPendingOperationsToComplete(del()));
#endif
return Matches(del());
}
#else
/// <summary>
/// Test whether the constraint is satisfied by an
/// ActualValueDelegate that returns the value to be tested.
/// The default implementation simply evaluates the delegate
/// but derived classes may override it to provide for delayed
/// processing.
/// </summary>
/// <param name="del">An <see cref="ActualValueDelegate" /></param>
/// <returns>True for success, false for failure</returns>
public virtual bool Matches(ActualValueDelegate del)
{
return Matches(del());
}
#endif
/// <summary>
/// Test whether the constraint is satisfied by a given reference.
/// The default implementation simply dereferences the value but
/// derived classes may override it to provide for delayed processing.
/// </summary>
/// <param name="actual">A reference to the value to be tested</param>
/// <returns>True for success, false for failure</returns>
#if CLR_2_0 || CLR_4_0
public virtual bool Matches<T>(ref T actual)
#else
public virtual bool Matches(ref bool actual)
#endif
{
return Matches(actual);
}
/// <summary>
/// Write the constraint description to a MessageWriter
/// </summary>
/// <param name="writer">The writer on which the description is displayed</param>
public abstract void WriteDescriptionTo(MessageWriter writer);
/// <summary>
/// Write the actual value for a failing constraint test to a
/// MessageWriter. The default implementation simply writes
/// the raw value of actual, leaving it to the writer to
/// perform any formatting.
/// </summary>
/// <param name="writer">The writer on which the actual value is displayed</param>
public virtual void WriteActualValueTo(MessageWriter writer)
{
writer.WriteActualValue(actual);
}
#endregion
#region ToString Override
/// <summary>
/// Default override of ToString returns the constraint DisplayName
/// followed by any arguments within angle brackets.
/// </summary>
/// <returns></returns>
public override string ToString()
{
string rep = GetStringRepresentation();
return this.builder == null ? rep : string.Format("<unresolved {0}>", rep);
}
/// <summary>
/// Returns the string representation of this constraint
/// </summary>
protected virtual string GetStringRepresentation()
{
switch (argcnt)
{
default:
case 0:
return string.Format("<{0}>", DisplayName);
case 1:
return string.Format("<{0} {1}>", DisplayName, _displayable(arg1));
case 2:
return string.Format("<{0} {1} {2}>", DisplayName, _displayable(arg1), _displayable(arg2));
}
}
private static string _displayable(object o)
{
if (o == null) return "null";
string fmt = o is string ? "\"{0}\"" : "{0}";
return string.Format(System.Globalization.CultureInfo.InvariantCulture, fmt, o);
}
#endregion
#region Operator Overloads
/// <summary>
/// This operator creates a constraint that is satisfied only if both
/// argument constraints are satisfied.
/// </summary>
public static Constraint operator &(Constraint left, Constraint right)
{
IResolveConstraint l = (IResolveConstraint)left;
IResolveConstraint r = (IResolveConstraint)right;
return new AndConstraint(l.Resolve(), r.Resolve());
}
/// <summary>
/// This operator creates a constraint that is satisfied if either
/// of the argument constraints is satisfied.
/// </summary>
public static Constraint operator |(Constraint left, Constraint right)
{
IResolveConstraint l = (IResolveConstraint)left;
IResolveConstraint r = (IResolveConstraint)right;
return new OrConstraint(l.Resolve(), r.Resolve());
}
/// <summary>
/// This operator creates a constraint that is satisfied if the
/// argument constraint is not satisfied.
/// </summary>
public static Constraint operator !(Constraint constraint)
{
IResolveConstraint r = constraint as IResolveConstraint;
return new NotConstraint(r == null ? new NullConstraint() : r.Resolve());
}
#endregion
#region Binary Operators
/// <summary>
/// Returns a ConstraintExpression by appending And
/// to the current constraint.
/// </summary>
public ConstraintExpression And
{
get
{
ConstraintBuilder builder = this.builder;
if (builder == null)
{
builder = new ConstraintBuilder();
builder.Append(this);
}
builder.Append(new AndOperator());
return new ConstraintExpression(builder);
}
}
/// <summary>
/// Returns a ConstraintExpression by appending And
/// to the current constraint.
/// </summary>
public ConstraintExpression With
{
get { return this.And; }
}
/// <summary>
/// Returns a ConstraintExpression by appending Or
/// to the current constraint.
/// </summary>
public ConstraintExpression Or
{
get
{
ConstraintBuilder builder = this.builder;
if (builder == null)
{
builder = new ConstraintBuilder();
builder.Append(this);
}
builder.Append(new OrOperator());
return new ConstraintExpression(builder);
}
}
#endregion
#region After Modifier
#if !NETCF && !SILVERLIGHT
/// <summary>
/// Returns a DelayedConstraint with the specified delay time.
/// </summary>
/// <param name="delayInMilliseconds">The delay in milliseconds.</param>
/// <returns></returns>
public DelayedConstraint After(int delayInMilliseconds)
{
return new DelayedConstraint(
builder == null ? this : builder.Resolve(),
delayInMilliseconds);
}
/// <summary>
/// Returns a DelayedConstraint with the specified delay time
/// and polling interval.
/// </summary>
/// <param name="delayInMilliseconds">The delay in milliseconds.</param>
/// <param name="pollingInterval">The interval at which to test the constraint.</param>
/// <returns></returns>
public DelayedConstraint After(int delayInMilliseconds, int pollingInterval)
{
return new DelayedConstraint(
builder == null ? this : builder.Resolve(),
delayInMilliseconds,
pollingInterval);
}
#endif
#endregion
#region IResolveConstraint Members
Constraint IResolveConstraint.Resolve()
{
return builder == null ? this : builder.Resolve();
}
#endregion
}
}
| |
// Window.cs
// Script#/Libraries/Web
// This source code is subject to terms and conditions of the Apache License, Version 2.0.
//
using System;
using System.Html.Data;
using System.Runtime.CompilerServices;
namespace System.Html {
/// <summary>
/// The window object represents the current browser window, and is the top-level
/// scripting object.
/// </summary>
[IgnoreNamespace]
[Imported]
[ScriptName("window")]
public static class Window {
[IntrinsicProperty]
public static ApplicationCache ApplicationCache {
get {
return null;
}
}
/// <summary>
/// IE only.
/// </summary>
[IntrinsicProperty]
public static DataTransfer ClipboardData {
get {
return null;
}
}
[IntrinsicProperty]
public static bool Closed {
get {
return false;
}
}
[IntrinsicProperty]
public static string DefaultStatus {
get {
return null;
}
set {
}
}
[IntrinsicProperty]
public static object DialogArguments {
get {
return null;
}
}
[IntrinsicProperty]
public static DocumentInstance Document {
get {
return null;
}
}
/// <summary>
/// Provides information about the current event being handled.
/// </summary>
[IntrinsicProperty]
public static ElementEvent Event {
get {
return null;
}
}
[IntrinsicProperty]
public static IFrameElement FrameElement {
get {
return null;
}
}
[IntrinsicProperty]
public static History History {
get {
return null;
}
}
[IntrinsicProperty]
public static int InnerHeight {
get {
return 0;
}
}
[IntrinsicProperty]
public static int InnerWidth {
get {
return 0;
}
}
[IntrinsicProperty]
public static Storage LocalStorage {
get {
return null;
}
}
[IntrinsicProperty]
public static Location Location {
get {
return null;
}
}
[InlineCode("window.location = {url}")]
public static void SetLocation(string url) {
}
[IntrinsicProperty]
public static Navigator Navigator {
get {
return null;
}
}
[IntrinsicProperty]
public static WindowInstance Parent {
get {
return null;
}
}
[IntrinsicProperty]
public static ErrorHandler Onerror {
get {
return null;
}
set {
}
}
[IntrinsicProperty]
public static WindowInstance Opener {
get {
return null;
}
}
[IntrinsicProperty]
public static Orientation Orientation {
get {
return Orientation.Portrait;
}
}
[IntrinsicProperty]
public static int OuterHeight {
get {
return 0;
}
}
[IntrinsicProperty]
public static int OuterWidth {
get {
return 0;
}
}
[IntrinsicProperty]
public static int PageXOffset {
get {
return 0;
}
}
[IntrinsicProperty]
public static int PageYOffset {
get {
return 0;
}
}
[IntrinsicProperty]
public static Screen Screen {
get {
return null;
}
}
[IntrinsicProperty]
[ScriptAlias("window")]
public static WindowInstance Instance {
get {
return null;
}
}
[IntrinsicProperty]
public static WindowInstance Self {
get {
return null;
}
}
[IntrinsicProperty]
public static Storage SessionStorage {
get {
return null;
}
}
[IntrinsicProperty]
public static string Status {
get {
return null;
}
set {
}
}
[IntrinsicProperty]
public static WindowInstance Top {
get {
return null;
}
}
[IntrinsicProperty]
public static WindowInstance[] Frames {
get {
return null;
}
}
/// <summary>
/// Adds a listener for the specified event.
/// </summary>
/// <param name="eventName">The name of the event such as 'load'.</param>
/// <param name="listener">The listener to be invoked in response to the event.</param>
public static void AddEventListener(string eventName, ElementEventListener listener) {
}
/// <summary>
/// Adds a listener for the specified event.
/// </summary>
/// <param name="eventName">The name of the event such as 'load'.</param>
/// <param name="listener">The listener to be invoked in response to the event.</param>
/// <param name="useCapture">Whether the listener wants to initiate capturing the event.</param>
public static void AddEventListener(string eventName, ElementEventListener listener, bool useCapture) {
}
public static void AttachEvent(string eventName, ElementEventHandler handler) {
}
public static void ClearInterval(int intervalID) {
}
public static void ClearTimeout(int timeoutID) {
}
public static void Close() {
}
public static void DetachEvent(string eventName, ElementEventHandler handler) {
}
public static bool DispatchEvent(MutableEvent eventObject) {
return false;
}
public static void Navigate(string url) {
}
public static WindowInstance Open(string url) {
return null;
}
public static WindowInstance Open(string url, string targetName) {
return null;
}
public static WindowInstance Open(string url, string targetName, string features) {
return null;
}
public static WindowInstance Open(string url, string targetName, string features, bool replace) {
return null;
}
public static void Print() {
}
/// <summary>
/// Removes a listener for the specified event.
/// </summary>
/// <param name="eventName">The name of the event such as 'load'.</param>
/// <param name="listener">The listener to be invoked in response to the event.</param>
public static void RemoveEventListener(string eventName, ElementEventListener listener) {
}
/// <summary>
/// Removes a listener for the specified event.
/// </summary>
/// <param name="eventName">The name of the event such as 'load'.</param>
/// <param name="listener">The listener to be invoked in response to the event.</param>
/// <param name="useCapture">Whether the listener wants to initiate capturing the event.</param>
public static void RemoveEventListener(string eventName, ElementEventListener listener, bool useCapture) {
}
public static void Scroll(int x, int y) {
}
public static void ScrollBy(int x, int y) {
}
public static void ScrollTo(int x, int y) {
}
public static int SetInterval(string code, int milliseconds) {
return 0;
}
public static int SetInterval(Action callback, int milliseconds) {
return 0;
}
public static int SetInterval(Delegate d, int milliseconds) {
return 0;
}
public static int SetTimeout(string code, int milliseconds) {
return 0;
}
public static int SetTimeout(Action callback, int milliseconds) {
return 0;
}
public static int SetTimeout(Delegate d, int milliseconds) {
return 0;
}
public static SqlDatabase OpenDatabase(string name, string version) {
return null;
}
public static SqlDatabase OpenDatabase(string name, string version, string displayName) {
return null;
}
public static SqlDatabase OpenDatabase(string name, string version, string displayName, int estimatedSize) {
return null;
}
public static SqlDatabase OpenDatabase(string name, string version, string displayName, int estimatedSize, SqlDatabaseCallback creationCallback) {
return null;
}
public static void PostMessage(string message, string targetOrigin) {
}
/// <summary>
/// Delegate that indicates the ability of the browser
/// to show a modal dialog.
/// </summary>
/// <remarks>
/// Not all browsers support this function, so code using
/// this needs to check for existence of the feature or the browser.
/// </remarks>
public static WindowInstance ShowModalDialog(string url, object dialogArguments, string features) {
return null;
}
/// <summary>
/// Displays a message box containing the specified message text.
/// </summary>
/// <param name="message">The text of the message.</param>
public static void Alert(string message) {
}
/// <summary>
/// Displays a message box containing the specified value converted
/// into a string.
/// </summary>
/// <param name="b">The boolean to display.</param>
public static void Alert(bool b) {
}
/// <summary>
/// Displays a message box containing the specified value converted
/// into a string.
/// </summary>
/// <param name="d">The date to display.</param>
public static void Alert(DateTime d) {
}
/// <summary>
/// Displays a message box containing the specified value converted
/// into a string.
/// </summary>
/// <param name="d">The number to display.</param>
public static void Alert(double d) {
}
/// <summary>
/// Prompts the user with a yes/no question.
/// </summary>
/// <param name="message">The text of the question.</param>
/// <returns>true if the user chooses yes; false otherwise.</returns>
public static bool Confirm(string message) {
return false;
}
/// <summary>
/// Prompts the user to enter a value.
/// </summary>
/// <param name="message">The text of the prompt.</param>
/// <returns>The value entered by the user.</returns>
public static string Prompt(string message) {
return null;
}
/// <summary>
/// Prompts the user to enter a value, along with providing a default
/// value.
/// </summary>
/// <param name="message">The text of the prompt.</param>
/// <param name="defaultValue">The default value for the prompt.</param>
/// <returns>The value entered by the user.</returns>
public static string Prompt(string message, string defaultValue) {
return null;
}
}
}
| |
//
// System.Web.UI.WebControls.WebParts.Part.cs
//
// Authors:
// Gaurav Vaish (gaurav[DOT]vaish[AT]gmail[DOT]com)
// Sanjay Gupta (gsanjay@novell.com)
//
// (C) 2004 Gaurav Vaish (http://www.mastergaurav.org)
// (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.
//
#if NET_2_0
using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI.WebControls;
namespace System.Web.UI.WebControls.WebParts
{
[DesignerAttribute ("System.Web.UI.Design.WebControls.WebParts.WebPartDesigner, System.Design",
"System.ComponentModel.Design.IDesigner")]
public class WebPart : Part, IWebPart, IWebActionable
{
private bool allowClose = true;
private bool allowEdit = true;
private bool allowHide = true;
private bool allowMinimize = true;
private bool allowZoneChange = true;
private bool allowHelp = true;
private bool isStatic = true;
private bool isStandalone = true;
private bool isClosed = true;
private PartChromeState chromeState = PartChromeState.Normal;
private PartChromeType chromeType = PartChromeType.Default;
private WebPartExportMode exportMode = WebPartExportMode.None;
private WebPartHelpMode helpMode = WebPartHelpMode.Navigate;
private string subtitle;
private string catalogIconImageUrl;
private string description;
private string titleIconImageUrl;
private string title;
private string titleUrl;
private WebPartVerbCollection verbCollection;
protected WebPart()
{
}
[WebSysDescriptionAttribute ("Determines Whether the Web Part can be closed."),
DefaultValueAttribute (true), WebCategoryAttribute ("Behavior of Web Part")]
//, PersonalizableAttribute
public virtual bool AllowClose {
get { return allowClose; }
set { allowClose = value; }
}
[WebSysDescriptionAttribute ("Determines Whether properties of the Web Part can be changed using the EditorZone."),
DefaultValueAttribute (true), WebCategoryAttribute ("Behavior of Web Part")]
//, PersonalizableAttribute
public virtual bool AllowEdit {
get { return allowEdit; }
set { allowEdit = value; }
}
[WebSysDescriptionAttribute ("Determines Whether properties of the Web Part can be changed using the EditorZone."),
DefaultValueAttribute (true), WebCategoryAttribute ("Behavior of Web Part")]
//, PersonalizableAttribute
public virtual bool AllowHelp {
get { return AllowHelp; }
set { allowHelp = value; }
}
[WebSysDescriptionAttribute ("Determines Whether the Web Part can be minimized."),
DefaultValueAttribute (true), WebCategoryAttribute ("Behavior of Web Part")]
//, PersonalizableAttribute
public virtual bool AllowMinimize {
get { return allowMinimize; }
set { allowMinimize = value; }
}
[WebSysDescriptionAttribute ("Determines Whether the Web Part can be moved to some other zone."),
DefaultValueAttribute (true), WebCategoryAttribute ("Behavior of Web Part")]
//, PersonalizableAttribute
public virtual bool AllowZoneChange {
get { return allowZoneChange; }
set { allowZoneChange = value; }
}
[BrowsableAttribute (false),
DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
public bool IsClosed {
get { return isClosed; }
}
[BrowsableAttribute (false),
DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
public bool IsStandalone
{
get { return isStandalone; }
}
//[PersonalizableAttribute ]
public override PartChromeState ChromeState {
get { return chromeState; }
set {
if(!Enum.IsDefined (typeof (PartChromeState), value))
throw new ArgumentException ("value");
chromeState = value;
}
}
//[PersonalizableAttribute ]
public override PartChromeType ChromeType {
get { return chromeType; }
set {
if(!Enum.IsDefined (typeof (PartChromeType), value))
throw new ArgumentException ("value");
chromeType = value;
}
}
[BrowsableAttribute (false),
DesignerSerializationVisibilityAttribute (System.ComponentModel.DesignerSerializationVisibility.Hidden),
LocalizableAttribute (true)]
string IWebPart.Subtitle {
get { return subtitle; }
}
[DefaultValueAttribute (""),
EditorAttribute ("System.Web.UI.Design.ImageUrlEditor, System.Design",
"System.Drawing.Design.UITypeEditor, System.Drawing") ,
WebCategoryAttribute ("Appearance of the Web Part"),
WebSysDescriptionAttribute ("Specifies URL of image which is displayed in WebPart's Catalog.")]
//UrlPropertyAttribute, PersonalizableAttribute
string IWebPart.CatalogIconImageUrl {
get { return catalogIconImageUrl; }
set { catalogIconImageUrl = value; }
}
string IWebPart.Description {
get { return description; }
set { description = value; }
}
string IWebPart.Title {
get { return title; }
set { title = value; }
}
[DefaultValueAttribute (""),
EditorAttribute ("System.Web.UI.Design.ImageUrlEditor, System.Design",
"System.Drawing.Design.UITypeEditor, System.Drawing"),
WebCategoryAttribute ("Appearance of the Web Part"),
WebSysDescriptionAttribute ("Specifies URL of image which is displayed in WebPart's title bar.")]
//UrlPropertyAttribute, PersonalizableAttribute
string IWebPart.TitleIconImageUrl
{
get { return titleIconImageUrl; }
set { titleIconImageUrl = value; }
}
[DefaultValueAttribute (""),
EditorAttribute ("System.Web.UI.Design.UrlEditor, System.Design",
"System.Drawing.Design.UITypeEditor, System.Drawing"),
WebCategoryAttribute ("Behavior of the Web Part"),
WebSysDescriptionAttribute ("Specifies URL of page, containing additional information about this WebPart.")]
//UrlPropertyAttribute, PersonalizableAttribute
string IWebPart.TitleUrl {
get { return titleUrl; }
set { titleUrl = value; }
}
[BrowsableAttribute (false),
DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
WebPartVerbCollection IWebActionable.Verbs {
get {
if (verbCollection == null) {
verbCollection = new WebPartVerbCollection ();
}
return verbCollection;
}
}
}
}
#endif
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Orleans;
using Orleans.Configuration;
using Orleans.Hosting;
using Orleans.Runtime;
using Orleans.Runtime.Configuration;
using Orleans.TestingHost;
using TestExtensions;
using UnitTests.TestHelper;
using Xunit;
using Xunit.Sdk;
namespace UnitTests.General
{
public class ConsistentRingProviderTests_Silo : TestClusterPerTest
{
private const int numAdditionalSilos = 3;
private readonly TimeSpan failureTimeout = TimeSpan.FromSeconds(30);
private readonly TimeSpan endWait = TimeSpan.FromMinutes(5);
enum Fail { First, Random, Last }
protected override void ConfigureTestCluster(TestClusterBuilder builder)
{
builder.AddSiloBuilderConfigurator<Configurator>();
builder.AddClientBuilderConfigurator<Configurator>();
}
private class Configurator : ISiloBuilderConfigurator, IClientBuilderConfigurator
{
public void Configure(ISiloHostBuilder hostBuilder)
{
hostBuilder.AddMemoryGrainStorage("MemoryStore")
.AddMemoryGrainStorageAsDefault()
.UseInMemoryReminderService();
}
public void Configure(IConfiguration configuration, IClientBuilder clientBuilder)
{
clientBuilder.Configure<GatewayOptions>(
options => options.GatewayListRefreshPeriod = TimeSpan.FromMilliseconds(100));
}
}
[Fact, TestCategory("Functional"), TestCategory("Ring")]
public async Task Ring_Basic()
{
await this.HostedCluster.StartAdditionalSilosAsync(numAdditionalSilos);
await this.HostedCluster.WaitForLivenessToStabilizeAsync();
VerificationScenario(0);
}
[Fact, TestCategory("Functional"), TestCategory("Ring")]
public async Task Ring_1F_Random()
{
await FailureTest(Fail.Random, 1);
}
[Fact, TestCategory("Functional"), TestCategory("Ring")]
public async Task Ring_1F_Beginning()
{
await FailureTest(Fail.First, 1);
}
[Fact, TestCategory("Functional"), TestCategory("Ring")]
public async Task Ring_1F_End()
{
await FailureTest(Fail.Last, 1);
}
[Fact, TestCategory("Functional"), TestCategory("Ring")]
public async Task Ring_2F_Random()
{
await FailureTest(Fail.Random, 2);
}
[Fact, TestCategory("Functional"), TestCategory("Ring")]
public async Task Ring_2F_Beginning()
{
await FailureTest(Fail.First, 2);
}
[Fact, TestCategory("Functional"), TestCategory("Ring")]
public async Task Ring_2F_End()
{
await FailureTest(Fail.Last, 2);
}
private async Task FailureTest(Fail failCode, int numOfFailures)
{
await this.HostedCluster.StartAdditionalSilosAsync(numAdditionalSilos);
await this.HostedCluster.WaitForLivenessToStabilizeAsync();
List<SiloHandle> failures = await getSilosToFail(failCode, numOfFailures);
foreach (SiloHandle fail in failures) // verify before failure
{
VerificationScenario(PickKey(fail.SiloAddress)); // fail.SiloAddress.GetConsistentHashCode());
}
logger.Info("FailureTest {0}, Code {1}, Stopping silos: {2}", numOfFailures, failCode, Utils.EnumerableToString(failures, handle => handle.SiloAddress.ToString()));
List<uint> keysToTest = new List<uint>();
foreach (SiloHandle fail in failures) // verify before failure
{
keysToTest.Add(PickKey(fail.SiloAddress)); //fail.SiloAddress.GetConsistentHashCode());
await this.HostedCluster.StopSiloAsync(fail);
}
await this.HostedCluster.WaitForLivenessToStabilizeAsync();
AssertEventually(() =>
{
foreach (var key in keysToTest) // verify after failure
{
VerificationScenario(key);
}
}, failureTimeout);
}
[Fact, TestCategory("Functional"), TestCategory("Ring")]
public async Task Ring_1J()
{
await JoinTest(1);
}
[Fact, TestCategory("Functional"), TestCategory("Ring")]
public async Task Ring_2J()
{
await JoinTest(2);
}
private async Task JoinTest(int numOfJoins)
{
logger.Info("JoinTest {0}", numOfJoins);
await this.HostedCluster.StartAdditionalSilosAsync(numAdditionalSilos - numOfJoins);
await this.HostedCluster.WaitForLivenessToStabilizeAsync();
List<SiloHandle> silos = await this.HostedCluster.StartAdditionalSilosAsync(numOfJoins);
await this.HostedCluster.WaitForLivenessToStabilizeAsync();
foreach (SiloHandle sh in silos)
{
VerificationScenario(PickKey(sh.SiloAddress));
}
Thread.Sleep(TimeSpan.FromSeconds(15));
}
[Fact, TestCategory("Functional"), TestCategory("Ring")]
public async Task Ring_1F1J()
{
await this.HostedCluster.StartAdditionalSilosAsync(numAdditionalSilos);
await this.HostedCluster.WaitForLivenessToStabilizeAsync();
List<SiloHandle> failures = await getSilosToFail(Fail.Random, 1);
uint keyToCheck = PickKey(failures[0].SiloAddress);// failures[0].SiloAddress.GetConsistentHashCode();
List<SiloHandle> joins = null;
// kill a silo and join a new one in parallel
logger.Info("Killing silo {0} and joining a silo", failures[0].SiloAddress);
var tasks = new Task[2]
{
Task.Factory.StartNew(() => this.HostedCluster.StopSiloAsync(failures[0])),
this.HostedCluster.StartAdditionalSilosAsync(1).ContinueWith(t => joins = t.GetAwaiter().GetResult())
};
Task.WaitAll(tasks, endWait);
await this.HostedCluster.WaitForLivenessToStabilizeAsync();
AssertEventually(() =>
{
VerificationScenario(keyToCheck); // verify failed silo's key
VerificationScenario(PickKey(joins[0].SiloAddress)); // verify newly joined silo's key
}, failureTimeout);
}
// failing the secondary in this scenario exposed the bug in DomainGrain ... so, we keep it as a separate test than Ring_1F1J
[Fact, TestCategory("Functional"), TestCategory("Ring")]
public async Task Ring_1Fsec1J()
{
await this.HostedCluster.StartAdditionalSilosAsync(numAdditionalSilos);
await this.HostedCluster.WaitForLivenessToStabilizeAsync();
//List<SiloHandle> failures = getSilosToFail(Fail.Random, 1);
SiloHandle fail = this.HostedCluster.SecondarySilos.First();
uint keyToCheck = PickKey(fail.SiloAddress); //fail.SiloAddress.GetConsistentHashCode();
List<SiloHandle> joins = null;
// kill a silo and join a new one in parallel
logger.Info("Killing secondary silo {0} and joining a silo", fail.SiloAddress);
var tasks = new Task[2]
{
Task.Factory.StartNew(() => this.HostedCluster.StopSiloAsync(fail)),
this.HostedCluster.StartAdditionalSilosAsync(1).ContinueWith(t => joins = t.GetAwaiter().GetResult())
};
Task.WaitAll(tasks, endWait);
await this.HostedCluster.WaitForLivenessToStabilizeAsync();
AssertEventually(() =>
{
VerificationScenario(keyToCheck); // verify failed silo's key
VerificationScenario(PickKey(joins[0].SiloAddress));
}, failureTimeout);
}
private uint PickKey(SiloAddress responsibleSilo)
{
int iteration = 10000;
var testHooks = this.Client.GetTestHooks(this.HostedCluster.Primary);
for (int i = 0; i < iteration; i++)
{
double next = random.NextDouble();
uint randomKey = (uint)((double)RangeFactory.RING_SIZE * next);
SiloAddress s = testHooks.GetConsistentRingPrimaryTargetSilo(randomKey).Result;
if (responsibleSilo.Equals(s))
return randomKey;
}
throw new Exception(String.Format("Could not pick a key that silo {0} will be responsible for. Primary.Ring = \n{1}",
responsibleSilo, testHooks.GetConsistentRingProviderDiagnosticInfo().Result));
}
private void VerificationScenario(uint testKey)
{
// setup
List<SiloAddress> silos = new List<SiloAddress>();
foreach (var siloHandle in this.HostedCluster.GetActiveSilos())
{
long hash = siloHandle.SiloAddress.GetConsistentHashCode();
int index = silos.FindLastIndex(siloAddr => siloAddr.GetConsistentHashCode() < hash) + 1;
silos.Insert(index, siloHandle.SiloAddress);
}
// verify parameter key
VerifyKey(testKey, silos);
// verify some other keys as well, apart from the parameter key
// some random keys
for (int i = 0; i < 3; i++)
{
VerifyKey((uint)random.Next(), silos);
}
// lowest key
uint lowest = (uint)(silos.First().GetConsistentHashCode() - 1);
VerifyKey(lowest, silos);
// highest key
uint highest = (uint)(silos.Last().GetConsistentHashCode() + 1);
VerifyKey(lowest, silos);
}
private void VerifyKey(uint key, List<SiloAddress> silos)
{
var testHooks = this.Client.GetTestHooks(this.HostedCluster.Primary);
SiloAddress truth = testHooks.GetConsistentRingPrimaryTargetSilo(key).Result; //expected;
//if (truth == null) // if the truth isn't passed, we compute it here
//{
// truth = silos.Find(siloAddr => (key <= siloAddr.GetConsistentHashCode()));
// if (truth == null)
// {
// truth = silos.First();
// }
//}
// lookup for 'key' should return 'truth' on all silos
foreach (var siloHandle in this.HostedCluster.GetActiveSilos()) // do this for each silo
{
SiloAddress s = testHooks.GetConsistentRingPrimaryTargetSilo((uint)key).Result;
Assert.Equal(truth, s);
}
}
private async Task<List<SiloHandle>> getSilosToFail(Fail fail, int numOfFailures)
{
List<SiloHandle> failures = new List<SiloHandle>();
int count = 0, index = 0;
// Figure out the primary directory partition and the silo hosting the ReminderTableGrain.
var tableGrain = this.GrainFactory.GetGrain<IReminderTableGrain>(Constants.ReminderTableGrainId);
var tableGrainId = ((GrainReference)tableGrain).GrainId;
SiloAddress reminderTableGrainPrimaryDirectoryAddress = (await TestUtils.GetDetailedGrainReport(this.HostedCluster.InternalGrainFactory, tableGrainId, this.HostedCluster.Primary)).PrimaryForGrain;
// ask a detailed report from the directory partition owner, and get the actionvation addresses
var addresses = (await TestUtils.GetDetailedGrainReport(this.HostedCluster.InternalGrainFactory, tableGrainId, this.HostedCluster.GetSiloForAddress(reminderTableGrainPrimaryDirectoryAddress))).LocalDirectoryActivationAddresses;
ActivationAddress reminderGrainActivation = addresses.FirstOrDefault();
SortedList<int, SiloHandle> ids = new SortedList<int, SiloHandle>();
foreach (var siloHandle in this.HostedCluster.GetActiveSilos())
{
SiloAddress siloAddress = siloHandle.SiloAddress;
if (siloAddress.Equals(this.HostedCluster.Primary.SiloAddress))
{
continue;
}
// Don't fail primary directory partition and the silo hosting the ReminderTableGrain.
if (siloAddress.Equals(reminderTableGrainPrimaryDirectoryAddress) || siloAddress.Equals(reminderGrainActivation.Silo))
{
continue;
}
ids.Add(siloHandle.SiloAddress.GetConsistentHashCode(), siloHandle);
}
// we should not fail the primary!
// we can't guarantee semantics of 'Fail' if it evalutes to the primary's address
switch (fail)
{
case Fail.First:
index = 0;
while (count++ < numOfFailures)
{
while (failures.Contains(ids.Values[index]))
{
index++;
}
failures.Add(ids.Values[index]);
}
break;
case Fail.Last:
index = ids.Count - 1;
while (count++ < numOfFailures)
{
while (failures.Contains(ids.Values[index]))
{
index--;
}
failures.Add(ids.Values[index]);
}
break;
case Fail.Random:
default:
while (count++ < numOfFailures)
{
SiloHandle r = ids.Values[random.Next(ids.Count)];
while (failures.Contains(r))
{
r = ids.Values[random.Next(ids.Count)];
}
failures.Add(r);
}
break;
}
return failures;
}
// for debugging only
private void printSilos(string msg)
{
SortedList<int, SiloAddress> ids = new SortedList<int, SiloAddress>(numAdditionalSilos + 2);
foreach (var siloHandle in this.HostedCluster.GetActiveSilos())
{
ids.Add(siloHandle.SiloAddress.GetConsistentHashCode(), siloHandle.SiloAddress);
}
logger.Info("{0} list of silos: ", msg);
foreach (var id in ids.Keys.ToList())
{
logger.Info("{0} -> {1}", ids[id], id);
}
}
private static void AssertEventually(Action assertion, TimeSpan timeout)
{
AssertEventually(assertion, timeout, TimeSpan.FromMilliseconds(500));
}
private static void AssertEventually(Action assertion, TimeSpan timeout, TimeSpan delayBetweenIterations)
{
var sw = Stopwatch.StartNew();
while (true)
{
try
{
assertion();
return;
}
catch (XunitException)
{
if (sw.ElapsedMilliseconds > timeout.TotalMilliseconds)
{
throw;
}
}
if (delayBetweenIterations > TimeSpan.Zero)
{
Thread.Sleep(delayBetweenIterations);
}
}
}
}
}
| |
using UnityEngine;
namespace Vacs
{
[ExecuteInEditMode]
[RequireComponent(typeof(MeshRenderer))]
[AddComponentMenu("Vacs/Renderer")]
public sealed class VacsRenderer : MonoBehaviour
{
#region Exposed attributes
[SerializeField] VacsData _data;
[SerializeField, Range(0, 1)] float _dissolve;
[SerializeField, Range(0, 1)] float _inflate;
[SerializeField, Range(0, 1)] float _voxelize;
[SerializeField, Range(0, 1)] float _jitter;
[SerializeField, Range(0, 1)] float _digitize;
public float dissolve { set { _dissolve = value; } }
public float inflate { set { _inflate = value; } }
public float voxelize { set { _voxelize = value; } }
public float jitter { set { _jitter = value; } }
public float digitize { set { _digitize = value; } }
#endregion
#region Hidden attributes
[SerializeField, HideInInspector] ComputeShader _computeDissolve;
[SerializeField, HideInInspector] ComputeShader _computeInflate;
[SerializeField, HideInInspector] ComputeShader _computeVoxelize;
[SerializeField, HideInInspector] ComputeShader _computeJitter;
[SerializeField, HideInInspector] ComputeShader _computeDigitize;
[SerializeField, HideInInspector] ComputeShader _computeReconstruct;
#endregion
#region Private objects
ComputeBuffer _positionSource;
ComputeBuffer _positionBuffer1;
ComputeBuffer _positionBuffer2;
ComputeBuffer _normalSource;
ComputeBuffer _normalBuffer;
ComputeBuffer _tangentSource;
ComputeBuffer _tangentBuffer;
MaterialPropertyBlock _drawProps;
float _randomSeed;
#endregion
#region Internal properties and methods
float globalTime {
get { return Application.isPlaying ? Time.time : 10; }
}
void SetupBuffers()
{
if (_positionSource == null) _positionSource = _data.CreatePositionBuffer();
if (_positionBuffer1 == null) _positionBuffer1 = _data.CreatePositionBuffer();
if (_positionBuffer2 == null) _positionBuffer2 = _data.CreatePositionBuffer();
if (_normalSource == null) _normalSource = _data.CreateNormalBuffer();
if (_normalBuffer == null) _normalBuffer = _data.CreateNormalBuffer();
if (_tangentSource == null) _tangentSource = _data.CreateTangentBuffer();
if (_tangentBuffer == null) _tangentBuffer = _data.CreateTangentBuffer();
}
void ReleaseBuffers()
{
if (_positionSource != null) _positionSource .Release();
if (_positionBuffer1 != null) _positionBuffer1.Release();
if (_positionBuffer2 != null) _positionBuffer2.Release();
_positionSource = _positionBuffer1 = _positionBuffer2 = null;
if (_normalSource != null) _normalSource.Release();
if (_normalBuffer != null) _normalBuffer.Release();
_normalSource = _normalBuffer = null;
if (_tangentSource != null) _tangentSource.Release();
if (_tangentBuffer != null) _tangentBuffer.Release();
_tangentSource = _tangentBuffer = null;
}
void ApplyCompute(
ComputeShader compute, int trianglePerThread, float amplitude,
ComputeBuffer inputBuffer, ComputeBuffer outputBuffer)
{
var kernel = compute.FindKernel("Main");
compute.SetBuffer(kernel, "PositionSource", _positionSource);
compute.SetBuffer(kernel, "NormalSource", _normalSource);
compute.SetBuffer(kernel, "TangentSource", _tangentSource);
compute.SetBuffer(kernel, "PositionInput", inputBuffer);
compute.SetBuffer(kernel, "PositionOutput", outputBuffer);
compute.SetInt("TriangleCount", _data.triangleCount);
compute.SetFloat("Amplitude", amplitude);
compute.SetFloat("RandomSeed", _randomSeed);
compute.SetFloat("Time", globalTime);
var c = compute.GetKernelThreadGroupSizeX(kernel) * trianglePerThread;
compute.Dispatch(kernel, (_data.triangleCount + c - 1) / c, 1, 1);
}
void UpdateVertices()
{
ApplyCompute(_computeDissolve, 1, _dissolve, _positionSource, _positionBuffer1);
ApplyCompute(_computeInflate, 1, _inflate, _positionBuffer1, _positionBuffer2);
ApplyCompute(_computeVoxelize, 1, _voxelize, _positionBuffer2, _positionBuffer1);
ApplyCompute(_computeJitter, 1, _jitter, _positionBuffer1, _positionBuffer2);
ApplyCompute(_computeDigitize, 2, _digitize, _positionBuffer2, _positionBuffer1);
var compute = _computeReconstruct;
var kernel = compute.FindKernel("Main");
compute.SetBuffer(kernel, "PositionSource", _positionSource);
compute.SetBuffer(kernel, "PositionModified", _positionBuffer1);
compute.SetBuffer(kernel, "NormalInput", _normalSource);
compute.SetBuffer(kernel, "NormalOutput", _normalBuffer);
compute.SetBuffer(kernel, "TangentInput", _tangentSource);
compute.SetBuffer(kernel, "TangentOutput", _tangentBuffer);
compute.SetInt("TriangleCount", _data.triangleCount);
var c = compute.GetKernelThreadGroupSizeX(kernel);
compute.Dispatch(kernel, (_data.triangleCount + c - 1) / c, 1, 1);
}
#endregion
#region External component handling
void UpdateMeshFilter()
{
var meshFilter = GetComponent<MeshFilter>();
if (meshFilter == null)
{
meshFilter = gameObject.AddComponent<MeshFilter>();
meshFilter.hideFlags = HideFlags.NotEditable;
}
if (meshFilter.sharedMesh != _data.templateMesh)
meshFilter.sharedMesh = _data.templateMesh;
}
void UpdateMeshRenderer()
{
var meshRenderer = GetComponent<MeshRenderer>();
if (_drawProps == null)
_drawProps = new MaterialPropertyBlock();
_drawProps.SetBuffer("_PositionBuffer", _positionBuffer1);
_drawProps.SetBuffer("_NormalBuffer", _normalBuffer);
_drawProps.SetBuffer("_TangentBuffer", _tangentBuffer);
_drawProps.SetFloat("_TriangleCount", _data.triangleCount);
meshRenderer.SetPropertyBlock(_drawProps);
}
#endregion
#region MonoBehaviour methods
void OnDisable()
{
// In edit mode, we release the compute buffers OnDisable not
// OnDestroy, because Unity spits out warnings before OnDestroy.
// (OnDestroy is too late to prevent warning.)
if (!Application.isPlaying) ReleaseBuffers();
}
void OnDestroy()
{
ReleaseBuffers();
}
void Start()
{
_randomSeed = Random.value;
}
void LateUpdate()
{
if (_data != null)
{
SetupBuffers();
UpdateVertices();
UpdateMeshFilter();
UpdateMeshRenderer();
}
}
#endregion
}
}
| |
//#define DEBUGREADERS
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Excel.Core;
using System.Data;
using System.Xml;
using System.Globalization;
using ExcelDataReader.Portable.Core;
using ExcelDataReader.Portable.Core.OpenXmlFormat;
namespace Excel
{
public class ExcelOpenXmlReader : IExcelDataReader
{
#region Members
private XlsxWorkbook _workbook;
private bool _isValid;
private bool _isClosed;
private bool _isFirstRead;
private string _exceptionMessage;
private int _depth;
private int _resultIndex;
private int _emptyRowCount;
private ZipWorker _zipWorker;
private XmlReader _xmlReader;
private Stream _sheetStream;
private object[] _cellsValues;
private object[] _savedCellsValues;
private bool disposed;
private bool _isFirstRowAsColumnNames;
private const string COLUMN = "Column";
private string instanceId = Guid.NewGuid().ToString();
private List<int> _defaultDateTimeStyles;
private string _namespaceUri;
private Encoding defaultEncoding = Encoding.UTF8;
#endregion
internal ExcelOpenXmlReader()
{
_isValid = true;
_isFirstRead = true;
_defaultDateTimeStyles = new List<int>(new int[]
{
14, 15, 16, 17, 18, 19, 20, 21, 22, 45, 46, 47
});
}
private void ReadGlobals()
{
_workbook = new XlsxWorkbook(
_zipWorker.GetWorkbookStream(),
_zipWorker.GetWorkbookRelsStream(),
_zipWorker.GetSharedStringsStream(),
_zipWorker.GetStylesStream());
CheckDateTimeNumFmts(_workbook.Styles.NumFmts);
}
private void CheckDateTimeNumFmts(List<XlsxNumFmt> list)
{
if (list.Count == 0) return;
foreach (XlsxNumFmt numFmt in list)
{
if (string.IsNullOrEmpty(numFmt.FormatCode)) continue;
string fc = numFmt.FormatCode.ToLower();
int pos;
while ((pos = fc.IndexOf('"')) > 0)
{
int endPos = fc.IndexOf('"', pos + 1);
if (endPos > 0) fc = fc.Remove(pos, endPos - pos + 1);
}
//it should only detect it as a date if it contains
//dd mm mmm yy yyyy
//h hh ss
//AM PM
//and only if these appear as "words" so either contained in [ ]
//or delimted in someway
//updated to not detect as date if format contains a #
var formatReader = new FormatReader() {FormatString = fc};
if (formatReader.IsDateFormatString())
{
_defaultDateTimeStyles.Add(numFmt.Id);
}
}
}
private void ReadSheetGlobals(XlsxWorksheet sheet)
{
if (_xmlReader != null) _xmlReader.Close();
if (_sheetStream != null) _sheetStream.Close();
_sheetStream = _zipWorker.GetWorksheetStream(sheet.Path);
if (null == _sheetStream) return;
_xmlReader = XmlReader.Create(_sheetStream);
//count rows and cols in case there is no dimension elements
int rows = 0;
int cols = 0;
_namespaceUri = null;
int biggestColumn = 0; //used when no col elements and no dimension
while (_xmlReader.Read())
{
if (_xmlReader.NodeType == XmlNodeType.Element && _xmlReader.LocalName == XlsxWorksheet.N_worksheet)
{
//grab the namespaceuri from the worksheet element
_namespaceUri = _xmlReader.NamespaceURI;
}
if (_xmlReader.NodeType == XmlNodeType.Element && _xmlReader.LocalName == XlsxWorksheet.N_dimension)
{
string dimValue = _xmlReader.GetAttribute(XlsxWorksheet.A_ref);
sheet.Dimension = new XlsxDimension(dimValue);
break;
}
//removed: Do not use col to work out number of columns as this is really for defining formatting, so may not contain all columns
//if (_xmlReader.NodeType == XmlNodeType.Element && _xmlReader.LocalName == XlsxWorksheet.N_col)
// cols++;
if (_xmlReader.NodeType == XmlNodeType.Element && _xmlReader.LocalName == XlsxWorksheet.N_row)
rows++;
//check cells so we can find size of sheet if can't work it out from dimension or col elements (dimension should have been set before the cells if it was available)
//ditto for cols
if (sheet.Dimension == null && cols == 0 && _xmlReader.NodeType == XmlNodeType.Element && _xmlReader.LocalName == XlsxWorksheet.N_c)
{
var refAttribute = _xmlReader.GetAttribute(XlsxWorksheet.A_r);
if (refAttribute != null)
{
var thisRef = ReferenceHelper.ReferenceToColumnAndRow(refAttribute);
if (thisRef[1] > biggestColumn)
biggestColumn = thisRef[1];
}
}
}
//if we didn't get a dimension element then use the calculated rows/cols to create it
if (sheet.Dimension == null)
{
if (cols == 0)
cols = biggestColumn;
if (rows == 0 || cols == 0)
{
sheet.IsEmpty = true;
return;
}
sheet.Dimension = new XlsxDimension(rows, cols);
//we need to reset our position to sheet data
_xmlReader.Close();
_sheetStream.Close();
_sheetStream = _zipWorker.GetWorksheetStream(sheet.Path);
_xmlReader = XmlReader.Create(_sheetStream);
}
//read up to the sheetData element. if this element is empty then there aren't any rows and we need to null out dimension
_xmlReader.ReadToFollowing(XlsxWorksheet.N_sheetData, _namespaceUri);
if (_xmlReader.IsEmptyElement)
{
sheet.IsEmpty = true;
}
}
private bool ReadSheetRow(XlsxWorksheet sheet)
{
if (null == _xmlReader) return false;
if (_emptyRowCount != 0)
{
_cellsValues = new object[sheet.ColumnsCount];
_emptyRowCount--;
_depth++;
return true;
}
if (_savedCellsValues != null)
{
_cellsValues = _savedCellsValues;
_savedCellsValues = null;
_depth++;
return true;
}
if ((_xmlReader.NodeType == XmlNodeType.Element && _xmlReader.LocalName == XlsxWorksheet.N_row) ||
_xmlReader.ReadToFollowing(XlsxWorksheet.N_row, _namespaceUri))
{
_cellsValues = new object[sheet.ColumnsCount];
int rowIndex = int.Parse(_xmlReader.GetAttribute(XlsxWorksheet.A_r));
if (rowIndex != (_depth + 1))
if (rowIndex != (_depth + 1))
{
_emptyRowCount = rowIndex - _depth - 1;
}
bool hasValue = false;
string a_s = String.Empty;
string a_t = String.Empty;
string a_r = String.Empty;
int col = 0;
int row = 0;
while (_xmlReader.Read())
{
if (_xmlReader.Depth == 2) break;
if (_xmlReader.NodeType == XmlNodeType.Element)
{
hasValue = false;
if (_xmlReader.LocalName == XlsxWorksheet.N_c)
{
a_s = _xmlReader.GetAttribute(XlsxWorksheet.A_s);
a_t = _xmlReader.GetAttribute(XlsxWorksheet.A_t);
a_r = _xmlReader.GetAttribute(XlsxWorksheet.A_r);
XlsxDimension.XlsxDim(a_r, out col, out row);
}
else if (_xmlReader.LocalName == XlsxWorksheet.N_v || _xmlReader.LocalName == XlsxWorksheet.N_t)
{
hasValue = true;
}
}
if (_xmlReader.NodeType == XmlNodeType.Text && hasValue)
{
double number;
object o = _xmlReader.Value;
var style = NumberStyles.Any;
var culture = CultureInfo.InvariantCulture;
if (double.TryParse(o.ToString(), style, culture, out number))
o = number;
if (null != a_t && a_t == XlsxWorksheet.A_s) //if string
{
o = Helpers.ConvertEscapeChars(_workbook.SST[int.Parse(o.ToString())]);
} // Requested change 4: missing (it appears that if should be else if)
else if (null != a_t && a_t == XlsxWorksheet.N_inlineStr) //if string inline
{
o = Helpers.ConvertEscapeChars(o.ToString());
}
else if (a_t == "b") //boolean
{
o = _xmlReader.Value == "1";
}
else if (null != a_s) //if something else
{
XlsxXf xf = _workbook.Styles.CellXfs[int.Parse(a_s)];
if (o != null && o.ToString() != string.Empty && IsDateTimeStyle(xf.NumFmtId))
o = Helpers.ConvertFromOATime(number);
else if (xf.NumFmtId == 49)
o = o.ToString();
}
if (col - 1 < _cellsValues.Length)
_cellsValues[col - 1] = o;
}
}
if (_emptyRowCount > 0)
{
_savedCellsValues = _cellsValues;
return ReadSheetRow(sheet);
}
_depth++;
return true;
}
_xmlReader.Close();
if (_sheetStream != null) _sheetStream.Close();
return false;
}
private bool InitializeSheetRead()
{
if (ResultsCount <= 0) return false;
ReadSheetGlobals(_workbook.Sheets[_resultIndex]);
if (_workbook.Sheets[_resultIndex].Dimension == null) return false;
_isFirstRead = false;
_depth = 0;
_emptyRowCount = 0;
return true;
}
private bool IsDateTimeStyle(int styleId)
{
return _defaultDateTimeStyles.Contains(styleId);
}
#region IExcelDataReader Members
public void Initialize(System.IO.Stream fileStream)
{
_zipWorker = new ZipWorker();
_zipWorker.Extract(fileStream);
if (!_zipWorker.IsValid)
{
_isValid = false;
_exceptionMessage = _zipWorker.ExceptionMessage;
Close();
return;
}
ReadGlobals();
}
public System.Data.DataSet AsDataSet()
{
return AsDataSet(true);
}
public System.Data.DataSet AsDataSet(bool convertOADateTime)
{
if (!_isValid) return null;
DataSet dataset = new DataSet();
for (int ind = 0; ind < _workbook.Sheets.Count; ind++)
{
DataTable table = new DataTable(_workbook.Sheets[ind].Name);
table.ExtendedProperties.Add("visiblestate", _workbook.Sheets[ind].VisibleState);
ReadSheetGlobals(_workbook.Sheets[ind]);
if (_workbook.Sheets[ind].Dimension == null) continue;
_depth = 0;
_emptyRowCount = 0;
//DataTable columns
if (!_isFirstRowAsColumnNames)
{
for (int i = 0; i < _workbook.Sheets[ind].ColumnsCount; i++)
{
table.Columns.Add(null, typeof(Object));
}
}
else if (ReadSheetRow(_workbook.Sheets[ind]))
{
for (int index = 0; index < _cellsValues.Length; index++)
{
if (_cellsValues[index] != null && _cellsValues[index].ToString().Length > 0)
Helpers.AddColumnHandleDuplicate(table, _cellsValues[index].ToString());
else
Helpers.AddColumnHandleDuplicate(table, string.Concat(COLUMN, index));
}
}
else continue;
table.BeginLoadData();
while (ReadSheetRow(_workbook.Sheets[ind]))
{
table.Rows.Add(_cellsValues);
}
if (table.Rows.Count > 0)
dataset.Tables.Add(table);
table.EndLoadData();
}
dataset.AcceptChanges();
Helpers.FixDataTypes(dataset);
return dataset;
}
public bool IsFirstRowAsColumnNames
{
get
{
return _isFirstRowAsColumnNames;
}
set
{
_isFirstRowAsColumnNames = value;
}
}
public Encoding Encoding
{
get { return null; }
}
public Encoding DefaultEncoding
{
get { return defaultEncoding; }
}
public bool IsValid
{
get { return _isValid; }
}
public string ExceptionMessage
{
get { return _exceptionMessage; }
}
public string Name
{
get
{
return (_resultIndex >= 0 && _resultIndex < ResultsCount) ? _workbook.Sheets[_resultIndex].Name : null;
}
}
public string VisibleState
{
get
{
return (_resultIndex >= 0 && _resultIndex < ResultsCount) ? _workbook.Sheets[_resultIndex].VisibleState : null;
}
}
public void Close()
{
_isClosed = true;
if (_xmlReader != null) _xmlReader.Close();
if (_sheetStream != null) _sheetStream.Close();
if (_zipWorker != null) _zipWorker.Dispose();
}
public int Depth
{
get { return _depth; }
}
public int ResultsCount
{
get { return _workbook == null ? -1 : _workbook.Sheets.Count; }
}
public bool IsClosed
{
get { return _isClosed; }
}
public bool NextResult()
{
if (_resultIndex >= (this.ResultsCount - 1)) return false;
_resultIndex++;
_isFirstRead = true;
_savedCellsValues = null;
return true;
}
public bool Read()
{
if (!_isValid) return false;
if (_isFirstRead && !InitializeSheetRead())
{
return false;
}
return ReadSheetRow(_workbook.Sheets[_resultIndex]);
}
public int FieldCount
{
get { return (_resultIndex >= 0 && _resultIndex < ResultsCount) ? _workbook.Sheets[_resultIndex].ColumnsCount : -1; }
}
public bool GetBoolean(int i)
{
if (IsDBNull(i)) return false;
return Boolean.Parse(_cellsValues[i].ToString());
}
public DateTime GetDateTime(int i)
{
if (IsDBNull(i)) return DateTime.MinValue;
try
{
return (DateTime)_cellsValues[i];
}
catch (InvalidCastException)
{
return DateTime.MinValue;
}
}
public decimal GetDecimal(int i)
{
if (IsDBNull(i)) return decimal.MinValue;
return decimal.Parse(_cellsValues[i].ToString());
}
public double GetDouble(int i)
{
if (IsDBNull(i)) return double.MinValue;
return double.Parse(_cellsValues[i].ToString());
}
public float GetFloat(int i)
{
if (IsDBNull(i)) return float.MinValue;
return float.Parse(_cellsValues[i].ToString());
}
public short GetInt16(int i)
{
if (IsDBNull(i)) return short.MinValue;
return short.Parse(_cellsValues[i].ToString());
}
public int GetInt32(int i)
{
if (IsDBNull(i)) return int.MinValue;
return int.Parse(_cellsValues[i].ToString());
}
public long GetInt64(int i)
{
if (IsDBNull(i)) return long.MinValue;
return long.Parse(_cellsValues[i].ToString());
}
public string GetString(int i)
{
if (IsDBNull(i)) return null;
return _cellsValues[i].ToString();
}
public object GetValue(int i)
{
return _cellsValues[i];
}
public bool IsDBNull(int i)
{
return (null == _cellsValues[i]) || (DBNull.Value == _cellsValues[i]);
}
public object this[int i]
{
get { return _cellsValues[i]; }
}
#endregion
#region IDisposable Members
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
// Check to see if Dispose has already been called.
if (!this.disposed)
{
if (disposing)
{
if (_xmlReader != null) ((IDisposable) _xmlReader).Dispose();
if (_sheetStream != null) _sheetStream.Dispose();
if (_zipWorker != null) _zipWorker.Dispose();
}
_zipWorker = null;
_xmlReader = null;
_sheetStream = null;
_workbook = null;
_cellsValues = null;
_savedCellsValues = null;
disposed = true;
}
}
~ExcelOpenXmlReader()
{
Dispose(false);
}
#endregion
#region Not Supported IDataReader Members
public DataTable GetSchemaTable()
{
throw new NotSupportedException();
}
public int RecordsAffected
{
get { throw new NotSupportedException(); }
}
#endregion
#region Not Supported IDataRecord Members
public byte GetByte(int i)
{
throw new NotSupportedException();
}
public long GetBytes(int i, long fieldOffset, byte[] buffer, int bufferoffset, int length)
{
throw new NotSupportedException();
}
public char GetChar(int i)
{
throw new NotSupportedException();
}
public long GetChars(int i, long fieldoffset, char[] buffer, int bufferoffset, int length)
{
throw new NotSupportedException();
}
public IDataReader GetData(int i)
{
throw new NotSupportedException();
}
public string GetDataTypeName(int i)
{
throw new NotSupportedException();
}
public Type GetFieldType(int i)
{
throw new NotSupportedException();
}
public Guid GetGuid(int i)
{
throw new NotSupportedException();
}
public string GetName(int i)
{
throw new NotSupportedException();
}
public int GetOrdinal(string name)
{
throw new NotSupportedException();
}
public int GetValues(object[] values)
{
throw new NotSupportedException();
}
public object this[string name]
{
get { throw new NotSupportedException(); }
}
#endregion
}
}
| |
using Kitware.VTK;
using System;
// input file is C:\VTK\Parallel\Testing\Tcl\TestExtractVOI.tcl
// output file is AVTestExtractVOI.cs
/// <summary>
/// The testing class derived from AVTestExtractVOI
/// </summary>
public class AVTestExtractVOIClass
{
/// <summary>
/// The main entry method called by the CSharp driver
/// </summary>
/// <param name="argv"></param>
public static void AVTestExtractVOI(String [] argv)
{
//Prefix Content is: ""
// to mark the origin[]
sphere = new vtkSphereSource();
sphere.SetRadius((double)2.0);
sphereMapper = vtkPolyDataMapper.New();
sphereMapper.SetInputConnection((vtkAlgorithmOutput)sphere.GetOutputPort());
sphereMapper.ImmediateModeRenderingOn();
sphereActor = new vtkActor();
sphereActor.SetMapper((vtkMapper)sphereMapper);
rt = new vtkRTAnalyticSource();
rt.SetWholeExtent((int)-50,(int)50,(int)-50,(int)50,(int)0,(int)0);
voi = new vtkExtractVOI();
voi.SetInputConnection((vtkAlgorithmOutput)rt.GetOutputPort());
voi.SetVOI((int)-11,(int)39,(int)5,(int)45,(int)0,(int)0);
voi.SetSampleRate((int)5,(int)5,(int)1);
// Get rid ambiguous triagulation issues.[]
surf = new vtkDataSetSurfaceFilter();
surf.SetInputConnection((vtkAlgorithmOutput)voi.GetOutputPort());
tris = new vtkTriangleFilter();
tris.SetInputConnection((vtkAlgorithmOutput)surf.GetOutputPort());
mapper = vtkPolyDataMapper.New();
mapper.SetInputConnection((vtkAlgorithmOutput)tris.GetOutputPort());
mapper.ImmediateModeRenderingOn();
mapper.SetScalarRange((double)130,(double)280);
actor = new vtkActor();
actor.SetMapper((vtkMapper)mapper);
ren = vtkRenderer.New();
ren.AddActor((vtkProp)actor);
ren.AddActor((vtkProp)sphereActor);
ren.ResetCamera();
camera = ren.GetActiveCamera();
//$camera SetPosition 68.1939 -23.4323 12.6465[]
//$camera SetViewUp 0.46563 0.882375 0.0678508 []
//$camera SetFocalPoint 3.65707 11.4552 1.83509 []
//$camera SetClippingRange 59.2626 101.825 []
renWin = vtkRenderWindow.New();
renWin.AddRenderer((vtkRenderer)ren);
iren = new vtkRenderWindowInteractor();
iren.SetRenderWindow((vtkRenderWindow)renWin);
iren.Initialize();
//deleteAllVTKObjects();
}
static string VTK_DATA_ROOT;
static int threshold;
static vtkSphereSource sphere;
static vtkPolyDataMapper sphereMapper;
static vtkActor sphereActor;
static vtkRTAnalyticSource rt;
static vtkExtractVOI voi;
static vtkDataSetSurfaceFilter surf;
static vtkTriangleFilter tris;
static vtkPolyDataMapper mapper;
static vtkActor actor;
static vtkRenderer ren;
static vtkCamera camera;
static vtkRenderWindow renWin;
static vtkRenderWindowInteractor iren;
///<summary> A Get Method for Static Variables </summary>
public static string GetVTK_DATA_ROOT()
{
return VTK_DATA_ROOT;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetVTK_DATA_ROOT(string toSet)
{
VTK_DATA_ROOT = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static int Getthreshold()
{
return threshold;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setthreshold(int toSet)
{
threshold = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkSphereSource Getsphere()
{
return sphere;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setsphere(vtkSphereSource toSet)
{
sphere = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkPolyDataMapper GetsphereMapper()
{
return sphereMapper;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetsphereMapper(vtkPolyDataMapper toSet)
{
sphereMapper = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkActor GetsphereActor()
{
return sphereActor;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetsphereActor(vtkActor toSet)
{
sphereActor = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkRTAnalyticSource Getrt()
{
return rt;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setrt(vtkRTAnalyticSource toSet)
{
rt = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkExtractVOI Getvoi()
{
return voi;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setvoi(vtkExtractVOI toSet)
{
voi = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkDataSetSurfaceFilter Getsurf()
{
return surf;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setsurf(vtkDataSetSurfaceFilter toSet)
{
surf = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkTriangleFilter Gettris()
{
return tris;
}
///<summary> A Set Method for Static Variables </summary>
public static void Settris(vtkTriangleFilter toSet)
{
tris = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkPolyDataMapper Getmapper()
{
return mapper;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setmapper(vtkPolyDataMapper toSet)
{
mapper = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkActor Getactor()
{
return actor;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setactor(vtkActor toSet)
{
actor = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkRenderer Getren()
{
return ren;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setren(vtkRenderer toSet)
{
ren = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkCamera Getcamera()
{
return camera;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setcamera(vtkCamera toSet)
{
camera = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkRenderWindow GetrenWin()
{
return renWin;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetrenWin(vtkRenderWindow toSet)
{
renWin = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkRenderWindowInteractor Getiren()
{
return iren;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setiren(vtkRenderWindowInteractor toSet)
{
iren = toSet;
}
///<summary>Deletes all static objects created</summary>
public static void deleteAllVTKObjects()
{
//clean up vtk objects
if(sphere!= null){sphere.Dispose();}
if(sphereMapper!= null){sphereMapper.Dispose();}
if(sphereActor!= null){sphereActor.Dispose();}
if(rt!= null){rt.Dispose();}
if(voi!= null){voi.Dispose();}
if(surf!= null){surf.Dispose();}
if(tris!= null){tris.Dispose();}
if(mapper!= null){mapper.Dispose();}
if(actor!= null){actor.Dispose();}
if(ren!= null){ren.Dispose();}
if(camera!= null){camera.Dispose();}
if(renWin!= null){renWin.Dispose();}
if(iren!= null){iren.Dispose();}
}
}
//--- end of script --//
| |
// -------------------------------------------------------------------------------------------------------------------
// <copyright file="StringDifference.cs" company="">
// Copyright 2017 Cyrille Dupuydauby
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace NFluent.Helpers
{
using System;
using System.Collections.Generic;
using Extensions;
/// <summary>
/// Describes difference between strings.
/// </summary>
internal enum DifferenceMode
{
/// <summary>
/// Strings are same.
/// </summary>
NoDifference,
/// <summary>
/// General difference.
/// </summary>
General,
/// <summary>
/// Difference only in case (e.g. Foo vs foo).
/// </summary>
CaseDifference,
/// <summary>
/// Contains at least one longer line.
/// </summary>
LongerLine,
/// <summary>
/// Contains at least one shorter line.
/// </summary>
ShorterLine,
/// <summary>
/// End of line marker is different.
/// </summary>
EndOfLine,
/// <summary>
/// Line(s) are missing.
/// </summary>
MissingLines,
/// <summary>
/// Extra lines found.
/// </summary>
ExtraLines,
/// <summary>
/// Different in spaces (one vs many, tabs vs spaces...).
/// </summary>
Spaces,
/// <summary>
/// String is longer.
/// </summary>
Longer,
/// <summary>
/// String is shorter.
/// </summary>
Shorter,
/// <summary>
/// Strings have the same length but are different.
/// </summary>
GeneralSameLength
}
internal class StringDifference
{
private const char Linefeed = '\n';
private const char CarriageReturn = '\r';
private StringDifference(DifferenceMode mode, int line, int position, string actual, string expected, bool isFulltext)
{
this.Kind = mode;
this.Line = line;
this.Position = position;
this.Expected = expected;
this.Actual = actual;
this.IsFullText = isFulltext;
}
public DifferenceMode Kind { get; }
public int Line { get; }
public string Expected { get; internal set; }
public string Actual { get; internal set; }
public int Position { get; }
private bool IsFullText { get; }
private static string[] SplitLines(string text)
{
var temp = new List<string>();
var index = 0;
while (index <=text.Length)
{
var start = index;
index = text.IndexOf(Linefeed, start);
if (index < 0)
{
temp.Add(text.Substring(start));
index = text.Length+1;
}
else
{
temp.Add(text.Substring(start, index+1-start));
index = index + 1;
}
}
return temp.ToArray();
}
public static IList<StringDifference> Analyze(string actual, string expected, bool caseInsensitive)
{
if (actual == expected)
{
return null;
}
var result = new List<StringDifference>();
var actualLines = SplitLines(actual);
var expectedLines = SplitLines(expected);
var sharedLines = Math.Min(actualLines.Length, expectedLines.Length);
var boolSingleLine = expectedLines.Length == 1;
for (var line = 0; line < sharedLines; line++)
{
var stringDifference = Build(line, actualLines[line], expectedLines[line], caseInsensitive, boolSingleLine);
if (stringDifference.Kind != DifferenceMode.NoDifference)
{
result.Add(stringDifference);
}
}
if (expectedLines.Length > sharedLines)
{
result.Add(Build(sharedLines, null, expectedLines[sharedLines], caseInsensitive, false));
}
else if (actualLines.Length > sharedLines)
{
result.Add(Build(sharedLines, actualLines[sharedLines], null, caseInsensitive, false));
}
return result;
}
/// <summary>
/// Summarize a list of issues to a single difference code.
/// </summary>
/// <param name="stringDifferences">
/// List of differences.
/// </param>
/// <returns>
/// A <see cref="DifferenceMode"/> value describing the overall differences.
/// </returns>
/// <remarks>
/// Returns <see cref="DifferenceMode.General"/> unless all differences are of same kind.
/// </remarks>
public static DifferenceMode Summarize(IEnumerable<StringDifference> stringDifferences)
{
var result = DifferenceMode.NoDifference;
foreach (var stringDifference in stringDifferences)
{
if (result == DifferenceMode.NoDifference)
{
result = stringDifference.Kind;
}
else if (result != stringDifference.Kind)
{
result = DifferenceMode.General;
// Stryker disable once Statement: Mutation does not alter behaviour
break;
}
}
return result;
}
public static string SummaryMessage(IList<StringDifference> differences)
{
return differences[0].GetErrorMessage(Summarize(differences));
}
/// <summary>
/// Transform a string to identify not printable difference
/// </summary>
/// <param name="textToScan"></param>
/// <returns></returns>
public string HighLightForDifference(string textToScan)
{
switch (this.Kind)
{
case DifferenceMode.Spaces:
textToScan = HighlightTabsIfAny(textToScan);
break;
case DifferenceMode.EndOfLine:
textToScan = HighlightCrlfOrLfIfAny(textToScan);
break;
}
return textToScan;
}
private string GetErrorMessage(DifferenceMode summary)
{
var mainText = GetMessage(summary);
const int extractLength = 20;
string actual;
string expected;
if (this.Line > 0 || this.Expected.Length > extractLength * 2 || this.Actual.Length > extractLength * 2)
{
actual = this.Actual.Extract(this.Position, extractLength);
expected = this.Expected.Extract(this.Position, extractLength);
}
else
{
actual = this.Actual;
expected = this.Expected;
}
actual = this.HighLightForDifference(actual);
expected = this.HighLightForDifference(expected);
if (!this.IsFullText || this.Actual != actual || this.Expected != expected)
{
if (summary == DifferenceMode.MissingLines)
{
mainText+=
$" At line {this.Line + 1}, expected '{HighlightCrlfOrLfIfAny(expected)}' but line is missing.";
}
else if (summary == DifferenceMode.ExtraLines)
{
mainText+=
$" Found line {this.Line + 1} '{HighlightCrlfOrLfIfAny(actual)}'.";
}
else
{
mainText += string.Format(
" At line {0}, col {3}, expected '{1}' was '{2}'.",
this.Line + 1,
HighlightCrlfOrLfIfAny(expected),
HighlightCrlfOrLfIfAny(actual),
this.Position + 1);
}
}
return mainText;
}
/// <summary>
/// Inserts <<CRLF>> before the first CRLF or <<LF>> before the first LF.
/// </summary>
/// <param name="str">The string.</param>
/// <returns>The same string but with <<CRLF>> inserted before the first CRLF or <<LF>> inserted before the first LF.</returns>
private static string HighlightCrlfOrLfIfAny(string str)
{
str = str.Replace("\r\n", "<<CRLF>>");
//str = str.Replace("\r", "<<CR>>"); //==> isolated CR are not considered as EOL markers
str = str.Replace("\n", "<<LF>>");
return str;
}
/// <summary>
/// Replace every tab char by "<<tab>>".
/// </summary>
/// <param name="str">The original string.</param>
/// <returns>The original string with every \t replaced with "<<tab>>".</returns>
private static string HighlightTabsIfAny(string str)
{
return str.Replace("\t", "<<tab>>");
}
private static StringDifference Build(int line, string actual, string expected, bool ignoreCase, bool isFullText)
{
if (actual == null)
{
return new StringDifference(DifferenceMode.MissingLines, line, 0, null, expected, isFullText);
}
if (expected == null)
{
return new StringDifference(DifferenceMode.ExtraLines, line, 0, actual, null, isFullText);
}
// check the common part of both strings
var j = 0;
var i = 0;
var type = DifferenceMode.NoDifference;
var position = 0;
for (;
i < actual.Length && j < expected.Length;
i++, j++)
{
var actualChar = actual[i];
var expectedChar = expected[j];
if (char.IsWhiteSpace(actualChar) && char.IsWhiteSpace(expectedChar))
{
// special case for end of line markers
if (IsEol(actualChar))
{
if (expectedChar == actualChar)
{
continue;
}
return new StringDifference(
IsEol(expectedChar) ? DifferenceMode.EndOfLine : DifferenceMode.ShorterLine, line, i,
actual, expected, isFullText);
}
if (IsEol(expectedChar))
{
return new StringDifference(DifferenceMode.LongerLine, line, i, actual, expected, isFullText);
}
var actualStart = i;
var expectedStart = j;
// we skip all spaces
while (ContainsWhiteSpaceAt(actual, i+1))
{
i++;
}
while (ContainsWhiteSpaceAt(expected, j+1))
{
j++;
}
if (actual.Substring(actualStart, i - actualStart)
!= expected.Substring(expectedStart, j - expectedStart))
{
if (type != DifferenceMode.Spaces)
{
type = DifferenceMode.Spaces;
position = i;
}
}
}
else if (actualChar == expectedChar)
{
}
else if (StringExtensions.CompareCharIgnoringCase(actualChar, expectedChar))
{
if (ignoreCase || type == DifferenceMode.CaseDifference)
{
continue;
}
// difference in case only
type = DifferenceMode.CaseDifference;
position = i;
}
else
{
type = DifferenceMode.General;
position = i;
break;
}
}
switch (type)
{
case DifferenceMode.General:
if (actual.Length == expected.Length)
{
type = DifferenceMode.GeneralSameLength;
}
return new StringDifference(type, line, position, actual, expected, isFullText);
case DifferenceMode.Spaces when i == actual.Length && j == expected.Length:
return new StringDifference(type, line, position, actual, expected, isFullText);
}
// strings are same so far
// the actualLine string is longer than expectedLine
if (i < actual.Length)
{
DifferenceMode difference;
if (IsEol(actual[i]))
{
// lines are missing, the error will be reported at next line
difference = DifferenceMode.NoDifference;
}
else
difference = isFullText ? DifferenceMode.Longer : DifferenceMode.LongerLine;
return new StringDifference(
difference,
line,
i,
actual,
expected,
isFullText);
}
if (j < expected.Length)
{
DifferenceMode difference;
if (IsEol(expected[j]))
{
// lines are missing, the error will be reported at next sline
difference = DifferenceMode.NoDifference;
}
else
difference = isFullText ? DifferenceMode.Shorter : DifferenceMode.ShorterLine;
return new StringDifference(
difference,
line,
j,
actual,
expected,
isFullText);
}
return new StringDifference(type, line, position, actual, expected, isFullText);
}
private static bool ContainsWhiteSpaceAt(string actual, int i)
{
return i < actual.Length && char.IsWhiteSpace(actual[i]) && !IsEol(actual[i]);
}
private static bool IsEol(char theChar)
{
return theChar == CarriageReturn || theChar == Linefeed;
}
/// <summary>
/// Get general message
/// </summary>
/// <param name="summary">Synthetic error</param>
/// <returns></returns>
public static string GetMessage(DifferenceMode summary)
{
string message;
switch (summary)
{
default:
message = "The {0} is different from {1}.";
break;
case DifferenceMode.GeneralSameLength:
message = "The {0} is different from the {1} but has same length.";
break;
case DifferenceMode.Spaces:
message = "The {0} has different spaces than {1}.";
break;
case DifferenceMode.EndOfLine:
message = "The {0} has different end of line markers than {1}.";
break;
case DifferenceMode.CaseDifference:
message = "The {0} is different in case from the {1}.";
break;
case DifferenceMode.ExtraLines:
message = "The {0} is different from {1}, it contains extra lines at the end.";
break;
case DifferenceMode.LongerLine:
message = "The {0} is different from {1}, one line is longer.";
break;
case DifferenceMode.ShorterLine:
message = "The {0} is different from {1}, one line is shorter.";
break;
case DifferenceMode.MissingLines:
message = "The {0} is different from {1}, it is missing some line(s).";
break;
case DifferenceMode.Longer:
message = "The {0} is different from {1}, it contains extra text at the end.";
break;
case DifferenceMode.Shorter:
message = "The {0} is different from {1}, it is missing the end.";
break;
}
return message;
}
}
}
| |
namespace Gu.SerializationAsserts.Newtonsoft.Json
{
using System;
using global::Newtonsoft.Json;
/// <summary> Test serialization using <see cref="JsonSerializer"/> </summary>
public static class JsonSerializerAssert
{
/// <summary>
/// 1. serializes <paramref name="expected"/> and <paramref name="actual"/> to Json strings using <see cref="JsonSerializer"/>
/// 2. Compares the Json using <see cref="JsonAssert"/>
/// </summary>
/// <typeparam name="T">The type</typeparam>
/// <param name="expected">The expected value</param>
/// <param name="actual">The actual value</param>
public static void Equal<T>(T expected, T actual)
{
var eJson = ToJson(expected, nameof(expected), null);
var aJson = ToJson(actual, nameof(actual), null);
JsonAssert.Equal(eJson, aJson);
}
/// <summary>
/// 1. serializes <paramref name="expected"/> and <paramref name="actual"/> to Json strings using <see cref="JsonSerializer"/>
/// 2. Compares the Json using <see cref="JsonAssert"/>
/// </summary>
/// <typeparam name="T">The type</typeparam>
/// <param name="expected">The expected value</param>
/// <param name="actual">The actual value</param>
/// <param name="settings">The settings to use when serializing and deserializing</param>
public static void Equal<T>(T expected, T actual, JsonSerializerSettings settings)
{
var eJson = ToJson(expected, nameof(expected), settings);
var aJson = ToJson(actual, nameof(actual), settings);
JsonAssert.Equal(eJson, aJson);
}
/// <summary>
/// 1 Serializes <paramref name="actual"/> to an Json string using <see cref="JsonSerializer"/>
/// 2 Compares the Json with <paramref name="expectedJson"/>
/// 3 Creates a <see cref="ContainerClass{T}"/>
/// 4 Serializes it to Json.
/// 5 Compares the Json
/// 6 Deserializes it to container class
/// 7 Does 2 & 3 again, we repeat this to catch any errors from deserializing
/// 8 Returns roundtripped instance
/// </summary>
/// <typeparam name="T">The type</typeparam>
/// <param name="expectedJson">The expected Json</param>
/// <param name="actual">The actual item</param>
/// <param name="options">How to compare the Json</param>
/// <returns>The roundtripped instance</returns>
public static T Equal<T>(string expectedJson, T actual, JsonAssertOptions options = JsonAssertOptions.Verbatim)
{
var actualJson = ToJson(actual, nameof(actual), null);
JsonAssert.Equal(expectedJson, actualJson, options);
return Roundtrip(actual);
}
/// <summary>
/// 1 Serializes <paramref name="actual"/> to an Json string using <see cref="JsonSerializer"/>
/// 2 Compares the Json with <paramref name="expectedJson"/>
/// 3 Creates a <see cref="ContainerClass{T}"/>
/// 4 Serializes it to Json.
/// 5 Compares the Json
/// 6 Deserializes it to container class
/// 7 Does 2 & 3 again, we repeat this to catch any errors from deserializing
/// 8 Returns roundtripped instance
/// </summary>
/// <typeparam name="T">The type</typeparam>
/// <param name="expectedJson">The expected Json</param>
/// <param name="actual">The actual item</param>
/// <param name="settings">The settings to use when deserializing</param>
/// <param name="options">How to compare the Json</param>
/// <returns>The roundtripped instance</returns>
public static T Equal<T>(string expectedJson, T actual, JsonSerializerSettings settings, JsonAssertOptions options = JsonAssertOptions.Verbatim)
{
var actualJson = ToJson(actual, nameof(actual), settings);
JsonAssert.Equal(expectedJson, actualJson, options);
return Roundtrip(actual, settings);
}
/// <summary>
/// 1. Places <paramref name="item"/> in a ContainerClass{T} container1
/// 2. Serializes container1
/// 3. Deserializes the containerJson to container2 and does FieldAssert.Equal(container1, container2);
/// 4. Serializes container2
/// 5. Checks JsonAssert.Equal(containerJson1, containerJson2, JsonAssertOptions.Verbatim);
/// </summary>
/// <typeparam name="T">The type of <paramref name="item"/></typeparam>
/// <param name="item">The instance to roundtrip</param>
/// <returns>The serialized and deserialized instance (container2.Other)</returns>
public static T Roundtrip<T>(T item)
{
Roundtripper.Simple(item, nameof(item), ToJson, FromJson<T>);
var roundtripped = Roundtripper.InContainer(
item,
nameof(item),
ToJson,
FromJson<ContainerClass<T>>,
(e, a) => JsonAssert.Equal(e, a, JsonAssertOptions.Verbatim));
FieldAssert.Equal(item, roundtripped);
return roundtripped;
}
/// <summary>
/// 1. Places <paramref name="item"/> in a ContainerClass{T} container1
/// 2. Serializes container1
/// 3. Deserializes the containerJson to container2 and does FieldAssert.Equal(container1, container2);
/// 4. Serializes container2
/// 5. Checks JsonAssert.Equal(containerJson1, containerJson2, JsonAssertOptions.Verbatim);
/// </summary>
/// <typeparam name="T">The type of <paramref name="item"/></typeparam>
/// <param name="item">The instance to roundtrip</param>
/// <param name="settings">The settings to use when serializing and deserializing.</param>
/// <returns>The serialized and deserialized instance (container2.Other)</returns>
public static T Roundtrip<T>(T item, JsonSerializerSettings settings)
{
Roundtripper.Simple(item, nameof(item), x => ToJson(x, settings), x => FromJson<T>(x, settings));
var roundtripped = Roundtripper.InContainer(
item,
nameof(item),
x => ToJson(x, settings),
x => FromJson<ContainerClass<T>>(x, settings),
(e, a) => JsonAssert.Equal(e, a, JsonAssertOptions.Verbatim));
FieldAssert.Equal(item, roundtripped);
return roundtripped;
}
/// <summary>
/// 1. Creates an JsonSerializer(typeof(T))
/// 2. Serialize <paramref name="item"/>
/// 3. Returns the Json
/// </summary>
/// <typeparam name="T">The type</typeparam>
/// <param name="item">The item to serialize</param>
/// <returns>The Json representation of <paramref name="item>"/></returns>
public static string ToJson<T>(T item)
{
return ToJson(item, nameof(item), null);
}
/// <summary>
/// 1. Creates an JsonSerializer(typeof(T))
/// 2. Serialize <paramref name="item"/>
/// 3. Returns the Json
/// </summary>
/// <typeparam name="T">The type</typeparam>
/// <param name="item">The item to serialize</param>
/// <param name="settings">The settings to use when serializing</param>
/// <returns>The Json representation of <paramref name="item>"/></returns>
public static string ToJson<T>(T item, JsonSerializerSettings settings)
{
return ToJson(item, nameof(item), settings);
}
/// <summary>
/// Get copy paste friendly Json for <paramref name="item"/>
/// </summary>
/// <typeparam name="T">The type of <paramref name="item"/></typeparam>
/// <param name="item">The item to serialize</param>
/// <returns>Json escaped and ready to paste in code.</returns>
public static string ToEscapedJson<T>(T item)
{
var json = ToJson(item);
return json.Escape(); // wasteful allocation here but np I think;
}
/// <summary>
/// Get copy paste friendly Json for <paramref name="item"/>
/// </summary>
/// <typeparam name="T">The type of <paramref name="item"/></typeparam>
/// <param name="item">The item to serialize</param>
/// <param name="settings">The settings to use when serializing</param>
/// <returns>Json escaped and ready to paste in code.</returns>
public static string ToEscapedJson<T>(T item, JsonSerializerSettings settings)
{
var json = ToJson(item, settings);
return json.Escape(); // wasteful allocation here but np I think;
}
/// <summary>
/// 1. Creates an JsonSerializer(typeof(T))
/// 2. Deserialize <paramref name="json"/>
/// 3. Returns the deserialized instance
/// </summary>
/// <typeparam name="T">The type</typeparam>
/// <param name="json">The string containing the Json</param>
/// <returns>The deserialized instance</returns>
public static T FromJson<T>(string json)
{
return FromJson<T>(json, nameof(json), null);
}
/// <summary>
/// 1. Creates an JsonSerializer(typeof(T))
/// 2. Deserialize <paramref name="json"/>
/// 3. Returns the deserialized instance
/// </summary>
/// <typeparam name="T">The type</typeparam>
/// <param name="json">The string containing the Json</param>
/// <param name="settings">The settings to use when deserializing</param>
/// <returns>The deserialized instance</returns>
public static T FromJson<T>(string json, JsonSerializerSettings settings)
{
return FromJson<T>(json, nameof(json), settings);
}
private static T FromJson<T>(string json, string parameterName, JsonSerializerSettings settings)
{
try
{
return JsonConvert.DeserializeObject<T>(json, settings);
}
catch (Exception e)
{
throw AssertException.CreateFromException($"Could not deserialize {parameterName} to an instance of type {typeof(T)}", e);
}
}
private static string ToJson<T>(T item, string parameterName, JsonSerializerSettings settings)
{
try
{
return JsonConvert.SerializeObject(item, settings);
}
catch (Exception e)
{
throw AssertException.CreateFromException($"Could not serialize{parameterName}.", e);
}
}
// Using new here to hide it so it not called by mistake
// ReSharper disable once UnusedMember.Local
private static new void Equals(object x, object y)
{
throw new NotSupportedException($"{x}, {y}");
}
}
}
| |
using System;
using System.IO;
namespace Pfim
{
/// <summary>
/// Utility class housing methods used by multiple image decoders
/// </summary>
public static class Util
{
/// <summary>
/// Buffer size to read data from
/// </summary>
private const int BUFFER_SIZE = 0x8000;
internal static MemoryStream CreateExposed(byte[] data)
{
return new MemoryStream(data, 0, data.Length, false, true);
}
/// <summary>
/// Takes all the bytes at and after an index and moves them to the front and fills the rest
/// of the buffer with information from the stream.
/// </summary>
/// <remarks>
/// This function is useful when the buffer doesn't have enough information to process a
/// certain amount of information thus more information from the stream has to be read. This
/// preserves the information that hasn't been read by putting it at the front.
/// </remarks>
/// <param name="str">Stream where more data will be read to fill in end of the buffer.</param>
/// <param name="buf">The buffer that contains the data that will be translated.</param>
/// <param name="bufIndex">
/// Start of the translation. The value initially at this index will be the value at index 0
/// in the buffer after translation.
/// </param>
/// <returns>
/// The total number of bytes read into the buffer and translated. May be less than the
/// buffer's length.
/// </returns>
public static int Translate(Stream str, byte[] buf, int bufLen, int bufIndex)
{
Buffer.BlockCopy(buf, bufIndex, buf, 0, bufLen - bufIndex);
int result = str.Read(buf, bufLen - bufIndex, bufIndex);
return result + bufLen - bufIndex;
}
/// <summary>
/// Sets all the values in a buffer to a single value.
/// </summary>
/// <param name="buffer">Buffer that will have its values set</param>
/// <param name="value">The value that the buffer will contain</param>
/// <param name="length">The number of bytes to write in the buffer</param>
public static unsafe void memset(int* buffer, int value, int length)
{
if (length > 16)
{
do
{
*buffer++ = value;
*buffer++ = value;
*buffer++ = value;
*buffer++ = value;
} while ((length -= 16) >= 16);
}
for (; length > 3; length -= 4)
*buffer++ = value;
}
/// <summary>
/// Sets all the values in a buffer to a single value.
/// </summary>
/// <param name="buffer">Buffer that will have its values set</param>
/// <param name="value">The value that the buffer will contain</param>
/// <param name="length">The number of bytes to write in the buffer</param>
public static unsafe void memset(byte* buffer, byte value, int length)
{
memset((int*)buffer, value << 24 | value << 16 | value << 8 | value, length);
int rem = length % 4;
for (int i = 0; i < rem; i++)
buffer[length - i - 1] = value;
}
public static void Fill(Stream stream, byte[] data, int dataLen, int bufSize = BUFFER_SIZE, int offset = 0)
{
if (stream is MemoryStream s && s.TryGetBuffer(out var arr))
{
Buffer.BlockCopy(arr.Array, (int)s.Position, data, offset, dataLen);
s.Position += dataLen;
}
else
{
InnerFill(stream, data, dataLen, bufSize, offset);
}
}
public static void Fill(Stream stream, byte[] data, int dataLen, int bufSize = BUFFER_SIZE) =>
Fill(stream, data, dataLen, bufSize, 0);
public static void InnerFillUnaligned(Stream str, byte[] buf, int bufLen, int width, int stride, int bufSize = BUFFER_SIZE, int offset = 0)
{
for (int i = offset; i < bufLen + offset; i += stride)
{
str.Read(buf, i, width);
}
}
public static void InnerFillUnaligned(Stream str, byte[] buf, int bufLen, int width, int stride, int bufSize = BUFFER_SIZE) =>
InnerFillUnaligned(str, buf, bufLen, width, stride, bufSize, 0);
/// <summary>
/// Fills the buffer all the way up with info from the stream
/// </summary>
/// <param name="str">Stream that will be used to fill the buffer</param>
/// <param name="buf">Buffer that will house the information from the stream</param>
/// <param name="bufSize">The chunk size of data that will be read from the stream</param>
private static void InnerFill(Stream str, byte[] buf, int dataLen, int bufSize = BUFFER_SIZE, int offset = 0)
{
int bufPosition = offset;
for (int i = dataLen / bufSize; i > 0; i--)
bufPosition += str.Read(buf, bufPosition, bufSize);
str.Read(buf, bufPosition, dataLen % bufSize);
}
/// <summary>
/// Fills a data array starting from the bottom left by reading from a stream.
/// </summary>
/// <param name="str">The stream to read data from</param>
/// <param name="data">The buffer to be filled with stream data</param>
/// <param name="rowSize">The size in bytes of each row in the stream</param>
/// <param name="bufSize">The chunk size of data that will be read from the stream</param>
/// <param name="stride">The number of bytes that make up a row in the data</param>
/// <param name="buffer">The temporary buffer used to read data in</param>
public static void FillBottomLeft(
Stream str,
byte[] data,
int dataLen,
int rowSize,
int stride,
byte[] buffer = null,
int bufSize = BUFFER_SIZE)
{
buffer = buffer ?? new byte[BUFFER_SIZE];
if (buffer.Length < bufSize)
{
throw new ArgumentException("must be longer than bufSize", nameof(buffer));
}
int bufferIndex = 0;
int rowsPerBuffer = Math.Min(bufSize, dataLen) / stride;
int dataIndex = dataLen - stride;
int rowsRead = 0;
int totalRows = dataLen / stride;
int rowsToRead = rowsPerBuffer;
if (rowsPerBuffer == 0)
throw new ArgumentOutOfRangeException(nameof(rowSize), "Row size must be small enough to fit in the buffer");
int workingSize = str.Read(buffer, 0, bufSize);
do
{
for (int i = 0; i < rowsToRead; i++)
{
Buffer.BlockCopy(buffer, bufferIndex, data, dataIndex, rowSize);
dataIndex -= stride;
bufferIndex += rowSize;
}
if (dataIndex >= 0)
{
workingSize = Translate(str, buffer, bufSize, bufferIndex);
bufferIndex = 0;
rowsRead += rowsPerBuffer;
rowsToRead = rowsRead + rowsPerBuffer < totalRows ? rowsPerBuffer : totalRows - rowsRead;
}
} while (dataIndex >= 0 && workingSize != 0);
}
/// <summary>
/// Calculates stride of an image in bytes given its width in pixels and pixel depth in bits
/// </summary>
/// <param name="width">Width in pixels</param>
/// <param name="pixelDepth">The number of bits that represents a pixel</param>
/// <returns>The number of bytes that consists of a single line</returns>
public static int Stride(int width, int pixelDepth)
{
if (width <= 0)
throw new ArgumentException("Width must be greater than zero", nameof(width));
else if (pixelDepth <= 0)
throw new ArgumentException("Pixel depth must be greater than zero", nameof(pixelDepth));
int bytesPerPixel = (pixelDepth + 7) / 8;
// Windows GDI+ requires that the stride be a multiple of four.
// Even if not being used for Windows GDI+ there isn't a anything
// bad with having extra space.
return 4 * ((width * bytesPerPixel + 3) / 4);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace Pervexel {
public class CompoundStream : Stream {
BinaryReader reader;
int sectorSize;
int shortSectorSize;
int shortStreamThreshold;
List<int> sat;
List<int> ssat;
int sscSector;
int sscSize;
List<Tuple<string, int, int>> userStreams;
public CompoundStream (Stream stream) {
if (stream == null)
throw new ArgumentNullException("stream");
if (!stream.CanRead || !stream.CanSeek)
throw new ArgumentException("stream");
reader = new BinaryReader(stream, Encoding.Unicode);
reader.BaseStream.Position = 0;
var header = reader.ReadBytes(76);
if (BitConverter.ToUInt64(header, 0) != 0xE11AB1A1E011CFD0)
throw new Exception("THERE IS NO MAGIC");
sectorSize = 1 << BitConverter.ToUInt16(header, 30);
shortSectorSize = 1 << BitConverter.ToUInt16(header, 32);
shortStreamThreshold = BitConverter.ToInt32(header, 56);
// master sector allocation table
var msat = new List<int>();
for (int i = 0; i < 109; i++) {
msat.Add(reader.ReadInt32());
}
for (var msatNext = BitConverter.ToInt32(header, 68); msatNext != -2; ) {
reader.BaseStream.Position = 512 + msatNext * sectorSize;
for (int i = 0; i < sectorSize - 4; i += 4) {
msat.Add(reader.ReadInt32());
}
msatNext = reader.ReadInt32();
}
// sector allocation table
sat = new List<int>();
foreach (var satSector in msat) {
if (satSector < 0)
continue;
reader.BaseStream.Position = 512 + satSector * sectorSize;
for (int i = 0; i < sectorSize; i += 4) {
sat.Add(reader.ReadInt32());
}
}
// short-stream sector allocation table
ssat = new List<int>();
for (var ssatNext = BitConverter.ToInt32(header, 60); ssatNext != -2; ) {
reader.BaseStream.Position = 512 + ssatNext * sectorSize;
for (var i = 0; i < sectorSize; i += 4) {
ssat.Add(reader.ReadInt32());
}
ssatNext = sat[ssatNext];
}
// directory
userStreams = new List<Tuple<string, int, int>>();
for (var dirNext = BitConverter.ToInt32(header, 48); dirNext != -2; ) {
reader.BaseStream.Position = 512 + dirNext * sectorSize;
for (var i = 0; i < sectorSize; i += 128) {
var entry = reader.ReadBytes(128);
// 00..64 name bytes
// 64..66 name length
// 66..67 type
// 67..68 color
// 68..72 left sibling index
// 72..76 right sibling index
// 76..80 first child index
// 80..116 reserved
// 116-120 sector
// 120-124 size
// 124-128 dunno
var type = entry[66];
if (type == 5) {
sscSector = BitConverter.ToInt32(entry, 116);
sscSize = BitConverter.ToInt32(entry, 120);
} else if (type == 2) {
var name = Encoding.Unicode.GetString(entry, 0, BitConverter.ToUInt16(entry, 64) - 2);
var sector = BitConverter.ToInt32(entry, 116);
var size = BitConverter.ToInt32(entry, 120);
userStreams.Add(Tuple.Create(name, size, sector));
}
}
dirNext = sat[dirNext];
}
}
class Segment {
internal int Position;
internal int Offset;
internal int Size;
public override string ToString () {
return string.Format("Position = {0}, Offset = {1}, Size = {2}", Position, Offset, Size);
}
}
private IEnumerable<Segment> GetSegments (int sector, int length, bool tryShort = true) {
if (length >= shortStreamThreshold || !tryShort) {
var left = length;
while (left > 0) {
if (left < sectorSize) {
yield return new Segment {
Position = length - left,
Offset = 512 + sector * sectorSize,
Size = left
};
break;
}
yield return new Segment {
Position = length - left,
Offset = 512 + sector * sectorSize,
Size = sectorSize
};
left -= sectorSize;
sector = sat[sector];
}
} else {
var segments = GetSegments(sscSector, sscSize, false).ToList();
var left = length;
while (left > 0) {
var offset = segments[sector * shortSectorSize / sectorSize].Offset + (sector * shortSectorSize) % sectorSize;
if (left < shortSectorSize) {
yield return new Segment {
Position = length - left,
Offset = offset,
Size = left
};
break;
}
yield return new Segment {
Position = length - left,
Offset = offset,
Size = shortSectorSize
};
left -= shortSectorSize;
sector = ssat[sector];
}
}
}
LinkedListNode<Segment> data;
int position;
int length;
public bool Open (string name) {
var userStream = userStreams.FirstOrDefault(s => s.Item1 == name);
if (userStream == null) {
data = null;
return false;
}
position = 0;
length = userStream.Item2;
data = new LinkedList<Segment>(GetSegments(userStream.Item3, userStream.Item2)).First;
reader.BaseStream.Position = data.Value.Offset;
return true;
}
#region stream
public override bool CanRead {
get { return true; }
}
public override bool CanSeek {
get { return true; }
}
public override bool CanWrite {
get { return false; }
}
public override void Flush () {
throw new NotSupportedException();
}
public override long Length {
get { return length; }
}
public override long Position {
get {
return position;
}
set {
Seek(value, SeekOrigin.Begin);
}
}
public override int Read (byte[] buffer, int offset, int count) {
var available = length - position;
if (available == 0)
return 0;
var segmentOffset = position - data.Value.Position;
var segmentLeft = data.Value.Size - segmentOffset;
count = Math.Min(available, Math.Min(segmentLeft, count));
var read = reader.BaseStream.Read(buffer, offset, count);
position += read;
if (segmentOffset + read == data.Value.Size && available > read) {
data = data.Next;
reader.BaseStream.Position = data.Value.Offset;
}
return read;
}
public override long Seek (long offset, SeekOrigin origin) {
var targetPosition = (int)offset;
if (origin == SeekOrigin.Current)
targetPosition += position;
else if (origin == SeekOrigin.End)
targetPosition += length;
if (targetPosition < 0)
targetPosition = 0;
else if (targetPosition > length)
targetPosition = length;
data = data.List.First;
while (true) {
if (targetPosition >= data.Value.Position && targetPosition < data.Value.Position + data.Value.Size)
break;
if (data.Next == null)
break;
data = data.Next;
}
reader.BaseStream.Position = data.Value.Offset + (targetPosition - data.Value.Position);
position = targetPosition;
return position;
}
public override void SetLength (long value) {
throw new NotSupportedException();
}
public override void Write (byte[] buffer, int offset, int count) {
throw new NotSupportedException();
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Runtime.InteropServices;
using System.Security;
using System.Windows;
using System.Windows.Media;
using System.Windows.Interop;
using MS.Win32;
#if PRESENTATION_CORE
using MS.Internal.PresentationCore;
#else
#error There is an attempt to use this class from an unexpected assembly.
#endif
namespace MS.Internal
{
/// <summary>
/// A utility class for converting Point and Rect data between co-ordinate spaces
/// </summary>
/// <remarks>
/// To avoid confusion, Avalon based Point and Rect variables are prefixed with
/// "point" and "rect" respectively, whereas Win32 POINT and RECT variables are
/// prefixed with "pt" and "rc" respectively.
/// </remarks>
[FriendAccessAllowed] // Built into Core, also used by Framework.
internal static class PointUtil
{
/// <summary>
/// Convert a point from "client" coordinate space of a window into
/// the coordinate space of the root element of the same window.
/// </summary>
public static Point ClientToRoot(Point point, PresentationSource presentationSource)
{
bool success = true;
return TryClientToRoot(point, presentationSource, true, out success);
}
public static Point TryClientToRoot(Point point, PresentationSource presentationSource, bool throwOnError, out bool success)
{
// Only do if we allow throwing on error or have a valid PresentationSource and CompositionTarget.
if (throwOnError || (presentationSource != null && presentationSource.CompositionTarget != null && !presentationSource.CompositionTarget.IsDisposed))
{
// Convert from pixels into measure units.
point = presentationSource.CompositionTarget.TransformFromDevice.Transform(point);
// REVIEW:
// We need to include the root element's transform until the MIL
// team fixes their APIs to do this.
point = TryApplyVisualTransform(point, presentationSource.RootVisual, true, throwOnError, out success);
}
else
{
success = false;
return new Point(0,0);
}
return point;
}
/// <summary>
/// Convert a point from the coordinate space of a root element of
/// a window into the "client" coordinate space of the same window.
/// </summary>
public static Point RootToClient(Point point, PresentationSource presentationSource)
{
// REVIEW:
// We need to include the root element's transform until the MIL
// team fixes their APIs to do this.
point = ApplyVisualTransform(point, presentationSource.RootVisual, false);
// Convert from measure units into pixels.
point = presentationSource.CompositionTarget.TransformToDevice.Transform(point);
return point;
}
/// <summary>
/// Convert a point from "above" the coordinate space of a
/// visual into the the coordinate space "below" the visual.
/// </summary>
public static Point ApplyVisualTransform(Point point, Visual v, bool inverse)
{
bool success = true;
return TryApplyVisualTransform(point, v, inverse, true, out success);
}
/// <summary>
/// Convert a point from "above" the coordinate space of a
/// visual into the the coordinate space "below" the visual.
/// </summary>
public static Point TryApplyVisualTransform(Point point, Visual v, bool inverse, bool throwOnError, out bool success)
{
success = true;
// Notes:
// 1) First of all the MIL should provide a way of transforming
// a point from the window to the root element.
// 2) A visual can currently have two properties that affect
// its coordinate space:
// A) Transform - any matrix
// B) Offset - a simpification for just a 2D offset.
// 3) In the future a Visual may have other properties that
// affect its coordinate space, which is why the MIL should
// provide this API in the first place.
//
// The following code was copied from the MIL's TransformToAncestor
// method on 12/16/2005.
//
if(v != null)
{
Matrix m = GetVisualTransform(v);
if (inverse)
{
if(throwOnError || m.HasInverse)
{
m.Invert();
}
else
{
success = false;
return new Point(0,0);
}
}
point = m.Transform(point);
}
return point;
}
/// <summary>
/// Gets the matrix that will convert a point
/// from "above" the coordinate space of a visual
/// into the the coordinate space "below" the visual.
/// </summary>
internal static Matrix GetVisualTransform(Visual v)
{
if (v != null)
{
Matrix m = Matrix.Identity;
Transform transform = VisualTreeHelper.GetTransform(v);
if (transform != null)
{
Matrix cm = transform.Value;
m = Matrix.Multiply(m, cm);
}
Vector offset = VisualTreeHelper.GetOffset(v);
m.Translate(offset.X, offset.Y);
return m;
}
return Matrix.Identity;
}
/// <summary>
/// Convert a point from "client" coordinate space of a window into
/// the coordinate space of the screen.
/// </summary>
public static Point ClientToScreen(Point pointClient, PresentationSource presentationSource)
{
// For now we only know how to use HwndSource.
HwndSource inputSource = presentationSource as HwndSource;
if(inputSource == null)
{
return pointClient;
}
HandleRef handleRef = new HandleRef(inputSource, inputSource.CriticalHandle);
NativeMethods.POINT ptClient = FromPoint(pointClient);
NativeMethods.POINT ptClientRTLAdjusted = AdjustForRightToLeft(ptClient, handleRef);
UnsafeNativeMethods.ClientToScreen(handleRef, ptClientRTLAdjusted);
return ToPoint(ptClientRTLAdjusted);
}
/// <summary>
/// Convert a point from the coordinate space of the screen into
/// the "client" coordinate space of a window.
/// </summary>
internal static Point ScreenToClient(Point pointScreen, PresentationSource presentationSource)
{
// For now we only know how to use HwndSource.
HwndSource inputSource = presentationSource as HwndSource;
if(inputSource == null)
{
return pointScreen;
}
HandleRef handleRef = new HandleRef(inputSource, inputSource.CriticalHandle);
NativeMethods.POINT ptClient = FromPoint(pointScreen);
SafeNativeMethods.ScreenToClient(handleRef, ptClient);
ptClient = AdjustForRightToLeft(ptClient, handleRef);
return ToPoint(ptClient);
}
/// <summary>
/// Converts a rectangle from element co-ordinate space to that of the root visual
/// </summary>
/// <param name="rectElement">
/// The rectangle to be converted
/// </param>
/// <param name="element">
/// The element whose co-ordinate space you wish to convert from
/// </param>
/// <param name="presentationSource">
/// The PresentationSource which hosts the specified Visual. This is passed in for performance reasons.
/// </param>
/// <returns>
/// The rectangle in the co-ordinate space of the root visual
/// </returns>
internal static Rect ElementToRoot(Rect rectElement, Visual element, PresentationSource presentationSource)
{
GeneralTransform transformElementToRoot = element.TransformToAncestor(presentationSource.RootVisual);
Rect rectRoot = transformElementToRoot.TransformBounds(rectElement);
return rectRoot;
}
/// <summary>
/// Converts a rectangle from root visual co-ordinate space to Win32 client
/// </summary>
/// <remarks>
/// RootToClient takes into account device DPI settings to convert to/from Avalon's assumed 96dpi
/// and any "root level" transforms applied to the root such as "right-to-left" inversions.
/// </remarks>
/// <param name="rectRoot">
/// The rectangle to be converted
/// </param>
/// <param name="presentationSource">
/// The PresentationSource which hosts the root visual. This is passed in for performance reasons.
/// </param>
/// <returns>
/// The rectangle in Win32 client co-ordinate space
/// </returns>
internal static Rect RootToClient(Rect rectRoot, PresentationSource presentationSource)
{
CompositionTarget target = presentationSource.CompositionTarget;
Matrix matrixRootTransform = PointUtil.GetVisualTransform(target.RootVisual);
Rect rectRootUntransformed = Rect.Transform(rectRoot, matrixRootTransform);
Matrix matrixDPI = target.TransformToDevice;
Rect rectClient = Rect.Transform(rectRootUntransformed, matrixDPI);
return rectClient;
}
/// <summary>
/// Converts a rectangle from Win32 client co-ordinate space to Win32 screen
/// </summary>
/// <remarks>
/// </remarks>
/// <param name="rectClient">
/// The rectangle to be converted
/// </param>
/// <param name="hwndSource">
/// The HwndSource corresponding to the Win32 window containing the rectangle
/// </param>
/// <returns>
/// The rectangle in Win32 screen co-ordinate space
/// </returns>
internal static Rect ClientToScreen(Rect rectClient, HwndSource hwndSource)
{
Point corner1 = ClientToScreen(rectClient.TopLeft, hwndSource);
Point corner2 = ClientToScreen(rectClient.BottomRight, hwndSource);
return new Rect(corner1, corner2);
}
/// <summary>
/// Adjusts a POINT to compensate for Win32 RTL conversion logic
/// </summary>
/// <remarks>
/// MITIGATION: AVALON_RTL_AND_WIN32RTL
///
/// When a window is marked with the WS_EX_LAYOUTRTL style, Win32
/// mirrors the coordinates during the various translation APIs.
///
/// Avalon also sets up mirroring transforms so that we properly
/// mirror the output since we render to DirectX, not a GDI DC.
///
/// Unfortunately, this means that our coordinates are already mirrored
/// by Win32, and Avalon mirrors them again. To work around this
/// problem, we un-mirror the coordinates from Win32 before hit-testing
/// in Avalon.
/// </remarks>
/// <param name="pt">
/// The POINT to be adjusted
/// </param>
/// <param name="handleRef">
/// A HandleRef to the hwnd containing the point to be adjusted
/// </param>
/// <returns>
/// The adjusted point
/// </returns>
internal static NativeMethods.POINT AdjustForRightToLeft(NativeMethods.POINT pt, HandleRef handleRef)
{
int windowStyle = SafeNativeMethods.GetWindowStyle(handleRef, true);
if(( windowStyle & NativeMethods.WS_EX_LAYOUTRTL ) == NativeMethods.WS_EX_LAYOUTRTL)
{
NativeMethods.RECT rcClient = new NativeMethods.RECT();
SafeNativeMethods.GetClientRect(handleRef, ref rcClient);
pt.x = rcClient.right - pt.x;
}
return pt;
}
/// <summary>
/// Adjusts a RECT to compensate for Win32 RTL conversion logic
/// </summary>
/// <remarks>
/// MITIGATION: AVALON_RTL_AND_WIN32RTL
///
/// When a window is marked with the WS_EX_LAYOUTRTL style, Win32
/// mirrors the coordinates during the various translation APIs.
///
/// Avalon also sets up mirroring transforms so that we properly
/// mirror the output since we render to DirectX, not a GDI DC.
///
/// Unfortunately, this means that our coordinates are already mirrored
/// by Win32, and Avalon mirrors them again. To work around this
/// problem, we un-mirror the coordinates from Win32 before hit-testing
/// in Avalon.
/// </remarks>
/// <param name="rc">
/// The RECT to be adjusted
/// </param>
/// <param name="handleRef">
/// </param>
/// <returns>
/// The adjusted rectangle
/// </returns>
internal static NativeMethods.RECT AdjustForRightToLeft(NativeMethods.RECT rc, HandleRef handleRef)
{
int windowStyle = SafeNativeMethods.GetWindowStyle(handleRef, true);
if(( windowStyle & NativeMethods.WS_EX_LAYOUTRTL ) == NativeMethods.WS_EX_LAYOUTRTL)
{
NativeMethods.RECT rcClient = new NativeMethods.RECT();
SafeNativeMethods.GetClientRect(handleRef, ref rcClient);
int width = rc.right - rc.left; // preserve width
rc.right = rcClient.right - rc.left; // set right of rect to be as far from right of window as left of rect was from left of window
rc.left = rc.right - width; // restore width by adjusting left and preserving right
}
return rc;
}
/// <summary>
/// Converts a location from an Avalon Point to a Win32 POINT
/// </summary>
/// <remarks>
/// Rounds "double" values to the nearest "int"
/// </remarks>
/// <param name="point">
/// The location as an Avalon Point
/// </param>
/// <returns>
/// The location as a Win32 POINT
/// </returns>
internal static NativeMethods.POINT FromPoint(Point point)
{
return new NativeMethods.POINT(DoubleUtil.DoubleToInt(point.X), DoubleUtil.DoubleToInt(point.Y));
}
/// <summary>
/// Converts a location from a Win32 POINT to an Avalon Point
/// </summary>
/// <param name="pt">
/// The location as a Win32 POINT
/// </param>
/// <returns>
/// The location as an Avalon Point
/// </returns>
internal static Point ToPoint(NativeMethods.POINT pt)
{
return new Point(pt.x, pt.y);
}
/// <summary>
/// Converts a rectangle from an Avalon Rect to a Win32 RECT
/// </summary>
/// <remarks>
/// Rounds "double" values to the nearest "int"
/// </remarks>
/// <param name="rect">
/// The rectangle as an Avalon Rect
/// </param>
/// <returns>
/// The rectangle as a Win32 RECT
/// </returns>
internal static NativeMethods.RECT FromRect(Rect rect)
{
NativeMethods.RECT rc = new NativeMethods.RECT();
rc.top = DoubleUtil.DoubleToInt(rect.Y);
rc.left = DoubleUtil.DoubleToInt(rect.X);
rc.bottom = DoubleUtil.DoubleToInt(rect.Bottom);
rc.right = DoubleUtil.DoubleToInt(rect.Right);
return rc;
}
/// <summary>
/// Converts a rectangle from a Win32 RECT to an Avalon Rect
/// </summary>
/// <param name="rc">
/// The rectangle as a Win32 RECT
/// </param>
/// <returns>
/// The rectangle as an Avalon Rect
/// </returns>
internal static Rect ToRect(NativeMethods.RECT rc)
{
Rect rect = new Rect();
rect.X = rc.left;
rect.Y = rc.top;
rect.Width = rc.right - rc.left;
rect.Height = rc.bottom - rc.top;
return rect;
}
}
}
| |
using Aardvark.Base.Sorting;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Aardvark.Base
{
/// <summary>
/// This interface enforces a common API for random number generators.
/// </summary>
public interface IRandomUniform
{
#region Info and Seeding
/// <summary>
/// Returns the number of random bits that the generator
/// delivers. This many bits are actually random in the
/// doubles returned by <see cref="UniformDouble()"/>.
/// </summary>
int RandomBits { get; }
/// <summary>
/// Returns true if the doubles generated by this random
/// generator contain 52 random mantissa bits.
/// </summary>
bool GeneratesFullDoubles { get; }
/// <summary>
/// Reinitializes the random generator with the specified seed.
/// </summary>
void ReSeed(int seed);
#endregion
#region Random Integers
/// <summary>
/// Returns a uniformly distributed integer in the interval
/// [0, 2^31-1].
/// </summary>
int UniformInt();
/// <summary>
/// Returns a uniformly distributed integer in the interval
/// [0, 2^32-1].
/// </summary>
uint UniformUInt();
/// <summary>
/// Returns a uniformly distributed integer in the interval
/// [0, 2^63-1].
/// </summary>
long UniformLong();
/// <summary>
/// Returns a uniformly distributed integer in the interval
/// [0, 2^64-1].
/// </summary>
ulong UniformULong();
#endregion
#region Random Floating Point Values
/// <summary>
/// Returns a uniformly distributed float in the half-open interval
/// [0.0f, 1.0f).
/// </summary>
float UniformFloat();
/// <summary>
/// Returns a uniformly distributed float in the closed interval
/// [0.0f, 1.0f].
/// </summary>
float UniformFloatClosed();
/// <summary>
/// Returns a uniformly distributed float in the open interval
/// (0.0f, 1.0f).
/// </summary>
float UniformFloatOpen();
/// <summary>
/// Returns a uniformly distributed double in the half-open interval
/// [0.0, 1.0). Note, that only RandomBits bits are guaranteed to be
/// random.
/// </summary>
double UniformDouble();
/// <summary>
/// Returns a uniformly distributed double in the closed interval
/// [0.0, 1.0]. Note, that only RandomBits bits are guaranteed to be
/// random.
/// </summary>
double UniformDoubleClosed();
/// <summary>
/// Returns a uniformly distributed double in the open interval
/// (0.0, 1.0). Note, that only RandomBits bits are guaranteed to be
/// random.
/// </summary>
double UniformDoubleOpen();
#endregion
}
public static class IRandomUniformExtensions
{
#region Random Bits
/// <summary>
/// Supply random bits one at a time. The currently unused bits are
/// maintained in the supplied reference parameter. Before the first
/// call randomBits must be 0.
/// </summary>
public static bool RandomBit(
this IRandomUniform rnd, ref int randomBits)
{
if (randomBits <= 1)
{
randomBits = rnd.UniformInt();
bool bit = (randomBits & 1) != 0;
randomBits = 0x40000000 | (randomBits >> 1);
return bit;
}
else
{
bool bit = (randomBits & 1) != 0;
randomBits >>= 1;
return bit;
}
}
#endregion
#region Random Integers
/// <summary>
/// Returns a uniformly distributed int in the interval [0, count-1].
/// In order to avoid excessive aliasing, two random numbers are used
/// when count is greater or equal 2^24 and the random generator
/// delivers 32 random bits or less. The method thus works fairly
/// decently for all integers.
/// </summary>
public static int UniformInt(this IRandomUniform rnd, int size)
{
if (rnd.GeneratesFullDoubles || size < 16777216)
return (int)(rnd.UniformDouble() * size);
else
return (int)(rnd.UniformDoubleFull() * size);
}
/// <summary>
/// Returns a uniformly distributed long in the interval [0, size-1].
/// NOTE: If count has more than about 48 bits, aliasing leads to
/// noticeable (greater 5%) shifts in the probabilities (i.e. one
/// long has a probability of x and the other a probability of
/// x * (2^(52-b)-1)/(2^(52-b)), where b is log(size)/log(2)).
/// </summary>
public static long UniformLong(this IRandomUniform rnd, long size)
{
if (rnd.GeneratesFullDoubles || size < 16777216)
return (long)(rnd.UniformDouble() * size);
else
return (long)(rnd.UniformDoubleFull() * size);
}
/// <summary>
/// Returns a uniform int which is guaranteed not to be zero.
/// </summary>
public static int UniformIntNonZero(this IRandomUniform rnd)
{
int r;
do { r = rnd.UniformInt(); } while (r == 0);
return r;
}
/// <summary>
/// Returns a uniform long which is guaranteed not to be zero.
/// </summary>
public static long UniformLongNonZero(this IRandomUniform rnd)
{
long r;
do { r = rnd.UniformLong(); } while (r == 0);
return r;
}
#endregion
#region Random Floating Point Values
/// <summary>
/// Returns a uniformly distributed double in the half-open interval
/// [0.0, 1.0). Note, that two random values are used to make all 53
/// bits random. If you use this repeatedly, consider using a 64-bit
/// random generator, which can provide such doubles directly using
/// UniformDouble().
/// </summary>
public static double UniformDoubleFull(this IRandomUniform rnd)
{
if (rnd.GeneratesFullDoubles) return rnd.UniformDouble();
long r = ((~0xfL & (long)rnd.UniformInt()) << 22)
| ((long)rnd.UniformInt() >> 5);
return r * (1.0 / 9007199254740992.0);
}
/// <summary>
/// Returns a uniformly distributed double in the closed interval
/// [0.0, 1.0]. Note, that two random values are used to make all 53
/// bits random.
/// </summary>
public static double UniformDoubleFullClosed(this IRandomUniform rnd)
{
if (rnd.GeneratesFullDoubles) return rnd.UniformDoubleClosed();
long r = ((~0xfL & (long)rnd.UniformInt()) << 22)
| ((long)rnd.UniformInt() >> 5);
return r * (1.0 / 9007199254740991.0);
}
/// <summary>
/// Returns a uniformly distributed double in the open interval
/// (0.0, 1.0). Note, that two random values are used to make all 53
/// bits random.
/// </summary>
public static double UniformDoubleFullOpen(this IRandomUniform rnd)
{
if (rnd.GeneratesFullDoubles) return rnd.UniformDoubleOpen();
long r;
do
{
r = ((~0xfL & (long)rnd.UniformInt()) << 22)
| ((long)rnd.UniformInt() >> 5);
}
while (r == 0);
return r * (1.0 / 9007199254740992.0);
}
#endregion
#region Creating Randomly Filled Arrays
/// <summary>
/// Create a random array of ints in the interval
/// [0, 2^31-1] of the specified length.
/// </summary>
public static int[] CreateUniformIntArray(
this IRandomUniform rnd, long length)
{
var array = new int[length];
rnd.FillUniform(array);
return array;
}
/// <summary>
/// Create a random array of longs in the interval
/// [0, 2^63-1] of the specified length.
/// </summary>
public static long[] CreateUniformLongArray(
this IRandomUniform rnd, long length)
{
var array = new long[length];
rnd.FillUniform(array);
return array;
}
/// <summary>
/// Create a random array of floats in the half-open interval
/// [0.0, 1.0) of the specified length.
/// </summary>
public static float[] CreateUniformFloatArray(
this IRandomUniform rnd, long length)
{
var array = new float[length];
rnd.FillUniform(array);
return array;
}
/// <summary>
/// Create a random array of doubles in the half-open interval
/// [0.0, 1.0) of the specified length.
/// </summary>
public static double[] CreateUniformDoubleArray(
this IRandomUniform rnd, long length)
{
var array = new double[length];
rnd.FillUniform(array);
return array;
}
/// <summary>
/// Create a random array of full doubles in the half-open interval
/// [0.0, 1.0) of the specified length.
/// </summary>
public static double[] CreateUniformDoubleFullArray(
this IRandomUniform rnd, long length)
{
var array = new double[length];
rnd.FillUniformFull(array);
return array;
}
/// <summary>
/// Fills the specified array with random ints in the interval
/// [0, 2^31-1].
/// </summary>
public static void FillUniform(this IRandomUniform rnd, int[] array)
{
long count = array.LongLength;
for (long i = 0; i < count; i++)
array[i] = rnd.UniformInt();
}
/// <summary>
/// Fills the specified array with random longs in the interval
/// [0, 2^63-1].
/// </summary>
public static void FillUniform(this IRandomUniform rnd, long[] array)
{
long count = array.LongLength;
for (long i = 0; i < count; i++)
array[i] = rnd.UniformLong();
}
/// <summary>
/// Fills the specified array with random floats in the half-open
/// interval [0.0f, 1.0f).
/// </summary>
public static void FillUniform(this IRandomUniform rnd, float[] array)
{
long count = array.LongLength;
for (long i = 0; i < count; i++)
array[i] = rnd.UniformFloat();
}
/// <summary>
/// Fills the specified array with random doubles in the half-open
/// interval [0.0, 1.0).
/// </summary>
public static void FillUniform(
this IRandomUniform rnd, double[] array)
{
long count = array.LongLength;
for (long i = 0; i < count; i++)
array[i] = rnd.UniformDouble();
}
/// <summary>
/// Fills the specified array with fully random doubles (53 random
/// bits) in the half-open interval [0.0, 1.0).
/// </summary>
public static void FillUniformFull(
this IRandomUniform rnd, double[] array)
{
long count = array.LongLength;
if (rnd.GeneratesFullDoubles)
{
for (long i = 0; i < count; i++)
array[i] = rnd.UniformDoubleFull();
}
else
{
for (long i = 0; i < count; i++)
array[i] = rnd.UniformDouble();
}
}
/// <summary>
/// Creates an array that contains a random permutation of the
/// ints in the interval [0, count-1].
/// </summary>
public static int[] CreatePermutationArray(
this IRandomUniform rnd, int count)
{
var p = new int[count].SetByIndex(i => i);
rnd.Randomize(p);
return p;
}
/// <summary>
/// Creates an array that contains a random permutation of the
/// numbers in the interval [0, count-1].
/// </summary>
public static long[] CreatePermutationArrayLong(
this IRandomUniform rnd, long count)
{
var p = new long[count].SetByIndexLong(i => i);
rnd.Randomize(p);
return p;
}
#endregion
#region Creationg a Random Subset (while maintaing order)
/// <summary>
/// Returns a random subset of an array with a supplied number of
/// elements (subsetCount). The elements in the subset are in the
/// same order as in the original array. O(count).
/// NOTE: this method needs to generate one random number for each
/// element of the original array. If subsetCount is significantly
/// smaller than count, it is more efficient to use
/// <see cref="CreateSmallRandomSubsetIndexArray"/> or
/// <see cref="CreateSmallRandomSubsetIndexArrayLong"/> or
/// <see cref="CreateSmallRandomOrderedSubsetIndexArray"/> or
/// <see cref="CreateSmallRandomOrderedSubsetIndexArrayLong"/>.
/// </summary>
public static T[] CreateRandomSubsetOfSize<T>(
this T[] array, long subsetCount, IRandomUniform rnd = null)
{
if (rnd == null) rnd = new RandomSystem();
long count = array.LongLength;
if (!(subsetCount >= 0 && subsetCount <= count)) throw new ArgumentOutOfRangeException(nameof(subsetCount));
var subset = new T[subsetCount];
long si = 0;
for (int ai = 0; ai < count && si < subsetCount; ai++)
{
var p = (double)(subsetCount - si) / (double)(count - ai);
if (rnd.UniformDouble() <= p) subset[si++] = array[ai];
}
return subset;
}
/// <summary>
/// Returns a random subset of the enumeration with a supplied number of
/// elements (subsetCount). The elements in the subset are in the
/// same order as in the input. O(count).
/// NOTE: The number of elements of the Enumerable need to be calculated, in case of true enumerations
/// the implementation of .Count() results in a second evaluation of the enumerable.
/// </summary>
public static T[] CreateRandomSubsetOfSize<T>(
this IEnumerable<T> input, long subsetCount, IRandomUniform rnd = null)
{
if (rnd == null) rnd = new RandomSystem();
long count = input.Count();
if (!(subsetCount >= 0 && subsetCount <= count)) throw new ArgumentOutOfRangeException(nameof(subsetCount));
var subset = new T[subsetCount];
long si = 0, ai = 0;
foreach (var a in input)
{
if (ai < count && si < subsetCount)
{
var p = (double)(subsetCount - si) / (double)(count - ai++);
if (rnd.UniformDouble() <= p) subset[si++] = a;
}
else
break;
}
return subset;
}
/// <summary>
/// Creates an unordered array of subsetCount long indices that
/// constitute a subset of all longs in the range [0, count-1].
/// O(subsetCount) for subsetCount << count.
/// NOTE: It is assumed that subsetCount is significantly smaller
/// than count. If this is not the case, use
/// CreateRandomSubsetOfSize instead.
/// WARNING: As subsetCount approaches count execution time
/// increases significantly.
/// </summary>
public static long[] CreateSmallRandomSubsetIndexArrayLong(
this IRandomUniform rnd, long subsetCount, long count)
{
if (!(subsetCount >= 0 && subsetCount <= count)) throw new ArgumentOutOfRangeException(nameof(subsetCount));
var subsetIndices = new LongSet(subsetCount);
for (int i = 0; i < subsetCount; i++)
{
long index;
do { index = rnd.UniformLong(count); }
while (!subsetIndices.TryAdd(index));
}
return subsetIndices.ToArray();
}
/// <summary>
/// Creates an ordered array of subsetCount long indices that
/// constitute a subset of all longs in the range [0, count-1].
/// O(subsetCount * log(subsetCount)) for subsetCount << count.
/// NOTE: It is assumed that subsetCount is significantly smaller
/// than count. If this is not the case, use
/// CreateRandomSubsetOfSize instead.
/// WARNING: As subsetCount approaches count execution time
/// increases significantly.
/// </summary>
public static long[] CreateSmallRandomOrderedSubsetIndexArrayLong(
this IRandomUniform rnd, long subsetCount, long count)
{
var subsetIndexArray = rnd.CreateSmallRandomSubsetIndexArrayLong(subsetCount, count);
subsetIndexArray.QuickSortAscending();
return subsetIndexArray;
}
/// <summary>
/// Creates an unordered array of subsetCount int indices that
/// constitute a subset of all ints in the range [0, count-1].
/// O(subsetCount) for subsetCount << count.
/// NOTE: It is assumed that subsetCount is significantly smaller
/// than count. If this is not the case, use
/// CreateRandomSubsetOfSize instead.
/// WARNING: As subsetCount approaches count execution time
/// increases significantly.
/// </summary>
public static int[] CreateSmallRandomSubsetIndexArray(
this IRandomUniform rnd, int subsetCount, int count)
{
if (!(subsetCount >= 0 && subsetCount <= count)) throw new ArgumentOutOfRangeException(nameof(subsetCount));
var subsetIndices = new IntSet(subsetCount);
for (int i = 0; i < subsetCount; i++)
{
int index;
do { index = rnd.UniformInt(count); }
while (!subsetIndices.TryAdd(index));
}
return subsetIndices.ToArray();
}
/// <summary>
/// Creates an ordered array of subsetCount int indices that
/// constitute a subset of all ints in the range [0, count-1].
/// O(subsetCount * log(subsetCount)) for subsetCount << count.
/// NOTE: It is assumed that subsetCount is significantly smaller
/// than count. If this is not the case, use
/// CreateRandomSubsetOfSize instead.
/// WARNING: As subsetCount approaches count execution time
/// increases significantly.
/// </summary>
public static int[] CreateSmallRandomOrderedSubsetIndexArray(
this IRandomUniform rnd, int subsetCount, int count)
{
var subsetIndexArray = rnd.CreateSmallRandomSubsetIndexArray(subsetCount, count);
subsetIndexArray.QuickSortAscending();
return subsetIndexArray;
}
#endregion
#region Randomizing Existing Arrays
/// <summary>
/// Randomly permute the first count elements of the
/// supplied array. This does work with counts of up
/// to about 2^50.
/// </summary>
public static void Randomize<T>(
this IRandomUniform rnd, T[] array, long count)
{
if (count <= (long)int.MaxValue)
{
int intCount = (int)count;
for (int i = 0; i < intCount; i++)
array.Swap(i, rnd.UniformInt(intCount));
}
else
{
for (long i = 0; i < count; i++)
array.Swap(i, rnd.UniformLong(count));
}
}
/// <summary>
/// Randomly permute the elements of the supplied array. This does
/// work with arrays up to a length of about 2^50.
/// </summary>
public static void Randomize<T>(
this IRandomUniform rnd, T[] array)
{
rnd.Randomize(array, array.LongLength);
}
/// <summary>
/// Randomly permute the elements of the supplied list.
/// </summary>
public static void Randomize<T>(
this IRandomUniform rnd, List<T> list)
{
int count = list.Count;
for (int i = 0; i < count; i++)
list.Swap(i, rnd.UniformInt(count));
}
/// <summary>
/// Randomly permute the specified number of elements in the supplied
/// array starting at the specified index.
/// </summary>
public static void Randomize<T>(
this IRandomUniform rnd, T[] array, int start, int count)
{
for (int i = start, e = start + count; i < e; i++)
array.Swap(i, start + rnd.UniformInt(count));
}
/// <summary>
/// Randomly permute the specified number of elements in the supplied
/// array starting at the specified index.
/// </summary>
public static void Randomize<T>(
this IRandomUniform rnd, T[] array, long start, long count)
{
for (long i = start, e = start + count; i < e; i++)
array.Swap(i, start + rnd.UniformLong(count));
}
/// <summary>
/// Randomly permute the specified number of elements in the supplied
/// list starting at the specified index.
/// </summary>
public static void Randomize<T>(
this IRandomUniform rnd, List<T> list, int start, int count)
{
for (int i = start; i < start + count; i++)
list.Swap(i, start + rnd.UniformInt(count));
}
#endregion
#region Random Distributions
/// <summary>
/// Generates normal distributed random variable with given mean and standard deviation.
/// Uses the Box-Muller Transformation to transform two uniform distributed random variables to one normal distributed value.
/// NOTE: If multiple normal distributed random values are required, consider using <see cref="RandomGaussian"/>.
/// </summary>
public static double Gaussian(this IRandomUniform rnd, double mean = 0.0, double stdDev = 1.0)
{
// Box-Muller Transformation
var u1 = 1.0 - rnd.UniformDouble(); // uniform (0,1] -> log requires > 0
var u2 = rnd.UniformDouble(); // uniform [0,1)
var randStdNormal = Fun.Sqrt(-2.0 * Fun.Log(u1)) *
Fun.Sin(Constant.PiTimesTwo * u2);
return mean + stdDev * randStdNormal;
}
#endregion
}
public static class IRandomEnumerableExtensions
{
#region Random Order
/// <summary>
/// Enumerates elements in random order.
/// </summary>
public static IEnumerable<T> RandomOrder<T>(this IEnumerable<T> self, IRandomUniform rnd = null)
{
var tmp = self.ToArray();
if (rnd == null) rnd = new RandomSystem();
var perm = rnd.CreatePermutationArray(tmp.Length);
return perm.Select(index => tmp[index]);
}
#endregion
}
}
| |
//
// Copyright (c) 2003-2006 Jaroslaw Kowalski <jaak@jkowalski.net>
// Copyright (c) 2006-2014 Piotr Fusik <piotr@fusik.info>
//
// 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.
//
// 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.Xml.Serialization;
namespace Sooda.QL
{
public class SoqlBooleanRelationalExpression : SoqlBooleanExpression
{
[XmlElement("Left")]
public SoqlExpression par1;
[XmlElement("Right")]
public SoqlExpression par2;
[XmlAttribute("operator")]
public SoqlRelationalOperator op;
public SoqlBooleanRelationalExpression() { }
public SoqlBooleanRelationalExpression(SoqlExpression par1, SoqlExpression par2, SoqlRelationalOperator op)
{
this.par1 = par1;
this.par2 = par2;
this.op = op;
}
// visitor pattern
public override void Accept(ISoqlVisitor visitor)
{
visitor.Visit(this);
}
public override SoqlExpression Simplify()
{
par1 = par1.Simplify();
par2 = par2.Simplify();
ISoqlConstantExpression cp1 = par1 as ISoqlConstantExpression;
ISoqlConstantExpression cp2 = par2 as ISoqlConstantExpression;
if (cp1 != null && cp2 != null)
{
object v1 = cp1.GetConstantValue();
object v2 = cp2.GetConstantValue();
object result = Compare(v1, v2, op);
if (result == null)
return new SoqlNullLiteral();
else
return new SoqlBooleanLiteralExpression((bool)result);
}
return this;
}
private static void PromoteTypes(ref object val1, ref object val2)
{
if (val1.GetType() == val2.GetType())
return;
if (val1 is SoodaObject)
{
val1 = ((SoodaObject)val1).GetPrimaryKeyValue();
}
if (val2 is SoodaObject)
{
val2 = ((SoodaObject)val2).GetPrimaryKeyValue();
}
if (val1 is DateTime || val2 is DateTime)
{
val1 = Convert.ToDateTime(val1);
val2 = Convert.ToDateTime(val2);
return;
}
if (val1 is string || val2 is string)
{
val1 = Convert.ToString(val1);
val2 = Convert.ToString(val2);
return;
}
if (val1 is double || val2 is double)
{
val1 = Convert.ToDouble(val1);
val2 = Convert.ToDouble(val2);
return;
}
if (val1 is float || val2 is float)
{
val1 = Convert.ToSingle(val1);
val2 = Convert.ToSingle(val2);
return;
}
if (val1 is decimal || val2 is decimal)
{
val1 = Convert.ToDecimal(val1);
val2 = Convert.ToDecimal(val2);
return;
}
if (val1 is long || val2 is long)
{
val1 = Convert.ToInt64(val1);
val2 = Convert.ToInt64(val2);
return;
}
if (val1 is int || val2 is int)
{
val1 = Convert.ToInt32(val1);
val2 = Convert.ToInt32(val2);
return;
}
if (val1 is short || val2 is short)
{
val1 = Convert.ToInt16(val1);
val2 = Convert.ToInt16(val2);
return;
}
if (val1 is sbyte || val2 is sbyte)
{
val1 = Convert.ToSByte(val1);
val2 = Convert.ToSByte(val2);
return;
}
if (val1 is bool || val2 is bool)
{
val1 = Convert.ToBoolean(val1);
val2 = Convert.ToBoolean(val2);
return;
}
throw new Exception("Cannot promote types " + val1.GetType().Name + " and " + val2.GetType().Name + " to one type.");
}
public static object Compare(object v1, object v2, SoqlRelationalOperator op)
{
v1 = Sooda.Utils.SqlTypesUtil.Unwrap(v1);
v2 = Sooda.Utils.SqlTypesUtil.Unwrap(v2);
if (v1 == null || v2 == null)
return null;
IComparer comparer = Comparer.Default;
PromoteTypes(ref v1, ref v2);
switch (op)
{
case SoqlRelationalOperator.Equal:
return comparer.Compare(v1, v2) == 0;
case SoqlRelationalOperator.NotEqual:
return comparer.Compare(v1, v2) != 0;
case SoqlRelationalOperator.Greater:
return comparer.Compare(v1, v2) > 0;
case SoqlRelationalOperator.GreaterOrEqual:
return comparer.Compare(v1, v2) >= 0;
case SoqlRelationalOperator.LessOrEqual:
return comparer.Compare(v1, v2) <= 0;
case SoqlRelationalOperator.Less:
return comparer.Compare(v1, v2) < 0;
case SoqlRelationalOperator.Like:
string s1 = Convert.ToString(v1);
string s2 = Convert.ToString(v2);
return SoqlUtils.Like(s1, s2);
default:
throw new NotSupportedException("Relational operator " + op + " is not supported.");
}
}
public override object Evaluate(ISoqlEvaluateContext context)
{
object v1 = par1.Evaluate(context);
object v2 = par2.Evaluate(context);
return Compare(v1, v2, op);
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
using System.Text.RegularExpressions;
using DynamicExpression = System.Linq.Dynamic.DynamicExpression;
namespace Verno
{
public static class StringExtensions
{
public static string ReadWord(this string sourceString, ref int startIdx)
{
return ReadWhile(sourceString, ref startIdx, char.IsLetterOrDigit);
}
public static string ReadRegex(this string sourceString, ref int startIdx, Regex regex)
{
var match = regex.Match(sourceString, startIdx);
if (match.Success)
{
startIdx = match.Index + match.Value.Length;
return match.Groups.Count > 1 ? match.Groups[1].Value : match.Value;
}
return "";
}
public static string ReadRegex(this string sourceString, string pattern)
{
int idx = 0;
return ReadRegex(sourceString, ref idx, new Regex(pattern));
}
public static string ReadFirstWord(this string sourceString)
{
int startIdx = 0;
return ReadWhile(sourceString, ref startIdx, char.IsLetterOrDigit);
}
public static string ReadWhile(this string sourceString, ref int startIdx, Predicate<char> whilePredicate)
{
return ReadWhile(sourceString, ref startIdx, (int idx) => whilePredicate(sourceString[idx]));
}
private static string ReadWhile(this string sourceString, ref int startIdx, Predicate<int> whilePredicate)
{
int start = FindFrom(sourceString, startIdx, whilePredicate);
for (int i = start; i < sourceString.Length; i++)
{
if (!whilePredicate(i))
{
startIdx = i;
return sourceString.Substring(start, i - start).Trim();
}
}
startIdx = sourceString.Length;
return sourceString.Substring(start).Trim();
}
public static string ReadTo(this string sourceString, ref int startIdx, params string[] toStrings)
{
/*return ReadWhile(sourceString, ref startIdx,
(int idx) => toStrings.Any(pred => sourceString.Length >= idx + pred.Length
&& sourceString.Substring(idx, pred.Length) == pred));*/
int start = startIdx;
for (int i = startIdx; i < sourceString.Length; i++)
{
if (toStrings.Any(pred => sourceString.Length >= i + pred.Length && sourceString.Substring(i, pred.Length) == pred))
{
startIdx = i + 1;
return sourceString.Substring(start, i - start).Trim();
}
}
startIdx = sourceString.Length;
return sourceString.Substring(start).Trim();
}
public static int FindFrom(this string sourceString, int startIdx, Predicate<char> toPredicate)
{
return FindFrom(sourceString, startIdx, (int idx) => toPredicate(sourceString[idx]));
}
private static int FindFrom(this string sourceString, int startIdx, Predicate<int> toPredicate)
{
for (int i = startIdx; i < sourceString.Length; i++)
{
if (toPredicate(i))
return i;
}
return sourceString.Length;
}
/// <summary>
/// Matching all capital letters in the input and seperate them with spaces to form a sentence.
/// If the input is an abbreviation text, no space will be added and returns the same input.
/// </summary>
/// <example>
/// input : HelloWorld
/// output : Hello World
/// </example>
/// <example>
/// input : BBC
/// output : BBC
/// </example>
/// <param name="input" />
/// <returns/>
public static string ToSentence(this string input)
{
if (string.IsNullOrEmpty(input))
return input;
//return as is if the input is just an abbreviation
if (Regex.Match(input, "[0-9A-Z]+$").Success)
return input;
//add a space before each capital letter, but not the first one.
var result = Regex.Replace(input, "(\\B[A-Z])", " $1");
return result;
}
/// <summary>
/// Return last "howMany" characters from "input" string.
/// </summary>
/// <param name="input">Input string</param>
/// <param name="howMany">Characters count to return</param>
/// <returns></returns>
public static string GetLast(this string input, int howMany)
{
if (string.IsNullOrEmpty(input)) return string.Empty;
var value = input.Trim();
return howMany >= value.Length ? value : value.Substring(value.Length - howMany);
}
/// <summary>
/// Return first "howMany" characters from "input" string.
/// </summary>
/// <param name="input">Input string</param>
/// <param name="howMany">Characters count to return</param>
/// <returns></returns>
public static string GetFirst(this string input, int howMany)
{
if (string.IsNullOrEmpty(input)) return string.Empty;
var value = input.Trim();
return howMany >= value.Length ? value : input.Substring(0, howMany);
}
public static bool IsNumber(this string input)
{
var match = Regex.Match(input, @"^[0-9]+$", RegexOptions.IgnoreCase);
return match.Success;
}
public static bool IsEmail(this string input)
{
var match = Regex.Match(input,
@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*", RegexOptions.IgnoreCase);
return match.Success;
}
public static bool IsPhone(this string input)
{
var match = Regex.Match(input,
@"^\+?(\d[\d-. ]+)?(\([\d-. ]+\))?[\d-. ]+\d$", RegexOptions.IgnoreCase);
return match.Success;
}
public static int ExtractNumber(this string input, int def)
{
if (string.IsNullOrEmpty(input)) return 0;
var match = Regex.Match(input, "[0-9]{1,9}", RegexOptions.IgnoreCase);
return match.Success ? int.Parse(match.Value) : def;
}
/// <summary>
/// Checks string object's value to array of string values
/// </summary>
/// <param name="value">Input string</param>
/// <param name="stringValues">Array of string values to compare</param>
/// <returns>Return true if any string value matches</returns>
public static bool In(this string value, params string[] stringValues)
{
return stringValues.Any(otherValue => String.CompareOrdinal(value, otherValue) == 0);
}
public static bool IsNullOrWhiteSpace(this string input)
{
return string.IsNullOrEmpty(input) || input.Trim() == string.Empty;
}
/// <summary>
/// Formats the string according to the specified mask
/// </summary>
/// <param name="input">The input string.</param>
/// <param name="mask">The mask for formatting. Like "A##-##-T-###Z"</param>
/// <returns>The formatted string</returns>
public static string FormatWithMask(this string input, string mask)
{
if (input.IsNullOrWhiteSpace()) return input;
var output = string.Empty;
var index = 0;
foreach (var m in mask)
{
if (m == '#')
{
if (index < input.Length)
{
output += input[index];
index++;
}
}
else
output += m;
}
return output;
}
public static string Format(this string stringFormat, params object[] pars)
{
return string.Format(stringFormat, pars);
}
/// <summary>
/// Supplements String.Format by letting you get properties from objects
/// </summary>
/// <example>
/// var sourceObject = new { simpleString = "string", integer = 3, Date = new DateTime(2013, 08, 19) };
/// Debug.WriteLine("Gettings property by name : '{0:simpleString}' event cast insensitive : {0:date}".Inject(sourceObject));
/// Debug.WriteLine("The property can be formatted by appending standard String.Format syntax after the property name like this {0:date:yyyy-MM-dd}".Inject(sourceObject));
/// Debug.WriteLine("Use culture info to format the value to a specific culture '{0:date:dddd}'".Inject(CultureInfo.GetCultureInfo("da-DK"), sourceObject));
/// Debug.WriteLine("Inject more values and event build in types {0:integer} {1} with build in properties {1:length}".Inject(sourceObject, "simple string"));
/// </example>
/// <param name="source">A composite format string</param>
/// <param name="formatProvider">An object that supplies culture-specific formatting information.</param>
/// <param name="args">An object array that contains zero or more objects to format.</param>
/// <returns>A copy of format in which the format items have been replaced by the string representation of the corresponding objects in args.</returns>
public static string FormatInject(this string source, IFormatProvider formatProvider, params object[] args)
{
var objectWrappers = new object[args.Length];
for (var i = 0; i < args.Length; i++)
{
objectWrappers[i] = new ObjectWrapper(args[i]);
}
return string.Format(formatProvider, source, objectWrappers);
}
public static string FormatInject(this string source, params object[] args)
{
return FormatInject(source, CultureInfo.CurrentUICulture, args);
}
private class ObjectWrapper : IFormattable
{
private readonly object _wrapped;
private static readonly Dictionary<string, FormatInfo> Cache = new Dictionary<string, FormatInfo>();
public ObjectWrapper(object wrapped)
{
_wrapped = wrapped;
}
public string ToString(string format, IFormatProvider formatProvider)
{
if (string.IsNullOrEmpty(format))
{
return _wrapped.ToString();
}
var type = _wrapped.GetType();
var key = type.FullName + ":" + format;
FormatInfo wrapperCache;
lock (Cache)
{
if (!Cache.TryGetValue(key, out wrapperCache))
{
wrapperCache = CreateFormatInfo(format, type);
Cache.Add(key, wrapperCache);
}
}
var value = wrapperCache.GetValueDelegate != null ? wrapperCache.GetValueDelegate.DynamicInvoke(_wrapped) : _wrapped;
var outputFormat = wrapperCache.OutputFormat;
return string.Format(formatProvider, outputFormat, value);
}
private delegate object GetDictionaryValueDelegate(IDictionary dic);
private static FormatInfo CreateFormatInfo(string format, Type type)
{
var split = format.Split(new[] { ':' }, 2);
var param = split[0];
var hasSubFormat = split.Length == 2;
var subFormat = hasSubFormat ? split[1] : string.Empty;
string outputFormat = "";
Delegate valueDelegate = null;
if (typeof(IDictionary).IsAssignableFrom(type))
{
valueDelegate = (GetDictionaryValueDelegate)delegate(IDictionary dic)
{
var key = param.ReadFirstWord();
var item = dic[key];
var parameter = Expression.Parameter(item.GetType(), key);
var expression = DynamicExpression.ParseLambda(new[] { parameter }, null, param);
return expression.Compile().DynamicInvoke(item);
};
outputFormat = hasSubFormat ? "{0:" + subFormat + "}" : "{0}";
}
else
{
string exp = "obj." + param;
var parameter = Expression.Parameter(type, "obj");
var expression = DynamicExpression.ParseLambda(new[] { parameter }, null, exp);
outputFormat = expression != null ? (hasSubFormat ? "{0:" + subFormat + "}" : "{0}") : "{0:" + format + "}";
valueDelegate = expression != null ? expression.Compile() : null;
}
return new FormatInfo(valueDelegate, outputFormat);
}
private class FormatInfo
{
public FormatInfo(Delegate getValueDelegate, string outputFormat)
{
GetValueDelegate = getValueDelegate;
OutputFormat = outputFormat;
}
public Delegate GetValueDelegate { get; private set; }
public string OutputFormat { get; private set; }
}
}
#if WindowsCE
public static string[] Split(this string str, string[] separator, StringSplitOptions options)
{
int numReplaces = 0;
int length = separator.Length;
int[] sepList = new int[str.Length];
int[] lengthList = new int[str.Length];
for (int i = 0; (i < str.Length) && (numReplaces < length); i++)
{
for (int j = 0; j < separator.Length; j++)
{
string sep = separator[j];
if (!string.IsNullOrEmpty(sep))
{
int num5 = sep.Length;
if (((str[i] == sep[0]) && (num5 <= (str.Length - i))) && ((num5 == 1) || (string.CompareOrdinal(str, i, sep, 0, num5) == 0)))
{
sepList[numReplaces] = i;
lengthList[numReplaces] = num5;
numReplaces++;
i += num5 - 1;
break;
}
}
}
}
int num = (numReplaces < int.MaxValue) ? (numReplaces + 1) : int.MaxValue;
string[] strArray = new string[num];
int startIndex = 0;
int num3 = 0;
for (int i = 0; (i < numReplaces) && (startIndex < str.Length); i++)
{
if ((sepList[i] - startIndex) > 0)
{
strArray[num3++] = str.Substring(startIndex, sepList[i] - startIndex);
}
startIndex = sepList[i] + ((lengthList == null) ? 1 : lengthList[i]);
if (num3 == (int.MaxValue - 1))
{
while ((i < (numReplaces - 1)) && (startIndex == sepList[++i]))
{
startIndex += (lengthList == null) ? 1 : lengthList[i];
}
break;
}
}
if (startIndex < str.Length)
{
strArray[num3++] = str.Substring(startIndex);
}
string[] strArray2 = strArray;
if (num3 != num)
{
strArray2 = new string[num3];
for (int j = 0; j < num3; j++)
{
strArray2[j] = strArray[j];
}
}
return strArray2;
}
#endif
}
#if WindowsCE
public enum StringSplitOptions
{
None,
RemoveEmptyEntries
}
#endif
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Dynamic.Utils;
using System.Linq.Expressions;
using System.Reflection;
namespace System.Dynamic
{
/// <summary>
/// Represents the dynamic binding and a binding logic of an object participating in the dynamic binding.
/// </summary>
public class DynamicMetaObject
{
private readonly Expression _expression;
private readonly BindingRestrictions _restrictions;
private readonly object _value;
private readonly bool _hasValue;
/// <summary>
/// Represents an empty array of type <see cref="DynamicMetaObject"/>. This field is read only.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2105:ArrayFieldsShouldNotBeReadOnly")]
public static readonly DynamicMetaObject[] EmptyMetaObjects = Array.Empty<DynamicMetaObject>();
/// <summary>
/// Initializes a new instance of the <see cref="DynamicMetaObject"/> class.
/// </summary>
/// <param name="expression">The expression representing this <see cref="DynamicMetaObject"/> during the dynamic binding process.</param>
/// <param name="restrictions">The set of binding restrictions under which the binding is valid.</param>
public DynamicMetaObject(Expression expression, BindingRestrictions restrictions)
{
ContractUtils.RequiresNotNull(expression, nameof(expression));
ContractUtils.RequiresNotNull(restrictions, nameof(restrictions));
_expression = expression;
_restrictions = restrictions;
}
/// <summary>
/// Initializes a new instance of the <see cref="DynamicMetaObject"/> class.
/// </summary>
/// <param name="expression">The expression representing this <see cref="DynamicMetaObject"/> during the dynamic binding process.</param>
/// <param name="restrictions">The set of binding restrictions under which the binding is valid.</param>
/// <param name="value">The runtime value represented by the <see cref="DynamicMetaObject"/>.</param>
public DynamicMetaObject(Expression expression, BindingRestrictions restrictions, object value)
: this(expression, restrictions)
{
_value = value;
_hasValue = true;
}
/// <summary>
/// The expression representing the <see cref="DynamicMetaObject"/> during the dynamic binding process.
/// </summary>
public Expression Expression
{
get
{
return _expression;
}
}
/// <summary>
/// The set of binding restrictions under which the binding is valid.
/// </summary>
public BindingRestrictions Restrictions
{
get
{
return _restrictions;
}
}
/// <summary>
/// The runtime value represented by this <see cref="DynamicMetaObject"/>.
/// </summary>
public object Value
{
get
{
return _value;
}
}
/// <summary>
/// Gets a value indicating whether the <see cref="DynamicMetaObject"/> has the runtime value.
/// </summary>
public bool HasValue
{
get
{
return _hasValue;
}
}
/// <summary>
/// Gets the <see cref="Type"/> of the runtime value or null if the <see cref="DynamicMetaObject"/> has no value associated with it.
/// </summary>
public Type RuntimeType
{
get
{
if (_hasValue)
{
Type ct = Expression.Type;
// valuetype at compile time, type cannot change.
if (ct.GetTypeInfo().IsValueType)
{
return ct;
}
if (_value != null)
{
return _value.GetType();
}
else
{
return null;
}
}
else
{
return null;
}
}
}
/// <summary>
/// Gets the limit type of the <see cref="DynamicMetaObject"/>.
/// </summary>
/// <remarks>Represents the most specific type known about the object represented by the <see cref="DynamicMetaObject"/>. <see cref="RuntimeType"/> if runtime value is available, a type of the <see cref="Expression"/> otherwise.</remarks>
public Type LimitType
{
get
{
return RuntimeType ?? Expression.Type;
}
}
/// <summary>
/// Performs the binding of the dynamic conversion operation.
/// </summary>
/// <param name="binder">An instance of the <see cref="ConvertBinder"/> that represents the details of the dynamic operation.</param>
/// <returns>The new <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
public virtual DynamicMetaObject BindConvert(ConvertBinder binder)
{
ContractUtils.RequiresNotNull(binder, nameof(binder));
return binder.FallbackConvert(this);
}
/// <summary>
/// Performs the binding of the dynamic get member operation.
/// </summary>
/// <param name="binder">An instance of the <see cref="GetMemberBinder"/> that represents the details of the dynamic operation.</param>
/// <returns>The new <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
public virtual DynamicMetaObject BindGetMember(GetMemberBinder binder)
{
ContractUtils.RequiresNotNull(binder, nameof(binder));
return binder.FallbackGetMember(this);
}
/// <summary>
/// Performs the binding of the dynamic set member operation.
/// </summary>
/// <param name="binder">An instance of the <see cref="SetMemberBinder"/> that represents the details of the dynamic operation.</param>
/// <param name="value">The <see cref="DynamicMetaObject"/> representing the value for the set member operation.</param>
/// <returns>The new <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
public virtual DynamicMetaObject BindSetMember(SetMemberBinder binder, DynamicMetaObject value)
{
ContractUtils.RequiresNotNull(binder, nameof(binder));
return binder.FallbackSetMember(this, value);
}
/// <summary>
/// Performs the binding of the dynamic delete member operation.
/// </summary>
/// <param name="binder">An instance of the <see cref="DeleteMemberBinder"/> that represents the details of the dynamic operation.</param>
/// <returns>The new <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
public virtual DynamicMetaObject BindDeleteMember(DeleteMemberBinder binder)
{
ContractUtils.RequiresNotNull(binder, nameof(binder));
return binder.FallbackDeleteMember(this);
}
/// <summary>
/// Performs the binding of the dynamic get index operation.
/// </summary>
/// <param name="binder">An instance of the <see cref="GetIndexBinder"/> that represents the details of the dynamic operation.</param>
/// <param name="indexes">An array of <see cref="DynamicMetaObject"/> instances - indexes for the get index operation.</param>
/// <returns>The new <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
public virtual DynamicMetaObject BindGetIndex(GetIndexBinder binder, DynamicMetaObject[] indexes)
{
ContractUtils.RequiresNotNull(binder, nameof(binder));
return binder.FallbackGetIndex(this, indexes);
}
/// <summary>
/// Performs the binding of the dynamic set index operation.
/// </summary>
/// <param name="binder">An instance of the <see cref="SetIndexBinder"/> that represents the details of the dynamic operation.</param>
/// <param name="indexes">An array of <see cref="DynamicMetaObject"/> instances - indexes for the set index operation.</param>
/// <param name="value">The <see cref="DynamicMetaObject"/> representing the value for the set index operation.</param>
/// <returns>The new <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
public virtual DynamicMetaObject BindSetIndex(SetIndexBinder binder, DynamicMetaObject[] indexes, DynamicMetaObject value)
{
ContractUtils.RequiresNotNull(binder, nameof(binder));
return binder.FallbackSetIndex(this, indexes, value);
}
/// <summary>
/// Performs the binding of the dynamic delete index operation.
/// </summary>
/// <param name="binder">An instance of the <see cref="DeleteIndexBinder"/> that represents the details of the dynamic operation.</param>
/// <param name="indexes">An array of <see cref="DynamicMetaObject"/> instances - indexes for the delete index operation.</param>
/// <returns>The new <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
public virtual DynamicMetaObject BindDeleteIndex(DeleteIndexBinder binder, DynamicMetaObject[] indexes)
{
ContractUtils.RequiresNotNull(binder, nameof(binder));
return binder.FallbackDeleteIndex(this, indexes);
}
/// <summary>
/// Performs the binding of the dynamic invoke member operation.
/// </summary>
/// <param name="binder">An instance of the <see cref="InvokeMemberBinder"/> that represents the details of the dynamic operation.</param>
/// <param name="args">An array of <see cref="DynamicMetaObject"/> instances - arguments to the invoke member operation.</param>
/// <returns>The new <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
public virtual DynamicMetaObject BindInvokeMember(InvokeMemberBinder binder, DynamicMetaObject[] args)
{
ContractUtils.RequiresNotNull(binder, nameof(binder));
return binder.FallbackInvokeMember(this, args);
}
/// <summary>
/// Performs the binding of the dynamic invoke operation.
/// </summary>
/// <param name="binder">An instance of the <see cref="InvokeBinder"/> that represents the details of the dynamic operation.</param>
/// <param name="args">An array of <see cref="DynamicMetaObject"/> instances - arguments to the invoke operation.</param>
/// <returns>The new <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
public virtual DynamicMetaObject BindInvoke(InvokeBinder binder, DynamicMetaObject[] args)
{
ContractUtils.RequiresNotNull(binder, nameof(binder));
return binder.FallbackInvoke(this, args);
}
/// <summary>
/// Performs the binding of the dynamic create instance operation.
/// </summary>
/// <param name="binder">An instance of the <see cref="CreateInstanceBinder"/> that represents the details of the dynamic operation.</param>
/// <param name="args">An array of <see cref="DynamicMetaObject"/> instances - arguments to the create instance operation.</param>
/// <returns>The new <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
public virtual DynamicMetaObject BindCreateInstance(CreateInstanceBinder binder, DynamicMetaObject[] args)
{
ContractUtils.RequiresNotNull(binder, nameof(binder));
return binder.FallbackCreateInstance(this, args);
}
/// <summary>
/// Performs the binding of the dynamic unary operation.
/// </summary>
/// <param name="binder">An instance of the <see cref="UnaryOperationBinder"/> that represents the details of the dynamic operation.</param>
/// <returns>The new <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
public virtual DynamicMetaObject BindUnaryOperation(UnaryOperationBinder binder)
{
ContractUtils.RequiresNotNull(binder, nameof(binder));
return binder.FallbackUnaryOperation(this);
}
/// <summary>
/// Performs the binding of the dynamic binary operation.
/// </summary>
/// <param name="binder">An instance of the <see cref="BinaryOperationBinder"/> that represents the details of the dynamic operation.</param>
/// <param name="arg">An instance of the <see cref="DynamicMetaObject"/> representing the right hand side of the binary operation.</param>
/// <returns>The new <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
public virtual DynamicMetaObject BindBinaryOperation(BinaryOperationBinder binder, DynamicMetaObject arg)
{
ContractUtils.RequiresNotNull(binder, nameof(binder));
return binder.FallbackBinaryOperation(this, arg);
}
/// <summary>
/// Returns the enumeration of all dynamic member names.
/// </summary>
/// <returns>The list of dynamic member names.</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
public virtual IEnumerable<string> GetDynamicMemberNames()
{
return Array.Empty<string>();
}
/// <summary>
/// Returns the list of expressions represented by the <see cref="DynamicMetaObject"/> instances.
/// </summary>
/// <param name="objects">An array of <see cref="DynamicMetaObject"/> instances to extract expressions from.</param>
/// <returns>The array of expressions.</returns>
internal static Expression[] GetExpressions(DynamicMetaObject[] objects)
{
ContractUtils.RequiresNotNull(objects, nameof(objects));
Expression[] res = new Expression[objects.Length];
for (int i = 0; i < objects.Length; i++)
{
DynamicMetaObject mo = objects[i];
ContractUtils.RequiresNotNull(mo, nameof(objects));
Expression expr = mo.Expression;
ContractUtils.RequiresNotNull(expr, nameof(objects));
res[i] = expr;
}
return res;
}
/// <summary>
/// Creates a meta-object for the specified object.
/// </summary>
/// <param name="value">The object to get a meta-object for.</param>
/// <param name="expression">The expression representing this <see cref="DynamicMetaObject"/> during the dynamic binding process.</param>
/// <returns>
/// If the given object implements <see cref="IDynamicMetaObjectProvider"/> and is not a remote object from outside the current AppDomain,
/// returns the object's specific meta-object returned by <see cref="IDynamicMetaObjectProvider.GetMetaObject"/>. Otherwise a plain new meta-object
/// with no restrictions is created and returned.
/// </returns>
public static DynamicMetaObject Create(object value, Expression expression)
{
ContractUtils.RequiresNotNull(expression, nameof(expression));
IDynamicMetaObjectProvider ido = value as IDynamicMetaObjectProvider;
if (ido != null)
{
var idoMetaObject = ido.GetMetaObject(expression);
if (idoMetaObject == null ||
!idoMetaObject.HasValue ||
idoMetaObject.Value == null ||
(object)idoMetaObject.Expression != (object)expression)
{
throw Error.InvalidMetaObjectCreated(ido.GetType());
}
return idoMetaObject;
}
else
{
return new DynamicMetaObject(expression, BindingRestrictions.Empty, value);
}
}
}
}
| |
//==============================================================================
// TorqueLab -> MeshRiverEditor - River Manager - NodeData
// Copyright (c) 2015 All Right Reserved, http://nordiklab.com/
//------------------------------------------------------------------------------
//==============================================================================
//==============================================================================
// TerrainObject Functions
//==============================================================================
$RiverEd_WidthRange = "0 200";
$RiverEd_DepthRange = "0 100";
//==============================================================================
//RiverManager.updateNodeStack();
function RiverManager::updateNodeStack(%this) {
RiverEd_NodePillSampleStack.visible = 0;
RiverEd_NodePillStack.visible = 1;
%stack = RiverEd_NodePillStack;
%stack.visible = 1;
%stack.clear();
for(%i=0; %i<RiverManager.nodeCount; %i++) {
%this.addNodePillToStack(%i);
}
}
function RiverManager::addNodePillToStack(%this,%nodeId) {
%fieldData = RiverManager.nodeData[%nodeId];
%pos = getField(%fieldData,0);
%width = getField(%fieldData,1);
%depth = getField(%fieldData,2);
RiverManager.nodeListModeId = 1;
switch$(RiverManager.nodeListModeId) {
case "0":
%pill = cloneObject(RiverEd_NodePillLinkSample);
case "1":
%pill = cloneObject(RiverEd_NodePillSample);
%pill-->Width.setText(%width);
%pill-->Width.updateFriends();
%pill-->Width.pill = %pill;
%pill-->Width_slider.pill = %pill;
%pill-->Depth.setText(%width);
%pill-->Depth.updateFriends();
%pill-->Depth.pill = %pill;
%pill-->Depth_slider.pill = %pill;
%pill-->Width_slider.range = $RiverEd_WidthRange;
%pill-->Depth_slider.range = $RiverEd_DepthRange;
%pill-->PosX.text = %pos.x;
%pill-->PosY.text = %pos.y;
%pill-->PosZ.text = %pos.z;
%pill-->PosX.pill = %pill;
%pill-->PosY.pill = %pill;
%pill-->PosZ.pill = %pill;
%pill-->PosX.altCommand = "$ThisControl.onAltCommand();";
%pill-->PosY.altCommand = "$ThisControl.onAltCommand();";
%pill-->PosZ.altCommand = "$ThisControl.onAltCommand();";
%pill-->positionCtrl.visible = RiverManager.showPositionEdit;
case "2":
%pill = cloneObject(RiverEd_NodePillSample);
%pill-->Width.setText(%width);
%pill-->Width.updateFriends();
%pill-->Width.pill = %pill;
%pill-->Width_slider.pill = %pill;
%pill-->PosX.text = %pos.x;
%pill-->PosY.text = %pos.y;
%pill-->PosZ.text = %pos.z;
%pill-->PosX.pill = %pill;
%pill-->PosY.pill = %pill;
%pill-->PosZ.pill = %pill;
}
%pill-->Linked.text = " ";
%pill-->buttonNode.text = "Node #\c1"@%nodeId;
%pill-->buttonNode.command = "RiverManager.selectNode("@%nodeId@");";
%pill-->deleteButton.command = "RiverManager.deleteNodeId("@%nodeId@");";
%pill-->Linked.setStateOn(false);
%pill.superClass = "RiverEd_NodePill";
%pill.internalName = "NodePill_"@%nodeId;
%pill.nodeId = %nodeId;
%pill-->Linked.pill = %pill;
%pill.linkCheck = %pill-->Linked;
RiverEd_NodePillStack.add(%pill);
}
//==============================================================================
// Update Node
//==============================================================================
//==============================================================================
function RiverEd_SingleNodeEdit::onValidate(%this) {
%type = %this.internalName;
RiverManager.updateNodeSetting("",%type,%this.getText());
}
//------------------------------------------------------------------------------
//==============================================================================
function RiverManager::updateNodeSetting(%this,%node,%field,%value,%isLink) {
%this.noNodeUpdate = true;
if (%node $= "")
%node = RiverEditorGui.getSelectedNode();
else
RiverEditorGui.setSelectedNode(%node);
switch$(%field) {
case "width":
%width = RiverEditorGui.getNodeWidth();
if (!%isLink) {
%widthDiff = %value - %width;
}
if (%isLink && RiverManager.linkRelative) {
%newValue = %width + %value;
%value = %newValue;
}
RiverEditorGui.setNodeWidth(%value);
case "depth":
%depth = RiverEditorGui.getNodeDepth();
if (!%isLink) {
%depthDiff = %value - %depth;
}
if (%isLink && RiverManager.linkRelative) {
%newValue = %depth + %value;
%value = %newValue;
}
RiverEditorGui.setNodeDepth(%value);
case "PosX":
%position = RiverEditorGui.getNodePosition();
if (!%isLink)
%posDiff = %value - %position.x;
if (%isLink && RiverManager.linkRelative)
%position.x = %position.x + %value;
else
%position.x = %value;
RiverEditorGui.setNodePosition(%position);
case "PosY":
%position = RiverEditorGui.getNodePosition();
if (!%isLink)
%posDiff =%value - %position.x;
if (%isLink && RiverManager.linkRelative)
%position.y = %position.y + %value;
else
%position.y = %value;
RiverEditorGui.setNodePosition(%position);
case "PosZ":
%position = RiverEditorGui.getNodePosition();
if (!%isLink)
%posDiff = %value - %position.z;
if (%isLink && RiverManager.linkRelative)
%position.z = %position.z + %value;
else
%position.z = %value;
RiverEditorGui.setNodePosition(%position);
case "position":
if (%isLink && RiverManager.linkRelative) {
%position = RiverEditorGui.getNodePosition();
%value = VectorAdd(%position,%value);
} else {
%position = RiverEditorGui.getNodePosition();
%posDiff = VectorSub(%value,%position);
}
RiverEditorGui.setNodePosition(%value);
}
if ($RiverEd_UpdateLinkedNodes && !%isLink) {
foreach$(%nodeLink in RiverManager.linkedList) {
if (%nodeLink $= %node)
continue;
if (RiverManager.linkRelative) {
if (%posDiff !$= "") {
%value = %posDiff;
} else if (%widthDiff !$= "") {
%value = %widthDiff;
} else if (%depthDiff !$= "") {
%value = %depthDiff;
}
}
%this.updateNodeSetting(%nodeLink,%field,%value,true);
}
RiverEditorGui.setSelectedNode(%node);
}
%this.noNodeUpdate = false;
RiverManager.onNodeModified(%node,"Pill");
}
//------------------------------------------------------------------------------
//==============================================================================
function RiverManager::updateNodeCtrlSetting(%this,%ctrl) {
//%pill = RiverManager.getParentPill(%ctrl);
%pill = %ctrl.pill;
%node = %pill.nodeId;
%fields = strreplace(%ctrl.internalName,"_"," ");
%field = getWord(%fields,0);
%value = %ctrl.getTypeValue();
%ctrl.updateFriends();
%this.updateNodeSetting(%node,%field,%value);
}
//------------------------------------------------------------------------------
//==============================================================================
function RiverManager::getParentPill(%this,%ctrl) {
%attempt = 0;
while(%attempt < 10) {
%parent = %ctrl.parentGroup;
if (%parent.superClass $= "RiverEd_NodePill")
return %parent;
%ctrl = %parent;
%attempt++;
}
return "";
}
//------------------------------------------------------------------------------
//==============================================================================
function RiverEd_NodeSlider::onMouseDragged(%this) {
%value = mFloatLength(%this.getValue(),3);
%this.setValue(%value);
RiverManager.updateNodeCtrlSetting(%this);
}
//------------------------------------------------------------------------------
//==============================================================================
function RiverEd_NodeEdit::onValidate(%this) {
//RiverManager.updateNodeCtrlSetting(%this);
}
//------------------------------------------------------------------------------
//==============================================================================
function RiverEd_NodeEdit::onCommand(%this) {
//RiverManager.updateNodeCtrlSetting(%this);
}
//------------------------------------------------------------------------------
//==============================================================================
function RiverEd_NodeEdit::onAltCommand(%this) {
RiverManager.updateNodeCtrlSetting(%this);
}
//------------------------------------------------------------------------------
//==============================================================================
function RiverEd_NodeListCheck::onClick(%this) {
RiverManager.onNodeSelected();
}
//------------------------------------------------------------------------------
//==============================================================================
function RiverEd_MaterialSelect::setMaterial(%this,%materialName,%a1,%a2) {
devLog("RiverEd_MaterialSelect::setMaterial(%this,%materialName,%a1,%a2)",%this,%materialName,%a1,%a2);
%type = %this.internalName;
%River = RiverManager.currentRiver;
if (!isObject(%River))
return;
MeshRiverInspector.inspect(%River);
%River.setFieldValue(%type@"Material",%materialName);
MeshRiverInspector.refresh();
MeshRiverInspector.apply();
%textEdit = MeshRiverEditorOptionsWindow.findObjectByInternalName(%type@"Material",true);
%textEdit.setText(%materialName);
devLog("Select Material for:",%type,"Is:",%materialName);
}
//------------------------------------------------------------------------------
//==============================================================================
function RiverEd_MaterialEdit::onValidate(%this) {
%type = %this.internalName;
devLog("Select Material for:",%type,"Is:",%this.getText());
}
//------------------------------------------------------------------------------
| |
using System;
using System.Runtime.InteropServices;
namespace Vanara.PInvoke
{
/// <summary>Items from Dhcpcsvc6.dll and Dhcpcsvc.dll.</summary>
public static partial class Dhcp
{
/// <summary>De-register handle that is an event</summary>
public const uint DHCPCAPI_DEREGISTER_HANDLE_EVENT = 0x01;
/// <summary>Handle returned is to an event</summary>
public const uint DHCPCAPI_REGISTER_HANDLE_EVENT = 0x01;
private const string Lib_Dhcp = "dhcpcsvc.dll";
/// <summary>
/// DHCP options. See <a href="https://kb.isc.org/docs/isc-dhcp-44-manual-pages-dhcp-options">ISC DHCP 4.4 Manual Pages -
/// dhcp-options</a> for some details.
/// </summary>
[PInvokeData("dhcpcsdk.h")]
public enum DHCP_OPTION_ID : uint
{
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member
OPTION_PAD = 0,
OPTION_SUBNET_MASK = 1,
OPTION_TIME_OFFSET = 2,
OPTION_ROUTER_ADDRESS = 3,
OPTION_TIME_SERVERS = 4,
OPTION_IEN116_NAME_SERVERS = 5,
OPTION_DOMAIN_NAME_SERVERS = 6,
OPTION_LOG_SERVERS = 7,
OPTION_COOKIE_SERVERS = 8,
OPTION_LPR_SERVERS = 9,
OPTION_IMPRESS_SERVERS = 10,
OPTION_RLP_SERVERS = 11,
OPTION_HOST_NAME = 12,
OPTION_BOOT_FILE_SIZE = 13,
OPTION_MERIT_DUMP_FILE = 14,
OPTION_DOMAIN_NAME = 15,
OPTION_SWAP_SERVER = 16,
OPTION_ROOT_DISK = 17,
OPTION_EXTENSIONS_PATH = 18,
OPTION_BE_A_ROUTER = 19,
OPTION_NON_LOCAL_SOURCE_ROUTING = 20,
OPTION_POLICY_FILTER_FOR_NLSR = 21,
OPTION_MAX_REASSEMBLY_SIZE = 22,
OPTION_DEFAULT_TTL = 23,
OPTION_PMTU_AGING_TIMEOUT = 24,
OPTION_PMTU_PLATEAU_TABLE = 25,
OPTION_MTU = 26,
OPTION_ALL_SUBNETS_MTU = 27,
OPTION_BROADCAST_ADDRESS = 28,
OPTION_PERFORM_MASK_DISCOVERY = 29,
OPTION_BE_A_MASK_SUPPLIER = 30,
OPTION_PERFORM_ROUTER_DISCOVERY = 31,
OPTION_ROUTER_SOLICITATION_ADDR = 32,
OPTION_STATIC_ROUTES = 33,
OPTION_TRAILERS = 34,
OPTION_ARP_CACHE_TIMEOUT = 35,
OPTION_ETHERNET_ENCAPSULATION = 36,
OPTION_TTL = 37,
OPTION_KEEP_ALIVE_INTERVAL = 38,
OPTION_KEEP_ALIVE_DATA_SIZE = 39,
OPTION_NETWORK_INFO_SERVICE_DOM = 40,
OPTION_NETWORK_INFO_SERVERS = 41,
OPTION_NETWORK_TIME_SERVERS = 42,
OPTION_VENDOR_SPEC_INFO = 43,
OPTION_NETBIOS_NAME_SERVER = 44,
OPTION_NETBIOS_DATAGRAM_SERVER = 45,
OPTION_NETBIOS_NODE_TYPE = 46,
OPTION_NETBIOS_SCOPE_OPTION = 47,
OPTION_XWINDOW_FONT_SERVER = 48,
OPTION_XWINDOW_DISPLAY_MANAGER = 49,
OPTION_REQUESTED_ADDRESS = 50,
OPTION_LEASE_TIME = 51,
OPTION_OK_TO_OVERLAY = 52,
OPTION_MESSAGE_TYPE = 53,
OPTION_SERVER_IDENTIFIER = 54,
OPTION_PARAMETER_REQUEST_LIST = 55,
OPTION_MESSAGE = 56,
OPTION_MESSAGE_LENGTH = 57,
OPTION_RENEWAL_TIME = 58,
OPTION_REBIND_TIME = 59,
OPTION_CLIENT_CLASS_INFO = 60,
OPTION_CLIENT_ID = 61,
OPTION_TFTP_SERVER_NAME = 66,
OPTION_BOOTFILE_NAME = 67,
OPTION_MSFT_IE_PROXY = 252,
OPTION_END = 255,
#pragma warning restore CS1591 // Missing XML comment for publicly visible type or member
}
/// <summary>Flags that specify the data being requested.</summary>
[PInvokeData("dhcpcsdk.h", MSDNShortId = "NF:dhcpcsdk.DhcpRequestParams")]
[Flags]
public enum DHCPCAPI_REQUEST
{
/// <summary>The request is persisted but no options are fetched.</summary>
DHCPCAPI_REQUEST_PERSISTENT = 0x01,
/// <summary>Options will be fetched from the server.</summary>
DHCPCAPI_REQUEST_SYNCHRONOUS = 0x02,
/// <summary>Request and return, set event on completion.</summary>
DHCPCAPI_REQUEST_ASYNCHRONOUS = 0x04,
/// <summary>Cancel request.</summary>
DHCPCAPI_REQUEST_CANCEL = 0x08,
}
/// <summary>
/// The <c>DhcpCApiCleanup</c> function enables DHCP to properly clean up resources allocated throughout the use of DHCP function
/// calls. The <c>DhcpCApiCleanup</c> function must only be called if a previous call to DhcpCApiInitialize executed successfully.
/// </summary>
/// <returns>None</returns>
// https://docs.microsoft.com/en-us/windows/win32/api/dhcpcsdk/nf-dhcpcsdk-dhcpcapicleanup void DhcpCApiCleanup();
[DllImport(Lib_Dhcp, SetLastError = false, ExactSpelling = true)]
[PInvokeData("dhcpcsdk.h", MSDNShortId = "NF:dhcpcsdk.DhcpCApiCleanup")]
public static extern void DhcpCApiCleanup();
/// <summary>
/// The <c>DhcpCApiInitialize</c> function must be the first function call made by users of DHCP; it prepares the system for all
/// other DHCP function calls. Other DHCP functions should only be called if the <c>DhcpCApiInitialize</c> function executes successfully.
/// </summary>
/// <param name="Version">Pointer to the DHCP version implemented by the client.</param>
/// <returns>Returns ERROR_SUCCESS upon successful completion.</returns>
// https://docs.microsoft.com/en-us/windows/win32/api/dhcpcsdk/nf-dhcpcsdk-dhcpcapiinitialize DWORD DhcpCApiInitialize( LPDWORD
// Version );
[DllImport(Lib_Dhcp, SetLastError = false, ExactSpelling = true)]
[PInvokeData("dhcpcsdk.h", MSDNShortId = "NF:dhcpcsdk.DhcpCApiInitialize")]
public static extern Win32Error DhcpCApiInitialize(out uint Version);
/// <summary>
/// The <c>DhcpDeRegisterParamChange</c> function releases resources associated with previously registered event notifications, and
/// closes the associated event handle.
/// </summary>
/// <param name="Flags">Reserved. Must be set to zero.</param>
/// <param name="Reserved">Reserved. Must be set to <c>NULL</c>.</param>
/// <param name="Event">
/// Must be the same value as the <c>HANDLE</c> variable in the DhcpRegisterParamChange function call for which the client is
/// deregistering event notification.
/// </param>
/// <returns>Returns ERROR_SUCCESS upon successful completion. Otherwise, returns Windows error codes.</returns>
/// <remarks>
/// The <c>DhcpDeRegisterParamChange</c> function must be made subsequent to an associated DhcpRegisterParamChange function call,
/// and the Flags parameter and the <c>HANDLE</c> variable passed in the Event parameter to <c>DhcpDeRegisterParamChange</c> must
/// match corresponding Flags parameter and the <c>HANDLE</c> variable of the previous and associated <c>DhcpRegisterParamChange</c>
/// function call.
/// </remarks>
// https://docs.microsoft.com/en-us/windows/win32/api/dhcpcsdk/nf-dhcpcsdk-dhcpderegisterparamchange DWORD
// DhcpDeRegisterParamChange( DWORD Flags, LPVOID Reserved, LPVOID Event );
[DllImport(Lib_Dhcp, SetLastError = false, ExactSpelling = true)]
[PInvokeData("dhcpcsdk.h", MSDNShortId = "NF:dhcpcsdk.DhcpDeRegisterParamChange")]
public static extern Win32Error DhcpDeRegisterParamChange([Optional] uint Flags, [Optional] IntPtr Reserved, HEVENT Event);
/// <summary>The <c>DhcpGetOriginalSubnetMask</c> is used to get the subnet mask of any given adapter name.</summary>
/// <param name="sAdapterName">[in] Contains the name of the local DHCP-enabled adapter for which the subnet mask is being retrieved.</param>
/// <param name="dwSubnetMask">[out] Pointer to the retrieved subnet mask.</param>
/// <returns>
/// <para>This function always returns 0.</para>
/// <para>Failure is indicated by a return value of 0 for the dwSubnetMask parameter.</para>
/// <list type="table">
/// <listheader>
/// <term>Return code</term>
/// <term>Description</term>
/// </listheader>
/// <item>
/// <description>ERROR_INVALID_PARAMETER</description>
/// <description>Returned if the sAdapterName parameter is invalid.</description>
/// </item>
/// </list>
/// </returns>
// https://docs.microsoft.com/en-us/previous-versions/bb656318(v=vs.85)
// void APIENTRY DhcpGetOriginalSubnetMask( __in LPCWSTR sAdapterName, __out DWORD *dwSubnetMask );
[DllImport(Lib_Dhcp, SetLastError = false, ExactSpelling = true)]
[PInvokeData("Dhcpcsdk.h")]
public static extern void DhcpGetOriginalSubnetMask([MarshalAs(UnmanagedType.LPWStr)] string sAdapterName, out DHCP_IP_ADDRESS dwSubnetMask);
/// <summary>
/// The <c>DhcpRegisterParamChange</c> function enables clients to register for notification of changes in DHCP configuration parameters.
/// </summary>
/// <param name="Flags">
/// Reserved. Must be set to DHCPCAPI_REGISTER_HANDLE_EVENT. If it is not set to this flag value, the API call will not be successful.
/// </param>
/// <param name="Reserved">Reserved. Must be set to <c>NULL</c>.</param>
/// <param name="AdapterName">GUID of the adapter for which event notification is being requested. Must be under 256 characters.</param>
/// <param name="ClassId">Reserved. Must be set to <c>NULL</c>.</param>
/// <param name="Params">
/// Parameters for which the client is interested in registering for notification, in the form of a DHCPCAPI_PARAMS_ARRAY structure.
/// </param>
/// <param name="Handle">
/// Attributes of Handle are determined by the value of Flags. In version 2 of the DHCP API, Flags must be set to
/// DHCPCAPI_REGISTER_HANDLE_EVENT, and therefore, Handle must be a pointer to a <c>HANDLE</c> variable that will hold the handle to
/// a Windows event that gets signaled when parameters specified in Params change. Note that this <c>HANDLE</c> variable is used in
/// a subsequent call to the <c>DhcpDeRegisterParamChange</c> function to deregister event notifications associated with this
/// particular call to the <c>DhcpRegisterParamChange</c> function.
/// </param>
/// <returns>
/// <para>Returns ERROR_SUCCESS upon successful completion. Otherwise, returns Windows error codes.</para>
/// <list type="table">
/// <listheader>
/// <term>Return code</term>
/// <term>Description</term>
/// </listheader>
/// <item>
/// <term>ERROR_INVALID_PARAMETER</term>
/// <term>Returned if the AdapterName parameter is over 256 characters long.</term>
/// </item>
/// </list>
/// </returns>
/// <remarks>
/// Version 2 of the DHCP Client API provides only event-based notification. With event-based notification in DHCP, clients enable
/// notification by having Handle point to a variable that, upon successful return, holds the EVENT handles that are signaled
/// whenever changes occur to the parameters requested in Params.
/// </remarks>
// https://docs.microsoft.com/en-us/windows/win32/api/dhcpcsdk/nf-dhcpcsdk-dhcpregisterparamchange DWORD DhcpRegisterParamChange(
// DWORD Flags, LPVOID Reserved, LPWSTR AdapterName, LPDHCPCAPI_CLASSID ClassId, DHCPCAPI_PARAMS_ARRAY Params, LPVOID Handle );
[DllImport(Lib_Dhcp, SetLastError = false, ExactSpelling = true)]
[PInvokeData("dhcpcsdk.h", MSDNShortId = "NF:dhcpcsdk.DhcpRegisterParamChange")]
public static extern Win32Error DhcpRegisterParamChange(uint Flags, [Optional] IntPtr Reserved, [MarshalAs(UnmanagedType.LPWStr)] string AdapterName,
[Optional] IntPtr ClassId, DHCPCAPI_PARAMS_ARRAY Params, out HEVENT Handle);
/// <summary>The <c>DhcpRemoveDNSRegistrations</c> function removes all DHCP-initiated DNS registrations for the client.</summary>
/// <returns>Returns ERROR_SUCCESS upon successful completion.</returns>
// https://docs.microsoft.com/en-us/windows/win32/api/dhcpcsdk/nf-dhcpcsdk-dhcpremovednsregistrations DWORD DhcpRemoveDNSRegistrations();
[DllImport(Lib_Dhcp, SetLastError = false, ExactSpelling = true)]
[PInvokeData("dhcpcsdk.h", MSDNShortId = "NF:dhcpcsdk.DhcpRemoveDNSRegistrations")]
public static extern Win32Error DhcpRemoveDNSRegistrations();
/// <summary>
/// The <c>DhcpRequestParams</c> function enables callers to synchronously, or synchronously and persistently obtain DHCP data from
/// a DHCP server.
/// </summary>
/// <param name="Flags">
/// <para>
/// Flags that specify the data being requested. This parameter is optional. The following possible values are supported and are not
/// mutually exclusive:
/// </para>
/// <list type="table">
/// <listheader>
/// <term>Value</term>
/// <term>Meaning</term>
/// </listheader>
/// <item>
/// <term>DHCPCAPI_REQUEST_PERSISTENT</term>
/// <term>The request is persisted but no options are fetched.</term>
/// </item>
/// <item>
/// <term>DHCPCAPI_REQUEST_SYNCHRONOUS</term>
/// <term>Options will be fetched from the server.</term>
/// </item>
/// </list>
/// </param>
/// <param name="Reserved">Reserved for future use. Must be set to <c>NULL</c>.</param>
/// <param name="AdapterName">GUID of the adapter on which requested data is being made. Must be under 256 characters.</param>
/// <param name="ClassId">
/// Class identifier (ID) that should be used if DHCP INFORM messages are being transmitted onto the network. This parameter is optional.
/// </param>
/// <param name="SendParams">
/// Optional data to be requested, in addition to the data requested in the RecdParams array. The SendParams parameter cannot
/// contain any of the standard options that the DHCP client sends by default.
/// </param>
/// <param name="RecdParams">
/// Array of DHCP data the caller is interested in receiving. This array must be empty prior to the <c>DhcpRequestParams</c>
/// function call.
/// </param>
/// <param name="Buffer">Buffer used for storing the data associated with requests made in RecdParams.</param>
/// <param name="pSize">
/// <para>Size of Buffer.</para>
/// <para>
/// Required size of the buffer, if it is insufficiently sized to hold the data, otherwise indicates size of the buffer which was
/// successfully filled.
/// </para>
/// </param>
/// <param name="RequestIdStr">
/// Application identifier (ID) used to facilitate a persistent request. Must be a printable string with no special characters
/// (commas, backslashes, colons, or other illegal characters may not be used). The specified application identifier (ID) is used in
/// a subsequent <c>DhcpUndoRequestParams</c> function call to clear the persistent request, as necessary.
/// </param>
/// <returns>
/// <para>Returns ERROR_SUCCESS upon successful completion.</para>
/// <para>
/// Upon return, RecdParams is filled with pointers to requested data, with corresponding data placed in Buffer. If pSize indicates
/// that Buffer has insufficient space to store returned data, the <c>DhcpRequestParams</c> function returns ERROR_MORE_DATA, and
/// returns the required buffer size in pSize. Note that the required size of Buffer may increase during the time that elapses
/// between the initial function call's return and a subsequent call; therefore, the required size of Buffer (indicated in pSize)
/// provides an indication of the approximate size required of Buffer, rather than guaranteeing that subsequent calls will return
/// successfully if Buffer is set to the size indicated in pSize.
/// </para>
/// <para>Other errors return appropriate Windows error codes.</para>
/// <list type="table">
/// <listheader>
/// <term>Return code</term>
/// <term>Description</term>
/// </listheader>
/// <item>
/// <term>ERROR_INVALID_PARAMETER</term>
/// <term>Returned if the AdapterName parameter is over 256 characters long.</term>
/// </item>
/// <item>
/// <term>ERROR_BUFFER_OVERFLOW</term>
/// <term>Returned if the AdapterName parameter is over 256 characters long.</term>
/// </item>
/// </list>
/// </returns>
/// <remarks>
/// <para>
/// DHCP clients store data obtained from a DHCP server in their local cache. If the DHCP client cache contains all data requested
/// in the RecdParams array of a <c>DhcpRequestParams</c> function call, the client returns data from its cache. If requested data
/// is not available in the client cache, the client processes the <c>DhcpRequestParams</c> function call by submitting a
/// DHCP-INFORM message to the DHCP server.
/// </para>
/// <para>
/// When the client submits a DHCP-INFORM message to the DHCP server, it includes any requests provided in the optional SendParams
/// parameter, and provides the Class identifier (ID) specified in the ClassId parameter, if provided.
/// </para>
/// <para>
/// Clients can also specify that DHCP data be retrieved from the DHCP server each time the DHCP client boots, which is considered a
/// persistent request. To enable persistent requests, the caller must specify the RequestIdStr parameter, and also specify the
/// additional <c>DHCPAPI_REQUEST_PERSISTENT</c> flag in the dwFlags parameter. This persistent request capability is especially
/// useful when clients need to automatically request application-critical information at each boot. To disable a persist request,
/// clients must call the function.
/// </para>
/// <para>
/// <c>Note</c> The callers of this API must not make blocking calls to this API, since it can take up to a maximum of 2 minutes to
/// return a code or status. UI behaviors in particular should not block on the return of this call, since it can introduce a
/// significant delay in UI response time.
/// </para>
/// <para>For more information about DHCP INFORM messages, and other standards-based information about DHCP, consult DHCP Standards.</para>
/// <para>To see the <c>DhcpRequestParams</c> function in use, see DHCP Examples.</para>
/// </remarks>
// https://docs.microsoft.com/en-us/windows/win32/api/dhcpcsdk/nf-dhcpcsdk-dhcprequestparams DWORD DhcpRequestParams( DWORD Flags,
// LPVOID Reserved, LPWSTR AdapterName, LPDHCPCAPI_CLASSID ClassId, DHCPCAPI_PARAMS_ARRAY SendParams, DHCPCAPI_PARAMS_ARRAY
// RecdParams, LPBYTE Buffer, LPDWORD pSize, LPWSTR RequestIdStr );
[DllImport(Lib_Dhcp, SetLastError = false, ExactSpelling = true)]
[PInvokeData("dhcpcsdk.h", MSDNShortId = "NF:dhcpcsdk.DhcpRequestParams")]
public static extern Win32Error DhcpRequestParams([Optional] DHCPCAPI_REQUEST Flags, [In, Optional] IntPtr Reserved, [MarshalAs(UnmanagedType.LPWStr)] string AdapterName,
in DHCPCAPI_CLASSID ClassId, DHCPCAPI_PARAMS_ARRAY SendParams, DHCPCAPI_PARAMS_ARRAY RecdParams, [Out] IntPtr Buffer, ref uint pSize, [Optional, MarshalAs(UnmanagedType.LPWStr)] string RequestIdStr);
/// <summary>
/// The <c>DhcpRequestParams</c> function enables callers to synchronously, or synchronously and persistently obtain DHCP data from
/// a DHCP server.
/// </summary>
/// <param name="Flags">
/// <para>
/// Flags that specify the data being requested. This parameter is optional. The following possible values are supported and are not
/// mutually exclusive:
/// </para>
/// <list type="table">
/// <listheader>
/// <term>Value</term>
/// <term>Meaning</term>
/// </listheader>
/// <item>
/// <term>DHCPCAPI_REQUEST_PERSISTENT</term>
/// <term>The request is persisted but no options are fetched.</term>
/// </item>
/// <item>
/// <term>DHCPCAPI_REQUEST_SYNCHRONOUS</term>
/// <term>Options will be fetched from the server.</term>
/// </item>
/// </list>
/// </param>
/// <param name="Reserved">Reserved for future use. Must be set to <c>NULL</c>.</param>
/// <param name="AdapterName">GUID of the adapter on which requested data is being made. Must be under 256 characters.</param>
/// <param name="ClassId">
/// Class identifier (ID) that should be used if DHCP INFORM messages are being transmitted onto the network. This parameter is optional.
/// </param>
/// <param name="SendParams">
/// Optional data to be requested, in addition to the data requested in the RecdParams array. The SendParams parameter cannot
/// contain any of the standard options that the DHCP client sends by default.
/// </param>
/// <param name="RecdParams">
/// Array of DHCP data the caller is interested in receiving. This array must be empty prior to the <c>DhcpRequestParams</c>
/// function call.
/// </param>
/// <param name="Buffer">Buffer used for storing the data associated with requests made in RecdParams.</param>
/// <param name="pSize">
/// <para>Size of Buffer.</para>
/// <para>
/// Required size of the buffer, if it is insufficiently sized to hold the data, otherwise indicates size of the buffer which was
/// successfully filled.
/// </para>
/// </param>
/// <param name="RequestIdStr">
/// Application identifier (ID) used to facilitate a persistent request. Must be a printable string with no special characters
/// (commas, backslashes, colons, or other illegal characters may not be used). The specified application identifier (ID) is used in
/// a subsequent <c>DhcpUndoRequestParams</c> function call to clear the persistent request, as necessary.
/// </param>
/// <returns>
/// <para>Returns ERROR_SUCCESS upon successful completion.</para>
/// <para>
/// Upon return, RecdParams is filled with pointers to requested data, with corresponding data placed in Buffer. If pSize indicates
/// that Buffer has insufficient space to store returned data, the <c>DhcpRequestParams</c> function returns ERROR_MORE_DATA, and
/// returns the required buffer size in pSize. Note that the required size of Buffer may increase during the time that elapses
/// between the initial function call's return and a subsequent call; therefore, the required size of Buffer (indicated in pSize)
/// provides an indication of the approximate size required of Buffer, rather than guaranteeing that subsequent calls will return
/// successfully if Buffer is set to the size indicated in pSize.
/// </para>
/// <para>Other errors return appropriate Windows error codes.</para>
/// <list type="table">
/// <listheader>
/// <term>Return code</term>
/// <term>Description</term>
/// </listheader>
/// <item>
/// <term>ERROR_INVALID_PARAMETER</term>
/// <term>Returned if the AdapterName parameter is over 256 characters long.</term>
/// </item>
/// <item>
/// <term>ERROR_BUFFER_OVERFLOW</term>
/// <term>Returned if the AdapterName parameter is over 256 characters long.</term>
/// </item>
/// </list>
/// </returns>
/// <remarks>
/// <para>
/// DHCP clients store data obtained from a DHCP server in their local cache. If the DHCP client cache contains all data requested
/// in the RecdParams array of a <c>DhcpRequestParams</c> function call, the client returns data from its cache. If requested data
/// is not available in the client cache, the client processes the <c>DhcpRequestParams</c> function call by submitting a
/// DHCP-INFORM message to the DHCP server.
/// </para>
/// <para>
/// When the client submits a DHCP-INFORM message to the DHCP server, it includes any requests provided in the optional SendParams
/// parameter, and provides the Class identifier (ID) specified in the ClassId parameter, if provided.
/// </para>
/// <para>
/// Clients can also specify that DHCP data be retrieved from the DHCP server each time the DHCP client boots, which is considered a
/// persistent request. To enable persistent requests, the caller must specify the RequestIdStr parameter, and also specify the
/// additional <c>DHCPAPI_REQUEST_PERSISTENT</c> flag in the dwFlags parameter. This persistent request capability is especially
/// useful when clients need to automatically request application-critical information at each boot. To disable a persist request,
/// clients must call the function.
/// </para>
/// <para>
/// <c>Note</c> The callers of this API must not make blocking calls to this API, since it can take up to a maximum of 2 minutes to
/// return a code or status. UI behaviors in particular should not block on the return of this call, since it can introduce a
/// significant delay in UI response time.
/// </para>
/// <para>For more information about DHCP INFORM messages, and other standards-based information about DHCP, consult DHCP Standards.</para>
/// <para>To see the <c>DhcpRequestParams</c> function in use, see DHCP Examples.</para>
/// </remarks>
// https://docs.microsoft.com/en-us/windows/win32/api/dhcpcsdk/nf-dhcpcsdk-dhcprequestparams DWORD DhcpRequestParams( DWORD Flags,
// LPVOID Reserved, LPWSTR AdapterName, LPDHCPCAPI_CLASSID ClassId, DHCPCAPI_PARAMS_ARRAY SendParams, DHCPCAPI_PARAMS_ARRAY
// RecdParams, LPBYTE Buffer, LPDWORD pSize, LPWSTR RequestIdStr );
[DllImport(Lib_Dhcp, SetLastError = false, ExactSpelling = true)]
[PInvokeData("dhcpcsdk.h", MSDNShortId = "NF:dhcpcsdk.DhcpRequestParams")]
public static extern Win32Error DhcpRequestParams([Optional] DHCPCAPI_REQUEST Flags, [In, Optional] IntPtr Reserved, [MarshalAs(UnmanagedType.LPWStr)] string AdapterName,
[In, Optional] IntPtr ClassId, DHCPCAPI_PARAMS_ARRAY SendParams, DHCPCAPI_PARAMS_ARRAY RecdParams, [Out] IntPtr Buffer, ref uint pSize, [Optional, MarshalAs(UnmanagedType.LPWStr)] string RequestIdStr);
/// <summary>
/// The <c>DhcpUndoRequestParams</c> function removes persistent requests previously made with a <c>DhcpRequestParams</c> function call.
/// </summary>
/// <param name="Flags">Reserved. Must be zero.</param>
/// <param name="Reserved">Reserved for future use. Must be set to <c>NULL</c>.</param>
/// <param name="AdapterName">
/// <para>GUID of the adapter for which information is no longer required. Must be under 256 characters.</para>
/// <para><c>Note</c> This parameter is no longer used.</para>
/// </param>
/// <param name="RequestIdStr">
/// Application identifier (ID) originally used to make a persistent request. This string must match the RequestIdStr parameter used
/// in the <c>DhcpRequestParams</c> function call that obtained the corresponding persistent request. Note that this must match the
/// previous application identifier (ID) used, and must be a printable string with no special characters (commas, backslashes,
/// colons, or other illegal characters may not be used).
/// </param>
/// <returns>Returns ERROR_SUCCESS upon successful completion. Otherwise, returns a Windows error code.</returns>
/// <remarks>
/// Persistent requests are typically made by the setup or installer process associated with the application. When appropriate, the
/// setup or installer process would likely make the <c>DhcpUndoRequestParams</c> function call to cancel its associated persistent request.
/// </remarks>
// https://docs.microsoft.com/en-us/windows/win32/api/dhcpcsdk/nf-dhcpcsdk-dhcpundorequestparams DWORD DhcpUndoRequestParams( DWORD
// Flags, LPVOID Reserved, LPWSTR AdapterName, LPWSTR RequestIdStr );
[DllImport(Lib_Dhcp, SetLastError = false, ExactSpelling = true)]
[PInvokeData("dhcpcsdk.h", MSDNShortId = "NF:dhcpcsdk.DhcpUndoRequestParams")]
public static extern Win32Error DhcpUndoRequestParams([Optional] uint Flags, [In, Optional] IntPtr Reserved, [MarshalAs(UnmanagedType.LPWStr)] string AdapterName, [Optional, MarshalAs(UnmanagedType.LPWStr)] string RequestIdStr);
/// <summary>Represents an 8-byte IP v4 address.</summary>
[PInvokeData("dhcpsapi.h")]
[StructLayout(LayoutKind.Sequential)]
public struct DHCP_IP_ADDRESS
{
/// <summary>The underlying value.</summary>
public uint value;
/// <summary>Initializes a new instance of the <see cref="DHCP_IP_ADDRESS"/> struct from a UInt32/DWORD.</summary>
/// <param name="val">The value.</param>
public DHCP_IP_ADDRESS(uint val = 0) => value = val;
/// <summary>Initializes a new instance of the <see cref="DHCP_IP_ADDRESS"/> struct from an <see cref="System.Net.IPAddress"/>.</summary>
/// <param name="ipaddr">The <see cref="System.Net.IPAddress"/> value.</param>
/// <exception cref="InvalidCastException"></exception>
public DHCP_IP_ADDRESS(System.Net.IPAddress ipaddr)
{
if (ipaddr is null) value = 0;
if (ipaddr.AddressFamily != System.Net.Sockets.AddressFamily.InterNetwork)
throw new InvalidCastException();
#pragma warning disable CS0618 // Type or member is obsolete
value = (uint)ipaddr.Address;
#pragma warning restore CS0618 // Type or member is obsolete
}
/// <summary>Performs an explicit conversion from <see cref="DHCP_IP_ADDRESS"/> to <see cref="System.Net.IPAddress"/>.</summary>
/// <param name="addr">The DWORD based address.</param>
/// <returns>The resulting <see cref="System.Net.IPAddress"/> instance from the conversion.</returns>
public static explicit operator System.Net.IPAddress(DHCP_IP_ADDRESS addr) =>
new System.Net.IPAddress(BitConverter.GetBytes(addr.value));
/// <summary>Performs an implicit conversion from <see cref="System.Net.IPAddress"/> to <see cref="DHCP_IP_ADDRESS"/>.</summary>
/// <param name="addr">The <see cref="System.Net.IPAddress"/> value.</param>
/// <returns>The resulting <see cref="DHCP_IP_ADDRESS"/> instance from the conversion.</returns>
public static implicit operator DHCP_IP_ADDRESS(System.Net.IPAddress addr) => new DHCP_IP_ADDRESS(addr);
/// <summary>Performs an implicit conversion from <see cref="System.UInt32"/> to <see cref="DHCP_IP_ADDRESS"/>.</summary>
/// <param name="addr">The address as four bytes.</param>
/// <returns>The resulting <see cref="DHCP_IP_ADDRESS"/> instance from the conversion.</returns>
public static implicit operator DHCP_IP_ADDRESS(uint addr) => new DHCP_IP_ADDRESS(addr);
/// <summary>Converts this address to standard notation.</summary>
/// <returns>A <see cref="System.String"/> that represents this instance.</returns>
public override string ToString() => ((System.Net.IPAddress)this).ToString();
/// <summary>Returns a hash code for this instance.</summary>
/// <returns>A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.</returns>
public override int GetHashCode() => value.GetHashCode();
}
/// <summary>The <c>DHCPAPI_PARAMS</c> structure is used to request DHCP parameters.</summary>
// https://docs.microsoft.com/en-us/windows/win32/api/dhcpcsdk/ns-dhcpcsdk-dhcpapi_params typedef struct _DHCPAPI_PARAMS { ULONG
// Flags; ULONG OptionId; BOOL IsVendor; #if ... LPBYTE Data; #else LPBYTE Data; #endif DWORD nBytesData; } DHCPAPI_PARAMS,
// *PDHCPAPI_PARAMS, *LPDHCPAPI_PARAMS, DHCPCAPI_PARAMS, *PDHCPCAPI_PARAMS, *LPDHCPCAPI_PARAMS;
[PInvokeData("dhcpcsdk.h", MSDNShortId = "NS:dhcpcsdk._DHCPAPI_PARAMS")]
[StructLayout(LayoutKind.Sequential)]
public struct DHCPAPI_PARAMS
{
/// <summary>Reserved. Must be set to zero.</summary>
public uint Flags;
/// <summary>Identifier for the DHCP parameter being requested.</summary>
public DHCP_OPTION_ID OptionId;
/// <summary>Specifies whether the DHCP parameter is vendor-specific. Set to <c>TRUE</c> if the parameter is vendor-specific.</summary>
[MarshalAs(UnmanagedType.Bool)]
public bool IsVendor;
/// <summary>Pointer to the parameter data.</summary>
public IntPtr Data;
/// <summary>Size of the data pointed to by <c>Data</c>, in bytes.</summary>
public uint nBytesData;
}
/// <summary>The <c>DHCPCAPI_CLASSID</c> structure defines a client Class ID.</summary>
// https://docs.microsoft.com/en-us/windows/win32/api/dhcpcsdk/ns-dhcpcsdk-dhcpcapi_classid typedef struct _DHCPCAPI_CLASSID { ULONG
// Flags; #if ... LPBYTE Data; #else LPBYTE Data; #endif ULONG nBytesData; } DHCPCAPI_CLASSID, *PDHCPCAPI_CLASSID, *LPDHCPCAPI_CLASSID;
[PInvokeData("dhcpcsdk.h", MSDNShortId = "NS:dhcpcsdk._DHCPCAPI_CLASSID")]
[StructLayout(LayoutKind.Sequential)]
public struct DHCPCAPI_CLASSID
{
/// <summary>Reserved. Must be set to zero.</summary>
public uint Flags;
/// <summary>Class ID binary data.</summary>
public IntPtr Data;
/// <summary>Size of <c>Data</c>, in bytes.</summary>
public uint nBytesData;
}
/// <summary>The <c>DHCPCAPI_PARAMS_ARRAY</c> structure stores an array of DHCPAPI_PARAMS structures used to query DHCP parameters.</summary>
// https://docs.microsoft.com/en-us/windows/win32/api/dhcpcsdk/ns-dhcpcsdk-dhcpcapi_params_array typedef struct
// _DHCPCAPI_PARAMS_ARARAY { ULONG nParams; #if ... LPDHCPCAPI_PARAMS Params; #else LPDHCPCAPI_PARAMS Params; #endif }
// DHCPCAPI_PARAMS_ARRAY, *PDHCPCAPI_PARAMS_ARRAY, *LPDHCPCAPI_PARAMS_ARRAY;
[PInvokeData("dhcpcsdk.h", MSDNShortId = "NS:dhcpcsdk._DHCPCAPI_PARAMS_ARARAY")]
[StructLayout(LayoutKind.Sequential)]
public struct DHCPCAPI_PARAMS_ARRAY
{
/// <summary>Number of elements in the <c>Params</c> array.</summary>
public uint nParams;
/// <summary>Array of DHCPAPI_PARAMS structures.</summary>
public IntPtr Params;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace BullsAndCows.Web.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
/*
* Licensed to the 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 Apache.Ignite.Core.Impl.Datastream
{
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using Apache.Ignite.Core.Datastream;
using Apache.Ignite.Core.Impl.Binary;
using Apache.Ignite.Core.Impl.Common;
using Apache.Ignite.Core.Impl.Unmanaged;
using UU = Apache.Ignite.Core.Impl.Unmanaged.UnmanagedUtils;
/// <summary>
/// Data streamer internal interface to get rid of generics.
/// </summary>
internal interface IDataStreamer
{
/// <summary>
/// Callback invoked on topology size change.
/// </summary>
/// <param name="topVer">New topology version.</param>
/// <param name="topSize">New topology size.</param>
void TopologyChange(long topVer, int topSize);
}
/// <summary>
/// Data streamer implementation.
/// </summary>
internal class DataStreamerImpl<TK, TV> : PlatformDisposableTarget, IDataStreamer, IDataStreamer<TK, TV>
{
#pragma warning disable 0420
/** Policy: continue. */
internal const int PlcContinue = 0;
/** Policy: close. */
internal const int PlcClose = 1;
/** Policy: cancel and close. */
internal const int PlcCancelClose = 2;
/** Policy: flush. */
internal const int PlcFlush = 3;
/** Operation: update. */
private const int OpUpdate = 1;
/** Operation: set receiver. */
private const int OpReceiver = 2;
/** Cache name. */
private readonly string _cacheName;
/** Lock. */
private readonly ReaderWriterLockSlim _rwLock = new ReaderWriterLockSlim();
/** Closed event. */
private readonly ManualResetEventSlim _closedEvt = new ManualResetEventSlim(false);
/** Close future. */
private readonly Future<object> _closeFut = new Future<object>();
/** GC handle to this streamer. */
private readonly long _hnd;
/** Topology version. */
private long _topVer;
/** Topology size. */
private int _topSize;
/** Buffer send size. */
private volatile int _bufSndSize;
/** Current data streamer batch. */
private volatile DataStreamerBatch<TK, TV> _batch;
/** Flusher. */
private readonly Flusher<TK, TV> _flusher;
/** Receiver. */
private volatile IStreamReceiver<TK, TV> _rcv;
/** Receiver handle. */
private long _rcvHnd;
/** Receiver binary mode. */
private readonly bool _keepBinary;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="target">Target.</param>
/// <param name="marsh">Marshaller.</param>
/// <param name="cacheName">Cache name.</param>
/// <param name="keepBinary">Binary flag.</param>
public DataStreamerImpl(IUnmanagedTarget target, Marshaller marsh, string cacheName, bool keepBinary)
: base(target, marsh)
{
_cacheName = cacheName;
_keepBinary = keepBinary;
// Create empty batch.
_batch = new DataStreamerBatch<TK, TV>();
// Allocate GC handle so that this data streamer could be easily dereferenced from native code.
WeakReference thisRef = new WeakReference(this);
_hnd = marsh.Ignite.HandleRegistry.Allocate(thisRef);
// Start topology listening. This call will ensure that buffer size member is updated.
UU.DataStreamerListenTopology(target, _hnd);
// Membar to ensure fields initialization before leaving constructor.
Thread.MemoryBarrier();
// Start flusher after everything else is initialized.
_flusher = new Flusher<TK, TV>(thisRef);
_flusher.RunThread();
}
/** <inheritDoc /> */
public string CacheName
{
get { return _cacheName; }
}
/** <inheritDoc /> */
public bool AllowOverwrite
{
get
{
_rwLock.EnterReadLock();
try
{
ThrowIfDisposed();
return UU.DataStreamerAllowOverwriteGet(Target);
}
finally
{
_rwLock.ExitReadLock();
}
}
set
{
_rwLock.EnterWriteLock();
try
{
ThrowIfDisposed();
UU.DataStreamerAllowOverwriteSet(Target, value);
}
finally
{
_rwLock.ExitWriteLock();
}
}
}
/** <inheritDoc /> */
public bool SkipStore
{
get
{
_rwLock.EnterReadLock();
try
{
ThrowIfDisposed();
return UU.DataStreamerSkipStoreGet(Target);
}
finally
{
_rwLock.ExitReadLock();
}
}
set
{
_rwLock.EnterWriteLock();
try
{
ThrowIfDisposed();
UU.DataStreamerSkipStoreSet(Target, value);
}
finally
{
_rwLock.ExitWriteLock();
}
}
}
/** <inheritDoc /> */
public int PerNodeBufferSize
{
get
{
_rwLock.EnterReadLock();
try
{
ThrowIfDisposed();
return UU.DataStreamerPerNodeBufferSizeGet(Target);
}
finally
{
_rwLock.ExitReadLock();
}
}
set
{
_rwLock.EnterWriteLock();
try
{
ThrowIfDisposed();
UU.DataStreamerPerNodeBufferSizeSet(Target, value);
_bufSndSize = _topSize * value;
}
finally
{
_rwLock.ExitWriteLock();
}
}
}
/** <inheritDoc /> */
public int PerNodeParallelOperations
{
get
{
_rwLock.EnterReadLock();
try
{
ThrowIfDisposed();
return UU.DataStreamerPerNodeParallelOperationsGet(Target);
}
finally
{
_rwLock.ExitReadLock();
}
}
set
{
_rwLock.EnterWriteLock();
try
{
ThrowIfDisposed();
UU.DataStreamerPerNodeParallelOperationsSet(Target, value);
}
finally
{
_rwLock.ExitWriteLock();
}
}
}
/** <inheritDoc /> */
public long AutoFlushFrequency
{
get
{
_rwLock.EnterReadLock();
try
{
ThrowIfDisposed();
return _flusher.Frequency;
}
finally
{
_rwLock.ExitReadLock();
}
}
set
{
_rwLock.EnterWriteLock();
try
{
ThrowIfDisposed();
_flusher.Frequency = value;
}
finally
{
_rwLock.ExitWriteLock();
}
}
}
/** <inheritDoc /> */
public Task Task
{
get
{
ThrowIfDisposed();
return _closeFut.Task;
}
}
/** <inheritDoc /> */
public IStreamReceiver<TK, TV> Receiver
{
get
{
ThrowIfDisposed();
return _rcv;
}
set
{
IgniteArgumentCheck.NotNull(value, "value");
var handleRegistry = Marshaller.Ignite.HandleRegistry;
_rwLock.EnterWriteLock();
try
{
ThrowIfDisposed();
if (_rcv == value)
return;
var rcvHolder = new StreamReceiverHolder(value,
(rec, grid, cache, stream, keepBinary) =>
StreamReceiverHolder.InvokeReceiver((IStreamReceiver<TK, TV>) rec, grid, cache, stream,
keepBinary));
var rcvHnd0 = handleRegistry.Allocate(rcvHolder);
try
{
DoOutOp(OpReceiver, w =>
{
w.WriteLong(rcvHnd0);
w.WriteObject(rcvHolder);
});
}
catch (Exception)
{
handleRegistry.Release(rcvHnd0);
throw;
}
if (_rcv != null)
handleRegistry.Release(_rcvHnd);
_rcv = value;
_rcvHnd = rcvHnd0;
}
finally
{
_rwLock.ExitWriteLock();
}
}
}
/** <inheritDoc /> */
public Task AddData(TK key, TV val)
{
ThrowIfDisposed();
IgniteArgumentCheck.NotNull(key, "key");
return Add0(new DataStreamerEntry<TK, TV>(key, val), 1);
}
/** <inheritDoc /> */
public Task AddData(KeyValuePair<TK, TV> pair)
{
ThrowIfDisposed();
return Add0(new DataStreamerEntry<TK, TV>(pair.Key, pair.Value), 1);
}
/** <inheritDoc /> */
public Task AddData(ICollection<KeyValuePair<TK, TV>> entries)
{
ThrowIfDisposed();
IgniteArgumentCheck.NotNull(entries, "entries");
return Add0(entries, entries.Count);
}
/** <inheritDoc /> */
public Task RemoveData(TK key)
{
ThrowIfDisposed();
IgniteArgumentCheck.NotNull(key, "key");
return Add0(new DataStreamerRemoveEntry<TK>(key), 1);
}
/** <inheritDoc /> */
public void TryFlush()
{
ThrowIfDisposed();
DataStreamerBatch<TK, TV> batch0 = _batch;
if (batch0 != null)
Flush0(batch0, false, PlcFlush);
}
/** <inheritDoc /> */
public void Flush()
{
ThrowIfDisposed();
DataStreamerBatch<TK, TV> batch0 = _batch;
if (batch0 != null)
Flush0(batch0, true, PlcFlush);
else
{
// Batch is null, i.e. data streamer is closing. Wait for close to complete.
_closedEvt.Wait();
}
}
/** <inheritDoc /> */
public void Close(bool cancel)
{
_flusher.Stop();
while (true)
{
DataStreamerBatch<TK, TV> batch0 = _batch;
if (batch0 == null)
{
// Wait for concurrent close to finish.
_closedEvt.Wait();
return;
}
if (Flush0(batch0, true, cancel ? PlcCancelClose : PlcClose))
{
_closeFut.OnDone(null, null);
_rwLock.EnterWriteLock();
try
{
base.Dispose(true);
if (_rcv != null)
Marshaller.Ignite.HandleRegistry.Release(_rcvHnd);
_closedEvt.Set();
}
finally
{
_rwLock.ExitWriteLock();
}
Marshaller.Ignite.HandleRegistry.Release(_hnd);
break;
}
}
}
/** <inheritDoc /> */
public IDataStreamer<TK1, TV1> WithKeepBinary<TK1, TV1>()
{
if (_keepBinary)
{
var result = this as IDataStreamer<TK1, TV1>;
if (result == null)
throw new InvalidOperationException(
"Can't change type of binary streamer. WithKeepBinary has been called on an instance of " +
"binary streamer with incompatible generic arguments.");
return result;
}
return new DataStreamerImpl<TK1, TV1>(UU.ProcessorDataStreamer(Marshaller.Ignite.InteropProcessor,
_cacheName, true), Marshaller, _cacheName, true);
}
/** <inheritDoc /> */
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
protected override void Dispose(bool disposing)
{
if (disposing)
Close(false); // Normal dispose: do not cancel
else
{
// Finalizer: just close Java streamer
try
{
if (_batch != null)
_batch.Send(this, PlcCancelClose);
}
catch (Exception)
{
// Finalizers should never throw
}
Marshaller.Ignite.HandleRegistry.Release(_hnd, true);
Marshaller.Ignite.HandleRegistry.Release(_rcvHnd, true);
base.Dispose(false);
}
}
/** <inheritDoc /> */
~DataStreamerImpl()
{
Dispose(false);
}
/** <inheritDoc /> */
public void TopologyChange(long topVer, int topSize)
{
_rwLock.EnterWriteLock();
try
{
ThrowIfDisposed();
if (_topVer < topVer)
{
_topVer = topVer;
_topSize = topSize;
_bufSndSize = topSize * UU.DataStreamerPerNodeBufferSizeGet(Target);
}
}
finally
{
_rwLock.ExitWriteLock();
}
}
/// <summary>
/// Internal add/remove routine.
/// </summary>
/// <param name="val">Value.</param>
/// <param name="cnt">Items count.</param>
/// <returns>Future.</returns>
private Task Add0(object val, int cnt)
{
int bufSndSize0 = _bufSndSize;
while (true)
{
var batch0 = _batch;
if (batch0 == null)
throw new InvalidOperationException("Data streamer is stopped.");
int size = batch0.Add(val, cnt);
if (size == -1)
{
// Batch is blocked, perform CAS.
Interlocked.CompareExchange(ref _batch,
new DataStreamerBatch<TK, TV>(batch0), batch0);
continue;
}
if (size >= bufSndSize0)
// Batch is too big, schedule flush.
Flush0(batch0, false, PlcContinue);
return batch0.Task;
}
}
/// <summary>
/// Internal flush routine.
/// </summary>
/// <param name="curBatch"></param>
/// <param name="wait">Whether to wait for flush to complete.</param>
/// <param name="plc">Whether this is the last batch.</param>
/// <returns>Whether this call was able to CAS previous batch</returns>
private bool Flush0(DataStreamerBatch<TK, TV> curBatch, bool wait, int plc)
{
// 1. Try setting new current batch to help further adders.
bool res = Interlocked.CompareExchange(ref _batch,
(plc == PlcContinue || plc == PlcFlush) ?
new DataStreamerBatch<TK, TV>(curBatch) : null, curBatch) == curBatch;
// 2. Perform actual send.
curBatch.Send(this, plc);
if (wait)
// 3. Wait for all futures to finish.
curBatch.AwaitCompletion();
return res;
}
/// <summary>
/// Start write.
/// </summary>
/// <returns>Writer.</returns>
internal void Update(Action<BinaryWriter> action)
{
_rwLock.EnterReadLock();
try
{
ThrowIfDisposed();
DoOutOp(OpUpdate, action);
}
finally
{
_rwLock.ExitReadLock();
}
}
/// <summary>
/// Flusher.
/// </summary>
private class Flusher<TK1, TV1>
{
/** State: running. */
private const int StateRunning = 0;
/** State: stopping. */
private const int StateStopping = 1;
/** State: stopped. */
private const int StateStopped = 2;
/** Data streamer. */
[SuppressMessage("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields",
Justification = "Incorrect warning")]
private readonly WeakReference _ldrRef;
/** Finish flag. */
[SuppressMessage("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields",
Justification = "Incorrect warning")]
private int _state;
/** Flush frequency. */
[SuppressMessage("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields",
Justification = "Incorrect warning")]
private long _freq;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="ldrRef">Data streamer weak reference..</param>
public Flusher(WeakReference ldrRef)
{
_ldrRef = ldrRef;
lock (this)
{
_state = StateRunning;
}
}
/// <summary>
/// Main flusher routine.
/// </summary>
private void Run()
{
bool force = false;
long curFreq = 0;
try
{
while (true)
{
if (curFreq > 0 || force)
{
var ldr = _ldrRef.Target as DataStreamerImpl<TK1, TV1>;
if (ldr == null)
return;
ldr.TryFlush();
force = false;
}
lock (this)
{
// Stop immediately.
if (_state == StateStopping)
return;
if (curFreq == _freq)
{
// Frequency is unchanged
if (curFreq == 0)
// Just wait for a second and re-try.
Monitor.Wait(this, 1000);
else
{
// Calculate remaining time.
DateTime now = DateTime.Now;
long ticks;
try
{
ticks = now.AddMilliseconds(curFreq).Ticks - now.Ticks;
if (ticks > int.MaxValue)
ticks = int.MaxValue;
}
catch (ArgumentOutOfRangeException)
{
// Handle possible overflow.
ticks = int.MaxValue;
}
Monitor.Wait(this, TimeSpan.FromTicks(ticks));
}
}
else
{
if (curFreq != 0)
force = true;
curFreq = _freq;
}
}
}
}
finally
{
// Let streamer know about stop.
lock (this)
{
_state = StateStopped;
Monitor.PulseAll(this);
}
}
}
/// <summary>
/// Frequency.
/// </summary>
public long Frequency
{
get
{
return Interlocked.Read(ref _freq);
}
set
{
lock (this)
{
if (_freq != value)
{
_freq = value;
Monitor.PulseAll(this);
}
}
}
}
/// <summary>
/// Stop flusher.
/// </summary>
public void Stop()
{
lock (this)
{
if (_state == StateRunning)
{
_state = StateStopping;
Monitor.PulseAll(this);
}
while (_state != StateStopped)
Monitor.Wait(this);
}
}
/// <summary>
/// Runs the flusher thread.
/// </summary>
public void RunThread()
{
new Thread(Run).Start();
}
}
#pragma warning restore 0420
}
}
| |
/* ====================================================================
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.HSSF.Record.Chart
{
using System;
using NPOI.HSSF.Record;
using NPOI.SS.Formula.PTG;
using NPOI.SS.Formula;
using NPOI.Util;
using System.Text;
/**
* Describes a linked data record. This record refers to the series data or text.<p/>
*
* @author Glen Stampoultzis (glens at apache.org)
*/
public class LinkedDataRecord : StandardRecord, ICloneable
{
public static short sid = 0x1051;
private static BitField customNumberFormat = BitFieldFactory.GetInstance(0x1);
private byte field_1_linkType;
public static byte LINK_TYPE_TITLE_OR_TEXT = 0;
public static byte LINK_TYPE_VALUES = 1;
public static byte LINK_TYPE_CATEGORIES = 2;
public static byte LINK_TYPE_SECONDARY_CATEGORIES = 3;
private byte field_2_referenceType;
public static byte REFERENCE_TYPE_DEFAULT_CATEGORIES = 0;
public static byte REFERENCE_TYPE_DIRECT = 1;
public static byte REFERENCE_TYPE_WORKSHEET = 2;
public static byte REFERENCE_TYPE_NOT_USED = 3;
public static byte REFERENCE_TYPE_ERROR_REPORTED = 4;
private short field_3_options;
private short field_4_indexNumberFmtRecord;
private Formula field_5_formulaOfLink;
public LinkedDataRecord()
{
}
public LinkedDataRecord(RecordInputStream in1)
{
field_1_linkType = (byte)in1.ReadByte();
field_2_referenceType = (byte)in1.ReadByte();
field_3_options = in1.ReadShort();
field_4_indexNumberFmtRecord = in1.ReadShort();
int encodedTokenLen = in1.ReadUShort();
field_5_formulaOfLink = Formula.Read(encodedTokenLen, in1);
}
public override String ToString()
{
StringBuilder buffer = new StringBuilder();
buffer.Append("[AI]\n");
buffer.Append(" .linkType = ").Append(HexDump.ByteToHex(LinkType)).Append('\n');
buffer.Append(" .referenceType = ").Append(HexDump.ByteToHex(ReferenceType)).Append('\n');
buffer.Append(" .options = ").Append(HexDump.ShortToHex(Options)).Append('\n');
buffer.Append(" .customNumberFormat = ").Append(IsCustomNumberFormat).Append('\n');
buffer.Append(" .indexNumberFmtRecord = ").Append(HexDump.ShortToHex(IndexNumberFmtRecord)).Append('\n');
buffer.Append(" .FormulaOfLink = ").Append('\n');
Ptg[] ptgs = field_5_formulaOfLink.Tokens;
for (int i = 0; i < ptgs.Length; i++)
{
Ptg ptg = ptgs[i];
buffer.Append(ptg.ToString()).Append(ptg.RVAType).Append('\n');
}
buffer.Append("[/AI]\n");
return buffer.ToString();
}
public override void Serialize(ILittleEndianOutput out1)
{
out1.WriteByte(field_1_linkType);
out1.WriteByte(field_2_referenceType);
out1.WriteShort(field_3_options);
out1.WriteShort(field_4_indexNumberFmtRecord);
field_5_formulaOfLink.Serialize(out1);
}
protected override int DataSize
{
get
{
return 1 + 1 + 2 + 2 + field_5_formulaOfLink.EncodedSize;
}
}
public override short Sid
{
get
{
return sid;
}
}
public override object Clone()
{
LinkedDataRecord rec = new LinkedDataRecord();
rec.field_1_linkType = field_1_linkType;
rec.field_2_referenceType = field_2_referenceType;
rec.field_3_options = field_3_options;
rec.field_4_indexNumberFmtRecord = field_4_indexNumberFmtRecord;
rec.field_5_formulaOfLink = field_5_formulaOfLink.Copy();
return rec;
}
/**
* Get the link type field for the LinkedData record.
*
* @return One of
* LINK_TYPE_TITLE_OR_TEXT
* LINK_TYPE_VALUES
* LINK_TYPE_CATEGORIES
*/
public byte LinkType
{
get
{
return field_1_linkType;
}
set
{
this.field_1_linkType = value;
}
}
/**
* Get the reference type field for the LinkedData record.
*
* @return One of
* REFERENCE_TYPE_DEFAULT_CATEGORIES
* REFERENCE_TYPE_DIRECT
* REFERENCE_TYPE_WORKSHEET
* REFERENCE_TYPE_NOT_USED
* REFERENCE_TYPE_ERROR_REPORTED
*/
public byte ReferenceType
{
get
{
return field_2_referenceType;
}
set
{
this.field_2_referenceType = value;
}
}
/**
* Get the options field for the LinkedData record.
*/
public short Options
{
get
{
return field_3_options;
}
set
{
this.field_3_options = value;
}
}
/**
* Get the index number fmt record field for the LinkedData record.
*/
public short IndexNumberFmtRecord
{
get
{
return field_4_indexNumberFmtRecord;
}
set
{
this.field_4_indexNumberFmtRecord = value;
}
}
/**
* Get the formula of link field for the LinkedData record.
*/
public Ptg[] FormulaOfLink
{
get
{
return field_5_formulaOfLink.Tokens;
}
set
{
this.field_5_formulaOfLink = Formula.Create(value);
}
}
/**
* true if this object has a custom number format
* @return the custom number format field value.
*/
public bool IsCustomNumberFormat
{
get
{
return customNumberFormat.IsSet(field_3_options);
}
set
{
field_3_options = customNumberFormat.SetShortBoolean(field_3_options, value);
}
}
}
}
| |
using System;
using System.Collections;
using System.Data.Common;
using System.IO;
namespace DbfDataReader
{
public class DbfDataReader : DbDataReader
{
private readonly DbfDataReaderOptions _options;
public DbfDataReader(string path)
: this(path, new DbfDataReaderOptions())
{
}
public DbfDataReader(string path, DbfDataReaderOptions options)
{
_options = options;
DbfTable = new DbfTable(path, options.Encoding);
DbfRecord = new DbfRecord(DbfTable);
}
public DbfDataReader(Stream stream, DbfDataReaderOptions options)
{
_options = options;
DbfTable = new DbfTable(stream, options.Encoding);
DbfRecord = new DbfRecord(DbfTable);
}
public DbfDataReader(Stream stream, Stream memoStream, DbfDataReaderOptions options)
{
_options = options;
DbfTable = new DbfTable(stream, memoStream, options.Encoding);
DbfRecord = new DbfRecord(DbfTable);
}
public DbfTable DbfTable { get; private set; }
public DbfRecord DbfRecord { get; private set; }
#if NETSTANDARD1_6_1
public void Close()
#else
public override void Close()
#endif
{
try
{
DbfTable.Close();
}
finally
{
DbfTable = null;
DbfRecord = null;
}
}
#if NETSTANDARD1_6_1
protected override void Dispose(bool disposing)
{
if (disposing)
{
Close();
}
}
#endif
public DbfRecord ReadRecord()
{
DbfRecord dbfRecord;
bool skip;
do
{
dbfRecord = DbfTable.ReadRecord();
if (dbfRecord == null)
break;
skip = _options.SkipDeletedRecords && DbfRecord.IsDeleted;
} while (skip);
return dbfRecord;
}
public T GetValue<T>(int ordinal)
{
return DbfRecord.GetValue<T>(ordinal);
}
public T? GetNullableValue<T>(int ordinal) where T : struct
{
return GetValue<T>(ordinal);
}
public override bool GetBoolean(int ordinal)
{
return (bool) GetValue(ordinal);
}
public override byte GetByte(int ordinal)
{
return GetValue<byte>(ordinal);
}
public override long GetBytes(int ordinal, long dataOffset, byte[] buffer, int bufferOffset, int length)
{
throw new NotImplementedException();
}
public override char GetChar(int ordinal)
{
return GetValue<char>(ordinal);
}
public override long GetChars(int ordinal, long dataOffset, char[] buffer, int bufferOffset, int length)
{
throw new NotImplementedException();
}
public override string GetDataTypeName(int ordinal)
{
throw new NotImplementedException();
}
public override DateTime GetDateTime(int ordinal)
{
return GetValue<DateTime>(ordinal);
}
public override decimal GetDecimal(int ordinal)
{
return GetValue<decimal>(ordinal);
}
public override double GetDouble(int ordinal)
{
return GetValue<double>(ordinal);
}
public override IEnumerator GetEnumerator()
{
throw new NotImplementedException();
}
public override bool NextResult()
{
return false;
}
public override bool Read()
{
bool result;
bool skip;
do
{
result = DbfTable.Read(DbfRecord);
if (!result)
break;
skip = _options.SkipDeletedRecords && DbfRecord.IsDeleted;
} while (skip);
return result;
}
public override int Depth => throw new NotImplementedException();
public override bool IsClosed => DbfTable.IsClosed;
public override int RecordsAffected => throw new NotImplementedException();
public override object this[string name]
{
get
{
var ordinal = GetOrdinal(name);
return GetValue(ordinal);
}
}
public override object this[int ordinal] => GetValue(ordinal);
public override int FieldCount => DbfTable.Columns.Count;
public override bool HasRows => DbfTable.Header.RecordCount > 0;
public override bool IsDBNull(int ordinal)
{
var value = GetValue(ordinal);
return value == null;
}
public override int GetValues(object[] values)
{
throw new NotImplementedException();
}
public override object GetValue(int ordinal)
{
return DbfRecord.GetValue(ordinal);
}
public override string GetString(int ordinal)
{
return DbfRecord.GetValue<string>(ordinal);
}
public override int GetOrdinal(string name)
{
var ordinal = 0;
foreach (var dbfColumn in DbfTable.Columns)
{
if (dbfColumn.Name == name) return ordinal;
ordinal++;
}
return -1;
}
public override string GetName(int ordinal)
{
var dbfColumn = DbfTable.Columns[ordinal];
return dbfColumn.Name;
}
public override long GetInt64(int ordinal)
{
return GetValue<long>(ordinal);
}
public override int GetInt32(int ordinal)
{
return GetValue<int>(ordinal);
}
public override short GetInt16(int ordinal)
{
return GetValue<short>(ordinal);
}
public override Guid GetGuid(int ordinal)
{
throw new NotImplementedException();
}
public override float GetFloat(int ordinal)
{
return GetValue<float>(ordinal);
}
public override Type GetFieldType(int ordinal)
{
return DbfRecord.GetFieldType(ordinal);
}
}
}
| |
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Linq;
using System.Text;
namespace EduHub.Data.Entities
{
/// <summary>
/// Teacher Replacements Data Set
/// </summary>
[GeneratedCode("EduHub Data", "0.9")]
public sealed partial class TCTRDataSet : EduHubDataSet<TCTR>
{
/// <inheritdoc />
public override string Name { get { return "TCTR"; } }
/// <inheritdoc />
public override bool SupportsEntityLastModified { get { return true; } }
internal TCTRDataSet(EduHubContext Context)
: base(Context)
{
Index_ROOM = new Lazy<NullDictionary<string, IReadOnlyList<TCTR>>>(() => this.ToGroupedNullDictionary(i => i.ROOM));
Index_TCTRKEY = new Lazy<Dictionary<DateTime, IReadOnlyList<TCTR>>>(() => this.ToGroupedDictionary(i => i.TCTRKEY));
Index_TEACH = new Lazy<NullDictionary<string, IReadOnlyList<TCTR>>>(() => this.ToGroupedNullDictionary(i => i.TEACH));
Index_TID = new Lazy<Dictionary<int, TCTR>>(() => this.ToDictionary(i => i.TID));
}
/// <summary>
/// Matches CSV file headers to actions, used to deserialize <see cref="TCTR" />
/// </summary>
/// <param name="Headers">The CSV column headers</param>
/// <returns>An array of actions which deserialize <see cref="TCTR" /> fields for each CSV column header</returns>
internal override Action<TCTR, string>[] BuildMapper(IReadOnlyList<string> Headers)
{
var mapper = new Action<TCTR, string>[Headers.Count];
for (var i = 0; i < Headers.Count; i++) {
switch (Headers[i]) {
case "TID":
mapper[i] = (e, v) => e.TID = int.Parse(v);
break;
case "TCTRKEY":
mapper[i] = (e, v) => e.TCTRKEY = DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
break;
case "TCTQ_TID":
mapper[i] = (e, v) => e.TCTQ_TID = v == null ? (int?)null : int.Parse(v);
break;
case "TEACH":
mapper[i] = (e, v) => e.TEACH = v;
break;
case "ROOM":
mapper[i] = (e, v) => e.ROOM = v;
break;
case "COMMENT_R":
mapper[i] = (e, v) => e.COMMENT_R = v;
break;
case "COUNT_EXTRAS":
mapper[i] = (e, v) => e.COUNT_EXTRAS = v;
break;
case "EXTRAS_VALUE":
mapper[i] = (e, v) => e.EXTRAS_VALUE = v == null ? (double?)null : double.Parse(v);
break;
case "ABSENTEE_TID":
mapper[i] = (e, v) => e.ABSENTEE_TID = v == null ? (int?)null : int.Parse(v);
break;
case "TEACHER_CLASH":
mapper[i] = (e, v) => e.TEACHER_CLASH = v;
break;
case "ROOM_CLASH":
mapper[i] = (e, v) => e.ROOM_CLASH = v;
break;
case "LW_DATE":
mapper[i] = (e, v) => e.LW_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
break;
case "LW_TIME":
mapper[i] = (e, v) => e.LW_TIME = v == null ? (short?)null : short.Parse(v);
break;
case "LW_USER":
mapper[i] = (e, v) => e.LW_USER = v;
break;
default:
mapper[i] = MapperNoOp;
break;
}
}
return mapper;
}
/// <summary>
/// Merges <see cref="TCTR" /> delta entities
/// </summary>
/// <param name="Entities">Iterator for base <see cref="TCTR" /> entities</param>
/// <param name="DeltaEntities">List of delta <see cref="TCTR" /> entities</param>
/// <returns>A merged <see cref="IEnumerable{TCTR}"/> of entities</returns>
internal override IEnumerable<TCTR> ApplyDeltaEntities(IEnumerable<TCTR> Entities, List<TCTR> DeltaEntities)
{
HashSet<int> Index_TID = new HashSet<int>(DeltaEntities.Select(i => i.TID));
using (var deltaIterator = DeltaEntities.GetEnumerator())
{
using (var entityIterator = Entities.GetEnumerator())
{
while (deltaIterator.MoveNext())
{
var deltaClusteredKey = deltaIterator.Current.TCTRKEY;
bool yieldEntity = false;
while (entityIterator.MoveNext())
{
var entity = entityIterator.Current;
bool overwritten = Index_TID.Remove(entity.TID);
if (entity.TCTRKEY.CompareTo(deltaClusteredKey) <= 0)
{
if (!overwritten)
{
yield return entity;
}
}
else
{
yieldEntity = !overwritten;
break;
}
}
yield return deltaIterator.Current;
if (yieldEntity)
{
yield return entityIterator.Current;
}
}
while (entityIterator.MoveNext())
{
yield return entityIterator.Current;
}
}
}
}
#region Index Fields
private Lazy<NullDictionary<string, IReadOnlyList<TCTR>>> Index_ROOM;
private Lazy<Dictionary<DateTime, IReadOnlyList<TCTR>>> Index_TCTRKEY;
private Lazy<NullDictionary<string, IReadOnlyList<TCTR>>> Index_TEACH;
private Lazy<Dictionary<int, TCTR>> Index_TID;
#endregion
#region Index Methods
/// <summary>
/// Find TCTR by ROOM field
/// </summary>
/// <param name="ROOM">ROOM value used to find TCTR</param>
/// <returns>List of related TCTR entities</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<TCTR> FindByROOM(string ROOM)
{
return Index_ROOM.Value[ROOM];
}
/// <summary>
/// Attempt to find TCTR by ROOM field
/// </summary>
/// <param name="ROOM">ROOM value used to find TCTR</param>
/// <param name="Value">List of related TCTR entities</param>
/// <returns>True if the list of related TCTR entities is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByROOM(string ROOM, out IReadOnlyList<TCTR> Value)
{
return Index_ROOM.Value.TryGetValue(ROOM, out Value);
}
/// <summary>
/// Attempt to find TCTR by ROOM field
/// </summary>
/// <param name="ROOM">ROOM value used to find TCTR</param>
/// <returns>List of related TCTR entities, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<TCTR> TryFindByROOM(string ROOM)
{
IReadOnlyList<TCTR> value;
if (Index_ROOM.Value.TryGetValue(ROOM, out value))
{
return value;
}
else
{
return null;
}
}
/// <summary>
/// Find TCTR by TCTRKEY field
/// </summary>
/// <param name="TCTRKEY">TCTRKEY value used to find TCTR</param>
/// <returns>List of related TCTR entities</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<TCTR> FindByTCTRKEY(DateTime TCTRKEY)
{
return Index_TCTRKEY.Value[TCTRKEY];
}
/// <summary>
/// Attempt to find TCTR by TCTRKEY field
/// </summary>
/// <param name="TCTRKEY">TCTRKEY value used to find TCTR</param>
/// <param name="Value">List of related TCTR entities</param>
/// <returns>True if the list of related TCTR entities is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByTCTRKEY(DateTime TCTRKEY, out IReadOnlyList<TCTR> Value)
{
return Index_TCTRKEY.Value.TryGetValue(TCTRKEY, out Value);
}
/// <summary>
/// Attempt to find TCTR by TCTRKEY field
/// </summary>
/// <param name="TCTRKEY">TCTRKEY value used to find TCTR</param>
/// <returns>List of related TCTR entities, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<TCTR> TryFindByTCTRKEY(DateTime TCTRKEY)
{
IReadOnlyList<TCTR> value;
if (Index_TCTRKEY.Value.TryGetValue(TCTRKEY, out value))
{
return value;
}
else
{
return null;
}
}
/// <summary>
/// Find TCTR by TEACH field
/// </summary>
/// <param name="TEACH">TEACH value used to find TCTR</param>
/// <returns>List of related TCTR entities</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<TCTR> FindByTEACH(string TEACH)
{
return Index_TEACH.Value[TEACH];
}
/// <summary>
/// Attempt to find TCTR by TEACH field
/// </summary>
/// <param name="TEACH">TEACH value used to find TCTR</param>
/// <param name="Value">List of related TCTR entities</param>
/// <returns>True if the list of related TCTR entities is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByTEACH(string TEACH, out IReadOnlyList<TCTR> Value)
{
return Index_TEACH.Value.TryGetValue(TEACH, out Value);
}
/// <summary>
/// Attempt to find TCTR by TEACH field
/// </summary>
/// <param name="TEACH">TEACH value used to find TCTR</param>
/// <returns>List of related TCTR entities, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<TCTR> TryFindByTEACH(string TEACH)
{
IReadOnlyList<TCTR> value;
if (Index_TEACH.Value.TryGetValue(TEACH, out value))
{
return value;
}
else
{
return null;
}
}
/// <summary>
/// Find TCTR by TID field
/// </summary>
/// <param name="TID">TID value used to find TCTR</param>
/// <returns>Related TCTR entity</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public TCTR FindByTID(int TID)
{
return Index_TID.Value[TID];
}
/// <summary>
/// Attempt to find TCTR by TID field
/// </summary>
/// <param name="TID">TID value used to find TCTR</param>
/// <param name="Value">Related TCTR entity</param>
/// <returns>True if the related TCTR entity is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByTID(int TID, out TCTR Value)
{
return Index_TID.Value.TryGetValue(TID, out Value);
}
/// <summary>
/// Attempt to find TCTR by TID field
/// </summary>
/// <param name="TID">TID value used to find TCTR</param>
/// <returns>Related TCTR entity, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public TCTR TryFindByTID(int TID)
{
TCTR value;
if (Index_TID.Value.TryGetValue(TID, out value))
{
return value;
}
else
{
return null;
}
}
#endregion
#region SQL Integration
/// <summary>
/// Returns a <see cref="SqlCommand"/> which checks for the existence of a TCTR table, and if not found, creates the table and associated indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[TCTR]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[TCTR](
[TID] int IDENTITY NOT NULL,
[TCTRKEY] datetime NOT NULL,
[TCTQ_TID] int NULL,
[TEACH] varchar(4) NULL,
[ROOM] varchar(4) NULL,
[COMMENT_R] varchar(MAX) NULL,
[COUNT_EXTRAS] varchar(1) NULL,
[EXTRAS_VALUE] float NULL,
[ABSENTEE_TID] int NULL,
[TEACHER_CLASH] varchar(1) NULL,
[ROOM_CLASH] varchar(1) NULL,
[LW_DATE] datetime NULL,
[LW_TIME] smallint NULL,
[LW_USER] varchar(128) NULL,
CONSTRAINT [TCTR_Index_TID] PRIMARY KEY NONCLUSTERED (
[TID] ASC
)
);
CREATE NONCLUSTERED INDEX [TCTR_Index_ROOM] ON [dbo].[TCTR]
(
[ROOM] ASC
);
CREATE CLUSTERED INDEX [TCTR_Index_TCTRKEY] ON [dbo].[TCTR]
(
[TCTRKEY] ASC
);
CREATE NONCLUSTERED INDEX [TCTR_Index_TEACH] ON [dbo].[TCTR]
(
[TEACH] ASC
);
END");
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which disables all non-clustered table indexes.
/// Typically called before <see cref="SqlBulkCopy"/> to improve performance.
/// <see cref="GetSqlRebuildIndexesCommand(SqlConnection)"/> should be called to rebuild and enable indexes after performance sensitive work is completed.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>A <see cref="SqlCommand"/> which (when executed) will disable all non-clustered table indexes</returns>
public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[TCTR]') AND name = N'TCTR_Index_ROOM')
ALTER INDEX [TCTR_Index_ROOM] ON [dbo].[TCTR] DISABLE;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[TCTR]') AND name = N'TCTR_Index_TEACH')
ALTER INDEX [TCTR_Index_TEACH] ON [dbo].[TCTR] DISABLE;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[TCTR]') AND name = N'TCTR_Index_TID')
ALTER INDEX [TCTR_Index_TID] ON [dbo].[TCTR] DISABLE;
");
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which rebuilds and enables all non-clustered table indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>A <see cref="SqlCommand"/> which (when executed) will rebuild and enable all non-clustered table indexes</returns>
public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[TCTR]') AND name = N'TCTR_Index_ROOM')
ALTER INDEX [TCTR_Index_ROOM] ON [dbo].[TCTR] REBUILD PARTITION = ALL;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[TCTR]') AND name = N'TCTR_Index_TEACH')
ALTER INDEX [TCTR_Index_TEACH] ON [dbo].[TCTR] REBUILD PARTITION = ALL;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[TCTR]') AND name = N'TCTR_Index_TID')
ALTER INDEX [TCTR_Index_TID] ON [dbo].[TCTR] REBUILD PARTITION = ALL;
");
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which deletes the <see cref="TCTR"/> entities passed
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <param name="Entities">The <see cref="TCTR"/> entities to be deleted</param>
public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<TCTR> Entities)
{
SqlCommand command = new SqlCommand();
int parameterIndex = 0;
StringBuilder builder = new StringBuilder();
List<int> Index_TID = new List<int>();
foreach (var entity in Entities)
{
Index_TID.Add(entity.TID);
}
builder.AppendLine("DELETE [dbo].[TCTR] WHERE");
// Index_TID
builder.Append("[TID] IN (");
for (int index = 0; index < Index_TID.Count; index++)
{
if (index != 0)
builder.Append(", ");
// TID
var parameterTID = $"@p{parameterIndex++}";
builder.Append(parameterTID);
command.Parameters.Add(parameterTID, SqlDbType.Int).Value = Index_TID[index];
}
builder.Append(");");
command.Connection = SqlConnection;
command.CommandText = builder.ToString();
return command;
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the TCTR data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the TCTR data set</returns>
public override EduHubDataSetDataReader<TCTR> GetDataSetDataReader()
{
return new TCTRDataReader(Load());
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the TCTR data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the TCTR data set</returns>
public override EduHubDataSetDataReader<TCTR> GetDataSetDataReader(List<TCTR> Entities)
{
return new TCTRDataReader(new EduHubDataSetLoadedReader<TCTR>(this, Entities));
}
// Modest implementation to primarily support SqlBulkCopy
private class TCTRDataReader : EduHubDataSetDataReader<TCTR>
{
public TCTRDataReader(IEduHubDataSetReader<TCTR> Reader)
: base (Reader)
{
}
public override int FieldCount { get { return 14; } }
public override object GetValue(int i)
{
switch (i)
{
case 0: // TID
return Current.TID;
case 1: // TCTRKEY
return Current.TCTRKEY;
case 2: // TCTQ_TID
return Current.TCTQ_TID;
case 3: // TEACH
return Current.TEACH;
case 4: // ROOM
return Current.ROOM;
case 5: // COMMENT_R
return Current.COMMENT_R;
case 6: // COUNT_EXTRAS
return Current.COUNT_EXTRAS;
case 7: // EXTRAS_VALUE
return Current.EXTRAS_VALUE;
case 8: // ABSENTEE_TID
return Current.ABSENTEE_TID;
case 9: // TEACHER_CLASH
return Current.TEACHER_CLASH;
case 10: // ROOM_CLASH
return Current.ROOM_CLASH;
case 11: // LW_DATE
return Current.LW_DATE;
case 12: // LW_TIME
return Current.LW_TIME;
case 13: // LW_USER
return Current.LW_USER;
default:
throw new ArgumentOutOfRangeException(nameof(i));
}
}
public override bool IsDBNull(int i)
{
switch (i)
{
case 2: // TCTQ_TID
return Current.TCTQ_TID == null;
case 3: // TEACH
return Current.TEACH == null;
case 4: // ROOM
return Current.ROOM == null;
case 5: // COMMENT_R
return Current.COMMENT_R == null;
case 6: // COUNT_EXTRAS
return Current.COUNT_EXTRAS == null;
case 7: // EXTRAS_VALUE
return Current.EXTRAS_VALUE == null;
case 8: // ABSENTEE_TID
return Current.ABSENTEE_TID == null;
case 9: // TEACHER_CLASH
return Current.TEACHER_CLASH == null;
case 10: // ROOM_CLASH
return Current.ROOM_CLASH == null;
case 11: // LW_DATE
return Current.LW_DATE == null;
case 12: // LW_TIME
return Current.LW_TIME == null;
case 13: // LW_USER
return Current.LW_USER == null;
default:
return false;
}
}
public override string GetName(int ordinal)
{
switch (ordinal)
{
case 0: // TID
return "TID";
case 1: // TCTRKEY
return "TCTRKEY";
case 2: // TCTQ_TID
return "TCTQ_TID";
case 3: // TEACH
return "TEACH";
case 4: // ROOM
return "ROOM";
case 5: // COMMENT_R
return "COMMENT_R";
case 6: // COUNT_EXTRAS
return "COUNT_EXTRAS";
case 7: // EXTRAS_VALUE
return "EXTRAS_VALUE";
case 8: // ABSENTEE_TID
return "ABSENTEE_TID";
case 9: // TEACHER_CLASH
return "TEACHER_CLASH";
case 10: // ROOM_CLASH
return "ROOM_CLASH";
case 11: // LW_DATE
return "LW_DATE";
case 12: // LW_TIME
return "LW_TIME";
case 13: // LW_USER
return "LW_USER";
default:
throw new ArgumentOutOfRangeException(nameof(ordinal));
}
}
public override int GetOrdinal(string name)
{
switch (name)
{
case "TID":
return 0;
case "TCTRKEY":
return 1;
case "TCTQ_TID":
return 2;
case "TEACH":
return 3;
case "ROOM":
return 4;
case "COMMENT_R":
return 5;
case "COUNT_EXTRAS":
return 6;
case "EXTRAS_VALUE":
return 7;
case "ABSENTEE_TID":
return 8;
case "TEACHER_CLASH":
return 9;
case "ROOM_CLASH":
return 10;
case "LW_DATE":
return 11;
case "LW_TIME":
return 12;
case "LW_USER":
return 13;
default:
throw new ArgumentOutOfRangeException(nameof(name));
}
}
}
#endregion
}
}
| |
#region License
/*
* All content copyright Marko Lahma, unless otherwise indicated. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
*/
#endregion
using System;
using System.Collections;
using System.Data.Common;
using System.Runtime.Serialization;
using System.Threading;
using System.Threading.Tasks;
using FakeItEasy;
using Microsoft.Data.SqlClient;
using NUnit.Framework;
using Quartz.Impl.AdoJobStore;
using Quartz.Impl.AdoJobStore.Common;
using Quartz.Simpl;
using Quartz.Spi;
namespace Quartz.Tests.Unit.Impl.AdoJobStore
{
/// <author>Marko Lahma (.NET)</author>
[TestFixture(typeof(BinaryObjectSerializer))]
[TestFixture(typeof(JsonObjectSerializer))]
public class StdAdoDelegateTest
{
private readonly IObjectSerializer serializer;
public StdAdoDelegateTest(Type serializerType)
{
serializer = (IObjectSerializer) Activator.CreateInstance(serializerType);
serializer.Initialize();
}
[Test]
public void TestSerializeJobData()
{
bool binary = serializer.GetType() == typeof(BinaryObjectSerializer);
var args = new DelegateInitializationArgs();
args.TablePrefix = "QRTZ_";
args.InstanceName = "TESTSCHED";
args.InstanceId = "INSTANCE";
args.DbProvider = new DbProvider(TestConstants.DefaultSqlServerProvider, "");
args.TypeLoadHelper = new SimpleTypeLoadHelper();
args.ObjectSerializer = serializer;
var del = new StdAdoDelegate();
del.Initialize(args);
var jdm = new JobDataMap();
del.SerializeJobData(jdm);
jdm.Clear();
jdm.Put("key", "value");
jdm.Put("key2", null);
del.SerializeJobData(jdm);
jdm.Clear();
jdm.Put("key1", "value");
jdm.Put("key2", null);
jdm.Put("key3", new NonSerializableTestClass());
try
{
del.SerializeJobData(jdm);
if (binary)
{
Assert.Fail("Private types should not be serializable by binary serialization");
}
}
catch (SerializationException e)
{
if (binary)
{
Assert.IsTrue(e.Message.IndexOf("key3", StringComparison.Ordinal) >= 0);
}
else
{
Assert.Fail($"Private types should be serializable when not using binary serialization: {e}");
}
}
}
private class NonSerializableTestClass
{
}
[Test]
public async Task TestSelectBlobTriggerWithNoBlobContent()
{
var dbProvider = A.Fake<IDbProvider>();
var connection = A.Fake<DbConnection>();
var transaction = A.Fake<DbTransaction>();
var command = (DbCommand) A.Fake<StubCommand>();
var dbMetadata = new DbMetadata();
A.CallTo(() => dbProvider.Metadata).Returns(dbMetadata);
A.CallTo(() => dbProvider.CreateCommand()).Returns(command);
var dataReader = A.Fake<DbDataReader>();
A.CallTo(command).Where(x => x.Method.Name == "ExecuteDbDataReaderAsync")
.WithReturnType<Task<DbDataReader>>()
.Returns(dataReader);
A.CallTo(command).Where(x => x.Method.Name == "get_DbParameterCollection")
.WithReturnType<DbParameterCollection>()
.Returns(new StubParameterCollection());
A.CallTo(() => command.CommandText).Returns("");
A.CallTo(command).Where(x => x.Method.Name == "CreateDbParameter")
.WithReturnType<DbParameter>()
.Returns(new SqlParameter());
var adoDelegate = new StdAdoDelegate();
var delegateInitializationArgs = new DelegateInitializationArgs
{
TablePrefix = "QRTZ_",
InstanceId = "TESTSCHED",
InstanceName = "INSTANCE",
TypeLoadHelper = new SimpleTypeLoadHelper(),
UseProperties = false,
InitString = "",
DbProvider = dbProvider
};
adoDelegate.Initialize(delegateInitializationArgs);
var conn = new ConnectionAndTransactionHolder(connection, transaction);
// First result set has results, second has none
A.CallTo(() => dataReader.ReadAsync(CancellationToken.None)).Returns(true).Once();
A.CallTo(() => dataReader.ReadAsync(CancellationToken.None)).Returns(false);
A.CallTo(() => dataReader[AdoConstants.ColumnTriggerType]).Returns(AdoConstants.TriggerTypeBlob);
IOperableTrigger trigger = await adoDelegate.SelectTrigger(conn, new TriggerKey("test"));
Assert.That(trigger, Is.Null);
}
[Test]
public async Task TestSelectSimpleTriggerWithExceptionWithExtendedProps()
{
var dbProvider = A.Fake<IDbProvider>();
var connection = A.Fake<DbConnection>();
var transaction = A.Fake<DbTransaction>();
var command = (DbCommand) A.Fake<StubCommand>();
var dbMetadata = new DbMetadata();
A.CallTo(() => dbProvider.Metadata).Returns(dbMetadata);
A.CallTo(() => dbProvider.CreateCommand()).Returns(command);
var dataReader = A.Fake<DbDataReader>();
A.CallTo(command).Where(x => x.Method.Name == "ExecuteDbDataReaderAsync")
.WithReturnType<Task<DbDataReader>>()
.Returns(Task.FromResult(dataReader));
A.CallTo(command).Where(x => x.Method.Name == "get_DbParameterCollection")
.WithReturnType<DbParameterCollection>()
.Returns(new StubParameterCollection());
A.CallTo(() => command.CommandText).Returns("");
A.CallTo(command).Where(x => x.Method.Name == "CreateDbParameter")
.WithReturnType<DbParameter>()
.Returns(new SqlParameter());
var persistenceDelegate = A.Fake<ITriggerPersistenceDelegate>();
var exception = new InvalidOperationException();
A.CallTo(() => persistenceDelegate.LoadExtendedTriggerProperties(A<ConnectionAndTransactionHolder>.Ignored, A<TriggerKey>.Ignored, CancellationToken.None)).Throws(exception);
StdAdoDelegate adoDelegate = new TestStdAdoDelegate(persistenceDelegate);
var delegateInitializationArgs = new DelegateInitializationArgs
{
TablePrefix = "QRTZ_",
InstanceId = "TESTSCHED",
InstanceName = "INSTANCE",
TypeLoadHelper = new SimpleTypeLoadHelper(),
UseProperties = false,
InitString = "",
DbProvider = dbProvider
};
adoDelegate.Initialize(delegateInitializationArgs);
// Mock basic trigger data
A.CallTo(() => dataReader.ReadAsync(CancellationToken.None)).Returns(true);
A.CallTo(() => dataReader[AdoConstants.ColumnTriggerType]).Returns(AdoConstants.TriggerTypeSimple);
A.CallTo(() => dataReader[A<string>._]).Returns("1");
try
{
var conn = new ConnectionAndTransactionHolder(connection, transaction);
await adoDelegate.SelectTrigger(conn, new TriggerKey("test"));
Assert.Fail("Trigger selection should result in exception");
}
catch (InvalidOperationException e)
{
Assert.That(e, Is.SameAs(exception));
}
A.CallTo(() => persistenceDelegate.LoadExtendedTriggerProperties(A<ConnectionAndTransactionHolder>.Ignored, A<TriggerKey>.Ignored, CancellationToken.None)).MustHaveHappened();
}
[Test]
public async Task TestSelectSimpleTriggerWithDeleteBeforeSelectExtendedProps()
{
var dbProvider = A.Fake<IDbProvider>();
var connection = A.Fake<DbConnection>();
var transaction = A.Fake<DbTransaction>();
var command = (DbCommand) A.Fake<StubCommand>();
var dbMetadata = new DbMetadata();
A.CallTo(() => dbProvider.Metadata).Returns(dbMetadata);
A.CallTo(() => dbProvider.CreateCommand()).Returns(command);
var dataReader = A.Fake<DbDataReader>();
A.CallTo(command).Where(x => x.Method.Name == "ExecuteDbDataReaderAsync")
.WithReturnType<Task<DbDataReader>>()
.Returns(Task.FromResult(dataReader));
A.CallTo(command).Where(x => x.Method.Name == "get_DbParameterCollection")
.WithReturnType<DbParameterCollection>()
.Returns(new StubParameterCollection());
A.CallTo(() => command.CommandText).Returns("");
A.CallTo(command).Where(x => x.Method.Name == "CreateDbParameter")
.WithReturnType<DbParameter>()
.Returns(new SqlParameter());
var persistenceDelegate = A.Fake<ITriggerPersistenceDelegate>();
var exception = new InvalidOperationException();
A.CallTo(() => persistenceDelegate.LoadExtendedTriggerProperties(A<ConnectionAndTransactionHolder>.Ignored, A<TriggerKey>.Ignored, CancellationToken.None)).Throws(exception);
StdAdoDelegate adoDelegate = new TestStdAdoDelegate(persistenceDelegate);
var delegateInitializationArgs = new DelegateInitializationArgs
{
TablePrefix = "QRTZ_",
InstanceId = "TESTSCHED",
InstanceName = "INSTANCE",
TypeLoadHelper = new SimpleTypeLoadHelper(),
UseProperties = false,
InitString = "",
DbProvider = dbProvider
};
adoDelegate.Initialize(delegateInitializationArgs);
// First result set has results, second has none
A.CallTo(() => dataReader.ReadAsync(CancellationToken.None)).Returns(true).Once();
A.CallTo(() => dataReader[AdoConstants.ColumnTriggerType]).Returns(AdoConstants.TriggerTypeSimple);
A.CallTo(() => dataReader[A<string>._]).Returns("1");
var conn = new ConnectionAndTransactionHolder(connection, transaction);
IOperableTrigger trigger = await adoDelegate.SelectTrigger(conn, new TriggerKey("test"));
Assert.That(trigger, Is.Null);
A.CallTo(() => persistenceDelegate.LoadExtendedTriggerProperties(A<ConnectionAndTransactionHolder>.Ignored, A<TriggerKey>.Ignored, CancellationToken.None)).MustHaveHappened();
}
[Test]
public void ShouldSupportAssemblyQualifiedTriggerPersistenceDelegates()
{
StdAdoDelegate adoDelegate = new TestStdAdoDelegate(new SimpleTriggerPersistenceDelegate());
var delegateInitializationArgs = new DelegateInitializationArgs
{
TablePrefix = "QRTZ_",
InstanceId = "TESTSCHED",
InstanceName = "INSTANCE",
TypeLoadHelper = new SimpleTypeLoadHelper(),
UseProperties = false,
InitString = "triggerPersistenceDelegateClasses=" + typeof(TestTriggerPersistenceDelegate).AssemblyQualifiedName + ";" + typeof(TestTriggerPersistenceDelegate).AssemblyQualifiedName,
DbProvider = A.Fake<IDbProvider>()
};
adoDelegate.Initialize(delegateInitializationArgs);
}
private class TestStdAdoDelegate : StdAdoDelegate
{
private readonly ITriggerPersistenceDelegate testDelegate;
public TestStdAdoDelegate(ITriggerPersistenceDelegate testDelegate)
{
this.testDelegate = testDelegate;
}
protected override ITriggerPersistenceDelegate FindTriggerPersistenceDelegate(string discriminator)
{
return testDelegate;
}
}
}
public abstract class StubCommand : DbCommand
{
protected StubCommand()
{
CommandText = "";
}
public override string CommandText { get; set; }
}
public class StubParameterCollection : DbParameterCollection
{
public override int Add(object value)
{
return -1;
}
public override bool Contains(object value)
{
return false;
}
public override void Clear()
{
}
public override int IndexOf(object value)
{
return -1;
}
public override void Insert(int index, object value)
{
}
public override void Remove(object value)
{
}
public override void RemoveAt(int index)
{
}
public override void RemoveAt(string parameterName)
{
}
protected override void SetParameter(int index, DbParameter value)
{
}
protected override void SetParameter(string parameterName, DbParameter value)
{
}
public override int Count => throw new NotImplementedException();
public override object SyncRoot => throw new NotImplementedException();
#if !NETCORE
public override bool IsFixedSize => throw new NotImplementedException();
public override bool IsReadOnly => throw new NotImplementedException();
public override bool IsSynchronized => throw new NotImplementedException();
#endif
public override int IndexOf(string parameterName)
{
throw new NotImplementedException();
}
public override IEnumerator GetEnumerator()
{
throw new NotImplementedException();
}
protected override DbParameter GetParameter(int index)
{
throw new NotImplementedException();
}
protected override DbParameter GetParameter(string parameterName)
{
throw new NotImplementedException();
}
public override bool Contains(string value)
{
return false;
}
public override void CopyTo(Array array, int index)
{
}
public override void AddRange(Array values)
{
}
}
public class TestTriggerPersistenceDelegate : SimpleTriggerPersistenceDelegate
{
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="WmlRadioButtonAdapter.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
#if WMLSUPPORT
namespace System.Web.UI.WebControls.Adapters {
using System;
using System.Collections;
using System.Collections.Specialized;
using System.Globalization;
using System.Web;
using System.Web.UI;
using System.Web.UI.Adapters;
using System.Web.Util;
public class WmlRadioButtonAdapter : WmlCheckBoxAdapter, IPostBackDataHandler {
private const String _groupPrefix = "__rb_";
protected new RadioButton Control {
get {
return (RadioButton)base.Control;
}
}
protected string GroupFormVariable {
get {
return _groupPrefix + Control.UniqueGroupName;
}
}
private void DetermineGroup(RadioButton r) {
if (RadioButtonGroups[r.UniqueGroupName] == null) {
RadioButtonGroups[r.UniqueGroupName] = RenderAsGroup(r);
}
}
private RadioButtonGroup GetGroupByName(string groupName) {
Debug.Assert(RadioButtonGroups.Contains(groupName), "Attemping to get group name without procesing group");
return RadioButtonGroups[groupName] as RadioButtonGroup;
}
// Returns a textual representation of a textbox.
protected override string InputElementText {
get {
return Control.Checked ? RadioButtonAdapter.AltSelectedText : RadioButtonAdapter.AltUnselectedText;
}
}
private bool IsWhiteSpace(string s) {
for (int i = 0; i < s.Length; i++) {
if (!Char.IsWhiteSpace(s, i)) return false;
}
return true;
}
private IDictionary RadioButtonGroups {
get {
if (Control.Page != null && Control.Page.Items[this.GetType()] == null) {
Control.Page.Items[this.GetType()] = new HybridDictionary();
}
return (HybridDictionary)Control.Page.Items[this.GetType()];
}
}
// Renders the control.
protected internal override void Render(HtmlTextWriter markupWriter) {
WmlTextWriter writer = (WmlTextWriter)markupWriter;
DetermineGroup(Control);
RadioButtonGroup group = GetGroupByName(Control.UniqueGroupName);
if (group != null) {
if (!group.RegisteredGroup) {
// GroupFormVariable is passed as the name & value becuase it is both the key
// for the postback data, and the WML client side var used to
// select an item in the list.
((WmlPageAdapter)PageAdapter).RegisterPostField(writer, GroupFormVariable, GroupFormVariable, true /*dynamic field*/, false /*random*/);
group.RegisteredGroup = true;
}
if (group.RenderAsGroup) {
// Render opening select if not already opened
if (!group.RenderedSelect) {
if (group.SelectedButton != null) {
((WmlPageAdapter)PageAdapter).AddFormVariable(writer, GroupFormVariable, group.SelectedButton, false /*random*/);
}
writer.WriteBeginSelect(GroupFormVariable, group.SelectedButton, null /*iname */,
null /*ivalue*/, Control.ToolTip, false /*multiple */);
if (!writer.AnalyzeMode) {
group.RenderedSelect = true;
}
}
// Render option
// We don't do autopostback if the radio button has been selected.
// This is to make it consistent that it only posts back if its
// state has been changed. Also, it avoids the problem of missing
// validation since the data changed event would not be fired if the
// selected radio button was posting back.
if (Control.AutoPostBack && !Control.Checked) {
((WmlPageAdapter)PageAdapter).RenderSelectOptionAsAutoPostBack(writer, Control.Text, Control.UniqueID);
}
else {
((WmlPageAdapter)PageAdapter).RenderSelectOption(writer, Control.Text, Control.UniqueID);
}
// Close, if list is finished
if (!writer.AnalyzeMode && --group.ButtonsInGroup == 0) {
writer.WriteEndSelect();
}
}
// must render as autopostback, radio buttons not in consecutive group.
else {
if (!Control.Enabled) {
RenderDisabled(writer);
return;
}
string iname = Control.Checked ? Control.ClientID : null;
string ivalue = Control.Checked ? "1" : null;
if (ivalue != null) {
((WmlPageAdapter)PageAdapter).AddFormVariable(writer, iname, ivalue, false /*random*/);
}
writer.WriteBeginSelect(null, null, iname, ivalue, Control.ToolTip, true /*multiple*/);
if (!Control.Checked) {
((WmlPageAdapter)PageAdapter).RenderSelectOptionAsAutoPostBack(writer, Control.Text, GroupFormVariable, Control.UniqueID);
}
else {
((WmlPageAdapter)PageAdapter).RenderSelectOption(writer, Control.Text, Control.UniqueID);
}
writer.WriteEndSelect();
}
}
}
// RenderAsGroup returns a RadioButtonGroup object if the group should be
// rendered in a single <select> statement, or null if autopostback should
// be enabled.
//
private RadioButtonGroup RenderAsGroup(RadioButton r) {
bool startedSequence = false;
bool finishedSequence = false;
RadioButtonGroup group = new RadioButtonGroup();
//
foreach (Control c in r.Parent.Controls) {
RadioButton radioSibling = c as RadioButton;
LiteralControl literalSibling = c as LiteralControl;
if (radioSibling != null && radioSibling.UniqueGroupName == r.UniqueGroupName) {
startedSequence = true;
group.ButtonsInGroup++;
if (radioSibling.Checked == true) {
group.SelectedButton = radioSibling.UniqueID;
}
if (finishedSequence || !radioSibling.Enabled) {
group.ButtonsInGroup = -1; // can't be rendered in a group
break;
}
}
else if (startedSequence && (literalSibling == null || !IsWhiteSpace(literalSibling.Text))) {
finishedSequence = true;
}
}
return group;
}
/// <internalonly/>
// Implements IPostBackDataHandler.LoadPostData.
protected override bool LoadPostData(String key, NameValueCollection data) {
bool dataChanged = false;
string selButtonID = data[GroupFormVariable];
if (!String.IsNullOrEmpty(selButtonID)) {
// Check if this radio button is now checked
if (StringUtil.EqualsIgnoreCase(selButtonID, Control.UniqueID)) {
if (Control.Checked == false) {
Control.Checked = true;
dataChanged = true;
}
}
else {
// Don't need to check if radiobutton was
// previously checked. We only raise an event
// for the radiobutton that is selected.
// This is how a normal RadioButton behaves.
Control.Checked = false;
}
}
return dataChanged;
}
/// <internalonly/>
// Implements IPostBackDataHandler.RaisePostDataChangedEvent()
protected override void RaisePostDataChangedEvent() {
((IPostBackDataHandler)Control).RaisePostDataChangedEvent();
}
}
internal class RadioButtonGroup {
public int ButtonsInGroup;
public bool RenderedSelect;
public bool RegisteredGroup;
public String SelectedButton;
public bool RenderAsGroup {
get {
if (ButtonsInGroup < 0) {
return false;
}
return true;
}
}
}
}
#endif
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using SampleMetadata;
using Xunit;
#pragma warning disable 0649 // Uninitialized field
namespace System.Reflection.Tests
{
public static class TypeTests_GetMember
{
[Fact]
public static void TestNull()
{
Type t = typeof(Mixed).Project();
Assert.Throws<ArgumentNullException>(() => t.GetMember(null, MemberTypes.All, BindingFlags.Public | BindingFlags.Instance));
}
[Fact]
public static void TestExtraBitsIgnored()
{
Type t = typeof(Mixed).Project();
MemberInfo[] expectedMembers = t.GetMember("*", MemberTypes.All, BindingFlags.Public | BindingFlags.Instance);
MemberInfo[] actualMembers = t.GetMember("*", (MemberTypes)(-1), BindingFlags.Public | BindingFlags.Instance);
Assert.Equal(expectedMembers.Length, actualMembers.Length);
}
[Fact]
public static void TestTypeInfoIsSynonymForNestedInfo()
{
Type t = typeof(Mixed).Project();
MemberInfo[] expectedMembers = t.GetMember("*", MemberTypes.NestedType, BindingFlags.Public | BindingFlags.Instance);
Assert.Equal(1, expectedMembers.Length);
Assert.Equal(typeof(Mixed.MyType).Project(), expectedMembers[0]);
MemberInfo[] actualMembers;
actualMembers = t.GetMember("*", MemberTypes.TypeInfo, BindingFlags.Public | BindingFlags.Instance);
Assert.Equal<MemberInfo>(expectedMembers, actualMembers);
actualMembers = t.GetMember("*", MemberTypes.NestedType | MemberTypes.TypeInfo, BindingFlags.Public | BindingFlags.Instance);
Assert.Equal<MemberInfo>(expectedMembers, actualMembers);
}
[Fact]
public static void TestReturnType()
{
Type t = typeof(Mixed).Project();
// Desktop compat: Type.GetMember() returns the most specific array type possible given the MemberType combinations passed in.
for (MemberTypes memberType = (MemberTypes)0; memberType <= MemberTypes.All; memberType++)
{
MemberInfo[] m = t.GetMember("*", memberType, BindingFlags.Public | BindingFlags.Instance);
Type actualElementType = m.GetType().GetElementType();
switch (memberType)
{
case MemberTypes.Constructor:
Assert.Equal(typeof(ConstructorInfo), actualElementType);
break;
case MemberTypes.Event:
Assert.Equal(typeof(EventInfo), actualElementType);
break;
case MemberTypes.Field:
Assert.Equal(typeof(FieldInfo), actualElementType);
break;
case MemberTypes.Method:
Assert.Equal(typeof(MethodInfo), actualElementType);
break;
case MemberTypes.Constructor | MemberTypes.Method:
Assert.Equal(typeof(MethodBase), actualElementType);
break;
case MemberTypes.Property:
Assert.Equal(typeof(PropertyInfo), actualElementType);
break;
case MemberTypes.NestedType:
case MemberTypes.TypeInfo:
Assert.Equal(typeof(Type), actualElementType);
break;
default:
Assert.Equal(typeof(MemberInfo), actualElementType);
break;
}
}
}
[Fact]
public static void TestMemberTypeCombos()
{
Type t = typeof(Mixed);
for (MemberTypes memberType = (MemberTypes)0; memberType <= MemberTypes.All; memberType++)
{
MemberInfo[] members = t.GetMember("*", memberType, BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
int constructors = 0;
int events = 0;
int fields = 0;
int methods = 0;
int nestedTypes = 0;
int properties = 0;
foreach (MemberInfo member in members)
{
switch (member.MemberType)
{
case MemberTypes.Constructor: constructors++; break;
case MemberTypes.Event: events++; break;
case MemberTypes.Field: fields++; break;
case MemberTypes.Method: methods++; break;
case MemberTypes.NestedType: nestedTypes++; break;
case MemberTypes.Property: properties++; break;
default:
Assert.True(false, "Bad member type.");
break;
}
}
int expectedConstructors = ((memberType & MemberTypes.Constructor) == 0) ? 0 : 1;
int expectedEvents = ((memberType & MemberTypes.Event) == 0) ? 0 : 1;
int expectedFields = ((memberType & MemberTypes.Field) == 0) ? 0 : 1;
int expectedMethods = ((memberType & MemberTypes.Method) == 0) ? 0 : 4;
int expectedNestedTypes = ((memberType & (MemberTypes.NestedType | MemberTypes.TypeInfo)) == 0) ? 0 : 1;
int expectedProperties = ((memberType & MemberTypes.Property) == 0) ? 0 : 1;
Assert.Equal(expectedConstructors, constructors);
Assert.Equal(expectedEvents, events);
Assert.Equal(expectedFields, fields);
Assert.Equal(expectedMethods, methods);
Assert.Equal(expectedNestedTypes, nestedTypes);
Assert.Equal(expectedProperties, properties);
}
}
[Fact]
public static void TestZeroMatch()
{
Type t = typeof(Mixed).Project();
MemberInfo[] members = t.GetMember("NOSUCHMEMBER", MemberTypes.All, BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
Assert.Equal(0, members.Length);
}
[Fact]
public static void TestCaseSensitive1()
{
Type t = typeof(Mixed).Project();
MemberInfo[] members = t.GetMember("MyField", MemberTypes.All, BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
Assert.Equal(1, members.Length);
Assert.True(members[0] is FieldInfo);
Assert.Equal("MyField", members[0].Name);
}
[Fact]
public static void TestCaseSensitive2()
{
Type t = typeof(Mixed).Project();
MemberInfo[] members = t.GetMember("MYFIELD", MemberTypes.All, BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
Assert.Equal(0, members.Length);
}
[Fact]
public static void TestCaseInsensitive1()
{
Type t = typeof(Mixed).Project();
MemberInfo[] members = t.GetMember("MyField", MemberTypes.All, BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.IgnoreCase);
Assert.Equal(1, members.Length);
Assert.True(members[0] is FieldInfo);
Assert.Equal("MyField", members[0].Name);
}
[Fact]
public static void TestCaseInsensitive2()
{
Type t = typeof(Mixed).Project();
MemberInfo[] members = t.GetMember("MYfiELD", MemberTypes.All, BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.IgnoreCase);
Assert.Equal(1, members.Length);
Assert.True(members[0] is FieldInfo);
Assert.Equal("MyField", members[0].Name);
}
[Fact]
public static void TestPrefixCaseSensitive1()
{
Type t = typeof(Mixed).Project();
MemberInfo[] members = t.GetMember("MyFi*", MemberTypes.All, BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
Assert.Equal(1, members.Length);
Assert.True(members[0] is FieldInfo);
Assert.Equal("MyField", members[0].Name);
}
[Fact]
public static void TestPrefixCaseSensitive2()
{
Type t = typeof(Mixed).Project();
MemberInfo[] members = t.GetMember("MYFI*", MemberTypes.All, BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
Assert.Equal(0, members.Length);
}
[Fact]
public static void TestPrefixCaseInsensitive1()
{
Type t = typeof(Mixed).Project();
MemberInfo[] members = t.GetMember("MyFi*", MemberTypes.All, BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.IgnoreCase);
Assert.Equal(1, members.Length);
Assert.True(members[0] is FieldInfo);
Assert.Equal("MyField", members[0].Name);
}
[Fact]
public static void TestPrefixCaseInsensitive2()
{
Type t = typeof(Mixed).Project();
MemberInfo[] members = t.GetMember("MYFI*", MemberTypes.All, BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.IgnoreCase);
Assert.Equal(1, members.Length);
Assert.True(members[0] is FieldInfo);
Assert.Equal("MyField", members[0].Name);
}
private class Mixed
{
public Mixed() { }
public event Action MyEvent { add { } remove { } }
public int MyField;
public void MyMethod() { }
public class MyType { }
public int MyProperty { get; }
}
}
}
| |
//---------------------------------------------------------------------------
//
// <copyright file="FigureLengthConverter.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
//
// Description: Figure length converter implementation
//
// History:
// 06/23/2005 : ghermann - Created (Adapted from GridLengthConverter)
//
//---------------------------------------------------------------------------
using MS.Internal;
using MS.Utility;
using System.ComponentModel;
using System.Windows;
using System;
using System.Security;
using System.ComponentModel.Design.Serialization;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Windows.Markup;
namespace System.Windows
{
/// <summary>
/// FigureLengthConverter - Converter class for converting
/// instances of other types to and from FigureLength instances.
/// </summary>
public class FigureLengthConverter: TypeConverter
{
//-------------------------------------------------------------------
//
// Public Methods
//
//-------------------------------------------------------------------
#region Public Methods
/// <summary>
/// Checks whether or not this class can convert from a given type.
/// </summary>
/// <param name="typeDescriptorContext">The ITypeDescriptorContext
/// for this call.</param>
/// <param name="sourceType">The Type being queried for support.</param>
/// <returns>
/// <c>true</c> if thie converter can convert from the provided type,
/// <c>false</c> otherwise.
/// </returns>
public override bool CanConvertFrom(
ITypeDescriptorContext typeDescriptorContext,
Type sourceType)
{
// We can only handle strings, integral and floating types
TypeCode tc = Type.GetTypeCode(sourceType);
switch (tc)
{
case TypeCode.String:
case TypeCode.Decimal:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.UInt16:
case TypeCode.UInt32:
case TypeCode.UInt64:
return true;
default:
return false;
}
}
/// <summary>
/// Checks whether or not this class can convert to a given type.
/// </summary>
/// <param name="typeDescriptorContext">The ITypeDescriptorContext
/// for this call.</param>
/// <param name="destinationType">The Type being queried for support.</param>
/// <returns>
/// <c>true</c> if this converter can convert to the provided type,
/// <c>false</c> otherwise.
/// </returns>
public override bool CanConvertTo(
ITypeDescriptorContext typeDescriptorContext,
Type destinationType)
{
return ( destinationType == typeof(InstanceDescriptor)
|| destinationType == typeof(string) );
}
/// <summary>
/// Attempts to convert to a FigureLength from the given object.
/// </summary>
/// <param name="typeDescriptorContext">The ITypeDescriptorContext for this call.</param>
/// <param name="cultureInfo">The CultureInfo which is respected when converting.</param>
/// <param name="source">The object to convert to a FigureLength.</param>
/// <returns>
/// The FigureLength instance which was constructed.
/// </returns>
/// <exception cref="ArgumentNullException">
/// An ArgumentNullException is thrown if the example object is null.
/// </exception>
/// <exception cref="ArgumentException">
/// An ArgumentException is thrown if the example object is not null
/// and is not a valid type which can be converted to a FigureLength.
/// </exception>
public override object ConvertFrom(
ITypeDescriptorContext typeDescriptorContext,
CultureInfo cultureInfo,
object source)
{
if (source != null)
{
if (source is string)
{
return (FromString((string)source, cultureInfo));
}
else
{
return new FigureLength(Convert.ToDouble(source, cultureInfo)); //conversion from numeric type
}
}
throw GetConvertFromException(source);
}
/// <summary>
/// Attempts to convert a FigureLength instance to the given type.
/// </summary>
/// <param name="typeDescriptorContext">The ITypeDescriptorContext for this call.</param>
/// <param name="cultureInfo">The CultureInfo which is respected when converting.</param>
/// <param name="value">The FigureLength to convert.</param>
/// <param name="destinationType">The type to which to convert the FigureLength instance.</param>
/// <returns>
/// The object which was constructed.
/// </returns>
/// <exception cref="ArgumentNullException">
/// An ArgumentNullException is thrown if the example object is null.
/// </exception>
/// <exception cref="ArgumentException">
/// An ArgumentException is thrown if the object is not null and is not a FigureLength,
/// or if the destinationType isn't one of the valid destination types.
/// </exception>
///<SecurityNote>
/// Critical: calls InstanceDescriptor ctor which LinkDemands
/// PublicOK: can only make an InstanceDescriptor for FigureLength, not an arbitrary class
///</SecurityNote>
[SecurityCritical]
public override object ConvertTo(
ITypeDescriptorContext typeDescriptorContext,
CultureInfo cultureInfo,
object value,
Type destinationType)
{
if (destinationType == null)
{
throw new ArgumentNullException("destinationType");
}
if ( value != null
&& value is FigureLength )
{
FigureLength fl = (FigureLength)value;
if (destinationType == typeof(string))
{
return (ToString(fl, cultureInfo));
}
if (destinationType == typeof(InstanceDescriptor))
{
ConstructorInfo ci = typeof(FigureLength).GetConstructor(new Type[] { typeof(double), typeof(FigureUnitType) });
return (new InstanceDescriptor(ci, new object[] { fl.Value, fl.FigureUnitType }));
}
}
throw GetConvertToException(value, destinationType);
}
#endregion Public Methods
//-------------------------------------------------------------------
//
// Internal Methods
//
//-------------------------------------------------------------------
#region Internal Methods
/// <summary>
/// Converts a FigureLength instance to a String given the CultureInfo.
/// </summary>
/// <param name="fl">FigureLength instance to convert.</param>
/// <param name="cultureInfo">Culture Info.</param>
/// <returns>String representation of the object.</returns>
static internal string ToString(FigureLength fl, CultureInfo cultureInfo)
{
switch (fl.FigureUnitType)
{
// for Auto print out "Auto". value is always "1.0"
case FigureUnitType.Auto:
return ("Auto");
case FigureUnitType.Pixel:
return Convert.ToString(fl.Value, cultureInfo);
default:
return Convert.ToString(fl.Value, cultureInfo) + " " + fl.FigureUnitType.ToString();
}
}
/// <summary>
/// Parses a FigureLength from a string given the CultureInfo.
/// </summary>
/// <param name="s">String to parse from.</param>
/// <param name="cultureInfo">Culture Info.</param>
/// <returns>Newly created FigureLength instance.</returns>
/// <remarks>
/// Formats:
/// "[value][unit]"
/// [value] is a double
/// [unit] is a string in FigureLength._unitTypes connected to a FigureUnitType
/// "[value]"
/// As above, but the FigureUnitType is assumed to be FigureUnitType.Pixel
/// "[unit]"
/// As above, but the value is assumed to be 1.0
/// This is only acceptable for a subset of FigureUnitType: Auto
/// </remarks>
static internal FigureLength FromString(string s, CultureInfo cultureInfo)
{
double value;
FigureUnitType unit;
XamlFigureLengthSerializer.FromString(s, cultureInfo,
out value, out unit);
return (new FigureLength(value, unit));
}
#endregion Internal Methods
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.