context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
using System;
using System.Linq;
using System.Web;
using System.Web.Compilation;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.SessionState;
using Umbraco.Core;
using Umbraco.Core.Logging;
using Umbraco.Core.Composing;
using Umbraco.Web.Models;
using Umbraco.Web.Routing;
using System.Collections.Generic;
using Current = Umbraco.Web.Composing.Current;
using Umbraco.Web.Features;
namespace Umbraco.Web.Mvc
{
public class RenderRouteHandler : IRouteHandler
{
// Define reserved dictionary keys for controller, action and area specified in route additional values data
internal static class ReservedAdditionalKeys
{
internal const string Controller = "c";
internal const string Action = "a";
internal const string Area = "ar";
}
private readonly IControllerFactory _controllerFactory;
private readonly IUmbracoContextAccessor _umbracoContextAccessor;
private readonly UmbracoContext _umbracoContext;
public RenderRouteHandler(IUmbracoContextAccessor umbracoContextAccessor, IControllerFactory controllerFactory)
{
_umbracoContextAccessor = umbracoContextAccessor ?? throw new ArgumentNullException(nameof(umbracoContextAccessor));
_controllerFactory = controllerFactory ?? throw new ArgumentNullException(nameof(controllerFactory));
}
public RenderRouteHandler(UmbracoContext umbracoContext, IControllerFactory controllerFactory)
{
_umbracoContext = umbracoContext ?? throw new ArgumentNullException(nameof(umbracoContext));
_controllerFactory = controllerFactory ?? throw new ArgumentNullException(nameof(controllerFactory));
}
private UmbracoContext UmbracoContext => _umbracoContext ?? _umbracoContextAccessor.UmbracoContext;
private UmbracoFeatures Features => Current.Factory.GetInstance<UmbracoFeatures>(); // TODO: inject
#region IRouteHandler Members
/// <summary>
/// Assigns the correct controller based on the Umbraco request and returns a standard MvcHandler to process the response,
/// this also stores the render model into the data tokens for the current RouteData.
/// </summary>
/// <param name="requestContext"></param>
/// <returns></returns>
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
if (UmbracoContext == null)
{
throw new NullReferenceException("There is no current UmbracoContext, it must be initialized before the RenderRouteHandler executes");
}
var request = UmbracoContext.PublishedRequest;
if (request == null)
{
throw new NullReferenceException("There is no current PublishedRequest, it must be initialized before the RenderRouteHandler executes");
}
SetupRouteDataForRequest(
new ContentModel(request.PublishedContent),
requestContext,
request);
return GetHandlerForRoute(requestContext, request);
}
#endregion
/// <summary>
/// Ensures that all of the correct DataTokens are added to the route values which are all required for rendering front-end umbraco views
/// </summary>
/// <param name="contentModel"></param>
/// <param name="requestContext"></param>
/// <param name="frequest"></param>
internal void SetupRouteDataForRequest(ContentModel contentModel, RequestContext requestContext, PublishedRequest frequest)
{
//put essential data into the data tokens, the 'umbraco' key is required to be there for the view engine
requestContext.RouteData.DataTokens.Add(Core.Constants.Web.UmbracoDataToken, contentModel); //required for the ContentModelBinder and view engine
requestContext.RouteData.DataTokens.Add(Core.Constants.Web.PublishedDocumentRequestDataToken, frequest); //required for RenderMvcController
requestContext.RouteData.DataTokens.Add(Core.Constants.Web.UmbracoContextDataToken, UmbracoContext); //required for UmbracoViewPage
}
private void UpdateRouteDataForRequest(ContentModel contentModel, RequestContext requestContext)
{
if (contentModel == null) throw new ArgumentNullException(nameof(contentModel));
if (requestContext == null) throw new ArgumentNullException(nameof(requestContext));
requestContext.RouteData.DataTokens[Core.Constants.Web.UmbracoDataToken] = contentModel;
// the rest should not change -- it's only the published content that has changed
}
/// <summary>
/// Checks the request and query strings to see if it matches the definition of having a Surface controller
/// posted/get value, if so, then we return a PostedDataProxyInfo object with the correct information.
/// </summary>
/// <param name="requestContext"></param>
/// <returns></returns>
internal static PostedDataProxyInfo GetFormInfo(RequestContext requestContext)
{
if (requestContext == null) throw new ArgumentNullException(nameof(requestContext));
//if it is a POST/GET then a value must be in the request
if (requestContext.HttpContext.Request.QueryString["ufprt"].IsNullOrWhiteSpace()
&& requestContext.HttpContext.Request.Form["ufprt"].IsNullOrWhiteSpace())
{
return null;
}
string encodedVal;
switch (requestContext.HttpContext.Request.RequestType)
{
case "POST":
//get the value from the request.
//this field will contain an encrypted version of the surface route vals.
encodedVal = requestContext.HttpContext.Request.Form["ufprt"];
break;
case "GET":
//this field will contain an encrypted version of the surface route vals.
encodedVal = requestContext.HttpContext.Request.QueryString["ufprt"];
break;
default:
return null;
}
if (!UmbracoHelper.DecryptAndValidateEncryptedRouteString(encodedVal, out var decodedParts))
return null;
foreach (var item in decodedParts.Where(x => new[] {
ReservedAdditionalKeys.Controller,
ReservedAdditionalKeys.Action,
ReservedAdditionalKeys.Area }.Contains(x.Key) == false))
{
// Populate route with additional values which aren't reserved values so they eventually to action parameters
requestContext.RouteData.Values[item.Key] = item.Value;
}
//return the proxy info without the surface id... could be a local controller.
return new PostedDataProxyInfo
{
ControllerName = HttpUtility.UrlDecode(decodedParts.Single(x => x.Key == ReservedAdditionalKeys.Controller).Value),
ActionName = HttpUtility.UrlDecode(decodedParts.Single(x => x.Key == ReservedAdditionalKeys.Action).Value),
Area = HttpUtility.UrlDecode(decodedParts.Single(x => x.Key == ReservedAdditionalKeys.Area).Value),
};
}
/// <summary>
/// Handles a posted form to an Umbraco URL and ensures the correct controller is routed to and that
/// the right DataTokens are set.
/// </summary>
/// <param name="requestContext"></param>
/// <param name="postedInfo"></param>
internal static IHttpHandler HandlePostedValues(RequestContext requestContext, PostedDataProxyInfo postedInfo)
{
if (requestContext == null) throw new ArgumentNullException(nameof(requestContext));
if (postedInfo == null) throw new ArgumentNullException(nameof(postedInfo));
//set the standard route values/tokens
requestContext.RouteData.Values["controller"] = postedInfo.ControllerName;
requestContext.RouteData.Values["action"] = postedInfo.ActionName;
IHttpHandler handler;
//get the route from the defined routes
using (RouteTable.Routes.GetReadLock())
{
Route surfaceRoute;
//find the controller in the route table
var surfaceRoutes = RouteTable.Routes.OfType<Route>()
.Where(x => x.Defaults != null &&
x.Defaults.ContainsKey("controller") &&
x.Defaults["controller"].ToString().InvariantEquals(postedInfo.ControllerName) &&
// Only return surface controllers
x.DataTokens["umbraco"].ToString().InvariantEquals("surface") &&
// Check for area token if the area is supplied
(postedInfo.Area.IsNullOrWhiteSpace() ? !x.DataTokens.ContainsKey("area") : x.DataTokens["area"].ToString().InvariantEquals(postedInfo.Area)))
.ToList();
// If more than one route is found, find one with a matching action
if (surfaceRoutes.Count > 1)
{
surfaceRoute = surfaceRoutes.FirstOrDefault(x =>
x.Defaults["action"] != null &&
x.Defaults["action"].ToString().InvariantEquals(postedInfo.ActionName));
}
else
{
surfaceRoute = surfaceRoutes.FirstOrDefault();
}
if (surfaceRoute == null)
throw new InvalidOperationException("Could not find a Surface controller route in the RouteTable for controller name " + postedInfo.ControllerName);
//set the area if one is there.
if (surfaceRoute.DataTokens.ContainsKey("area"))
{
requestContext.RouteData.DataTokens["area"] = surfaceRoute.DataTokens["area"];
}
//set the 'Namespaces' token so the controller factory knows where to look to construct it
if (surfaceRoute.DataTokens.ContainsKey("Namespaces"))
{
requestContext.RouteData.DataTokens["Namespaces"] = surfaceRoute.DataTokens["Namespaces"];
}
handler = surfaceRoute.RouteHandler.GetHttpHandler(requestContext);
}
return handler;
}
/// <summary>
/// Returns a RouteDefinition object based on the current content request
/// </summary>
/// <param name="requestContext"></param>
/// <param name="request"></param>
/// <returns></returns>
internal virtual RouteDefinition GetUmbracoRouteDefinition(RequestContext requestContext, PublishedRequest request)
{
if (requestContext == null) throw new ArgumentNullException(nameof(requestContext));
if (request == null) throw new ArgumentNullException(nameof(request));
var defaultControllerType = Current.DefaultRenderMvcControllerType;
var defaultControllerName = ControllerExtensions.GetControllerName(defaultControllerType);
//creates the default route definition which maps to the 'UmbracoController' controller
var def = new RouteDefinition
{
ControllerName = defaultControllerName,
ControllerType = defaultControllerType,
PublishedRequest = request,
ActionName = ((Route)requestContext.RouteData.Route).Defaults["action"].ToString(),
HasHijackedRoute = false
};
//check that a template is defined), if it doesn't and there is a hijacked route it will just route
// to the index Action
if (request.HasTemplate)
{
//the template Alias should always be already saved with a safe name.
//if there are hyphens in the name and there is a hijacked route, then the Action will need to be attributed
// with the action name attribute.
var templateName = request.TemplateAlias.Split('.')[0].ToSafeAlias();
def.ActionName = templateName;
}
//check if there's a custom controller assigned, base on the document type alias.
var controllerType = _controllerFactory.GetControllerTypeInternal(requestContext, request.PublishedContent.ContentType.Alias);
//check if that controller exists
if (controllerType != null)
{
//ensure the controller is of type IRenderMvcController and ControllerBase
if (TypeHelper.IsTypeAssignableFrom<IRenderController>(controllerType)
&& TypeHelper.IsTypeAssignableFrom<ControllerBase>(controllerType))
{
//set the controller and name to the custom one
def.ControllerType = controllerType;
def.ControllerName = ControllerExtensions.GetControllerName(controllerType);
if (def.ControllerName != defaultControllerName)
{
def.HasHijackedRoute = true;
}
}
else
{
Current.Logger.Warn<RenderRouteHandler>("The current Document Type {ContentTypeAlias} matches a locally declared controller of type {ControllerName}. Custom Controllers for Umbraco routing must implement '{UmbracoRenderController}' and inherit from '{UmbracoControllerBase}'.",
request.PublishedContent.ContentType.Alias,
controllerType.FullName,
typeof(IRenderController).FullName,
typeof(ControllerBase).FullName);
//we cannot route to this custom controller since it is not of the correct type so we'll continue with the defaults
// that have already been set above.
}
}
//store the route definition
requestContext.RouteData.DataTokens[Core.Constants.Web.UmbracoRouteDefinitionDataToken] = def;
return def;
}
internal IHttpHandler GetHandlerOnMissingTemplate(PublishedRequest request)
{
if (request == null) throw new ArgumentNullException(nameof(request));
// missing template, so we're in a 404 here
// so the content, if any, is a custom 404 page of some sort
if (request.HasPublishedContent == false)
// means the builder could not find a proper document to handle 404
return new PublishedContentNotFoundHandler();
if (request.HasTemplate == false)
// means the engine could find a proper document, but the document has no template
// at that point there isn't much we can do and there is no point returning
// to Mvc since Mvc can't do much
return new PublishedContentNotFoundHandler("In addition, no template exists to render the custom 404.");
return null;
}
/// <summary>
/// this will determine the controller and set the values in the route data
/// </summary>
/// <param name="requestContext"></param>
/// <param name="request"></param>
internal IHttpHandler GetHandlerForRoute(RequestContext requestContext, PublishedRequest request)
{
if (requestContext == null) throw new ArgumentNullException(nameof(requestContext));
if (request == null) throw new ArgumentNullException(nameof(request));
var routeDef = GetUmbracoRouteDefinition(requestContext, request);
//Need to check for a special case if there is form data being posted back to an Umbraco URL
var postedInfo = GetFormInfo(requestContext);
if (postedInfo != null)
{
return HandlePostedValues(requestContext, postedInfo);
}
//Here we need to check if there is no hijacked route and no template assigned,
//if this is the case we want to return a blank page, but we'll leave that up to the NoTemplateHandler.
//We also check if templates have been disabled since if they are then we're allowed to render even though there's no template,
//for example for json rendering in headless.
if ((request.HasTemplate == false && Features.Disabled.DisableTemplates == false)
&& routeDef.HasHijackedRoute == false)
{
request.UpdateToNotFound(); // request will go 404
// HandleHttpResponseStatus returns a value indicating that the request should
// not be processed any further, eg because it has been redirect. then, exit.
if (UmbracoModule.HandleHttpResponseStatus(requestContext.HttpContext, request, Current.Logger))
return null;
var handler = GetHandlerOnMissingTemplate(request);
// if it's not null it's the PublishedContentNotFoundHandler (no document was found to handle 404, or document with no template was found)
// if it's null it means that a document was found
// if we have a handler, return now
if (handler != null)
return handler;
// else we are running Mvc
// update the route data - because the PublishedContent has changed
UpdateRouteDataForRequest(
new ContentModel(request.PublishedContent),
requestContext);
// update the route definition
routeDef = GetUmbracoRouteDefinition(requestContext, request);
}
//no post values, just route to the controller/action required (local)
requestContext.RouteData.Values["controller"] = routeDef.ControllerName;
if (string.IsNullOrWhiteSpace(routeDef.ActionName) == false)
requestContext.RouteData.Values["action"] = routeDef.ActionName;
// Set the session state requirements
requestContext.HttpContext.SetSessionStateBehavior(GetSessionStateBehavior(requestContext, routeDef.ControllerName));
// reset the friendly path so in the controllers and anything occurring after this point in time,
//the URL is reset back to the original request.
requestContext.HttpContext.RewritePath(UmbracoContext.OriginalRequestUrl.PathAndQuery);
return new UmbracoMvcHandler(requestContext);
}
private SessionStateBehavior GetSessionStateBehavior(RequestContext requestContext, string controllerName)
{
return _controllerFactory.GetControllerSessionBehavior(requestContext, controllerName);
}
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ScrollViewerInertiaScroller.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Microsoft.Kinect.Toolkit.Controls
{
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Threading;
internal enum AnimationState
{
None,
Inertial,
Stopping
}
/// <summary>
/// Helper class to animate the viewport on a ScrollViewer using
/// a very simplistic physics model.
/// </summary>
internal class ScrollViewerInertiaScroller
{
private const double Friction = 1000.0;
private readonly DispatcherTimer timer = new DispatcherTimer();
private AnimationState currentState = AnimationState.None;
private DateTime lastTickTime;
private int horizontalDirection;
private int verticalDirection;
private Vector currentSpeed;
private ScrollViewer scrollViewer;
private bool slowEnoughForSelection = true;
private double rightScrollExtent;
private double bottomScrollExtent;
public ScrollViewerInertiaScroller()
{
// this does not necessarily guarantee fresh data per frame however. this should update once per draw instead.
this.timer.Interval = TimeSpan.FromMilliseconds(1000.0 / 120.0);
this.timer.Tick += this.TimerOnTick;
}
public event EventHandler<EventArgs> SlowEnoughForSelectionChanged;
public bool AnimatingHorizontally { get; set; }
public bool AnimatingVertically { get; set; }
public AnimationState AnimationState
{
get
{
return this.currentState;
}
}
public double CurrentFriction { get; set; }
public bool SlowEnoughForSelection
{
get
{
return this.slowEnoughForSelection;
}
set
{
bool oldValue = this.slowEnoughForSelection;
this.slowEnoughForSelection = value;
if ((oldValue != value) && (this.SlowEnoughForSelectionChanged != null))
{
this.SlowEnoughForSelectionChanged(this, EventArgs.Empty);
}
}
}
public Vector BounceBackVelocity { get; set; }
/// <summary>
/// Adjusts a speed value to grow non-linearly above the pre-defined speed cutoff
/// </summary>
/// <param name="speed">speed to convert</param>
/// <returns>converted speed</returns>
public static double GetConvertedEffectiveSpeed(double speed)
{
const double SpeedCutoff = 1600.0;
double finalSpeed = speed;
if (finalSpeed > SpeedCutoff)
{
finalSpeed = SpeedCutoff + Math.Pow(finalSpeed - SpeedCutoff, 0.85);
}
return finalSpeed;
}
/// <summary>
/// Start inertia scrolling
/// </summary>
/// <param name="view">View to animate</param>
/// <param name="initialVelocity">starting velocity in units per second</param>
/// <param name="state">the new animator state</param>
/// <param name="canScrollHorizontal">enables horizontal scrolling</param>
/// <param name="canScrollVertical">enables vertical scrolling</param>
public void Start(
ScrollViewer view, Vector initialVelocity, AnimationState state, bool canScrollHorizontal, bool canScrollVertical)
{
double newCurrentHorizontalVelocity = GetConvertedEffectiveSpeed(Math.Abs(initialVelocity.X));
double newCurrentVerticalVelocity = GetConvertedEffectiveSpeed(Math.Abs(initialVelocity.Y));
this.AnimatingHorizontally = canScrollHorizontal;
this.AnimatingVertically = canScrollVertical;
this.lastTickTime = DateTime.UtcNow;
this.currentSpeed = new Vector(newCurrentHorizontalVelocity, newCurrentVerticalVelocity);
this.SlowEnoughForSelection = false;
this.CurrentFriction = Friction;
this.horizontalDirection = Math.Sign(initialVelocity.X);
this.verticalDirection = Math.Sign(initialVelocity.Y);
this.currentState = state;
this.scrollViewer = view;
this.rightScrollExtent = this.scrollViewer.ExtentWidth - this.scrollViewer.ViewportWidth;
this.bottomScrollExtent = this.scrollViewer.ExtentHeight - this.scrollViewer.ViewportHeight;
this.timer.Start();
}
/// <summary>
/// Sets current speed to the greater of the current speed and the supplied speed
/// </summary>
/// <param name="velocity">new velocity to be applied, if greater than current velocity</param>
public void UpdateSpeedFromContinuousScrolling(Vector velocity)
{
var adjustedVelocity = new Vector(GetConvertedEffectiveSpeed(Math.Abs(velocity.X)), GetConvertedEffectiveSpeed(Math.Abs(velocity.Y)));
if (this.currentState != AnimationState.Inertial)
{
return;
}
if (this.AnimatingHorizontally && (-Math.Sign(velocity.X) == this.horizontalDirection))
{
this.currentSpeed.X = Math.Max(adjustedVelocity.X, this.currentSpeed.X);
}
if (this.AnimatingVertically && (-Math.Sign(velocity.Y) == this.verticalDirection))
{
this.currentSpeed.Y = Math.Max(adjustedVelocity.Y, this.currentSpeed.Y);
}
}
/// <summary>
/// Stop inertia scrolling
/// </summary>
public void Stop()
{
this.currentState = this.currentState == AnimationState.Inertial ? AnimationState.Stopping : AnimationState.None;
this.currentSpeed = new Vector(0, 0);
this.SlowEnoughForSelection = true;
}
private void TimerOnTick(object sender, EventArgs eventArgs)
{
const double MinSpeed = 30.0;
this.SlowEnoughForSelection = (this.currentSpeed.X <= MinSpeed) && (this.currentSpeed.Y <= MinSpeed);
if (this.scrollViewer == null)
{
return;
}
DateTime currentTime = DateTime.UtcNow;
double timeDelta = (currentTime - this.lastTickTime).TotalSeconds;
this.lastTickTime = currentTime;
if (this.currentState == AnimationState.None)
{
return;
}
if (this.currentState == AnimationState.Stopping)
{
this.timer.Stop();
this.currentState = AnimationState.None;
return;
}
// Figure out how far we should move the view
Vector pixelsToMove = this.currentSpeed * timeDelta;
pixelsToMove.X *= this.horizontalDirection;
pixelsToMove.Y *= this.verticalDirection;
var currentOffset = new Vector(scrollViewer.HorizontalOffset, scrollViewer.VerticalOffset);
var newOffset = currentOffset + pixelsToMove;
// Check the horizontal limits and snap to them when exceeded.
Vector bounceBackVelocity = new Vector(0.0, 0.0);
if (newOffset.X < 0)
{
// Reached left inner limit, so snap to it
newOffset.X = 0;
bounceBackVelocity.X = currentSpeed.X * this.horizontalDirection;
this.currentSpeed.X = 0.0;
}
else if (newOffset.X > this.rightScrollExtent)
{
// Reached right inner limit so snap to it
newOffset.X = this.rightScrollExtent;
bounceBackVelocity.X = currentSpeed.X * this.horizontalDirection;
this.currentSpeed.X = 0.0;
}
else
{
// Apply friction
this.currentSpeed.X -= this.CurrentFriction * timeDelta;
}
// Check the vertical limits and snap to them when exceeded.
if (newOffset.Y < 0)
{
// Reached top inner limit, so snap to it
newOffset.Y = 0;
bounceBackVelocity.Y = currentSpeed.Y * this.verticalDirection;
this.currentSpeed.Y = 0.0;
}
else if (newOffset.Y > this.bottomScrollExtent)
{
// Reached bottom inner limit so snap to it
newOffset.Y = this.bottomScrollExtent;
bounceBackVelocity.Y = currentSpeed.Y * this.verticalDirection;
this.currentSpeed.Y = 0.0;
}
else
{
// Apply friction
this.currentSpeed.Y -= this.CurrentFriction * timeDelta;
}
this.BounceBackVelocity = bounceBackVelocity;
if (this.AnimatingHorizontally)
{
this.scrollViewer.ScrollToHorizontalOffset(newOffset.X);
}
if (this.AnimatingVertically)
{
this.scrollViewer.ScrollToVerticalOffset(newOffset.Y);
}
if ((this.currentSpeed.X < MinSpeed) && (this.currentSpeed.Y < MinSpeed))
{
this.Stop();
}
}
}
}
| |
using System;
using Csla;
using ParentLoad.DataAccess;
using ParentLoad.DataAccess.ERLevel;
namespace ParentLoad.Business.ERLevel
{
/// <summary>
/// A07_Country_Child (editable child object).<br/>
/// This is a generated base class of <see cref="A07_Country_Child"/> business object.
/// </summary>
/// <remarks>
/// This class is an item of <see cref="A06_Country"/> collection.
/// </remarks>
[Serializable]
public partial class A07_Country_Child : BusinessBase<A07_Country_Child>
{
#region State Fields
[NotUndoable]
[NonSerialized]
internal int country_ID1 = 0;
#endregion
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="Country_Child_Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> Country_Child_NameProperty = RegisterProperty<string>(p => p.Country_Child_Name, "Country Child Name");
/// <summary>
/// Gets or sets the Country Child Name.
/// </summary>
/// <value>The Country Child Name.</value>
public string Country_Child_Name
{
get { return GetProperty(Country_Child_NameProperty); }
set { SetProperty(Country_Child_NameProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="A07_Country_Child"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="A07_Country_Child"/> object.</returns>
internal static A07_Country_Child NewA07_Country_Child()
{
return DataPortal.CreateChild<A07_Country_Child>();
}
/// <summary>
/// Factory method. Loads a <see cref="A07_Country_Child"/> object from the given A07_Country_ChildDto.
/// </summary>
/// <param name="data">The <see cref="A07_Country_ChildDto"/>.</param>
/// <returns>A reference to the fetched <see cref="A07_Country_Child"/> object.</returns>
internal static A07_Country_Child GetA07_Country_Child(A07_Country_ChildDto data)
{
A07_Country_Child obj = new A07_Country_Child();
// show the framework that this is a child object
obj.MarkAsChild();
obj.Fetch(data);
obj.MarkOld();
return obj;
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="A07_Country_Child"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public A07_Country_Child()
{
// Use factory methods and do not use direct creation.
// show the framework that this is a child object
MarkAsChild();
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="A07_Country_Child"/> object properties.
/// </summary>
[Csla.RunLocal]
protected override void Child_Create()
{
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="A07_Country_Child"/> object from the given <see cref="A07_Country_ChildDto"/>.
/// </summary>
/// <param name="data">The A07_Country_ChildDto to use.</param>
private void Fetch(A07_Country_ChildDto data)
{
// Value properties
LoadProperty(Country_Child_NameProperty, data.Country_Child_Name);
// parent properties
country_ID1 = data.Parent_Country_ID;
var args = new DataPortalHookArgs(data);
OnFetchRead(args);
}
/// <summary>
/// Inserts a new <see cref="A07_Country_Child"/> object in the database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert(A06_Country parent)
{
var dto = new A07_Country_ChildDto();
dto.Parent_Country_ID = parent.Country_ID;
dto.Country_Child_Name = Country_Child_Name;
using (var dalManager = DalFactoryParentLoad.GetManager())
{
var args = new DataPortalHookArgs(dto);
OnInsertPre(args);
var dal = dalManager.GetProvider<IA07_Country_ChildDal>();
using (BypassPropertyChecks)
{
var resultDto = dal.Insert(dto);
args = new DataPortalHookArgs(resultDto);
}
OnInsertPost(args);
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="A07_Country_Child"/> object.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update(A06_Country parent)
{
if (!IsDirty)
return;
var dto = new A07_Country_ChildDto();
dto.Parent_Country_ID = parent.Country_ID;
dto.Country_Child_Name = Country_Child_Name;
using (var dalManager = DalFactoryParentLoad.GetManager())
{
var args = new DataPortalHookArgs(dto);
OnUpdatePre(args);
var dal = dalManager.GetProvider<IA07_Country_ChildDal>();
using (BypassPropertyChecks)
{
var resultDto = dal.Update(dto);
args = new DataPortalHookArgs(resultDto);
}
OnUpdatePost(args);
}
}
/// <summary>
/// Self deletes the <see cref="A07_Country_Child"/> object from database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf(A06_Country parent)
{
using (var dalManager = DalFactoryParentLoad.GetManager())
{
var args = new DataPortalHookArgs();
OnDeletePre(args);
var dal = dalManager.GetProvider<IA07_Country_ChildDal>();
using (BypassPropertyChecks)
{
dal.Delete(parent.Country_ID);
}
OnDeletePost(args);
}
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
// <OWNER>[....]</OWNER>
//
//
// RNGCryptoServiceProvider.cs
//
namespace System.Security.Cryptography {
using Microsoft.Win32;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
#if !FEATURE_CORECLR
[System.Runtime.InteropServices.ComVisible(true)]
#endif // !FEATURE_CORECLR
public sealed class RNGCryptoServiceProvider : RandomNumberGenerator {
#if !FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
SafeProvHandle m_safeProvHandle;
bool m_ownsHandle;
#else // !FEATURE_CORECLR
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
SafeCspHandle m_cspHandle;
#endif // !FEATURE_CORECLR
//
// public constructors
//
#if !FEATURE_CORECLR
#if !FEATURE_PAL
public RNGCryptoServiceProvider() : this((CspParameters) null) {}
#else // !FEATURE_PAL
public RNGCryptoServiceProvider() { }
#endif // !FEATURE_PAL
#if !FEATURE_PAL
public RNGCryptoServiceProvider(string str) : this((CspParameters) null) {}
public RNGCryptoServiceProvider(byte[] rgb) : this((CspParameters) null) {}
[System.Security.SecuritySafeCritical] // auto-generated
public RNGCryptoServiceProvider(CspParameters cspParams) {
if (cspParams != null) {
m_safeProvHandle = Utils.AcquireProvHandle(cspParams);
m_ownsHandle = true;
}
else {
m_safeProvHandle = Utils.StaticProvHandle;
m_ownsHandle = false;
}
}
[System.Security.SecuritySafeCritical] // auto-generated
protected override void Dispose(bool disposing) {
base.Dispose(disposing);
if (disposing && m_ownsHandle) {
m_safeProvHandle.Dispose();
}
}
#endif // !FEATURE_PAL
#else // !FEATURE_CORECLR
#if FEATURE_CORECLR
[System.Security.SecuritySafeCritical] // auto-generated
#endif
public RNGCryptoServiceProvider() {
m_cspHandle = CapiNative.AcquireCsp(null,
CapiNative.ProviderNames.MicrosoftEnhanced,
CapiNative.ProviderType.RsaFull,
CapiNative.CryptAcquireContextFlags.VerifyContext);
}
#endif // !FEATURE_CORECLR
//
// public methods
//
#if !FEATURE_CORECLR
[System.Security.SecuritySafeCritical] // auto-generated
public override void GetBytes(byte[] data) {
if (data == null) throw new ArgumentNullException("data");
Contract.EndContractBlock();
#if !FEATURE_PAL
GetBytes(m_safeProvHandle, data, data.Length);
#else
if (!Win32Native.Random(true, data, data.Length))
throw new CryptographicException(Marshal.GetLastWin32Error());
#endif // !FEATURE_PAL
}
[System.Security.SecuritySafeCritical] // auto-generated
public override void GetNonZeroBytes(byte[] data) {
if (data == null)
throw new ArgumentNullException("data");
Contract.EndContractBlock();
#if !FEATURE_PAL
GetNonZeroBytes(m_safeProvHandle, data, data.Length);
#else
GetBytes(data);
int indexOfFirst0Byte = data.Length;
for (int i = 0; i < data.Length; i++) {
if (data[i] == 0) {
indexOfFirst0Byte = i;
break;
}
}
for (int i = indexOfFirst0Byte; i < data.Length; i++) {
if (data[i] != 0) {
data[indexOfFirst0Byte++] = data[i];
}
}
while (indexOfFirst0Byte < data.Length) {
// this should be more than enough to fill the rest in one iteration
byte[] tmp = new byte[2 * (data.Length - indexOfFirst0Byte)];
GetBytes(tmp);
for (int i = 0; i < tmp.Length; i++) {
if (tmp[i] != 0) {
data[indexOfFirst0Byte++] = tmp[i];
if (indexOfFirst0Byte >= data.Length) break;
}
}
}
#endif // !FEATURE_PAL
}
#else // !FEATURE_CORECLR
#if FEATURE_CORECLR
[System.Security.SecuritySafeCritical] // auto-generated
#endif
protected override void Dispose(bool disposing) {
try {
if (disposing) {
if (m_cspHandle != null) {
m_cspHandle.Dispose();
}
}
}
finally {
base.Dispose(disposing);
}
}
#if FEATURE_CORECLR
[System.Security.SecuritySafeCritical] // auto-generated
#endif
public override void GetBytes(byte[] data) {
if (data == null) {
throw new ArgumentNullException("data");
}
Contract.EndContractBlock();
if (data.Length > 0) {
CapiNative.GenerateRandomBytes(m_cspHandle, data);
}
}
#if FEATURE_CORECLR
[System.Security.SecuritySafeCritical] // auto-generated
#endif
public override void GetBytes(byte[] data, int offset, int count) {
if (data == null) throw new ArgumentNullException("data");
if (offset < 0) throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (count < 0) throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (offset + count > data.Length) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
if (count > 0) {
CapiNative.GenerateRandomBytes(m_cspHandle, data, offset, count);
}
}
#endif // !FEATURE_CORECLR
#if !FEATURE_PAL
[System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
[ResourceExposure(ResourceScope.None)]
private static extern void GetBytes(SafeProvHandle hProv, byte[] randomBytes, int count);
[System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
[ResourceExposure(ResourceScope.None)]
private static extern void GetNonZeroBytes(SafeProvHandle hProv, byte[] randomBytes, int count);
#endif
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using Pathfinding;
namespace Pathfinding {
/** Simplifies a path using raycasting.
* \ingroup modifiers
* This modifier will try to remove as many nodes as possible from the path using raycasting (linecasting) to validate the node removal.
* Either graph raycasts or Physics.Raycast */
[AddComponentMenu ("Pathfinding/Modifiers/Raycast Simplifier")]
[System.Serializable]
public class RaycastModifier : MonoModifier {
#if UNITY_EDITOR
[UnityEditor.MenuItem ("CONTEXT/Seeker/Add Raycast Simplifier Modifier")]
public static void AddComp (UnityEditor.MenuCommand command) {
(command.context as Component).gameObject.AddComponent (typeof(RaycastModifier));
}
#endif
public override ModifierData input {
get { return ModifierData.VectorPath | ModifierData.StrictVectorPath; }
}
public override ModifierData output {
get { return ModifierData.VectorPath; }
}
[HideInInspector]
public bool useRaycasting = true;
[HideInInspector]
public LayerMask mask = -1;
[HideInInspector]
public bool thickRaycast = false;
[HideInInspector]
public float thickRaycastRadius = 0;
[HideInInspector]
public Vector3 raycastOffset = Vector3.zero;
/* Use the exact points used to query the path. If false, the start and end points will be snapped to the node positions.*/
//public bool exactStartAndEnd = true;
/* Ignore exact start and end points clamped by other modifiers. Other modifiers which modify the start and end points include for example the StartEndModifier. If enabled this modifier will ignore anything that modifier does when calculating the simplification.*/
//public bool overrideClampedExacts = false;
[HideInInspector]
public bool subdivideEveryIter = false;
public int iterations = 2;
/** Use raycasting on the graphs. Only currently works with GridGraph and NavmeshGraph and RecastGraph. \astarpro */
[HideInInspector]
public bool useGraphRaycasting = false;
/** To avoid too many memory allocations. An array is kept between the checks and filled in with the positions instead of allocating a new one every time.*/
private static List<Vector3> nodes;
public override void Apply (Path p, ModifierData source) {
//System.DateTime startTime = System.DateTime.UtcNow;
if (iterations <= 0) {
return;
}
if (nodes == null) {
nodes = new List<Vector3> (p.vectorPath.Count);
} else {
nodes.Clear ();
}
nodes.AddRange (p.vectorPath);
// = new List<Vector3> (p.vectorPath);
for (int it=0;it<iterations;it++) {
if (subdivideEveryIter && it != 0) {
if (nodes.Capacity < nodes.Count*3) {
nodes.Capacity = nodes.Count*3;
}
int preLength = nodes.Count;
for (int j=0;j<preLength-1;j++) {
nodes.Add (Vector3.zero);
nodes.Add (Vector3.zero);
}
for (int j=preLength-1;j > 0;j--) {
Vector3 p1 = nodes[j];
Vector3 p2 = nodes[j+1];
nodes[j*3] = nodes[j];
if (j != preLength-1) {
nodes[j*3+1] = Vector3.Lerp (p1,p2,0.33F);
nodes[j*3+2] = Vector3.Lerp (p1,p2,0.66F);
}
}
}
int i = 0;
while (i < nodes.Count-2) {
Vector3 start = nodes[i];
Vector3 end = nodes[i+2];
/*if (i == 0 && exactStartAndEnd) {
if (overrideClampedExacts) {
start = p.originalStartPoint;
} else {
start = p.startPoint;
}
}
if (i == nodes.Count-3 && exactStartAndEnd) {
if (overrideClampedExacts) {
end = p.originalEndPoint;
} else {
end = p.endPoint;
}
}*/
//if (ValidateLine (nodes[i],nodes[i+2],start,end)) {
System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch ();
watch.Start ();
if (ValidateLine (null,null,start,end)) {
//Debug.Log ("+++ Simplified "+i+" +++");
//Debug.DrawLine (start+raycastOffset,end+raycastOffset,new Color (1,0,0.5F));
nodes.RemoveAt (i+1);
//i++;
} else {
//Debug.DrawLine (start,end,Color.red);
i++;
}
watch.Stop ();
//Debug.Log ("Validate Line Took "+(watch.ElapsedTicks * 0.0001) +" Magnitude: "+(start-end).magnitude);
}
}
//ValidateLine (null,null,nodes[0],nodes[nodes.Count-1]);
p.vectorPath.Clear ();
p.vectorPath.AddRange (nodes);
//System.DateTime endTime2 = System.DateTime.UtcNow;
//float theTime2 = (endTime2-startTime).Ticks*0.0001F;
//Debug.Log ("Raycast Modifier : Time "+theTime2.ToString ("0.00"));
/*p.vectorPath = new Vector3[p.path.Length];
for (int i=0;i<p.path.Length;i++) {
Vector3 point = p.path[i].position;
if (i == 0 && exactStartAndEnd) {
if (overrideClampedExacts) {
point = p.originalStartPoint;
} else {
point = p.startPoint;
}
} else if (i == p.path.Length-1 && exactStartAndEnd) {
if (overrideClampedExacts) {
point = p.originalEndPoint;
} else {
point = p.endPoint;
}
}
p.vectorPath[i] = point;
}*/
}
public bool ValidateLine (GraphNode n1, GraphNode n2, Vector3 v1, Vector3 v2) {
if (useRaycasting) {
if (thickRaycast && thickRaycastRadius > 0) {
RaycastHit hit;
if (Physics.SphereCast (v1+raycastOffset, thickRaycastRadius,v2-v1,out hit, (v2-v1).magnitude,mask)) {
//Debug.DrawRay (hit.point,Vector3.up*5,Color.yellow);
return false;
}
} else {
RaycastHit hit;
if (Physics.Linecast (v1+raycastOffset,v2+raycastOffset,out hit, mask)) {
//Debug.DrawRay (hit.point,Vector3.up*5,Color.yellow);
return false;
}
}
}
if (useGraphRaycasting && n1 == null) {
n1 = AstarPath.active.GetNearest (v1).node;
n2 = AstarPath.active.GetNearest (v2).node;
}
if (useGraphRaycasting && n1 != null && n2 != null) {
NavGraph graph = AstarData.GetGraph (n1);
NavGraph graph2 = AstarData.GetGraph (n2);
if (graph != graph2) {
return false;
}
if (graph != null) {
IRaycastableGraph rayGraph = graph as IRaycastableGraph;
if (rayGraph != null) {
if (rayGraph.Linecast (v1,v2, n1)) {
return false;
}
}
}
}
return true;
}
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System.Collections.Generic;
using System.Linq;
using Xunit;
using Xunit.Abstractions;
namespace Tests
{
/// <summary>
/// Unit tests for ExtractorTests
/// </summary>
public class ExtractorTests
{
private readonly ITestOutputHelper _testOutputHelper;
public ExtractorTests(ITestOutputHelper testOutputHelper)
{
_testOutputHelper = testOutputHelper;
}
private static IEnumerable<Options> ExtractorTestData
{
get
{
yield return new Options(
sourceFile: @"Foxtrot\Tests\CheckerTests\CC1080.cs",
foxtrotOptions: null,
useContractReferenceAssemblies: true,
compilerOptions: null,
references: new[] { "mscorlib.dll", "System.dll", "ClousotTestHarness.dll" },
libPaths: new[] { @"Microsoft.Research\RegressionTest\ClousotTestHarness\bin\debug" },
compilerCode: "CS",
useBinDir: false,
useExe: false,
mustSucceed: true);
yield return new Options(
sourceFile: @"Foxtrot\Tests\CheckerTests\CC1078.cs",
foxtrotOptions: null,
useContractReferenceAssemblies: true,
compilerOptions: null,
references: new[] { "mscorlib.dll", "System.dll", "ClousotTestHarness.dll" },
libPaths: new[] { @"Microsoft.Research\RegressionTest\ClousotTestHarness\bin\debug" },
compilerCode: "CS",
useBinDir: false,
useExe: false,
mustSucceed: false);
yield return new Options(
sourceFile: @"Foxtrot\Tests\CheckerTests\CC1000.cs",
foxtrotOptions: null,
useContractReferenceAssemblies: true,
compilerOptions: null,
references: new[] { "mscorlib.dll", "System.dll", "ClousotTestHarness.dll" },
libPaths: new[] { @"Microsoft.Research\RegressionTest\ClousotTestHarness\bin\debug" },
compilerCode: "CS",
useBinDir: false,
useExe: false,
mustSucceed: false);
yield return new Options(
sourceFile: @"Foxtrot\Tests\CheckerTests\CC1001.cs",
foxtrotOptions: null,
useContractReferenceAssemblies: true,
compilerOptions: null,
references: new[] { "mscorlib.dll", "System.dll", "ClousotTestHarness.dll" },
libPaths: new[] { @"Microsoft.Research\RegressionTest\ClousotTestHarness\bin\debug" },
compilerCode: "CS",
useBinDir: false,
useExe: false,
mustSucceed: false);
yield return new Options(
sourceFile: @"Foxtrot\Tests\CheckerTests\CC1002.cs",
foxtrotOptions: null,
useContractReferenceAssemblies: true,
compilerOptions: null,
references: new[] { @"System.Core.dll" },
libPaths: new[] { @"Microsoft.Research\RegressionTest\ClousotTestHarness\bin\debug" },
compilerCode: "CS",
useBinDir: false,
useExe: false,
mustSucceed: false);
yield return new Options(
sourceFile: @"Foxtrot\Tests\CheckerTests\CC1003.cs",
foxtrotOptions: null,
useContractReferenceAssemblies: true,
compilerOptions: null,
references: new[] { "mscorlib.dll", "System.dll", "ClousotTestHarness.dll" },
libPaths: new[] { @"Microsoft.Research\RegressionTest\ClousotTestHarness\bin\debug" },
compilerCode: "CS",
useBinDir: false,
useExe: false,
mustSucceed: false);
yield return new Options(
sourceFile: @"Foxtrot\Tests\CheckerTests\CC1004.cs",
foxtrotOptions: null,
useContractReferenceAssemblies: true,
compilerOptions: null,
references: new[] { "mscorlib.dll", "System.dll", "ClousotTestHarness.dll" },
libPaths: new[] { @"Microsoft.Research\RegressionTest\ClousotTestHarness\bin\debug" },
compilerCode: "CS",
useBinDir: false,
useExe: false,
mustSucceed: false);
yield return new Options(
sourceFile: @"Foxtrot\Tests\CheckerTests\CC1005.cs",
foxtrotOptions: null,
useContractReferenceAssemblies: true,
compilerOptions: null,
references: new[] { "mscorlib.dll", "System.dll", "ClousotTestHarness.dll" },
libPaths: new[] { @"Microsoft.Research\RegressionTest\ClousotTestHarness\bin\debug" },
compilerCode: "CS",
useBinDir: false,
useExe: false,
mustSucceed: false);
yield return new Options(
sourceFile: @"Foxtrot\Tests\CheckerTests\CC1006.cs",
foxtrotOptions: null,
useContractReferenceAssemblies: true,
compilerOptions: null,
references: new[] { "mscorlib.dll", "System.dll", "ClousotTestHarness.dll" },
libPaths: new[] { @"Microsoft.Research\RegressionTest\ClousotTestHarness\bin\debug" },
compilerCode: "CS",
useBinDir: false,
useExe: false,
mustSucceed: false);
yield return new Options(
sourceFile: @"Foxtrot\Tests\CheckerTests\CC1008.cs",
foxtrotOptions: null,
useContractReferenceAssemblies: true,
compilerOptions: null,
references: new[] { "mscorlib.dll", "System.dll", "ClousotTestHarness.dll" },
libPaths: new[] { @"Microsoft.Research\RegressionTest\ClousotTestHarness\bin\debug" },
compilerCode: "CS",
useBinDir: false,
useExe: false,
mustSucceed: false);
yield return new Options(
sourceFile: @"Foxtrot\Tests\CheckerTests\CC1009.cs",
foxtrotOptions: null,
useContractReferenceAssemblies: true,
compilerOptions: null,
references: new[] { "mscorlib.dll", "System.dll", "ClousotTestHarness.dll" },
libPaths: new[] { @"Microsoft.Research\RegressionTest\ClousotTestHarness\bin\debug" },
compilerCode: "CS",
useBinDir: false,
useExe: false,
mustSucceed: false);
yield return new Options(
sourceFile: @"Foxtrot\Tests\CheckerTests\CC1010.cs",
foxtrotOptions: null,
useContractReferenceAssemblies: true,
compilerOptions: null,
references: new[] { "mscorlib.dll", "System.dll", "ClousotTestHarness.dll" },
libPaths: new[] { @"Microsoft.Research\RegressionTest\ClousotTestHarness\bin\debug" },
compilerCode: "CS",
useBinDir: false,
useExe: false,
mustSucceed: false);
yield return new Options(
sourceFile: @"Foxtrot\Tests\CheckerTests\CC1011.cs",
foxtrotOptions: null,
useContractReferenceAssemblies: true,
compilerOptions: null,
references: new[] { "mscorlib.dll", "System.dll", "ClousotTestHarness.dll" },
libPaths: new[] { @"Microsoft.Research\RegressionTest\ClousotTestHarness\bin\debug" },
compilerCode: "CS",
useBinDir: false,
useExe: false,
mustSucceed: false);
yield return new Options(
sourceFile: @"Foxtrot\Tests\CheckerTests\CC1012.cs",
foxtrotOptions: null,
useContractReferenceAssemblies: true,
compilerOptions: null,
references: new[] { "mscorlib.dll", "System.dll", "ClousotTestHarness.dll" },
libPaths: new[] { @"Microsoft.Research\RegressionTest\ClousotTestHarness\bin\debug" },
compilerCode: "CS",
useBinDir: false,
useExe: false,
mustSucceed: false);
yield return new Options(
sourceFile: @"Foxtrot\Tests\CheckerTests\CC1013.cs",
foxtrotOptions: null,
useContractReferenceAssemblies: true,
compilerOptions: null,
references: new[] { "mscorlib.dll", "System.dll", "ClousotTestHarness.dll" },
libPaths: new[] { @"Microsoft.Research\RegressionTest\ClousotTestHarness\bin\debug" },
compilerCode: "CS",
useBinDir: false,
useExe: false,
mustSucceed: false);
yield return new Options(
sourceFile: @"Foxtrot\Tests\CheckerTests\CC1014.cs",
foxtrotOptions: null,
useContractReferenceAssemblies: true,
compilerOptions: null,
references: new[] { "mscorlib.dll", "System.dll", "ClousotTestHarness.dll" },
libPaths: new[] { @"Microsoft.Research\RegressionTest\ClousotTestHarness\bin\debug" },
compilerCode: "CS",
useBinDir: false,
useExe: false,
mustSucceed: false);
yield return new Options(
sourceFile: @"Foxtrot\Tests\CheckerTests\CC1015.cs",
foxtrotOptions: null,
useContractReferenceAssemblies: true,
compilerOptions: @"/optimize",
references: new[] { "mscorlib.dll", "System.dll", "ClousotTestHarness.dll" },
libPaths: new[] { @"Microsoft.Research\RegressionTest\ClousotTestHarness\bin\debug" },
compilerCode: "",
useBinDir: false,
useExe: false,
mustSucceed: false);
yield return new Options(
sourceFile: @"Foxtrot\Tests\CheckerTests\CC1016.cs",
foxtrotOptions: null,
useContractReferenceAssemblies: true,
compilerOptions: null,
references: new[] { "mscorlib.dll", "System.dll", "ClousotTestHarness.dll" },
libPaths: new[] { @"Microsoft.Research\RegressionTest\ClousotTestHarness\bin\debug" },
compilerCode: "CS",
useBinDir: false,
useExe: false,
mustSucceed: false);
yield return new Options(
sourceFile: @"Foxtrot\Tests\CheckerTests\CheckerErrors.cs",
foxtrotOptions: null,
useContractReferenceAssemblies: true,
compilerOptions: null,
references: new[] { "mscorlib.dll", "System.dll", "ClousotTestHarness.dll" },
libPaths: new[] { @"Microsoft.Research\RegressionTest\ClousotTestHarness\bin\debug" },
compilerCode: "CS",
useBinDir: false,
useExe: false,
mustSucceed: false);
}
}
public static IEnumerable<object> ExtractorTest
{
get
{
return Enumerable.Range(0, ExtractorTestData.Count()).Select(i => new object[] { i });
}
}
[Theory]
[MemberData("ExtractorTest")]
[Trait("Category", "Runtime")]
[Trait("Category", "CoreTest")]
[Trait("Category", "V4.0")]
[Trait("Category", "Short")]
public void ExtractorFailures(int testIndex)
{
Options options = ExtractorTestData.ElementAt(testIndex);
options.ContractFramework = @".NetFramework\v4.0";
options.BuildFramework = @".NetFramework\v4.0";
options.FoxtrotOptions = options.FoxtrotOptions + " /nologo /verbose:4 /iw:-";
TestDriver.BuildExtractExpectFailureOrWarnings(_testOutputHelper, options);
}
}
}
| |
using DotArguments.Exceptions;
using DotArguments.Tests.TestContainers;
using NUnit.Framework;
namespace DotArguments.Tests
{
/// <summary>
/// Argument definition test.
/// </summary>
[TestFixture]
public class ArgumentDefinitionTest
{
/// <summary>
/// Test non corrupt containers.
/// </summary>
[Test]
public void TestNonCorruptContainer1()
{
var def = new ArgumentDefinition(typeof(ArgumentContainer1));
Assert.AreEqual(0, def.PositionalArguments.Count);
Assert.AreEqual(0, def.LongNamedArguments.Count);
Assert.AreEqual(0, def.ShortNamedArguments.Count);
Assert.IsNull(def.RemainingArguments);
}
/// <summary>
/// Test non corrupt containers.
/// </summary>
[Test]
public void TestNonCorruptContainer2()
{
var def = new ArgumentDefinition(typeof(ArgumentContainer2));
Assert.AreEqual(1, def.PositionalArguments.Count);
Assert.AreEqual(1, def.LongNamedArguments.Count);
Assert.AreEqual(1, def.ShortNamedArguments.Count);
Assert.IsNull(def.RemainingArguments);
Assert.AreEqual("Name", def.PositionalArguments[0].Property.Name);
Assert.AreEqual("Age", def.LongNamedArguments["age"].Property.Name);
Assert.AreEqual("Age", def.ShortNamedArguments['a'].Property.Name);
}
/// <summary>
/// Test non corrupt containers.
/// </summary>
[Test]
public void TestNonCorruptContainer3()
{
var def = new ArgumentDefinition(typeof(ArgumentContainer3));
Assert.AreEqual(1, def.PositionalArguments.Count);
Assert.AreEqual(0, def.LongNamedArguments.Count);
Assert.AreEqual(0, def.ShortNamedArguments.Count);
Assert.IsNotNull(def.RemainingArguments);
Assert.AreEqual("Name", def.PositionalArguments[0].Property.Name);
Assert.AreEqual("Remaining", def.RemainingArguments.Property.Name);
}
/// <summary>
/// Test non corrupt containers.
/// </summary>
[Test]
public void TestNonCorruptContainer4()
{
var def = new ArgumentDefinition(typeof(ArgumentContainer4));
Assert.AreEqual(0, def.PositionalArguments.Count);
Assert.AreEqual(1, def.LongNamedArguments.Count);
Assert.AreEqual(1, def.ShortNamedArguments.Count);
Assert.IsNull(def.RemainingArguments);
Assert.AreEqual("Verbose", def.LongNamedArguments["verbose"].Property.Name);
Assert.AreEqual("Verbose", def.ShortNamedArguments['v'].Property.Name);
}
/// <summary>
/// Test non corrupt containers.
/// </summary>
[Test]
public void TestNonCorruptContainer5()
{
var def = new ArgumentDefinition(typeof(ArgumentContainer5));
Assert.AreEqual(0, def.PositionalArguments.Count);
Assert.AreEqual(2, def.LongNamedArguments.Count);
Assert.AreEqual(1, def.ShortNamedArguments.Count);
Assert.IsNull(def.RemainingArguments);
Assert.AreEqual("Verbose", def.LongNamedArguments["verbose"].Property.Name);
Assert.AreEqual("Verbose", def.ShortNamedArguments['v'].Property.Name);
Assert.AreEqual("Name", def.LongNamedArguments["name"].Property.Name);
}
/// <summary>
/// Test non corrupt containers.
/// </summary>
[Test]
public void TestNonCorruptContainer6()
{
var def = new ArgumentDefinition(typeof(ArgumentContainer7));
Assert.AreEqual(0, def.PositionalArguments.Count);
Assert.AreEqual(3, def.LongNamedArguments.Count);
Assert.AreEqual(0, def.ShortNamedArguments.Count);
Assert.IsNull(def.RemainingArguments);
Assert.AreEqual("desc-short-1", def.LongNamedArguments["name1"].DescriptionAttribute.Short);
Assert.AreEqual("desc-long-1", def.LongNamedArguments["name1"].DescriptionAttribute.Long);
Assert.AreEqual("desc-short-2", def.LongNamedArguments["name2"].DescriptionAttribute.Short);
Assert.AreEqual("desc-long-2", def.LongNamedArguments["name2"].DescriptionAttribute.Long);
Assert.IsNull(def.LongNamedArguments["name3"].DescriptionAttribute);
}
/// <summary>
/// Test that properties with mutltiple <see cref="ArgumentAttribute"/>s are
/// detected properly.
/// </summary>
[Test]
public void TestDetectionOfMultipleArgumentAttributes()
{
AssertHelper.AssertExceptionWithMessage(
typeof(ArgumentDefinitionException),
Is.StringContaining("more than one"),
() =>
{
new ArgumentDefinition(typeof(CorruptArgumentContainer1));
});
}
/// <summary>
/// Test that problems with the positional indices are detected properly.
/// </summary>
[Test]
public void TestDetectionOfPositionalIndicesProblems()
{
AssertHelper.AssertExceptionWithMessage(
typeof(ArgumentDefinitionException),
Is.StringContaining("already in use"),
() =>
{
new ArgumentDefinition(typeof(CorruptArgumentContainer2));
});
AssertHelper.AssertExceptionWithMessage(
typeof(ArgumentDefinitionException),
Is.StringContaining("is missing"),
() =>
{
new ArgumentDefinition(typeof(CorruptArgumentContainer3));
});
AssertHelper.AssertExceptionWithMessage(
typeof(ArgumentDefinitionException),
Is.StringContaining("must start at"),
() =>
{
new ArgumentDefinition(typeof(CorruptArgumentContainer4));
});
}
/// <summary>
/// Test that problems with the names detected properly.
/// </summary>
[Test]
public void TestDetectionOfNamingProblems()
{
AssertHelper.AssertExceptionWithMessage(
typeof(ArgumentDefinitionException),
Is.StringContaining("Long name").And.StringContaining("already in use"),
() =>
{
new ArgumentDefinition(typeof(CorruptArgumentContainer5));
});
AssertHelper.AssertExceptionWithMessage(
typeof(ArgumentDefinitionException),
Is.StringContaining("Short name").And.StringContaining("already in use"),
() =>
{
new ArgumentDefinition(typeof(CorruptArgumentContainer6));
});
}
/// <summary>
/// Test that multiple <see cref="RemainingArgumentAttribute"/> annotations
/// are detected properly.
/// </summary>
[Test]
public void TestDetectionOfMultipleRemainingArguments()
{
AssertHelper.AssertExceptionWithMessage(
typeof(ArgumentDefinitionException),
Is.StringContaining("can only be used once"),
() =>
{
new ArgumentDefinition(typeof(CorruptArgumentContainer7));
});
}
/// <summary>
/// Test that <see cref="RemainingArgumentAttribute"/> annotations on non
/// <see cref="string[]"/> properties are detected properly.
/// </summary>
[Test]
public void TestDetectionOfRemainingArgumentsOnNonStringArrays()
{
AssertHelper.AssertExceptionWithMessage(
typeof(ArgumentDefinitionException),
Is.StringContaining("must have type System.String[]"),
() =>
{
new ArgumentDefinition(typeof(CorruptArgumentContainer8));
});
}
/// <summary>
/// Test that <see cref="NamedSwitchArgumentAttribute"/> annotations on non
/// <see cref="bool"/> properties are detected properly.
/// </summary>
[Test]
public void TestDetectionOfNamedSwitchArgumentsOnNonBooleans()
{
AssertHelper.AssertExceptionWithMessage(
typeof(ArgumentDefinitionException),
Is.StringContaining("must have type System.Boolean"),
() =>
{
new ArgumentDefinition(typeof(CorruptArgumentContainer9));
});
}
/// <summary>
/// Test that invalid long names are detected properly.
/// </summary>
[Test]
public void TestDetectionOfInvalidLongNames()
{
AssertHelper.AssertExceptionWithMessage(
typeof(ArgumentDefinitionException),
Is.StringContaining("at least 2 characters"),
() =>
{
new ArgumentDefinition(typeof(CorruptArgumentContainer10));
});
AssertHelper.AssertExceptionWithMessage(
typeof(ArgumentDefinitionException),
Is.StringContaining("match regex"),
() =>
{
new ArgumentDefinition(typeof(CorruptArgumentContainer11));
});
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
namespace System.Collections.ObjectModel
{
[DebuggerTypeProxy(typeof(CollectionDebugView<>))]
[DebuggerDisplay("Count = {Count}")]
public abstract class KeyedCollection<TKey, TItem> : Collection<TItem>
{
private const int defaultThreshold = 0;
private readonly IEqualityComparer<TKey> _comparer;
private Dictionary<TKey, TItem> _dict;
private int _keyCount;
private readonly int _threshold;
protected KeyedCollection() : this(null, defaultThreshold) { }
protected KeyedCollection(IEqualityComparer<TKey> comparer) : this(comparer, defaultThreshold) { }
protected KeyedCollection(IEqualityComparer<TKey> comparer, int dictionaryCreationThreshold)
: base(new List<TItem>()) // Be explicit about the use of List<T> so we can foreach over
// Items internally without enumerator allocations.
{
if (comparer == null)
{
comparer = EqualityComparer<TKey>.Default;
}
if (dictionaryCreationThreshold == -1)
{
dictionaryCreationThreshold = int.MaxValue;
}
if (dictionaryCreationThreshold < -1)
{
throw new ArgumentOutOfRangeException("dictionaryCreationThreshold", SR.ArgumentOutOfRange_InvalidThreshold);
}
_comparer = comparer;
_threshold = dictionaryCreationThreshold;
}
/// <summary>
/// Enables the use of foreach internally without allocations using <see cref="List{T}"/>'s struct enumerator.
/// </summary>
new private List<TItem> Items
{
get
{
Debug.Assert(base.Items is List<TItem>);
return (List<TItem>)base.Items;
}
}
public IEqualityComparer<TKey> Comparer
{
get
{
return _comparer;
}
}
public TItem this[TKey key]
{
get
{
if (key == null)
{
throw new ArgumentNullException("key");
}
if (_dict != null)
{
return _dict[key];
}
foreach (TItem item in Items)
{
if (_comparer.Equals(GetKeyForItem(item), key)) return item;
}
throw new KeyNotFoundException();
}
}
public bool Contains(TKey key)
{
if (key == null)
{
throw new ArgumentNullException("key");
}
if (_dict != null)
{
return _dict.ContainsKey(key);
}
foreach (TItem item in Items)
{
if (_comparer.Equals(GetKeyForItem(item), key)) return true;
}
return false;
}
private bool ContainsItem(TItem item)
{
TKey key;
if ((_dict == null) || ((key = GetKeyForItem(item)) == null))
{
return Items.Contains(item);
}
TItem itemInDict;
bool exist = _dict.TryGetValue(key, out itemInDict);
if (exist)
{
return EqualityComparer<TItem>.Default.Equals(itemInDict, item);
}
return false;
}
public bool Remove(TKey key)
{
if (key == null)
{
throw new ArgumentNullException("key");
}
if (_dict != null)
{
TItem item;
return _dict.TryGetValue(key, out item) && Remove(item);
}
for (int i = 0; i < Items.Count; i++)
{
if (_comparer.Equals(GetKeyForItem(Items[i]), key))
{
RemoveItem(i);
return true;
}
}
return false;
}
protected IDictionary<TKey, TItem> Dictionary
{
get { return _dict; }
}
protected void ChangeItemKey(TItem item, TKey newKey)
{
// Check if the item exists in the collection
if (!ContainsItem(item))
{
throw new ArgumentException(SR.Argument_ItemNotExist);
}
TKey oldKey = GetKeyForItem(item);
if (!_comparer.Equals(oldKey, newKey))
{
if (newKey != null)
{
AddKey(newKey, item);
}
if (oldKey != null)
{
RemoveKey(oldKey);
}
}
}
protected override void ClearItems()
{
base.ClearItems();
if (_dict != null)
{
_dict.Clear();
}
_keyCount = 0;
}
protected abstract TKey GetKeyForItem(TItem item);
protected override void InsertItem(int index, TItem item)
{
TKey key = GetKeyForItem(item);
if (key != null)
{
AddKey(key, item);
}
base.InsertItem(index, item);
}
protected override void RemoveItem(int index)
{
TKey key = GetKeyForItem(Items[index]);
if (key != null)
{
RemoveKey(key);
}
base.RemoveItem(index);
}
protected override void SetItem(int index, TItem item)
{
TKey newKey = GetKeyForItem(item);
TKey oldKey = GetKeyForItem(Items[index]);
if (_comparer.Equals(oldKey, newKey))
{
if (newKey != null && _dict != null)
{
_dict[newKey] = item;
}
}
else
{
if (newKey != null)
{
AddKey(newKey, item);
}
if (oldKey != null)
{
RemoveKey(oldKey);
}
}
base.SetItem(index, item);
}
private void AddKey(TKey key, TItem item)
{
if (_dict != null)
{
_dict.Add(key, item);
}
else if (_keyCount == _threshold)
{
CreateDictionary();
_dict.Add(key, item);
}
else
{
if (Contains(key))
{
throw new ArgumentException(SR.Format(SR.Argument_AddingDuplicate, key));
}
_keyCount++;
}
}
private void CreateDictionary()
{
_dict = new Dictionary<TKey, TItem>(_comparer);
foreach (TItem item in Items)
{
TKey key = GetKeyForItem(item);
if (key != null)
{
_dict.Add(key, item);
}
}
}
private void RemoveKey(TKey key)
{
Debug.Assert(key != null, "key shouldn't be null!");
if (_dict != null)
{
_dict.Remove(key);
}
else
{
_keyCount--;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using DarkMultiPlayerCommon;
namespace DarkMultiPlayer
{
public class ModWorker
{
private static ModWorker singleton = new ModWorker();
public ModControlMode modControl = ModControlMode.ENABLED_STOP_INVALID_PART_SYNC;
public bool dllListBuilt = false;
//Dll files, built at startup
private Dictionary<string, string> dllList;
//Accessed from ModWindow
private List<string> allowedParts;
private string lastModFileData = "";
public string failText
{
private set;
get;
}
public static ModWorker fetch
{
get
{
return singleton;
}
}
private bool CheckFile(string relativeFileName, string referencefileHash)
{
string fullFileName = Path.Combine(KSPUtil.ApplicationRootPath, Path.Combine("GameData", relativeFileName));
string fileHash = Common.CalculateSHA256Hash(fullFileName);
if (fileHash != referencefileHash)
{
DarkLog.Debug(relativeFileName + " hash mismatch");
return false;
}
return true;
}
public void BuildDllFileList()
{
dllList = new Dictionary<string, string>();
string[] checkList = Directory.GetFiles(Path.Combine(KSPUtil.ApplicationRootPath, "GameData"), "*", SearchOption.AllDirectories);
foreach (string checkFile in checkList)
{
//Only check DLL's
if (checkFile.ToLower().EndsWith(".dll"))
{
//We want the relative path to check against, example: DarkMultiPlayer/Plugins/DarkMultiPlayer.dll
//Strip off everything from GameData
//Replace windows backslashes with mac/linux forward slashes.
//Make it lowercase so we don't worry about case sensitivity.
string relativeFilePath = checkFile.ToLowerInvariant().Substring(checkFile.ToLowerInvariant().IndexOf("gamedata") + 9).Replace('\\', '/');
string fileHash = Common.CalculateSHA256Hash(checkFile);
dllList.Add(relativeFilePath, fileHash);
DarkLog.Debug("Hashed file: " + relativeFilePath + ", hash: " + fileHash);
}
}
}
public bool ParseModFile(string modFileData)
{
if (modControl == ModControlMode.DISABLED)
{
return true;
}
bool modCheckOk = true;
//Save mod file so we can recheck it.
lastModFileData = modFileData;
//Err...
string tempModFilePath = Path.Combine(Path.Combine(Path.Combine(Path.Combine(Path.Combine(KSPUtil.ApplicationRootPath, "GameData"), "DarkMultiPlayer"), "Plugins"), "Data"), "DMPModControl.txt");
using (StreamWriter sw = new StreamWriter(tempModFilePath))
{
sw.WriteLine("#This file is downloaded from the server during connection. It is saved here for convenience.");
sw.WriteLine(lastModFileData);
}
//Parse
Dictionary<string,string> parseRequired = new Dictionary<string, string>();
Dictionary<string,string> parseOptional = new Dictionary<string, string>();
List<string> parseWhiteBlackList = new List<string>();
List<string> parsePartsList = new List<string>();
bool isWhiteList = false;
string readMode = "";
using (StringReader sr = new StringReader(modFileData))
{
while (true)
{
string currentLine = sr.ReadLine();
if (currentLine == null)
{
//Done reading
break;
}
//Remove tabs/spaces from the start & end.
string trimmedLine = currentLine.Trim();
if (trimmedLine.StartsWith("#") || String.IsNullOrEmpty(trimmedLine))
{
//Skip comments or empty lines.
continue;
}
if (trimmedLine.StartsWith("!"))
{
//New section
switch (trimmedLine.Substring(1))
{
case "required-files":
case "optional-files":
case "partslist":
readMode = trimmedLine.Substring(1);
break;
case "resource-blacklist":
readMode = trimmedLine.Substring(1);
isWhiteList = false;
break;
case "resource-whitelist":
readMode = trimmedLine.Substring(1);
isWhiteList = true;
break;
}
}
else
{
switch (readMode)
{
case "required-files":
{
string lowerFixedLine = trimmedLine.ToLowerInvariant().Replace('\\', '/');
if (lowerFixedLine.Contains("="))
{
string[] splitLine = lowerFixedLine.Split('=');
if (splitLine.Length == 2)
{
if (!parseRequired.ContainsKey(splitLine[0]))
{
parseRequired.Add(splitLine[0], splitLine[1].ToLowerInvariant());
}
}
else
{
if (splitLine.Length == 1)
{
if (!parseRequired.ContainsKey(splitLine[0]))
{
parseRequired.Add(splitLine[0], "");
}
}
}
}
else
{
if (!parseRequired.ContainsKey(lowerFixedLine))
{
parseRequired.Add(lowerFixedLine, "");
}
}
}
break;
case "optional-files":
{
string lowerFixedLine = trimmedLine.ToLowerInvariant().Replace('\\', '/');
if (lowerFixedLine.Contains("="))
{
string[] splitLine = lowerFixedLine.Split('=');
if (splitLine.Length == 2)
{
if (!parseOptional.ContainsKey(splitLine[0]))
{
parseOptional.Add(splitLine[0], splitLine[1]);
}
}
else
{
if (splitLine.Length == 1)
{
if (!parseOptional.ContainsKey(splitLine[0]))
{
parseOptional.Add(splitLine[0], "");
}
}
}
}
else
{
if (!parseOptional.ContainsKey(lowerFixedLine))
{
parseOptional.Add(lowerFixedLine, "");
}
}
}
break;
case "resource-whitelist":
case "resource-blacklist":
{
string lowerFixedLine = trimmedLine.ToLowerInvariant().Replace('\\', '/');
//Resource is dll's only.
if (lowerFixedLine.ToLowerInvariant().EndsWith(".dll"))
{
if (parseWhiteBlackList.Contains(lowerFixedLine))
{
parseWhiteBlackList.Add(lowerFixedLine);
}
}
}
break;
case "partslist":
if (!parsePartsList.Contains(trimmedLine))
{
parsePartsList.Add(trimmedLine);
}
break;
}
}
}
}
string[] currentGameDataFiles = Directory.GetFiles(Path.Combine(KSPUtil.ApplicationRootPath, "GameData"), "*", SearchOption.AllDirectories);
List<string> currentGameDataFilesNormal = new List<string>();
List<string> currentGameDataFilesLower = new List<string>();
foreach (string currentFile in currentGameDataFiles)
{
string relativeFilePath = currentFile.Substring(currentFile.ToLowerInvariant().IndexOf("gamedata") + 9).Replace('\\', '/');
currentGameDataFilesNormal.Add(relativeFilePath);
currentGameDataFilesLower.Add(relativeFilePath.ToLowerInvariant());
}
//Check
StringBuilder sb = new StringBuilder();
//Check Required
foreach (KeyValuePair<string, string> requiredEntry in parseRequired)
{
if (!requiredEntry.Key.EndsWith("dll"))
{
//Protect against windows-style entries in DMPModControl.txt. Also use case insensitive matching.
if (!currentGameDataFilesLower.Contains(requiredEntry.Key))
{
modCheckOk = false;
DarkLog.Debug("Required file " + requiredEntry.Key + " is missing!");
sb.AppendLine("Required file " + requiredEntry.Key + " is missing!");
continue;
}
//If the entry has a SHA sum, we need to check it.
if (requiredEntry.Value != "")
{
string normalCaseFileName = currentGameDataFilesNormal[currentGameDataFilesLower.IndexOf(requiredEntry.Key)];
string fullFileName = Path.Combine(Path.Combine(KSPUtil.ApplicationRootPath, "GameData"), normalCaseFileName);
if (!CheckFile(fullFileName, requiredEntry.Value))
{
modCheckOk = false;
DarkLog.Debug("Required file " + requiredEntry.Key + " does not match hash " + requiredEntry.Value + "!");
sb.AppendLine("Required file " + requiredEntry.Key + " does not match hash " + requiredEntry.Value + "!");
continue;
}
}
}
else
{
//DLL entries are cached from startup.
if (!dllList.ContainsKey(requiredEntry.Key))
{
modCheckOk = false;
DarkLog.Debug("Required file " + requiredEntry.Key + " is missing!");
sb.AppendLine("Required file " + requiredEntry.Key + " is missing!");
continue;
}
if (requiredEntry.Value != "")
{
if (dllList[requiredEntry.Key] != requiredEntry.Value)
{
modCheckOk = false;
DarkLog.Debug("Required file " + requiredEntry.Key + " does not match hash " + requiredEntry.Value + "!");
sb.AppendLine("Required file " + requiredEntry.Key + " does not match hash " + requiredEntry.Value + "!");
continue;
}
}
}
}
//Check Optional
foreach (KeyValuePair<string, string> optionalEntry in parseOptional)
{
if (!optionalEntry.Key.EndsWith("dll"))
{
//Protect against windows-style entries in DMPModControl.txt. Also use case insensitive matching.
if (!currentGameDataFilesLower.Contains(optionalEntry.Key))
{
//File is optional, nothing to check if it doesn't exist.
continue;
}
//If the entry has a SHA sum, we need to check it.
if (optionalEntry.Value != "")
{
string normalCaseFileName = currentGameDataFilesNormal[currentGameDataFilesLower.IndexOf(optionalEntry.Key)];
string fullFileName = Path.Combine(Path.Combine(KSPUtil.ApplicationRootPath, "GameData"), normalCaseFileName);
if (!CheckFile(fullFileName, optionalEntry.Value))
{
modCheckOk = false;
DarkLog.Debug("Optional file " + optionalEntry.Key + " does not match hash " + optionalEntry.Value + "!");
sb.AppendLine("Optional file " + optionalEntry.Key + " does not match hash " + optionalEntry.Value + "!");
continue;
}
}
}
else
{
//DLL entries are cached from startup.
if (!dllList.ContainsKey(optionalEntry.Key))
{
//File is optional, nothing to check if it doesn't exist.
continue;
}
if (optionalEntry.Value != "")
{
if (dllList[optionalEntry.Key] != optionalEntry.Value)
{
modCheckOk = false;
DarkLog.Debug("Optional file " + optionalEntry.Key + " does not match hash " + optionalEntry.Value + "!");
sb.AppendLine("Optional file " + optionalEntry.Key + " does not match hash " + optionalEntry.Value + "!");
continue;
}
}
}
}
if (isWhiteList)
{
//Check Resource whitelist
List<string> autoAllowed = new List<string>();
autoAllowed.Add("darkmultiplayer/plugins/darkmultiplayer.dll");
autoAllowed.Add("darkmultiplayer/plugins/darkmultiplayer-common.dll");
//Leave the old one there if the user forgets to delete it.
autoAllowed.Add("darkmultiplayer/plugins/messagewriter.dll");
autoAllowed.Add("darkmultiplayer/plugins/messagewriter2.dll");
//Compression
autoAllowed.Add("darkmultiplayer/plugins/icsharpcode.sharpziplib.dll");
foreach (KeyValuePair<string, string> dllResource in dllList)
{
//Allow DMP files
if (autoAllowed.Contains(dllResource.Key))
{
continue;
}
//Check required (Required implies whitelist)
if (parseRequired.ContainsKey(dllResource.Key))
{
continue;
}
//Check optional (Optional implies whitelist)
if (parseOptional.ContainsKey(dllResource.Key))
{
continue;
}
//Check whitelist
if (parseWhiteBlackList.Contains(dllResource.Key))
{
continue;
}
modCheckOk = false;
DarkLog.Debug("Non-whitelisted resource " + dllResource.Key + " exists on client!");
sb.AppendLine("Non-whitelisted resource " + dllResource.Key + " exists on client!");
}
}
else
{
//Check Resource blacklist
foreach (string blacklistEntry in parseWhiteBlackList)
{
if (dllList.ContainsKey(blacklistEntry.ToLowerInvariant()))
{
modCheckOk = false;
DarkLog.Debug("Banned resource " + blacklistEntry + " exists on client!");
sb.AppendLine("Banned resource " + blacklistEntry + " exists on client!");
}
}
}
if (!modCheckOk)
{
failText = sb.ToString();
ModWindow.fetch.display = true;
return false;
}
allowedParts = parsePartsList;
DarkLog.Debug("Mod check passed!");
return true;
}
public List<string> GetAllowedPartsList()
{
//Return a copy
if (modControl == ModControlMode.DISABLED)
{
return null;
}
return new List<string>(allowedParts);
}
public void GenerateModControlFile(bool whitelistMode)
{
string gameDataDir = Path.Combine(KSPUtil.ApplicationRootPath, "GameData");
string[] topLevelFiles = Directory.GetFiles(gameDataDir);
string[] modDirectories = Directory.GetDirectories(gameDataDir);
List<string> requiredFiles = new List<string>();
List<string> optionalFiles = new List<string>();
List<string> partsList = Common.GetStockParts();
//If whitelisting, add top level dll's to required (It's usually things like modulemanager)
foreach (string dllFile in topLevelFiles)
{
if (Path.GetExtension(dllFile).ToLower() == ".dll")
{
requiredFiles.Add(Path.GetFileName(dllFile));
}
}
foreach (string modDirectory in modDirectories)
{
string lowerDirectoryName = modDirectory.Substring(modDirectory.ToLower().IndexOf("gamedata") + 9).ToLower();
if (lowerDirectoryName.StartsWith("squad"))
{
continue;
}
if (lowerDirectoryName.StartsWith("nasamission"))
{
continue;
}
if (lowerDirectoryName.StartsWith("darkmultiplayer"))
{
continue;
}
bool modIsRequired = false;
string[] partFiles = Directory.GetFiles(Path.Combine(gameDataDir, modDirectory), "*", SearchOption.AllDirectories);
List<string> modDllFiles = new List<string>();
List<string> modPartCfgFiles = new List<string>();
foreach (string partFile in partFiles)
{
bool fileIsPartFile = false;
string relativeFileName = partFile.Substring(partFile.ToLower().IndexOf("gamedata") + 9).Replace(@"\", "/");
if (Path.GetExtension(partFile).ToLower() == ".cfg")
{
ConfigNode cn = ConfigNode.Load(partFile);
if (cn == null)
{
continue;
}
foreach (ConfigNode partNode in cn.GetNodes("PART"))
{
string partName = partNode.GetValue("name");
if (partName != null)
{
DarkLog.Debug("Part detected in " + relativeFileName + " , name: " + partName);
partName = partName.Replace('_', '.');
modIsRequired = true;
fileIsPartFile = true;
partsList.Add(partName);
}
}
}
if (fileIsPartFile)
{
modPartCfgFiles.Add(relativeFileName);
}
if (Path.GetExtension(partFile).ToLower() == ".dll")
{
modDllFiles.Add(relativeFileName);
}
}
if (modIsRequired)
{
if (modDllFiles.Count > 0)
{
//If the mod as a plugin, just require that. It's clear enough.
requiredFiles.AddRange(modDllFiles);
}
else
{
//If the mod does *not* have a plugin (Scoop-o-matic is an example), add the part files to required instead.
requiredFiles.AddRange(modPartCfgFiles);
}
}
else
{
if (whitelistMode)
{
optionalFiles.AddRange(modDllFiles);
}
}
}
string modFileData = Common.GenerateModFileStringData(requiredFiles.ToArray(), optionalFiles.ToArray(), whitelistMode, new string[0], partsList.ToArray());
string saveModFile = Path.Combine(KSPUtil.ApplicationRootPath, "DMPModControl.txt");
using (StreamWriter sw = new StreamWriter(saveModFile, false))
{
sw.Write(modFileData);
}
ScreenMessages.PostScreenMessage("DMPModFile.txt file generated in your KSP folder", 5f, ScreenMessageStyle.UPPER_CENTER);
}
public void CheckCommonStockParts()
{
int totalParts = 0;
int missingParts = 0;
List<string> stockParts = Common.GetStockParts();
DarkLog.Debug("Missing parts start");
foreach (AvailablePart part in PartLoader.LoadedPartsList)
{
totalParts++;
if (!stockParts.Contains(part.name))
{
missingParts++;
DarkLog.Debug("Missing '" + part.name + "'");
}
}
DarkLog.Debug("Missing parts end");
if (missingParts != 0)
{
ScreenMessages.PostScreenMessage(missingParts + " missing part(s) from Common.dll printed to debug log (" + totalParts + " total)", 5f, ScreenMessageStyle.UPPER_CENTER);
}
else
{
ScreenMessages.PostScreenMessage("No missing parts out of from Common.dll (" + totalParts + " total)", 5f, ScreenMessageStyle.UPPER_CENTER);
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.ComponentModel.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeFixes.Suppression;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Shell.TableControl;
using Microsoft.VisualStudio.Shell.TableManager;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.TableDataSource
{
/// <summary>
/// Service to maintain information about the suppression state of specific set of items in the error list.
/// </summary>
[Export(typeof(IVisualStudioDiagnosticListSuppressionStateService))]
internal class VisualStudioDiagnosticListSuppressionStateService : IVisualStudioDiagnosticListSuppressionStateService
{
private readonly VisualStudioWorkspace _workspace;
private readonly IVsUIShell _shellService;
private readonly IWpfTableControl _tableControl;
private int _selectedActiveItems;
private int _selectedSuppressedItems;
private int _selectedRoslynItems;
private int _selectedCompilerDiagnosticItems;
private int _selectedNoLocationDiagnosticItems;
private int _selectedNonSuppressionStateItems;
[ImportingConstructor]
public VisualStudioDiagnosticListSuppressionStateService(
SVsServiceProvider serviceProvider,
VisualStudioWorkspace workspace)
{
_workspace = workspace;
_shellService = (IVsUIShell)serviceProvider.GetService(typeof(SVsUIShell));
var errorList = serviceProvider.GetService(typeof(SVsErrorList)) as IErrorList;
_tableControl = errorList?.TableControl;
ClearState();
InitializeFromTableControlIfNeeded();
}
private int SelectedItems => _selectedActiveItems + _selectedSuppressedItems + _selectedNonSuppressionStateItems;
// If we can suppress either in source or in suppression file, we enable suppress context menu.
public bool CanSuppressSelectedEntries => CanSuppressSelectedEntriesInSource || CanSuppressSelectedEntriesInSuppressionFiles;
// If at least one suppressed item is selected, we enable remove suppressions.
public bool CanRemoveSuppressionsSelectedEntries => _selectedSuppressedItems > 0;
// If at least one Roslyn active item with location is selected, we enable suppress in source.
// Note that we do not support suppress in source when mix of Roslyn and non-Roslyn items are selected as in-source suppression has different meaning and implementation for these.
public bool CanSuppressSelectedEntriesInSource => _selectedActiveItems > 0 &&
_selectedRoslynItems == _selectedActiveItems &&
(_selectedRoslynItems - _selectedNoLocationDiagnosticItems) > 0;
// If at least one Roslyn active item is selected, we enable suppress in suppression file.
// Also, compiler diagnostics cannot be suppressed in suppression file, so there must be at least one non-compiler item.
public bool CanSuppressSelectedEntriesInSuppressionFiles => _selectedActiveItems > 0 &&
(_selectedRoslynItems - _selectedCompilerDiagnosticItems) > 0;
private void ClearState()
{
_selectedActiveItems = 0;
_selectedSuppressedItems = 0;
_selectedRoslynItems = 0;
_selectedCompilerDiagnosticItems = 0;
_selectedNoLocationDiagnosticItems = 0;
_selectedNonSuppressionStateItems = 0;
}
private void InitializeFromTableControlIfNeeded()
{
if (_tableControl == null)
{
return;
}
if (SelectedItems == _tableControl.SelectedEntries.Count())
{
// We already have up-to-date state data, so don't need to re-compute.
return;
}
ClearState();
if (ProcessEntries(_tableControl.SelectedEntries, added: true))
{
UpdateQueryStatus();
}
}
/// <summary>
/// Updates suppression state information when the selected entries change in the error list.
/// </summary>
public void ProcessSelectionChanged(TableSelectionChangedEventArgs e)
{
var hasAddedSuppressionStateEntry = ProcessEntries(e.AddedEntries, added: true);
var hasRemovedSuppressionStateEntry = ProcessEntries(e.RemovedEntries, added: false);
// If any entry that supports suppression state was ever involved, update query status since each item in the error list
// can have different context menu.
if (hasAddedSuppressionStateEntry || hasRemovedSuppressionStateEntry)
{
UpdateQueryStatus();
}
InitializeFromTableControlIfNeeded();
}
private bool ProcessEntries(IEnumerable<ITableEntryHandle> entryHandles, bool added)
{
var hasSuppressionStateEntry = false;
foreach (var entryHandle in entryHandles)
{
if (EntrySupportsSuppressionState(entryHandle, out var isRoslynEntry, out var isSuppressedEntry, out var isCompilerDiagnosticEntry, out var isNoLocationDiagnosticEntry))
{
hasSuppressionStateEntry = true;
HandleSuppressionStateEntry(isRoslynEntry, isSuppressedEntry, isCompilerDiagnosticEntry, isNoLocationDiagnosticEntry, added);
}
else
{
HandleNonSuppressionStateEntry(added);
}
}
return hasSuppressionStateEntry;
}
private static bool EntrySupportsSuppressionState(ITableEntryHandle entryHandle, out bool isRoslynEntry, out bool isSuppressedEntry, out bool isCompilerDiagnosticEntry, out bool isNoLocationDiagnosticEntry)
{
isNoLocationDiagnosticEntry = !entryHandle.TryGetValue(StandardTableColumnDefinitions.DocumentName, out string filePath) ||
string.IsNullOrEmpty(filePath);
var roslynSnapshot = GetEntriesSnapshot(entryHandle, out var index);
if (roslynSnapshot == null)
{
isRoslynEntry = false;
isCompilerDiagnosticEntry = false;
return IsNonRoslynEntrySupportingSuppressionState(entryHandle, out isSuppressedEntry);
}
var diagnosticData = roslynSnapshot?.GetItem(index)?.Primary;
if (!IsEntryWithConfigurableSuppressionState(diagnosticData))
{
isRoslynEntry = false;
isSuppressedEntry = false;
isCompilerDiagnosticEntry = false;
return false;
}
isRoslynEntry = true;
isSuppressedEntry = diagnosticData.IsSuppressed;
isCompilerDiagnosticEntry = SuppressionHelpers.IsCompilerDiagnostic(diagnosticData);
return true;
}
private static bool IsNonRoslynEntrySupportingSuppressionState(ITableEntryHandle entryHandle, out bool isSuppressedEntry)
{
if (entryHandle.TryGetValue(SuppressionStateColumnDefinition.ColumnName, out string suppressionStateValue))
{
isSuppressedEntry = suppressionStateValue == ServicesVSResources.Suppressed;
return true;
}
isSuppressedEntry = false;
return false;
}
/// <summary>
/// Returns true if an entry's suppression state can be modified.
/// </summary>
/// <returns></returns>
private static bool IsEntryWithConfigurableSuppressionState(DiagnosticData entry)
{
// Compiler diagnostics with severity 'Error' are not configurable.
// Additionally, diagnostics coming from build are from a snapshot (as opposed to live diagnostics) and cannot be configured.
return entry != null &&
!SuppressionHelpers.IsNotConfigurableDiagnostic(entry) &&
!entry.IsBuildDiagnostic();
}
private static AbstractTableEntriesSnapshot<DiagnosticData> GetEntriesSnapshot(ITableEntryHandle entryHandle)
{
return GetEntriesSnapshot(entryHandle, out var index);
}
private static AbstractTableEntriesSnapshot<DiagnosticData> GetEntriesSnapshot(ITableEntryHandle entryHandle, out int index)
{
if (!entryHandle.TryGetSnapshot(out var snapshot, out index))
{
return null;
}
return snapshot as AbstractTableEntriesSnapshot<DiagnosticData>;
}
/// <summary>
/// Gets <see cref="DiagnosticData"/> objects for selected error list entries.
/// For remove suppression, the method also returns selected external source diagnostics.
/// </summary>
public async Task<ImmutableArray<DiagnosticData>> GetSelectedItemsAsync(bool isAddSuppression, CancellationToken cancellationToken)
{
var builder = ArrayBuilder<DiagnosticData>.GetInstance();
Dictionary<string, Project> projectNameToProjectMapOpt = null;
Dictionary<Project, ImmutableDictionary<string, Document>> filePathToDocumentMapOpt = null;
foreach (var entryHandle in _tableControl.SelectedEntries)
{
cancellationToken.ThrowIfCancellationRequested();
DiagnosticData diagnosticData = null;
var roslynSnapshot = GetEntriesSnapshot(entryHandle, out var index);
if (roslynSnapshot != null)
{
diagnosticData = roslynSnapshot.GetItem(index)?.Primary;
}
else if (!isAddSuppression)
{
// For suppression removal, we also need to handle FxCop entries.
if (!IsNonRoslynEntrySupportingSuppressionState(entryHandle, out var isSuppressedEntry) ||
!isSuppressedEntry)
{
continue;
}
string filePath = null;
int line = -1; // FxCop only supports line, not column.
DiagnosticDataLocation location = null;
if (entryHandle.TryGetValue(StandardTableColumnDefinitions.ErrorCode, out string errorCode) && !string.IsNullOrEmpty(errorCode) &&
entryHandle.TryGetValue(StandardTableColumnDefinitions.ErrorCategory, out string category) && !string.IsNullOrEmpty(category) &&
entryHandle.TryGetValue(StandardTableColumnDefinitions.Text, out string message) && !string.IsNullOrEmpty(message) &&
entryHandle.TryGetValue(StandardTableColumnDefinitions.ProjectName, out string projectName) && !string.IsNullOrEmpty(projectName))
{
if (projectNameToProjectMapOpt == null)
{
projectNameToProjectMapOpt = new Dictionary<string, Project>();
foreach (var p in _workspace.CurrentSolution.Projects)
{
projectNameToProjectMapOpt[p.Name] = p;
}
}
cancellationToken.ThrowIfCancellationRequested();
if (!projectNameToProjectMapOpt.TryGetValue(projectName, out var project))
{
// bail out
continue;
}
Document document = null;
var hasLocation = (entryHandle.TryGetValue(StandardTableColumnDefinitions.DocumentName, out filePath) && !string.IsNullOrEmpty(filePath)) &&
(entryHandle.TryGetValue(StandardTableColumnDefinitions.Line, out line) && line >= 0);
if (hasLocation)
{
if (string.IsNullOrEmpty(filePath) || line < 0)
{
// bail out
continue;
}
filePathToDocumentMapOpt = filePathToDocumentMapOpt ?? new Dictionary<Project, ImmutableDictionary<string, Document>>();
if (!filePathToDocumentMapOpt.TryGetValue(project, out var filePathMap))
{
filePathMap = await GetFilePathToDocumentMapAsync(project, cancellationToken).ConfigureAwait(false);
filePathToDocumentMapOpt[project] = filePathMap;
}
if (!filePathMap.TryGetValue(filePath, out document))
{
// bail out
continue;
}
var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
var linePosition = new LinePosition(line, 0);
var linePositionSpan = new LinePositionSpan(start: linePosition, end: linePosition);
var textSpan = (await tree.GetTextAsync(cancellationToken).ConfigureAwait(false)).Lines.GetTextSpan(linePositionSpan);
location = new DiagnosticDataLocation(document.Id, textSpan, filePath,
originalStartLine: linePosition.Line, originalStartColumn: linePosition.Character,
originalEndLine: linePosition.Line, originalEndColumn: linePosition.Character);
}
Contract.ThrowIfNull(project);
Contract.ThrowIfFalse((document != null) == (location != null));
// Create a diagnostic with correct values for fields we care about: id, category, message, isSuppressed, location
// and default values for the rest of the fields (not used by suppression fixer).
diagnosticData = new DiagnosticData(
id: errorCode,
category: category,
message: message,
enuMessageForBingSearch: message,
severity: DiagnosticSeverity.Warning,
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true,
warningLevel: 1,
isSuppressed: isSuppressedEntry,
title: message,
location: location,
customTags: SuppressionHelpers.SynthesizedExternalSourceDiagnosticCustomTags,
properties: ImmutableDictionary<string, string>.Empty,
workspace: _workspace,
projectId: project.Id);
}
}
if (IsEntryWithConfigurableSuppressionState(diagnosticData))
{
builder.Add(diagnosticData);
}
}
return builder.ToImmutableAndFree();
}
private static async Task<ImmutableDictionary<string, Document>> GetFilePathToDocumentMapAsync(Project project, CancellationToken cancellationToken)
{
var builder = ImmutableDictionary.CreateBuilder<string, Document>();
foreach (var document in project.Documents)
{
cancellationToken.ThrowIfCancellationRequested();
var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
var filePath = tree.FilePath;
if (filePath != null)
{
builder.Add(filePath, document);
}
}
return builder.ToImmutable();
}
private static void UpdateSelectedItems(bool added, ref int count)
{
if (added)
{
count++;
}
else
{
count--;
}
}
private void HandleSuppressionStateEntry(bool isRoslynEntry, bool isSuppressedEntry, bool isCompilerDiagnosticEntry, bool isNoLocationDiagnosticEntry, bool added)
{
if (isRoslynEntry)
{
UpdateSelectedItems(added, ref _selectedRoslynItems);
}
if (isCompilerDiagnosticEntry)
{
UpdateSelectedItems(added, ref _selectedCompilerDiagnosticItems);
}
if (isNoLocationDiagnosticEntry)
{
UpdateSelectedItems(added, ref _selectedNoLocationDiagnosticItems);
}
if (isSuppressedEntry)
{
UpdateSelectedItems(added, ref _selectedSuppressedItems);
}
else
{
UpdateSelectedItems(added, ref _selectedActiveItems);
}
}
private void HandleNonSuppressionStateEntry(bool added)
{
UpdateSelectedItems(added, ref _selectedNonSuppressionStateItems);
}
private void UpdateQueryStatus()
{
// Force the shell to refresh the QueryStatus for all the command since default behavior is it only does query
// when focus on error list has changed, not individual items.
if (_shellService != null)
{
_shellService.UpdateCommandUI(0);
}
}
}
}
| |
using Mvc.Datatables.DynamicLinq;
using Mvc.Datatables.Reflection;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Mvc.Datatables.Processing
{
public class DataTableFilterProcessor : IDataTableFilterProcessor
{
private static readonly List<ReturnedFilteredQueryForType> _filters = new List<ReturnedFilteredQueryForType>()
{
Guard(IsBoolType, TypeFilters.BoolFilter),
Guard(IsDateTimeType, TypeFilters.DateTimeFilter),
Guard(IsDateTimeOffsetType, TypeFilters.DateTimeOffsetFilter),
Guard(IsNumericType, TypeFilters.NumericFilter),
Guard(IsEnumType, TypeFilters.EnumFilter),
Guard(arg => arg.Type == typeof (string), TypeFilters.StringFilter),
};
public delegate string ReturnedFilteredQueryForType(string query, string columnName, DataTablesPropertyInfo columnType, List<object> parametersForLinqQuery);
public delegate string GuardedFilter(string query, string columnName, DataTablesPropertyInfo columnType, List<object> parametersForLinqQuery);
public virtual IQueryable<T> ApplyFiltersAndSort<T>(IFilterRequest filter, IQueryable<T> data)
{
var outputProperties = DataTablesTypeInfo<T>.Properties;
return ApplyFiltersAndSort<T>(filter, data, outputProperties);
}
public virtual IQueryable<T> ApplyFiltersAndSort<T>(IFilterRequest filter, IQueryable<T> data, DataTablesPropertyInfo[] objColumns)
{
if (!string.IsNullOrEmpty(filter.Search.Value))
{
var parts = new List<string>();
var parameters = new List<object>();
for (var i = 0; i < filter.Columns.Count; i++)
{
if (filter.Columns[i].Searchable)
{
try
{
string currentColumnSource = !string.IsNullOrWhiteSpace(filter.Columns[i].Name) ? filter.Columns[i].Name : filter.Columns[i].Data;
var currentColumn = objColumns.SingleOrDefault(x => x.Name == currentColumnSource);
if (currentColumn == null && objColumns.Length > i)
currentColumn = objColumns[i];
if (currentColumn != null)
{
var filterClause = GetFilterClause(filter.Search.Value, currentColumn, parameters);
if (string.IsNullOrWhiteSpace(filterClause) == false)
{
parts.Add(filterClause);
}
}
}
catch (Exception)
{
// If the clause doesn't work, skip it!
}
}
}
var values = parts.Where(p => p != null);
string searchQuery = string.Join(" or ", values);
if (string.IsNullOrWhiteSpace(searchQuery) == false)
data = data.Where(searchQuery, parameters.ToArray());
}
foreach (KeyValuePair<int, IColumn> column in filter.Columns.OrderBy(x => x.Key))
{
if (column.Value.Searchable)
{
var searchColumn = column.Value.Search;
if (!string.IsNullOrWhiteSpace(searchColumn.Value))
{
string currentColumnSource = !string.IsNullOrWhiteSpace(column.Value.Name) ? column.Value.Name : column.Value.Data;
var currentColumn = objColumns.SingleOrDefault(x => x.Name == currentColumnSource);
if (currentColumn == null && objColumns.Length > column.Key)
currentColumn = objColumns[column.Key];
if (currentColumn != null)
{
var parameters = new List<object>();
var filterClause = GetFilterClause(searchColumn.Value, currentColumn, parameters);
if (string.IsNullOrWhiteSpace(filterClause) == false)
{
data = data.Where(filterClause, parameters.ToArray());
}
}
}
}
}
string sortString = "";
for (int i = 0; i < filter.Sort.Count; i++)
{
int columnNumber = filter.Sort[i].Column;
if (columnNumber < filter.Columns.Count)
{
string currentColumnSource = !string.IsNullOrWhiteSpace(filter.Columns[columnNumber].Name) ? filter.Columns[columnNumber].Name : filter.Columns[columnNumber].Data;
var currentColumn = objColumns.SingleOrDefault(x => x.Name == currentColumnSource);
if (currentColumn == null && objColumns.Length > columnNumber)
currentColumn = objColumns[columnNumber];
if (currentColumn != null)
{
string columnName = currentColumn.PropertyInfo.Name;
string sortDir = filter.Sort[i].Direction.AsString();
if (i != 0)
sortString += ", ";
sortString += columnName + " " + sortDir;
}
}
}
if (string.IsNullOrWhiteSpace(sortString) && objColumns.Length > 0)
sortString = objColumns[0].PropertyInfo.Name;
if (!string.IsNullOrWhiteSpace(sortString))
data = data.OrderBy(sortString);
return data;
}
private static ReturnedFilteredQueryForType Guard(Func<DataTablesPropertyInfo, bool> guard, GuardedFilter filter)
{
return (q, c, t, p) =>
{
if (!guard(t))
return null;
else
return filter(q, c, t, p);
};
}
public static void RegisterFilter<T>(GuardedFilter filter)
{
_filters.Add(Guard(arg => arg is T, filter));
}
private static string GetFilterClause(string query, DataTablesPropertyInfo column, List<object> parametersForLinqQuery)
{
Func<string, string> filterClause = (queryPart) =>
_filters.Select(
f => f(queryPart, column.PropertyInfo.Name, column, parametersForLinqQuery))
.FirstOrDefault(filterPart => filterPart != null) ?? "";
var queryParts = query.Split('|').Select(filterClause).Where(fc => fc != "").ToArray();
if (queryParts.Any())
{
return "(" + string.Join(") OR (", queryParts) + ")";
}
return null;
}
public static bool IsNumericType(DataTablesPropertyInfo propertyInfo)
{
var type = propertyInfo.Type;
return IsNumericType(type);
}
private static bool IsNumericType(Type type)
{
if (type == null || type.IsEnum)
{
return false;
}
switch (Type.GetTypeCode(type))
{
case TypeCode.Byte:
case TypeCode.Decimal:
case TypeCode.Double:
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.SByte:
case TypeCode.Single:
case TypeCode.UInt16:
case TypeCode.UInt32:
case TypeCode.UInt64:
return true;
case TypeCode.Object:
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
{
return IsNumericType(Nullable.GetUnderlyingType(type));
}
return false;
}
return false;
}
public static bool IsEnumType(DataTablesPropertyInfo propertyInfo)
{
return propertyInfo.Type.IsEnum;
}
public static bool IsBoolType(DataTablesPropertyInfo propertyInfo)
{
return propertyInfo.Type == typeof(bool) || propertyInfo.Type == typeof(bool?);
}
public static bool IsDateTimeType(DataTablesPropertyInfo propertyInfo)
{
return propertyInfo.Type == typeof(DateTime) || propertyInfo.Type == typeof(DateTime?);
}
public static bool IsDateTimeOffsetType(DataTablesPropertyInfo propertyInfo)
{
return propertyInfo.Type == typeof(DateTimeOffset) || propertyInfo.Type == typeof(DateTimeOffset?);
}
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
namespace Northwind{
/// <summary>
/// Strongly-typed collection for the Invoice class.
/// </summary>
[Serializable]
public partial class InvoiceCollection : ReadOnlyList<Invoice, InvoiceCollection>
{
public InvoiceCollection() {}
}
/// <summary>
/// This is Read-only wrapper class for the Invoices view.
/// </summary>
[Serializable]
public partial class Invoice : ReadOnlyRecord<Invoice>, IReadOnlyRecord
{
#region Default Settings
protected static void SetSQLProps()
{
GetTableSchema();
}
#endregion
#region Schema Accessor
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
{
SetSQLProps();
}
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("Invoices", TableType.View, DataService.GetInstance("Northwind"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarShipName = new TableSchema.TableColumn(schema);
colvarShipName.ColumnName = "ShipName";
colvarShipName.DataType = DbType.String;
colvarShipName.MaxLength = 40;
colvarShipName.AutoIncrement = false;
colvarShipName.IsNullable = true;
colvarShipName.IsPrimaryKey = false;
colvarShipName.IsForeignKey = false;
colvarShipName.IsReadOnly = false;
schema.Columns.Add(colvarShipName);
TableSchema.TableColumn colvarShipAddress = new TableSchema.TableColumn(schema);
colvarShipAddress.ColumnName = "ShipAddress";
colvarShipAddress.DataType = DbType.String;
colvarShipAddress.MaxLength = 60;
colvarShipAddress.AutoIncrement = false;
colvarShipAddress.IsNullable = true;
colvarShipAddress.IsPrimaryKey = false;
colvarShipAddress.IsForeignKey = false;
colvarShipAddress.IsReadOnly = false;
schema.Columns.Add(colvarShipAddress);
TableSchema.TableColumn colvarShipCity = new TableSchema.TableColumn(schema);
colvarShipCity.ColumnName = "ShipCity";
colvarShipCity.DataType = DbType.String;
colvarShipCity.MaxLength = 15;
colvarShipCity.AutoIncrement = false;
colvarShipCity.IsNullable = true;
colvarShipCity.IsPrimaryKey = false;
colvarShipCity.IsForeignKey = false;
colvarShipCity.IsReadOnly = false;
schema.Columns.Add(colvarShipCity);
TableSchema.TableColumn colvarShipRegion = new TableSchema.TableColumn(schema);
colvarShipRegion.ColumnName = "ShipRegion";
colvarShipRegion.DataType = DbType.String;
colvarShipRegion.MaxLength = 15;
colvarShipRegion.AutoIncrement = false;
colvarShipRegion.IsNullable = true;
colvarShipRegion.IsPrimaryKey = false;
colvarShipRegion.IsForeignKey = false;
colvarShipRegion.IsReadOnly = false;
schema.Columns.Add(colvarShipRegion);
TableSchema.TableColumn colvarShipPostalCode = new TableSchema.TableColumn(schema);
colvarShipPostalCode.ColumnName = "ShipPostalCode";
colvarShipPostalCode.DataType = DbType.String;
colvarShipPostalCode.MaxLength = 10;
colvarShipPostalCode.AutoIncrement = false;
colvarShipPostalCode.IsNullable = true;
colvarShipPostalCode.IsPrimaryKey = false;
colvarShipPostalCode.IsForeignKey = false;
colvarShipPostalCode.IsReadOnly = false;
schema.Columns.Add(colvarShipPostalCode);
TableSchema.TableColumn colvarShipCountry = new TableSchema.TableColumn(schema);
colvarShipCountry.ColumnName = "ShipCountry";
colvarShipCountry.DataType = DbType.String;
colvarShipCountry.MaxLength = 15;
colvarShipCountry.AutoIncrement = false;
colvarShipCountry.IsNullable = true;
colvarShipCountry.IsPrimaryKey = false;
colvarShipCountry.IsForeignKey = false;
colvarShipCountry.IsReadOnly = false;
schema.Columns.Add(colvarShipCountry);
TableSchema.TableColumn colvarCustomerID = new TableSchema.TableColumn(schema);
colvarCustomerID.ColumnName = "CustomerID";
colvarCustomerID.DataType = DbType.String;
colvarCustomerID.MaxLength = 5;
colvarCustomerID.AutoIncrement = false;
colvarCustomerID.IsNullable = true;
colvarCustomerID.IsPrimaryKey = false;
colvarCustomerID.IsForeignKey = false;
colvarCustomerID.IsReadOnly = false;
schema.Columns.Add(colvarCustomerID);
TableSchema.TableColumn colvarCustomerName = new TableSchema.TableColumn(schema);
colvarCustomerName.ColumnName = "CustomerName";
colvarCustomerName.DataType = DbType.String;
colvarCustomerName.MaxLength = 40;
colvarCustomerName.AutoIncrement = false;
colvarCustomerName.IsNullable = false;
colvarCustomerName.IsPrimaryKey = false;
colvarCustomerName.IsForeignKey = false;
colvarCustomerName.IsReadOnly = false;
schema.Columns.Add(colvarCustomerName);
TableSchema.TableColumn colvarAddress = new TableSchema.TableColumn(schema);
colvarAddress.ColumnName = "Address";
colvarAddress.DataType = DbType.String;
colvarAddress.MaxLength = 60;
colvarAddress.AutoIncrement = false;
colvarAddress.IsNullable = true;
colvarAddress.IsPrimaryKey = false;
colvarAddress.IsForeignKey = false;
colvarAddress.IsReadOnly = false;
schema.Columns.Add(colvarAddress);
TableSchema.TableColumn colvarCity = new TableSchema.TableColumn(schema);
colvarCity.ColumnName = "City";
colvarCity.DataType = DbType.String;
colvarCity.MaxLength = 15;
colvarCity.AutoIncrement = false;
colvarCity.IsNullable = true;
colvarCity.IsPrimaryKey = false;
colvarCity.IsForeignKey = false;
colvarCity.IsReadOnly = false;
schema.Columns.Add(colvarCity);
TableSchema.TableColumn colvarRegion = new TableSchema.TableColumn(schema);
colvarRegion.ColumnName = "Region";
colvarRegion.DataType = DbType.String;
colvarRegion.MaxLength = 15;
colvarRegion.AutoIncrement = false;
colvarRegion.IsNullable = true;
colvarRegion.IsPrimaryKey = false;
colvarRegion.IsForeignKey = false;
colvarRegion.IsReadOnly = false;
schema.Columns.Add(colvarRegion);
TableSchema.TableColumn colvarPostalCode = new TableSchema.TableColumn(schema);
colvarPostalCode.ColumnName = "PostalCode";
colvarPostalCode.DataType = DbType.String;
colvarPostalCode.MaxLength = 10;
colvarPostalCode.AutoIncrement = false;
colvarPostalCode.IsNullable = true;
colvarPostalCode.IsPrimaryKey = false;
colvarPostalCode.IsForeignKey = false;
colvarPostalCode.IsReadOnly = false;
schema.Columns.Add(colvarPostalCode);
TableSchema.TableColumn colvarCountry = new TableSchema.TableColumn(schema);
colvarCountry.ColumnName = "Country";
colvarCountry.DataType = DbType.String;
colvarCountry.MaxLength = 15;
colvarCountry.AutoIncrement = false;
colvarCountry.IsNullable = true;
colvarCountry.IsPrimaryKey = false;
colvarCountry.IsForeignKey = false;
colvarCountry.IsReadOnly = false;
schema.Columns.Add(colvarCountry);
TableSchema.TableColumn colvarSalesperson = new TableSchema.TableColumn(schema);
colvarSalesperson.ColumnName = "Salesperson";
colvarSalesperson.DataType = DbType.String;
colvarSalesperson.MaxLength = 31;
colvarSalesperson.AutoIncrement = false;
colvarSalesperson.IsNullable = false;
colvarSalesperson.IsPrimaryKey = false;
colvarSalesperson.IsForeignKey = false;
colvarSalesperson.IsReadOnly = false;
schema.Columns.Add(colvarSalesperson);
TableSchema.TableColumn colvarOrderID = new TableSchema.TableColumn(schema);
colvarOrderID.ColumnName = "OrderID";
colvarOrderID.DataType = DbType.Int32;
colvarOrderID.MaxLength = 0;
colvarOrderID.AutoIncrement = false;
colvarOrderID.IsNullable = false;
colvarOrderID.IsPrimaryKey = false;
colvarOrderID.IsForeignKey = false;
colvarOrderID.IsReadOnly = false;
schema.Columns.Add(colvarOrderID);
TableSchema.TableColumn colvarOrderDate = new TableSchema.TableColumn(schema);
colvarOrderDate.ColumnName = "OrderDate";
colvarOrderDate.DataType = DbType.DateTime;
colvarOrderDate.MaxLength = 0;
colvarOrderDate.AutoIncrement = false;
colvarOrderDate.IsNullable = true;
colvarOrderDate.IsPrimaryKey = false;
colvarOrderDate.IsForeignKey = false;
colvarOrderDate.IsReadOnly = false;
schema.Columns.Add(colvarOrderDate);
TableSchema.TableColumn colvarRequiredDate = new TableSchema.TableColumn(schema);
colvarRequiredDate.ColumnName = "RequiredDate";
colvarRequiredDate.DataType = DbType.DateTime;
colvarRequiredDate.MaxLength = 0;
colvarRequiredDate.AutoIncrement = false;
colvarRequiredDate.IsNullable = true;
colvarRequiredDate.IsPrimaryKey = false;
colvarRequiredDate.IsForeignKey = false;
colvarRequiredDate.IsReadOnly = false;
schema.Columns.Add(colvarRequiredDate);
TableSchema.TableColumn colvarShippedDate = new TableSchema.TableColumn(schema);
colvarShippedDate.ColumnName = "ShippedDate";
colvarShippedDate.DataType = DbType.DateTime;
colvarShippedDate.MaxLength = 0;
colvarShippedDate.AutoIncrement = false;
colvarShippedDate.IsNullable = true;
colvarShippedDate.IsPrimaryKey = false;
colvarShippedDate.IsForeignKey = false;
colvarShippedDate.IsReadOnly = false;
schema.Columns.Add(colvarShippedDate);
TableSchema.TableColumn colvarShipperName = new TableSchema.TableColumn(schema);
colvarShipperName.ColumnName = "ShipperName";
colvarShipperName.DataType = DbType.String;
colvarShipperName.MaxLength = 40;
colvarShipperName.AutoIncrement = false;
colvarShipperName.IsNullable = false;
colvarShipperName.IsPrimaryKey = false;
colvarShipperName.IsForeignKey = false;
colvarShipperName.IsReadOnly = false;
schema.Columns.Add(colvarShipperName);
TableSchema.TableColumn colvarProductID = new TableSchema.TableColumn(schema);
colvarProductID.ColumnName = "ProductID";
colvarProductID.DataType = DbType.Int32;
colvarProductID.MaxLength = 0;
colvarProductID.AutoIncrement = false;
colvarProductID.IsNullable = false;
colvarProductID.IsPrimaryKey = false;
colvarProductID.IsForeignKey = false;
colvarProductID.IsReadOnly = false;
schema.Columns.Add(colvarProductID);
TableSchema.TableColumn colvarProductName = new TableSchema.TableColumn(schema);
colvarProductName.ColumnName = "ProductName";
colvarProductName.DataType = DbType.String;
colvarProductName.MaxLength = 40;
colvarProductName.AutoIncrement = false;
colvarProductName.IsNullable = false;
colvarProductName.IsPrimaryKey = false;
colvarProductName.IsForeignKey = false;
colvarProductName.IsReadOnly = false;
schema.Columns.Add(colvarProductName);
TableSchema.TableColumn colvarUnitPrice = new TableSchema.TableColumn(schema);
colvarUnitPrice.ColumnName = "UnitPrice";
colvarUnitPrice.DataType = DbType.Currency;
colvarUnitPrice.MaxLength = 0;
colvarUnitPrice.AutoIncrement = false;
colvarUnitPrice.IsNullable = false;
colvarUnitPrice.IsPrimaryKey = false;
colvarUnitPrice.IsForeignKey = false;
colvarUnitPrice.IsReadOnly = false;
schema.Columns.Add(colvarUnitPrice);
TableSchema.TableColumn colvarQuantity = new TableSchema.TableColumn(schema);
colvarQuantity.ColumnName = "Quantity";
colvarQuantity.DataType = DbType.Int16;
colvarQuantity.MaxLength = 0;
colvarQuantity.AutoIncrement = false;
colvarQuantity.IsNullable = false;
colvarQuantity.IsPrimaryKey = false;
colvarQuantity.IsForeignKey = false;
colvarQuantity.IsReadOnly = false;
schema.Columns.Add(colvarQuantity);
TableSchema.TableColumn colvarDiscount = new TableSchema.TableColumn(schema);
colvarDiscount.ColumnName = "Discount";
colvarDiscount.DataType = DbType.Single;
colvarDiscount.MaxLength = 0;
colvarDiscount.AutoIncrement = false;
colvarDiscount.IsNullable = false;
colvarDiscount.IsPrimaryKey = false;
colvarDiscount.IsForeignKey = false;
colvarDiscount.IsReadOnly = false;
schema.Columns.Add(colvarDiscount);
TableSchema.TableColumn colvarExtendedPrice = new TableSchema.TableColumn(schema);
colvarExtendedPrice.ColumnName = "ExtendedPrice";
colvarExtendedPrice.DataType = DbType.Currency;
colvarExtendedPrice.MaxLength = 0;
colvarExtendedPrice.AutoIncrement = false;
colvarExtendedPrice.IsNullable = true;
colvarExtendedPrice.IsPrimaryKey = false;
colvarExtendedPrice.IsForeignKey = false;
colvarExtendedPrice.IsReadOnly = false;
schema.Columns.Add(colvarExtendedPrice);
TableSchema.TableColumn colvarFreight = new TableSchema.TableColumn(schema);
colvarFreight.ColumnName = "Freight";
colvarFreight.DataType = DbType.Currency;
colvarFreight.MaxLength = 0;
colvarFreight.AutoIncrement = false;
colvarFreight.IsNullable = true;
colvarFreight.IsPrimaryKey = false;
colvarFreight.IsForeignKey = false;
colvarFreight.IsReadOnly = false;
schema.Columns.Add(colvarFreight);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["Northwind"].AddSchema("Invoices",schema);
}
}
#endregion
#region Query Accessor
public static Query CreateQuery()
{
return new Query(Schema);
}
#endregion
#region .ctors
public Invoice()
{
SetSQLProps();
SetDefaults();
MarkNew();
}
public Invoice(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
{
ForceDefaults();
}
MarkNew();
}
public Invoice(object keyID)
{
SetSQLProps();
LoadByKey(keyID);
}
public Invoice(string columnName, object columnValue)
{
SetSQLProps();
LoadByParam(columnName,columnValue);
}
#endregion
#region Props
[XmlAttribute("ShipName")]
[Bindable(true)]
public string ShipName
{
get
{
return GetColumnValue<string>("ShipName");
}
set
{
SetColumnValue("ShipName", value);
}
}
[XmlAttribute("ShipAddress")]
[Bindable(true)]
public string ShipAddress
{
get
{
return GetColumnValue<string>("ShipAddress");
}
set
{
SetColumnValue("ShipAddress", value);
}
}
[XmlAttribute("ShipCity")]
[Bindable(true)]
public string ShipCity
{
get
{
return GetColumnValue<string>("ShipCity");
}
set
{
SetColumnValue("ShipCity", value);
}
}
[XmlAttribute("ShipRegion")]
[Bindable(true)]
public string ShipRegion
{
get
{
return GetColumnValue<string>("ShipRegion");
}
set
{
SetColumnValue("ShipRegion", value);
}
}
[XmlAttribute("ShipPostalCode")]
[Bindable(true)]
public string ShipPostalCode
{
get
{
return GetColumnValue<string>("ShipPostalCode");
}
set
{
SetColumnValue("ShipPostalCode", value);
}
}
[XmlAttribute("ShipCountry")]
[Bindable(true)]
public string ShipCountry
{
get
{
return GetColumnValue<string>("ShipCountry");
}
set
{
SetColumnValue("ShipCountry", value);
}
}
[XmlAttribute("CustomerID")]
[Bindable(true)]
public string CustomerID
{
get
{
return GetColumnValue<string>("CustomerID");
}
set
{
SetColumnValue("CustomerID", value);
}
}
[XmlAttribute("CustomerName")]
[Bindable(true)]
public string CustomerName
{
get
{
return GetColumnValue<string>("CustomerName");
}
set
{
SetColumnValue("CustomerName", value);
}
}
[XmlAttribute("Address")]
[Bindable(true)]
public string Address
{
get
{
return GetColumnValue<string>("Address");
}
set
{
SetColumnValue("Address", value);
}
}
[XmlAttribute("City")]
[Bindable(true)]
public string City
{
get
{
return GetColumnValue<string>("City");
}
set
{
SetColumnValue("City", value);
}
}
[XmlAttribute("Region")]
[Bindable(true)]
public string Region
{
get
{
return GetColumnValue<string>("Region");
}
set
{
SetColumnValue("Region", value);
}
}
[XmlAttribute("PostalCode")]
[Bindable(true)]
public string PostalCode
{
get
{
return GetColumnValue<string>("PostalCode");
}
set
{
SetColumnValue("PostalCode", value);
}
}
[XmlAttribute("Country")]
[Bindable(true)]
public string Country
{
get
{
return GetColumnValue<string>("Country");
}
set
{
SetColumnValue("Country", value);
}
}
[XmlAttribute("Salesperson")]
[Bindable(true)]
public string Salesperson
{
get
{
return GetColumnValue<string>("Salesperson");
}
set
{
SetColumnValue("Salesperson", value);
}
}
[XmlAttribute("OrderID")]
[Bindable(true)]
public int OrderID
{
get
{
return GetColumnValue<int>("OrderID");
}
set
{
SetColumnValue("OrderID", value);
}
}
[XmlAttribute("OrderDate")]
[Bindable(true)]
public DateTime? OrderDate
{
get
{
return GetColumnValue<DateTime?>("OrderDate");
}
set
{
SetColumnValue("OrderDate", value);
}
}
[XmlAttribute("RequiredDate")]
[Bindable(true)]
public DateTime? RequiredDate
{
get
{
return GetColumnValue<DateTime?>("RequiredDate");
}
set
{
SetColumnValue("RequiredDate", value);
}
}
[XmlAttribute("ShippedDate")]
[Bindable(true)]
public DateTime? ShippedDate
{
get
{
return GetColumnValue<DateTime?>("ShippedDate");
}
set
{
SetColumnValue("ShippedDate", value);
}
}
[XmlAttribute("ShipperName")]
[Bindable(true)]
public string ShipperName
{
get
{
return GetColumnValue<string>("ShipperName");
}
set
{
SetColumnValue("ShipperName", value);
}
}
[XmlAttribute("ProductID")]
[Bindable(true)]
public int ProductID
{
get
{
return GetColumnValue<int>("ProductID");
}
set
{
SetColumnValue("ProductID", value);
}
}
[XmlAttribute("ProductName")]
[Bindable(true)]
public string ProductName
{
get
{
return GetColumnValue<string>("ProductName");
}
set
{
SetColumnValue("ProductName", value);
}
}
[XmlAttribute("UnitPrice")]
[Bindable(true)]
public decimal UnitPrice
{
get
{
return GetColumnValue<decimal>("UnitPrice");
}
set
{
SetColumnValue("UnitPrice", value);
}
}
[XmlAttribute("Quantity")]
[Bindable(true)]
public short Quantity
{
get
{
return GetColumnValue<short>("Quantity");
}
set
{
SetColumnValue("Quantity", value);
}
}
[XmlAttribute("Discount")]
[Bindable(true)]
public float Discount
{
get
{
return GetColumnValue<float>("Discount");
}
set
{
SetColumnValue("Discount", value);
}
}
[XmlAttribute("ExtendedPrice")]
[Bindable(true)]
public decimal? ExtendedPrice
{
get
{
return GetColumnValue<decimal?>("ExtendedPrice");
}
set
{
SetColumnValue("ExtendedPrice", value);
}
}
[XmlAttribute("Freight")]
[Bindable(true)]
public decimal? Freight
{
get
{
return GetColumnValue<decimal?>("Freight");
}
set
{
SetColumnValue("Freight", value);
}
}
#endregion
#region Columns Struct
public struct Columns
{
public static string ShipName = @"ShipName";
public static string ShipAddress = @"ShipAddress";
public static string ShipCity = @"ShipCity";
public static string ShipRegion = @"ShipRegion";
public static string ShipPostalCode = @"ShipPostalCode";
public static string ShipCountry = @"ShipCountry";
public static string CustomerID = @"CustomerID";
public static string CustomerName = @"CustomerName";
public static string Address = @"Address";
public static string City = @"City";
public static string Region = @"Region";
public static string PostalCode = @"PostalCode";
public static string Country = @"Country";
public static string Salesperson = @"Salesperson";
public static string OrderID = @"OrderID";
public static string OrderDate = @"OrderDate";
public static string RequiredDate = @"RequiredDate";
public static string ShippedDate = @"ShippedDate";
public static string ShipperName = @"ShipperName";
public static string ProductID = @"ProductID";
public static string ProductName = @"ProductName";
public static string UnitPrice = @"UnitPrice";
public static string Quantity = @"Quantity";
public static string Discount = @"Discount";
public static string ExtendedPrice = @"ExtendedPrice";
public static string Freight = @"Freight";
}
#endregion
#region IAbstractRecord Members
public new CT GetColumnValue<CT>(string columnName) {
return base.GetColumnValue<CT>(columnName);
}
public object GetColumnValue(string columnName) {
return base.GetColumnValue<object>(columnName);
}
#endregion
}
}
| |
// <copyright file="DataGenerator.Strings.cs" company="Adrian Mos">
// Copyright (c) Adrian Mos with all rights reserved. Part of the IX Framework.
// </copyright>
using System;
using JetBrains.Annotations;
namespace IX.StandardExtensions.TestUtils
{
/// <summary>
/// A static class that is used for generating random data for testing.
/// </summary>
public static partial class DataGenerator
{
// Character classes
#pragma warning disable SA1134 // Attributes should not share line - R# attributes
[NotNull] private static readonly char[] LowerCaseAlphaCharacters;
[NotNull] private static readonly char[] UpperCaseAlphaCharacters;
[NotNull] private static readonly char[] NumericCharacters;
[NotNull] private static readonly char[] BasicSymbolCharacters;
// Complex character classes
[NotNull] private static readonly char[] AlphaCharacters;
[NotNull] private static readonly char[] AlphaNumericCharacters;
[NotNull] private static readonly char[] AllCharacters;
#pragma warning restore SA1134 // Attributes should not share line
/// <summary>
/// Generates a random string.
/// </summary>
/// <returns>A random string.</returns>
public static string RandomLowercaseString()
{
int length;
lock (R)
{
length = R.Next();
}
return RandomString(
R,
length,
LowerCaseAlphaCharacters);
}
/// <summary>
/// Generates a random string.
/// </summary>
/// <param name="random">The random generator to use.</param>
/// <returns>A random string.</returns>
public static string RandomLowercaseString(Random random)
{
int length;
lock (random)
{
length = random.Next();
}
return RandomString(
random,
length,
LowerCaseAlphaCharacters);
}
/// <summary>
/// Generates a random string.
/// </summary>
/// <param name="length">The length of the string to generate.</param>
/// <returns>A random string.</returns>
public static string RandomLowercaseString(int length) => RandomString(
R,
length,
LowerCaseAlphaCharacters);
/// <summary>
/// Generates a random string.
/// </summary>
/// <param name="random">The random generator to use.</param>
/// <param name="length">The length of the string to generate.</param>
/// <returns>A random string.</returns>
public static string RandomLowercaseString(
Random random,
int length) => RandomString(
random,
length,
LowerCaseAlphaCharacters);
/// <summary>
/// Generates a random string.
/// </summary>
/// <returns>A random string.</returns>
public static string RandomUppercaseString()
{
int length;
lock (R)
{
length = R.Next();
}
return RandomString(
R,
length,
UpperCaseAlphaCharacters);
}
/// <summary>
/// Generates a random string.
/// </summary>
/// <param name="random">The random generator to use.</param>
/// <returns>A random string.</returns>
public static string RandomUppercaseString(Random random)
{
int length;
lock (random)
{
length = random.Next();
}
return RandomString(
random,
length,
UpperCaseAlphaCharacters);
}
/// <summary>
/// Generates a random string.
/// </summary>
/// <param name="length">The length of the string to generate.</param>
/// <returns>A random string.</returns>
public static string RandomUppercaseString(int length) => RandomString(
R,
length,
UpperCaseAlphaCharacters);
/// <summary>
/// Generates a random string.
/// </summary>
/// <param name="random">The random generator to use.</param>
/// <param name="length">The length of the string to generate.</param>
/// <returns>A random string.</returns>
public static string RandomUppercaseString(
Random random,
int length) => RandomString(
random,
length,
UpperCaseAlphaCharacters);
/// <summary>
/// Generates a random string.
/// </summary>
/// <returns>A random string.</returns>
public static string RandomNumericString()
{
int length;
lock (R)
{
length = R.Next();
}
return RandomString(
R,
length,
NumericCharacters);
}
/// <summary>
/// Generates a random string.
/// </summary>
/// <param name="random">The random generator to use.</param>
/// <returns>A random string.</returns>
public static string RandomNumericString(Random random)
{
int length;
lock (random)
{
length = random.Next();
}
return RandomString(
random,
length,
NumericCharacters);
}
/// <summary>
/// Generates a random string.
/// </summary>
/// <param name="length">The length of the string to generate.</param>
/// <returns>A random string.</returns>
public static string RandomNumericString(int length) => RandomString(
R,
length,
NumericCharacters);
/// <summary>
/// Generates a random string.
/// </summary>
/// <param name="random">The random generator to use.</param>
/// <param name="length">The length of the string to generate.</param>
/// <returns>A random string.</returns>
public static string RandomNumericString(
Random random,
int length) => RandomString(
random,
length,
NumericCharacters);
/// <summary>
/// Generates a random string.
/// </summary>
/// <returns>A random string.</returns>
public static string RandomSymbolString()
{
int length;
lock (R)
{
length = R.Next();
}
return RandomString(
R,
length,
BasicSymbolCharacters);
}
/// <summary>
/// Generates a random string.
/// </summary>
/// <param name="random">The random generator to use.</param>
/// <returns>A random string.</returns>
public static string RandomSymbolString(Random random)
{
int length;
lock (random)
{
length = random.Next();
}
return RandomString(
random,
length,
BasicSymbolCharacters);
}
/// <summary>
/// Generates a random string.
/// </summary>
/// <param name="length">The length of the string to generate.</param>
/// <returns>A random string.</returns>
public static string RandomSymbolString(int length) => RandomString(
R,
length,
BasicSymbolCharacters);
/// <summary>
/// Generates a random string.
/// </summary>
/// <param name="random">The random generator to use.</param>
/// <param name="length">The length of the string to generate.</param>
/// <returns>A random string.</returns>
public static string RandomSymbolString(
Random random,
int length) => RandomString(
random,
length,
BasicSymbolCharacters);
/// <summary>
/// Generates a random string.
/// </summary>
/// <returns>A random string.</returns>
public static string RandomAlphaString()
{
int length;
lock (R)
{
length = R.Next();
}
return RandomString(
R,
length,
AlphaCharacters);
}
/// <summary>
/// Generates a random string.
/// </summary>
/// <param name="random">The random generator to use.</param>
/// <returns>A random string.</returns>
public static string RandomAlphaString(Random random)
{
int length;
lock (random)
{
length = random.Next();
}
return RandomString(
random,
length,
AlphaCharacters);
}
/// <summary>
/// Generates a random string.
/// </summary>
/// <param name="length">The length of the string to generate.</param>
/// <returns>A random string.</returns>
public static string RandomAlphaString(int length) => RandomString(
R,
length,
AlphaCharacters);
/// <summary>
/// Generates a random string.
/// </summary>
/// <param name="random">The random generator to use.</param>
/// <param name="length">The length of the string to generate.</param>
/// <returns>A random string.</returns>
public static string RandomAlphaString(
Random random,
int length) => RandomString(
random,
length,
AlphaCharacters);
/// <summary>
/// Generates a random string.
/// </summary>
/// <returns>A random string.</returns>
public static string RandomAlphanumericString()
{
int length;
lock (R)
{
length = R.Next();
}
return RandomString(
R,
length,
AlphaNumericCharacters);
}
/// <summary>
/// Generates a random string.
/// </summary>
/// <param name="random">The random generator to use.</param>
/// <returns>A random string.</returns>
public static string RandomAlphanumericString(Random random)
{
int length;
lock (random)
{
length = random.Next();
}
return RandomString(
random,
length,
AlphaNumericCharacters);
}
/// <summary>
/// Generates a random string.
/// </summary>
/// <param name="length">The length of the string to generate.</param>
/// <returns>A random string.</returns>
public static string RandomAlphanumericString(int length) => RandomString(
R,
length,
AlphaNumericCharacters);
/// <summary>
/// Generates a random string.
/// </summary>
/// <param name="random">The random generator to use.</param>
/// <param name="length">The length of the string to generate.</param>
/// <returns>A random string.</returns>
public static string RandomAlphanumericString(
Random random,
int length) => RandomString(
random,
length,
AlphaNumericCharacters);
/// <summary>
/// Generates a random string.
/// </summary>
/// <returns>A random string.</returns>
public static string RandomString()
{
int length;
lock (R)
{
length = R.Next();
}
return RandomString(
R,
length,
AllCharacters);
}
/// <summary>
/// Generates a random string.
/// </summary>
/// <param name="random">The random generator to use.</param>
/// <returns>A random string.</returns>
public static string RandomString(Random random)
{
int length;
lock (random)
{
length = random.Next();
}
return RandomString(
random,
length,
AllCharacters);
}
/// <summary>
/// Generates a random string.
/// </summary>
/// <param name="length">The length of the string to generate.</param>
/// <returns>A random string.</returns>
public static string RandomString(int length) => RandomString(
R,
length,
AllCharacters);
/// <summary>
/// Generates a random string.
/// </summary>
/// <param name="random">The random generator to use.</param>
/// <param name="length">The length of the string to generate.</param>
/// <returns>A random string.</returns>
public static string RandomString(
Random random,
int length) => RandomString(
random,
length,
AllCharacters);
/// <summary>
/// Generates a random string.
/// </summary>
/// <param name="random">The random generator to use.</param>
/// <param name="fromCharacters">The array of characters from which to generate the string.</param>
/// <returns>A random string.</returns>
public static string RandomString(
Random random,
char[] fromCharacters)
{
int length;
lock (random)
{
length = random.Next();
}
return RandomString(
random,
length,
fromCharacters);
}
/// <summary>
/// Generates a random string.
/// </summary>
/// <param name="random">The random generator to use.</param>
/// <param name="length">The length of the string to generate.</param>
/// <param name="fromCharacters">The array of characters from which to generate the string.</param>
/// <returns>A random string.</returns>
public static string RandomString(
Random random,
int length,
char[] fromCharacters)
{
var randomString = new char[length];
int position;
for (var i = 0; i < length; i++)
{
lock (R)
{
position = random.Next(fromCharacters.Length);
}
randomString[i] = fromCharacters[position];
}
return new string(randomString);
}
}
}
| |
//
// Copyright (c) 2004-2021 Jaroslaw Kowalski <[email protected]>, 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.Internal.Fakeables
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Xml;
internal class AppEnvironmentWrapper : IAppEnvironment
{
#if !NETSTANDARD1_3 && !SILVERLIGHT
private const string UnknownProcessName = "<unknown>";
private string _entryAssemblyLocation;
private string _entryAssemblyFileName;
private string _currentProcessFilePath;
private string _currentProcessBaseName;
private int? _currentProcessId;
/// <inheritdoc />
public string EntryAssemblyLocation => _entryAssemblyLocation ?? (_entryAssemblyLocation = LookupEntryAssemblyLocation());
/// <inheritdoc />
public string EntryAssemblyFileName => _entryAssemblyFileName ?? (_entryAssemblyFileName = LookupEntryAssemblyFileName());
/// <inheritdoc />
public string CurrentProcessFilePath => _currentProcessFilePath ?? (_currentProcessFilePath = LookupCurrentProcessFilePathWithFallback());
/// <inheritdoc />
public string CurrentProcessBaseName => _currentProcessBaseName ?? (_currentProcessBaseName = string.IsNullOrEmpty(CurrentProcessFilePath) ? UnknownProcessName : Path.GetFileNameWithoutExtension(CurrentProcessFilePath));
/// <inheritdoc />
public int CurrentProcessId => _currentProcessId ?? (_currentProcessId = LookupCurrentProcessIdWithFallback()).Value;
#endif
/// <inheritdoc />
public string AppDomainBaseDirectory => AppDomain.BaseDirectory;
/// <inheritdoc />
public string AppDomainConfigurationFile => AppDomain.ConfigurationFile;
/// <inheritdoc />
public IEnumerable<string> PrivateBinPath => AppDomain.PrivateBinPath;
/// <inheritdoc />
public string UserTempFilePath => Path.GetTempPath();
/// <inheritdoc />
public IAppDomain AppDomain { get; internal set; }
public AppEnvironmentWrapper(IAppDomain appDomain)
{
AppDomain = appDomain;
}
/// <inheritdoc />
public bool FileExists(string path)
{
return File.Exists(path);
}
/// <inheritdoc />
public XmlReader LoadXmlFile(string path)
{
return XmlReader.Create(path);
}
#if !NETSTANDARD1_3 && !SILVERLIGHT
private static string LookupEntryAssemblyLocation()
{
return AssemblyHelpers.GetAssemblyFileLocation(System.Reflection.Assembly.GetEntryAssembly());
}
private static string LookupEntryAssemblyFileName()
{
try
{
return Path.GetFileName(System.Reflection.Assembly.GetEntryAssembly()?.Location ?? string.Empty);
}
catch (Exception ex)
{
if (ex.MustBeRethrownImmediately())
throw;
return string.Empty;
}
}
private static string LookupCurrentProcessFilePathWithFallback()
{
try
{
var processFilePath = LookupCurrentProcessFilePath();
return processFilePath ?? LookupCurrentProcessFilePathNative();
}
catch (Exception ex)
{
if (ex.MustBeRethrownImmediately())
throw;
return LookupCurrentProcessFilePathNative();
}
}
private static string LookupCurrentProcessFilePath()
{
try
{
var currentProcess = Process.GetCurrentProcess();
return currentProcess?.MainModule.FileName;
}
catch (Exception ex)
{
if (ex.MustBeRethrownImmediately())
throw;
// May throw a SecurityException or Access Denied when running from an IIS app. pool process
return null;
}
}
private static int LookupCurrentProcessIdWithFallback()
{
try
{
var processId = LookupCurrentProcessId();
return processId ?? LookupCurrentProcessIdNative();
}
catch (Exception ex)
{
if (ex.MustBeRethrownImmediately())
throw;
// May throw a SecurityException if running from an IIS app. pool process (Cannot compile method)
return LookupCurrentProcessIdNative();
}
}
private static int? LookupCurrentProcessId()
{
try
{
var currentProcess = Process.GetCurrentProcess();
return currentProcess?.Id;
}
catch (Exception ex)
{
if (ex.MustBeRethrownImmediately())
throw;
// May throw a SecurityException or Access Denied when running from an IIS app. pool process
return null;
}
}
#endif
#if !SILVERLIGHT && !__IOS__ && !__ANDROID__ && !NETSTANDARD
private static string LookupCurrentProcessFilePathNative()
{
try
{
if (!PlatformDetector.IsWin32)
return string.Empty;
return LookupCurrentProcessFilePathWin32();
}
catch (Exception ex)
{
if (ex.MustBeRethrownImmediately())
throw;
return string.Empty;
}
}
[System.Security.SecuritySafeCritical]
private static string LookupCurrentProcessFilePathWin32()
{
try
{
var sb = new System.Text.StringBuilder(512);
if (0 == NativeMethods.GetModuleFileName(IntPtr.Zero, sb, sb.Capacity))
{
throw new InvalidOperationException("Cannot determine program name.");
}
return sb.ToString();
}
catch (Exception ex)
{
if (ex.MustBeRethrownImmediately())
throw;
return string.Empty;
}
}
private static int LookupCurrentProcessIdNative()
{
try
{
if (!PlatformDetector.IsWin32)
return 0;
return LookupCurrentProcessIdWin32();
}
catch (Exception ex)
{
if (ex.MustBeRethrownImmediately())
throw;
return 0;
}
}
[System.Security.SecuritySafeCritical]
private static int LookupCurrentProcessIdWin32()
{
try
{
return NativeMethods.GetCurrentProcessId();
}
catch (Exception ex)
{
if (ex.MustBeRethrownImmediately())
throw;
return 0;
}
}
#else
private static string LookupCurrentProcessFilePathNative()
{
return string.Empty;
}
private static int LookupCurrentProcessIdNative()
{
return 0;
}
#endif
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Reflection;
using Xunit;
namespace System.Linq.Expressions.Tests
{
public class PostDecrementAssignTests : IncDecAssignTests
{
[Theory]
[PerCompilationType(nameof(Int16sAndDecrements))]
[PerCompilationType(nameof(NullableInt16sAndDecrements))]
[PerCompilationType(nameof(UInt16sAndDecrements))]
[PerCompilationType(nameof(NullableUInt16sAndDecrements))]
[PerCompilationType(nameof(Int32sAndDecrements))]
[PerCompilationType(nameof(NullableInt32sAndDecrements))]
[PerCompilationType(nameof(UInt32sAndDecrements))]
[PerCompilationType(nameof(NullableUInt32sAndDecrements))]
[PerCompilationType(nameof(Int64sAndDecrements))]
[PerCompilationType(nameof(NullableInt64sAndDecrements))]
[PerCompilationType(nameof(UInt64sAndDecrements))]
[PerCompilationType(nameof(NullableUInt64sAndDecrements))]
[PerCompilationType(nameof(DecimalsAndDecrements))]
[PerCompilationType(nameof(NullableDecimalsAndDecrements))]
[PerCompilationType(nameof(SinglesAndDecrements))]
[PerCompilationType(nameof(NullableSinglesAndDecrements))]
[PerCompilationType(nameof(DoublesAndDecrements))]
[PerCompilationType(nameof(NullableDoublesAndDecrements))]
public void ReturnsCorrectValues(Type type, object value, object _, bool useInterpreter)
{
ParameterExpression variable = Expression.Variable(type);
BlockExpression block = Expression.Block(
new[] { variable },
Expression.Assign(variable, Expression.Constant(value, type)),
Expression.PostDecrementAssign(variable)
);
Assert.True(Expression.Lambda<Func<bool>>(Expression.Equal(Expression.Constant(value, type), block)).Compile(useInterpreter)());
}
[Theory]
[PerCompilationType(nameof(Int16sAndDecrements))]
[PerCompilationType(nameof(NullableInt16sAndDecrements))]
[PerCompilationType(nameof(UInt16sAndDecrements))]
[PerCompilationType(nameof(NullableUInt16sAndDecrements))]
[PerCompilationType(nameof(Int32sAndDecrements))]
[PerCompilationType(nameof(NullableInt32sAndDecrements))]
[PerCompilationType(nameof(UInt32sAndDecrements))]
[PerCompilationType(nameof(NullableUInt32sAndDecrements))]
[PerCompilationType(nameof(Int64sAndDecrements))]
[PerCompilationType(nameof(NullableInt64sAndDecrements))]
[PerCompilationType(nameof(UInt64sAndDecrements))]
[PerCompilationType(nameof(NullableUInt64sAndDecrements))]
[PerCompilationType(nameof(DecimalsAndDecrements))]
[PerCompilationType(nameof(NullableDecimalsAndDecrements))]
[PerCompilationType(nameof(SinglesAndDecrements))]
[PerCompilationType(nameof(NullableSinglesAndDecrements))]
[PerCompilationType(nameof(DoublesAndDecrements))]
[PerCompilationType(nameof(NullableDoublesAndDecrements))]
public void AssignsCorrectValues(Type type, object value, object result, bool useInterpreter)
{
ParameterExpression variable = Expression.Variable(type);
LabelTarget target = Expression.Label(type);
BlockExpression block = Expression.Block(
new[] { variable },
Expression.Assign(variable, Expression.Constant(value, type)),
Expression.PostDecrementAssign(variable),
Expression.Return(target, variable),
Expression.Label(target, Expression.Default(type))
);
Assert.True(Expression.Lambda<Func<bool>>(Expression.Equal(Expression.Constant(result, type), block)).Compile(useInterpreter)());
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void SingleNanToNan(bool useInterpreter)
{
TestPropertyClass<float> instance = new TestPropertyClass<float>();
instance.TestInstance = float.NaN;
Assert.True(float.IsNaN(
Expression.Lambda<Func<float>>(
Expression.PostDecrementAssign(
Expression.Property(
Expression.Constant(instance),
typeof(TestPropertyClass<float>),
"TestInstance"
)
)
).Compile(useInterpreter)()
));
Assert.True(float.IsNaN(instance.TestInstance));
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void DoubleNanToNan(bool useInterpreter)
{
TestPropertyClass<double> instance = new TestPropertyClass<double>();
instance.TestInstance = double.NaN;
Assert.True(double.IsNaN(
Expression.Lambda<Func<double>>(
Expression.PostDecrementAssign(
Expression.Property(
Expression.Constant(instance),
typeof(TestPropertyClass<double>),
"TestInstance"
)
)
).Compile(useInterpreter)()
));
Assert.True(double.IsNaN(instance.TestInstance));
}
[Theory]
[PerCompilationType(nameof(DecrementOverflowingValues))]
public void OverflowingValuesThrow(object value, bool useInterpreter)
{
ParameterExpression variable = Expression.Variable(value.GetType());
Action overflow = Expression.Lambda<Action>(
Expression.Block(
typeof(void),
new[] { variable },
Expression.Assign(variable, Expression.Constant(value)),
Expression.PostDecrementAssign(variable)
)
).Compile(useInterpreter);
Assert.Throws<OverflowException>(overflow);
}
[Theory]
[MemberData(nameof(UnincrementableAndUndecrementableTypes))]
public void InvalidOperandType(Type type)
{
ParameterExpression variable = Expression.Variable(type);
Assert.Throws<InvalidOperationException>(() => Expression.PostDecrementAssign(variable));
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void MethodCorrectResult(bool useInterpreter)
{
ParameterExpression variable = Expression.Variable(typeof(string));
BlockExpression block = Expression.Block(
new[] { variable },
Expression.Assign(variable, Expression.Constant("hello")),
Expression.PostDecrementAssign(variable, typeof(IncDecAssignTests).GetTypeInfo().GetDeclaredMethod("SillyMethod"))
);
Assert.Equal("hello", Expression.Lambda<Func<string>>(block).Compile(useInterpreter)());
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void MethodCorrectAssign(bool useInterpreter)
{
ParameterExpression variable = Expression.Variable(typeof(string));
LabelTarget target = Expression.Label(typeof(string));
BlockExpression block = Expression.Block(
new[] { variable },
Expression.Assign(variable, Expression.Constant("hello")),
Expression.PostDecrementAssign(variable, typeof(IncDecAssignTests).GetTypeInfo().GetDeclaredMethod("SillyMethod")),
Expression.Return(target, variable),
Expression.Label(target, Expression.Default(typeof(string)))
);
Assert.Equal("Eggplant", Expression.Lambda<Func<string>>(block).Compile(useInterpreter)());
}
[Fact]
public void IncorrectMethodType()
{
Expression variable = Expression.Variable(typeof(int));
MethodInfo method = typeof(IncDecAssignTests).GetTypeInfo().GetDeclaredMethod("SillyMethod");
Assert.Throws<InvalidOperationException>(() => Expression.PostDecrementAssign(variable, method));
}
[Fact]
public void IncorrectMethodParameterCount()
{
Expression variable = Expression.Variable(typeof(string));
MethodInfo method = typeof(object).GetTypeInfo().GetDeclaredMethod("ReferenceEquals");
Assert.Throws<ArgumentException>(() => Expression.PostDecrementAssign(variable, method));
}
[Fact]
public void IncorrectMethodReturnType()
{
Expression variable = Expression.Variable(typeof(int));
MethodInfo method = typeof(IncDecAssignTests).GetTypeInfo().GetDeclaredMethod("GetString");
Assert.Throws<ArgumentException>(() => Expression.PostDecrementAssign(variable, method));
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void StaticMemberAccessCorrect(bool useInterpreter)
{
TestPropertyClass<double>.TestStatic = 2.0;
Assert.Equal(
2.0,
Expression.Lambda<Func<double>>(
Expression.PostDecrementAssign(
Expression.Property(null, typeof(TestPropertyClass<double>), "TestStatic")
)
).Compile(useInterpreter)()
);
Assert.Equal(1.0, TestPropertyClass<double>.TestStatic);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void InstanceMemberAccessCorrect(bool useInterpreter)
{
TestPropertyClass<int> instance = new TestPropertyClass<int>();
instance.TestInstance = 2;
Assert.Equal(
2,
Expression.Lambda<Func<int>>(
Expression.PostDecrementAssign(
Expression.Property(
Expression.Constant(instance),
typeof(TestPropertyClass<int>),
"TestInstance"
)
)
).Compile(useInterpreter)()
);
Assert.Equal(1, instance.TestInstance);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void ArrayAccessCorrect(bool useInterpreter)
{
int[] array = new int[1];
array[0] = 2;
Assert.Equal(
2,
Expression.Lambda<Func<int>>(
Expression.PostDecrementAssign(
Expression.ArrayAccess(Expression.Constant(array), Expression.Constant(0))
)
).Compile(useInterpreter)()
);
Assert.Equal(1, array[0]);
}
[Fact]
public void CanReduce()
{
ParameterExpression variable = Expression.Variable(typeof(int));
UnaryExpression op = Expression.PostDecrementAssign(variable);
Assert.True(op.CanReduce);
Assert.NotSame(op, op.ReduceAndCheck());
}
[Fact]
public void NullOperand()
{
Assert.Throws<ArgumentNullException>("expression", () => Expression.PostDecrementAssign(null));
}
[Fact]
public void UnwritableOperand()
{
Assert.Throws<ArgumentException>("expression", () => Expression.PostDecrementAssign(Expression.Constant(1)));
}
[Fact]
public void UnreadableOperand()
{
Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly");
Assert.Throws<ArgumentException>("expression", () => Expression.PostDecrementAssign(value));
}
[Fact]
public void UpdateSameOperandSameNode()
{
UnaryExpression op = Expression.PostDecrementAssign(Expression.Variable(typeof(int)));
Assert.Same(op, op.Update(op.Operand));
}
[Fact]
public void UpdateDiffOperandDiffNode()
{
UnaryExpression op = Expression.PostDecrementAssign(Expression.Variable(typeof(int)));
Assert.NotSame(op, op.Update(Expression.Variable(typeof(int))));
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Win32.SafeHandles;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
using System.Threading;
namespace System.Diagnostics
{
public partial class Process : IDisposable
{
private static readonly UTF8Encoding s_utf8NoBom =
new UTF8Encoding(encoderShouldEmitUTF8Identifier: false);
private static volatile bool s_initialized = false;
private static readonly object s_initializedGate = new object();
private static readonly Interop.Sys.SigChldCallback s_sigChildHandler = OnSigChild;
private static readonly ReaderWriterLockSlim s_processStartLock = new ReaderWriterLockSlim();
private static int s_childrenUsingTerminalCount;
/// <summary>
/// Puts a Process component in state to interact with operating system processes that run in a
/// special mode by enabling the native property SeDebugPrivilege on the current thread.
/// </summary>
public static void EnterDebugMode()
{
// Nop.
}
/// <summary>
/// Takes a Process component out of the state that lets it interact with operating system processes
/// that run in a special mode.
/// </summary>
public static void LeaveDebugMode()
{
// Nop.
}
[CLSCompliant(false)]
public static Process Start(string fileName, string userName, SecureString password, string domain)
{
throw new PlatformNotSupportedException(SR.ProcessStartWithPasswordAndDomainNotSupported);
}
[CLSCompliant(false)]
public static Process Start(string fileName, string arguments, string userName, SecureString password, string domain)
{
throw new PlatformNotSupportedException(SR.ProcessStartWithPasswordAndDomainNotSupported);
}
/// <summary>Terminates the associated process immediately.</summary>
public void Kill()
{
EnsureState(State.HaveId);
// Check if we know the process has exited. This avoids us targetting another
// process that has a recycled PID. This only checks our internal state, the Kill call below
// activly checks if the process is still alive.
if (GetHasExited(refresh: false))
{
return;
}
int killResult = Interop.Sys.Kill(_processId, Interop.Sys.Signals.SIGKILL);
if (killResult != 0)
{
Interop.Error error = Interop.Sys.GetLastError();
// Don't throw if the process has exited.
if (error == Interop.Error.ESRCH)
{
return;
}
throw new Win32Exception(); // same exception as on Windows
}
}
private bool GetHasExited(bool refresh)
=> GetWaitState().GetExited(out _, refresh);
private IEnumerable<Exception> KillTree()
{
List<Exception> exceptions = null;
KillTree(ref exceptions);
return exceptions ?? Enumerable.Empty<Exception>();
}
private void KillTree(ref List<Exception> exceptions)
{
// If the process has exited, we can no longer determine its children.
// If we know the process has exited, stop already.
if (GetHasExited(refresh: false))
{
return;
}
// Stop the process, so it won't start additional children.
// This is best effort: kill can return before the process is stopped.
int stopResult = Interop.Sys.Kill(_processId, Interop.Sys.Signals.SIGSTOP);
if (stopResult != 0)
{
Interop.Error error = Interop.Sys.GetLastError();
// Ignore 'process no longer exists' error.
if (error != Interop.Error.ESRCH)
{
AddException(ref exceptions, new Win32Exception());
}
return;
}
IReadOnlyList<Process> children = GetChildProcesses();
int killResult = Interop.Sys.Kill(_processId, Interop.Sys.Signals.SIGKILL);
if (killResult != 0)
{
Interop.Error error = Interop.Sys.GetLastError();
// Ignore 'process no longer exists' error.
if (error != Interop.Error.ESRCH)
{
AddException(ref exceptions, new Win32Exception());
}
}
foreach (Process childProcess in children)
{
childProcess.KillTree(ref exceptions);
childProcess.Dispose();
}
void AddException(ref List<Exception> list, Exception e)
{
if (list == null)
{
list = new List<Exception>();
}
list.Add(e);
}
}
/// <summary>Discards any information about the associated process.</summary>
private void RefreshCore()
{
// Nop. No additional state to reset.
}
/// <summary>Additional logic invoked when the Process is closed.</summary>
private void CloseCore()
{
if (_waitStateHolder != null)
{
_waitStateHolder.Dispose();
_waitStateHolder = null;
}
}
/// <summary>Additional configuration when a process ID is set.</summary>
partial void ConfigureAfterProcessIdSet()
{
// Make sure that we configure the wait state holder for this process object, which we can only do once we have a process ID.
Debug.Assert(_haveProcessId, $"{nameof(ConfigureAfterProcessIdSet)} should only be called once a process ID is set");
// Initialize WaitStateHolder for non-child processes
GetWaitState();
}
/// <devdoc>
/// Make sure we are watching for a process exit.
/// </devdoc>
/// <internalonly/>
private void EnsureWatchingForExit()
{
if (!_watchingForExit)
{
lock (this)
{
if (!_watchingForExit)
{
Debug.Assert(_waitHandle == null);
Debug.Assert(_registeredWaitHandle == null);
Debug.Assert(Associated, "Process.EnsureWatchingForExit called with no associated process");
_watchingForExit = true;
try
{
_waitHandle = new ProcessWaitHandle(GetWaitState());
_registeredWaitHandle = ThreadPool.RegisterWaitForSingleObject(_waitHandle,
new WaitOrTimerCallback(CompletionCallback), _waitHandle, -1, true);
}
catch
{
_waitHandle?.Dispose();
_waitHandle = null;
_watchingForExit = false;
throw;
}
}
}
}
}
/// <summary>
/// Instructs the Process component to wait the specified number of milliseconds for the associated process to exit.
/// </summary>
private bool WaitForExitCore(int milliseconds)
{
bool exited = GetWaitState().WaitForExit(milliseconds);
Debug.Assert(exited || milliseconds != Timeout.Infinite);
if (exited && milliseconds == Timeout.Infinite) // if we have a hard timeout, we cannot wait for the streams
{
if (_output != null)
{
_output.WaitUtilEOF();
}
if (_error != null)
{
_error.WaitUtilEOF();
}
}
return exited;
}
/// <summary>Gets the main module for the associated process.</summary>
public ProcessModule MainModule
{
get
{
ProcessModuleCollection pmc = Modules;
return pmc.Count > 0 ? pmc[0] : null;
}
}
/// <summary>Checks whether the process has exited and updates state accordingly.</summary>
private void UpdateHasExited()
{
int? exitCode;
_exited = GetWaitState().GetExited(out exitCode, refresh: true);
if (_exited && exitCode != null)
{
_exitCode = exitCode.Value;
}
}
/// <summary>Gets the time that the associated process exited.</summary>
private DateTime ExitTimeCore
{
get { return GetWaitState().ExitTime; }
}
/// <summary>
/// Gets or sets a value indicating whether the associated process priority
/// should be temporarily boosted by the operating system when the main window
/// has focus.
/// </summary>
private bool PriorityBoostEnabledCore
{
get { return false; } //Nop
set { } // Nop
}
/// <summary>
/// Gets or sets the overall priority category for the associated process.
/// </summary>
private ProcessPriorityClass PriorityClassCore
{
// This mapping is relatively arbitrary. 0 is normal based on the man page,
// and the other values above and below are simply distributed evenly.
get
{
EnsureState(State.HaveNonExitedId);
int pri = 0;
int errno = Interop.Sys.GetPriority(Interop.Sys.PriorityWhich.PRIO_PROCESS, _processId, out pri);
if (errno != 0) // Interop.Sys.GetPriority returns GetLastWin32Error()
{
throw new Win32Exception(errno); // match Windows exception
}
Debug.Assert(pri >= -20 && pri <= 20);
return
pri < -15 ? ProcessPriorityClass.RealTime :
pri < -10 ? ProcessPriorityClass.High :
pri < -5 ? ProcessPriorityClass.AboveNormal :
pri == 0 ? ProcessPriorityClass.Normal :
pri <= 10 ? ProcessPriorityClass.BelowNormal :
ProcessPriorityClass.Idle;
}
set
{
EnsureState(State.HaveNonExitedId);
int pri = 0; // Normal
switch (value)
{
case ProcessPriorityClass.RealTime: pri = -19; break;
case ProcessPriorityClass.High: pri = -11; break;
case ProcessPriorityClass.AboveNormal: pri = -6; break;
case ProcessPriorityClass.BelowNormal: pri = 10; break;
case ProcessPriorityClass.Idle: pri = 19; break;
default:
Debug.Assert(value == ProcessPriorityClass.Normal, "Input should have been validated by caller");
break;
}
int result = Interop.Sys.SetPriority(Interop.Sys.PriorityWhich.PRIO_PROCESS, _processId, pri);
if (result == -1)
{
throw new Win32Exception(); // match Windows exception
}
}
}
/// <summary>Gets the ID of the current process.</summary>
private static int GetCurrentProcessId()
{
return Interop.Sys.GetPid();
}
/// <summary>Checks whether the argument is a direct child of this process.</summary>
private bool IsParentOf(Process possibleChildProcess) =>
Id == possibleChildProcess.ParentProcessId;
private bool Equals(Process process) =>
Id == process.Id;
partial void ThrowIfExited(bool refresh)
{
// Don't allocate a ProcessWaitState.Holder unless we're refreshing.
if (_waitStateHolder == null && !refresh)
{
return;
}
if (GetHasExited(refresh))
{
throw new InvalidOperationException(SR.Format(SR.ProcessHasExited, _processId.ToString()));
}
}
/// <summary>
/// Gets a short-term handle to the process, with the given access. If a handle exists,
/// then it is reused. If the process has exited, it throws an exception.
/// </summary>
private SafeProcessHandle GetProcessHandle()
{
if (_haveProcessHandle)
{
ThrowIfExited(refresh: true);
return _processHandle;
}
EnsureState(State.HaveNonExitedId | State.IsLocal);
return new SafeProcessHandle(_processId, GetSafeWaitHandle());
}
/// <summary>
/// Starts the process using the supplied start info.
/// With UseShellExecute option, we'll try the shell tools to launch it(e.g. "open fileName")
/// </summary>
/// <param name="startInfo">The start info with which to start the process.</param>
private bool StartCore(ProcessStartInfo startInfo)
{
EnsureInitialized();
string filename;
string[] argv;
if (startInfo.UseShellExecute)
{
if (startInfo.RedirectStandardInput || startInfo.RedirectStandardOutput || startInfo.RedirectStandardError)
{
throw new InvalidOperationException(SR.CantRedirectStreams);
}
}
int stdinFd = -1, stdoutFd = -1, stderrFd = -1;
string[] envp = CreateEnvp(startInfo);
string cwd = !string.IsNullOrWhiteSpace(startInfo.WorkingDirectory) ? startInfo.WorkingDirectory : null;
bool setCredentials = !string.IsNullOrEmpty(startInfo.UserName);
uint userId = 0;
uint groupId = 0;
uint[] groups = null;
if (setCredentials)
{
(userId, groupId, groups) = GetUserAndGroupIds(startInfo);
}
// .NET applications don't echo characters unless there is a Console.Read operation.
// Unix applications expect the terminal to be in an echoing state by default.
// To support processes that interact with the terminal (e.g. 'vi'), we need to configure the
// terminal to echo. We keep this configuration as long as there are children possibly using the terminal.
bool usesTerminal = !(startInfo.RedirectStandardInput &&
startInfo.RedirectStandardOutput &&
startInfo.RedirectStandardError);
if (startInfo.UseShellExecute)
{
string verb = startInfo.Verb;
if (verb != string.Empty &&
!string.Equals(verb, "open", StringComparison.OrdinalIgnoreCase))
{
throw new Win32Exception(Interop.Errors.ERROR_NO_ASSOCIATION);
}
// On Windows, UseShellExecute of executables and scripts causes those files to be executed.
// To achieve this on Unix, we check if the file is executable (x-bit).
// Some files may have the x-bit set even when they are not executable. This happens for example
// when a Windows filesystem is mounted on Linux. To handle that, treat it as a regular file
// when exec returns ENOEXEC (file format cannot be executed).
bool isExecuting = false;
filename = ResolveExecutableForShellExecute(startInfo.FileName, cwd);
if (filename != null)
{
argv = ParseArgv(startInfo);
isExecuting = ForkAndExecProcess(filename, argv, envp, cwd,
startInfo.RedirectStandardInput, startInfo.RedirectStandardOutput, startInfo.RedirectStandardError,
setCredentials, userId, groupId, groups,
out stdinFd, out stdoutFd, out stderrFd, usesTerminal,
throwOnNoExec: false); // return false instead of throwing on ENOEXEC
}
// use default program to open file/url
if (!isExecuting)
{
filename = GetPathToOpenFile();
argv = ParseArgv(startInfo, filename, ignoreArguments: true);
ForkAndExecProcess(filename, argv, envp, cwd,
startInfo.RedirectStandardInput, startInfo.RedirectStandardOutput, startInfo.RedirectStandardError,
setCredentials, userId, groupId, groups,
out stdinFd, out stdoutFd, out stderrFd, usesTerminal);
}
}
else
{
filename = ResolvePath(startInfo.FileName);
argv = ParseArgv(startInfo);
if (Directory.Exists(filename))
{
throw new Win32Exception(SR.DirectoryNotValidAsInput);
}
ForkAndExecProcess(filename, argv, envp, cwd,
startInfo.RedirectStandardInput, startInfo.RedirectStandardOutput, startInfo.RedirectStandardError,
setCredentials, userId, groupId, groups,
out stdinFd, out stdoutFd, out stderrFd, usesTerminal);
}
// Configure the parent's ends of the redirection streams.
// We use UTF8 encoding without BOM by-default(instead of Console encoding as on Windows)
// as there is no good way to get this information from the native layer
// and we do not want to take dependency on Console contract.
if (startInfo.RedirectStandardInput)
{
Debug.Assert(stdinFd >= 0);
_standardInput = new StreamWriter(OpenStream(stdinFd, FileAccess.Write),
startInfo.StandardInputEncoding ?? s_utf8NoBom, StreamBufferSize)
{ AutoFlush = true };
}
if (startInfo.RedirectStandardOutput)
{
Debug.Assert(stdoutFd >= 0);
_standardOutput = new StreamReader(OpenStream(stdoutFd, FileAccess.Read),
startInfo.StandardOutputEncoding ?? s_utf8NoBom, true, StreamBufferSize);
}
if (startInfo.RedirectStandardError)
{
Debug.Assert(stderrFd >= 0);
_standardError = new StreamReader(OpenStream(stderrFd, FileAccess.Read),
startInfo.StandardErrorEncoding ?? s_utf8NoBom, true, StreamBufferSize);
}
return true;
}
private bool ForkAndExecProcess(
string filename, string[] argv, string[] envp, string cwd,
bool redirectStdin, bool redirectStdout, bool redirectStderr,
bool setCredentials, uint userId, uint groupId, uint[] groups,
out int stdinFd, out int stdoutFd, out int stderrFd,
bool usesTerminal, bool throwOnNoExec = true)
{
if (string.IsNullOrEmpty(filename))
{
throw new Win32Exception(Interop.Error.ENOENT.Info().RawErrno);
}
// Lock to avoid races with OnSigChild
// By using a ReaderWriterLock we allow multiple processes to start concurrently.
s_processStartLock.EnterReadLock();
try
{
if (usesTerminal)
{
ConfigureTerminalForChildProcesses(1);
}
int childPid;
// Invoke the shim fork/execve routine. It will create pipes for all requested
// redirects, fork a child process, map the pipe ends onto the appropriate stdin/stdout/stderr
// descriptors, and execve to execute the requested process. The shim implementation
// is used to fork/execve as executing managed code in a forked process is not safe (only
// the calling thread will transfer, thread IDs aren't stable across the fork, etc.)
int errno = Interop.Sys.ForkAndExecProcess(
filename, argv, envp, cwd,
redirectStdin, redirectStdout, redirectStderr,
setCredentials, userId, groupId, groups,
out childPid,
out stdinFd, out stdoutFd, out stderrFd);
if (errno == 0)
{
// Ensure we'll reap this process.
// note: SetProcessId will set this if we don't set it first.
_waitStateHolder = new ProcessWaitState.Holder(childPid, isNewChild: true, usesTerminal);
// Store the child's information into this Process object.
Debug.Assert(childPid >= 0);
SetProcessId(childPid);
SetProcessHandle(new SafeProcessHandle(_processId, GetSafeWaitHandle()));
return true;
}
else
{
if (!throwOnNoExec &&
new Interop.ErrorInfo(errno).Error == Interop.Error.ENOEXEC)
{
return false;
}
throw new Win32Exception(errno);
}
}
finally
{
s_processStartLock.ExitReadLock();
if (_waitStateHolder == null && usesTerminal)
{
// We failed to launch a child that could use the terminal.
s_processStartLock.EnterWriteLock();
ConfigureTerminalForChildProcesses(-1);
s_processStartLock.ExitWriteLock();
}
}
}
// -----------------------------
// ---- PAL layer ends here ----
// -----------------------------
/// <summary>Finalizable holder for the underlying shared wait state object.</summary>
private ProcessWaitState.Holder _waitStateHolder;
/// <summary>Size to use for redirect streams and stream readers/writers.</summary>
private const int StreamBufferSize = 4096;
/// <summary>Converts the filename and arguments information from a ProcessStartInfo into an argv array.</summary>
/// <param name="psi">The ProcessStartInfo.</param>
/// <param name="resolvedExe">Resolved executable to open ProcessStartInfo.FileName</param>
/// <param name="ignoreArguments">Don't pass ProcessStartInfo.Arguments</param>
/// <returns>The argv array.</returns>
private static string[] ParseArgv(ProcessStartInfo psi, string resolvedExe = null, bool ignoreArguments = false)
{
if (string.IsNullOrEmpty(resolvedExe) &&
(ignoreArguments || (string.IsNullOrEmpty(psi.Arguments) && psi.ArgumentList.Count == 0)))
{
return new string[] { psi.FileName };
}
var argvList = new List<string>();
if (!string.IsNullOrEmpty(resolvedExe))
{
argvList.Add(resolvedExe);
if (resolvedExe.Contains("kfmclient"))
{
argvList.Add("openURL"); // kfmclient needs OpenURL
}
}
argvList.Add(psi.FileName);
if (!ignoreArguments)
{
if (!string.IsNullOrEmpty(psi.Arguments))
{
ParseArgumentsIntoList(psi.Arguments, argvList);
}
else
{
argvList.AddRange(psi.ArgumentList);
}
}
return argvList.ToArray();
}
/// <summary>Converts the environment variables information from a ProcessStartInfo into an envp array.</summary>
/// <param name="psi">The ProcessStartInfo.</param>
/// <returns>The envp array.</returns>
private static string[] CreateEnvp(ProcessStartInfo psi)
{
var envp = new string[psi.Environment.Count];
int index = 0;
foreach (var pair in psi.Environment)
{
envp[index++] = pair.Key + "=" + pair.Value;
}
return envp;
}
private static string ResolveExecutableForShellExecute(string filename, string workingDirectory)
{
// Determine if filename points to an executable file.
// filename may be an absolute path, a relative path or a uri.
string resolvedFilename = null;
// filename is an absolute path
if (Path.IsPathRooted(filename))
{
if (File.Exists(filename))
{
resolvedFilename = filename;
}
}
// filename is a uri
else if (Uri.TryCreate(filename, UriKind.Absolute, out Uri uri))
{
if (uri.IsFile && uri.Host == "" && File.Exists(uri.LocalPath))
{
resolvedFilename = uri.LocalPath;
}
}
// filename is relative
else
{
// The WorkingDirectory property specifies the location of the executable.
// If WorkingDirectory is an empty string, the current directory is understood to contain the executable.
workingDirectory = workingDirectory != null ? Path.GetFullPath(workingDirectory) :
Directory.GetCurrentDirectory();
string filenameInWorkingDirectory = Path.Combine(workingDirectory, filename);
// filename is a relative path in the working directory
if (File.Exists(filenameInWorkingDirectory))
{
resolvedFilename = filenameInWorkingDirectory;
}
// find filename on PATH
else
{
resolvedFilename = FindProgramInPath(filename);
}
}
if (resolvedFilename == null)
{
return null;
}
if (Interop.Sys.Access(resolvedFilename, Interop.Sys.AccessMode.X_OK) == 0)
{
return resolvedFilename;
}
else
{
return null;
}
}
/// <summary>Resolves a path to the filename passed to ProcessStartInfo. </summary>
/// <param name="filename">The filename.</param>
/// <returns>The resolved path. It can return null in case of URLs.</returns>
private static string ResolvePath(string filename)
{
// Follow the same resolution that Windows uses with CreateProcess:
// 1. First try the exact path provided
// 2. Then try the file relative to the executable directory
// 3. Then try the file relative to the current directory
// 4. then try the file in each of the directories specified in PATH
// Windows does additional Windows-specific steps between 3 and 4,
// and we ignore those here.
// If the filename is a complete path, use it, regardless of whether it exists.
if (Path.IsPathRooted(filename))
{
// In this case, it doesn't matter whether the file exists or not;
// it's what the caller asked for, so it's what they'll get
return filename;
}
// Then check the executable's directory
string path = GetExePath();
if (path != null)
{
try
{
path = Path.Combine(Path.GetDirectoryName(path), filename);
if (File.Exists(path))
{
return path;
}
}
catch (ArgumentException) { } // ignore any errors in data that may come from the exe path
}
// Then check the current directory
path = Path.Combine(Directory.GetCurrentDirectory(), filename);
if (File.Exists(path))
{
return path;
}
// Then check each directory listed in the PATH environment variables
return FindProgramInPath(filename);
}
/// <summary>
/// Gets the path to the program
/// </summary>
/// <param name="program"></param>
/// <returns></returns>
private static string FindProgramInPath(string program)
{
string path;
string pathEnvVar = Environment.GetEnvironmentVariable("PATH");
if (pathEnvVar != null)
{
var pathParser = new StringParser(pathEnvVar, ':', skipEmpty: true);
while (pathParser.MoveNext())
{
string subPath = pathParser.ExtractCurrent();
path = Path.Combine(subPath, program);
if (File.Exists(path))
{
return path;
}
}
}
return null;
}
/// <summary>Convert a number of "jiffies", or ticks, to a TimeSpan.</summary>
/// <param name="ticks">The number of ticks.</param>
/// <returns>The equivalent TimeSpan.</returns>
internal static TimeSpan TicksToTimeSpan(double ticks)
{
// Look up the number of ticks per second in the system's configuration,
// then use that to convert to a TimeSpan
long ticksPerSecond = Interop.Sys.SysConf(Interop.Sys.SysConfName._SC_CLK_TCK);
if (ticksPerSecond <= 0)
{
throw new Win32Exception();
}
return TimeSpan.FromSeconds(ticks / (double)ticksPerSecond);
}
/// <summary>Opens a stream around the specified file descriptor and with the specified access.</summary>
/// <param name="fd">The file descriptor.</param>
/// <param name="access">The access mode.</param>
/// <returns>The opened stream.</returns>
private static FileStream OpenStream(int fd, FileAccess access)
{
Debug.Assert(fd >= 0);
return new FileStream(
new SafeFileHandle((IntPtr)fd, ownsHandle: true),
access, StreamBufferSize, isAsync: false);
}
/// <summary>Parses a command-line argument string into a list of arguments.</summary>
/// <param name="arguments">The argument string.</param>
/// <param name="results">The list into which the component arguments should be stored.</param>
/// <remarks>
/// This follows the rules outlined in "Parsing C++ Command-Line Arguments" at
/// https://msdn.microsoft.com/en-us/library/17w5ykft.aspx.
/// </remarks>
private static void ParseArgumentsIntoList(string arguments, List<string> results)
{
// Iterate through all of the characters in the argument string.
for (int i = 0; i < arguments.Length; i++)
{
while (i < arguments.Length && (arguments[i] == ' ' || arguments[i] == '\t'))
i++;
if (i == arguments.Length)
break;
results.Add(GetNextArgument(arguments, ref i));
}
}
private static string GetNextArgument(string arguments, ref int i)
{
var currentArgument = StringBuilderCache.Acquire();
bool inQuotes = false;
while (i < arguments.Length)
{
// From the current position, iterate through contiguous backslashes.
int backslashCount = 0;
while (i < arguments.Length && arguments[i] == '\\')
{
i++;
backslashCount++;
}
if (backslashCount > 0)
{
if (i >= arguments.Length || arguments[i] != '"')
{
// Backslashes not followed by a double quote:
// they should all be treated as literal backslashes.
currentArgument.Append('\\', backslashCount);
}
else
{
// Backslashes followed by a double quote:
// - Output a literal slash for each complete pair of slashes
// - If one remains, use it to make the subsequent quote a literal.
currentArgument.Append('\\', backslashCount / 2);
if (backslashCount % 2 != 0)
{
currentArgument.Append('"');
i++;
}
}
continue;
}
char c = arguments[i];
// If this is a double quote, track whether we're inside of quotes or not.
// Anything within quotes will be treated as a single argument, even if
// it contains spaces.
if (c == '"')
{
if (inQuotes && i < arguments.Length - 1 && arguments[i + 1] == '"')
{
// Two consecutive double quotes inside an inQuotes region should result in a literal double quote
// (the parser is left in the inQuotes region).
// This behavior is not part of the spec of code:ParseArgumentsIntoList, but is compatible with CRT
// and .NET Framework.
currentArgument.Append('"');
i++;
}
else
{
inQuotes = !inQuotes;
}
i++;
continue;
}
// If this is a space/tab and we're not in quotes, we're done with the current
// argument, it should be added to the results and then reset for the next one.
if ((c == ' ' || c == '\t') && !inQuotes)
{
break;
}
// Nothing special; add the character to the current argument.
currentArgument.Append(c);
i++;
}
return StringBuilderCache.GetStringAndRelease(currentArgument);
}
/// <summary>Gets the wait state for this Process object.</summary>
private ProcessWaitState GetWaitState()
{
if (_waitStateHolder == null)
{
EnsureState(State.HaveId);
_waitStateHolder = new ProcessWaitState.Holder(_processId);
}
return _waitStateHolder._state;
}
private SafeWaitHandle GetSafeWaitHandle()
=> GetWaitState().EnsureExitedEvent().GetSafeWaitHandle();
private static (uint userId, uint groupId, uint[] groups) GetUserAndGroupIds(ProcessStartInfo startInfo)
{
Debug.Assert(!string.IsNullOrEmpty(startInfo.UserName));
(uint? userId, uint? groupId) = GetUserAndGroupIds(startInfo.UserName);
Debug.Assert(userId.HasValue == groupId.HasValue, "userId and groupId both need to have values, or both need to be null.");
if (!userId.HasValue)
{
throw new Win32Exception(SR.Format(SR.UserDoesNotExist, startInfo.UserName));
}
uint[] groups = Interop.Sys.GetGroupList(startInfo.UserName, groupId.Value);
if (groups == null)
{
throw new Win32Exception(SR.Format(SR.UserGroupsCannotBeDetermined, startInfo.UserName));
}
return (userId.Value, groupId.Value, groups);
}
private unsafe static (uint? userId, uint? groupId) GetUserAndGroupIds(string userName)
{
Interop.Sys.Passwd? passwd;
// First try with a buffer that should suffice for 99% of cases.
// Note: on CentOS/RedHat 7.1 systems, getpwnam_r returns 'user not found' if the buffer is too small
// see https://bugs.centos.org/view.php?id=7324
const int BufLen = Interop.Sys.Passwd.InitialBufferSize;
byte* stackBuf = stackalloc byte[BufLen];
if (TryGetPasswd(userName, stackBuf, BufLen, out passwd))
{
if (passwd == null)
{
return (null, null);
}
return (passwd.Value.UserId, passwd.Value.GroupId);
}
// Fallback to heap allocations if necessary, growing the buffer until
// we succeed. TryGetPasswd will throw if there's an unexpected error.
int lastBufLen = BufLen;
while (true)
{
lastBufLen *= 2;
byte[] heapBuf = new byte[lastBufLen];
fixed (byte* buf = &heapBuf[0])
{
if (TryGetPasswd(userName, buf, heapBuf.Length, out passwd))
{
if (passwd == null)
{
return (null, null);
}
return (passwd.Value.UserId, passwd.Value.GroupId);
}
}
}
}
private static unsafe bool TryGetPasswd(string name, byte* buf, int bufLen, out Interop.Sys.Passwd? passwd)
{
// Call getpwnam_r to get the passwd struct
Interop.Sys.Passwd tempPasswd;
int error = Interop.Sys.GetPwNamR(name, out tempPasswd, buf, bufLen);
// If the call succeeds, give back the passwd retrieved
if (error == 0)
{
passwd = tempPasswd;
return true;
}
// If the current user's entry could not be found, give back null,
// but still return true as false indicates the buffer was too small.
if (error == -1)
{
passwd = null;
return true;
}
var errorInfo = new Interop.ErrorInfo(error);
// If the call failed because the buffer was too small, return false to
// indicate the caller should try again with a larger buffer.
if (errorInfo.Error == Interop.Error.ERANGE)
{
passwd = null;
return false;
}
// Otherwise, fail.
throw new Win32Exception(errorInfo.RawErrno, errorInfo.GetErrorMessage());
}
public IntPtr MainWindowHandle => IntPtr.Zero;
private bool CloseMainWindowCore() => false;
public string MainWindowTitle => string.Empty;
public bool Responding => true;
private bool WaitForInputIdleCore(int milliseconds) => throw new InvalidOperationException(SR.InputIdleUnkownError);
private static void EnsureInitialized()
{
if (s_initialized)
{
return;
}
lock (s_initializedGate)
{
if (!s_initialized)
{
if (!Interop.Sys.InitializeTerminalAndSignalHandling())
{
throw new Win32Exception();
}
// Register our callback.
Interop.Sys.RegisterForSigChld(s_sigChildHandler);
s_initialized = true;
}
}
}
private static void OnSigChild(bool reapAll)
{
// Lock to avoid races with Process.Start
s_processStartLock.EnterWriteLock();
try
{
ProcessWaitState.CheckChildren(reapAll);
}
finally
{
s_processStartLock.ExitWriteLock();
}
}
/// <summary>
/// This method is called when the number of child processes that are using the terminal changes.
/// It updates the terminal configuration if necessary.
/// </summary>
internal static void ConfigureTerminalForChildProcesses(int increment)
{
Debug.Assert(increment != 0);
int childrenUsingTerminalRemaining = Interlocked.Add(ref s_childrenUsingTerminalCount, increment);
if (increment > 0)
{
Debug.Assert(s_processStartLock.IsReadLockHeld);
// At least one child is using the terminal.
Interop.Sys.ConfigureTerminalForChildProcess(childUsesTerminal: true);
}
else
{
Debug.Assert(s_processStartLock.IsWriteLockHeld);
if (childrenUsingTerminalRemaining == 0)
{
// No more children are using the terminal.
Interop.Sys.ConfigureTerminalForChildProcess(childUsesTerminal: false);
}
}
}
}
}
| |
// Copyright (c) 2015, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using System.Xml;
using Microsoft.Win32;
using WebsitePanel.Providers.SharePoint;
using WebsitePanel.Providers.Utils;
using WebsitePanel.Server.Utils;
namespace WebsitePanel.Providers.HostedSolution
{
/// <summary>
/// Provides hosted SharePoint server functionality implementation.
/// </summary>
public class HostedSharePointServer2013 : HostingServiceProviderBase, IHostedSharePointServer
{
#region Delegate
private delegate TReturn SharePointAction<TReturn>(HostedSharePointServer2013Impl impl);
#endregion
#region Fields
protected string LanguagePacksPath;
protected string Wss3Registry32Key;
protected string Wss3RegistryKey;
#endregion
#region Properties
public string BackupTemporaryFolder
{
get { return ProviderSettings["BackupTemporaryFolder"]; }
}
public Uri RootWebApplicationUri
{
get { return new Uri(ProviderSettings["RootWebApplicationUri"]); }
}
#endregion
#region Constructor
public HostedSharePointServer2013()
{
Wss3RegistryKey = @"SOFTWARE\Microsoft\Shared Tools\Web Server Extensions\15.0";
Wss3Registry32Key = @"SOFTWARE\Wow6432Node\Microsoft\Shared Tools\Web Server Extensions\15.0";
LanguagePacksPath = @"%commonprogramfiles%\microsoft shared\Web Server Extensions\15\HCCab\";
}
#endregion
#region Methods
/// <summary>Gets list of supported languages by this installation of SharePoint.</summary>
/// <returns>List of supported languages</returns>
public int[] GetSupportedLanguages()
{
var impl = new HostedSharePointServer2013Impl();
return impl.GetSupportedLanguages(RootWebApplicationUri);
}
/// <summary>Gets list of SharePoint collections within root web application.</summary>
/// <returns>List of SharePoint collections within root web application.</returns>
public SharePointSiteCollection[] GetSiteCollections()
{
return ExecuteSharePointAction(impl => impl.GetSiteCollections(RootWebApplicationUri));
}
/// <summary>Gets SharePoint collection within root web application with given name.</summary>
/// <param name="url">Url that uniquely identifies site collection to be loaded.</param>
/// <returns>SharePoint collection within root web application with given name.</returns>
public SharePointSiteCollection GetSiteCollection(string url)
{
return ExecuteSharePointAction(impl => impl.GetSiteCollection(RootWebApplicationUri, url));
}
/// <summary>Creates site collection within predefined root web application.</summary>
/// <param name="siteCollection">Information about site coolection to be created.</param>
public void CreateSiteCollection(SharePointSiteCollection siteCollection)
{
ExecuteSharePointAction<object>(delegate(HostedSharePointServer2013Impl impl)
{
impl.CreateSiteCollection(RootWebApplicationUri, siteCollection);
return null;
});
}
/// <summary>Deletes site collection under given url.</summary>
/// <param name="siteCollection">The site collection to be deleted.</param>
public void DeleteSiteCollection(SharePointSiteCollection siteCollection)
{
ExecuteSharePointAction<object>(delegate(HostedSharePointServer2013Impl impl)
{
impl.DeleteSiteCollection(RootWebApplicationUri, siteCollection);
return null;
});
}
/// <summary>Backups site collection under give url.</summary>
/// <param name="url">Url that uniquely identifies site collection to be deleted.</param>
/// <param name="filename">Resulting backup file name.</param>
/// <param name="zip">A value which shows whether created backup must be archived.</param>
/// <returns>Created backup full path.</returns>
public string BackupSiteCollection(string url, string filename, bool zip)
{
return ExecuteSharePointAction(impl => impl.BackupSiteCollection(RootWebApplicationUri, url, filename, zip, BackupTemporaryFolder));
}
/// <summary>Restores site collection under given url from backup.</summary>
/// <param name="siteCollection">Site collection to be restored.</param>
/// <param name="filename">Backup file name to restore from.</param>
public void RestoreSiteCollection(SharePointSiteCollection siteCollection, string filename)
{
ExecuteSharePointAction<object>(delegate(HostedSharePointServer2013Impl impl)
{
impl.RestoreSiteCollection(RootWebApplicationUri, siteCollection, filename);
return null;
});
}
/// <summary>Gets binary data chunk of specified size from specified offset.</summary>
/// <param name="path">Path to file to get bunary data chunk from.</param>
/// <param name="offset">Offset from which to start data reading.</param>
/// <param name="length">Binary data chunk length.</param>
/// <returns>Binary data chunk read from file.</returns>
public virtual byte[] GetTempFileBinaryChunk(string path, int offset, int length)
{
byte[] buffer = FileUtils.GetFileBinaryChunk(path, offset, length);
if (buffer.Length < length)
{
FileUtils.DeleteFile(path);
}
return buffer;
}
/// <summary>Appends supplied binary data chunk to file.</summary>
/// <param name="fileName">Non existent file name to append to.</param>
/// <param name="path">Full path to existent file to append to.</param>
/// <param name="chunk">Binary data chunk to append to.</param>
/// <returns>Path to file that was appended with chunk.</returns>
public virtual string AppendTempFileBinaryChunk(string fileName, string path, byte[] chunk)
{
if (path == null)
{
path = Path.Combine(Path.GetTempPath(), fileName);
if (FileUtils.FileExists(path))
{
FileUtils.DeleteFile(path);
}
}
FileUtils.AppendFileBinaryContent(path, chunk);
return path;
}
public void UpdateQuotas(string url, long maxStorage, long warningStorage)
{
ExecuteSharePointAction<object>(delegate(HostedSharePointServer2013Impl impl)
{
impl.UpdateQuotas(RootWebApplicationUri, url, maxStorage, warningStorage);
return null;
});
}
public SharePointSiteDiskSpace[] CalculateSiteCollectionsDiskSpace(string[] urls)
{
return ExecuteSharePointAction(impl => impl.CalculateSiteCollectionDiskSpace(RootWebApplicationUri, urls));
}
public long GetSiteCollectionSize(string url)
{
return ExecuteSharePointAction(impl => impl.GetSiteCollectionSize(RootWebApplicationUri, url));
}
public void SetPeoplePickerOu(string site, string ou)
{
ExecuteSharePointAction<object>(delegate(HostedSharePointServer2013Impl impl)
{
impl.SetPeoplePickerOu(site, ou);
return null;
});
}
public override bool IsInstalled()
{
return IsSharePointInstalled();
}
/// <summary>Deletes service items that represent SharePoint site collection.</summary>
/// <param name="items">Items to be deleted.</param>
public override void DeleteServiceItems(ServiceProviderItem[] items)
{
foreach (ServiceProviderItem item in items)
{
var sharePointSiteCollection = item as SharePointSiteCollection;
if (sharePointSiteCollection != null)
{
try
{
DeleteSiteCollection(sharePointSiteCollection);
}
catch (Exception ex)
{
Log.WriteError(String.Format("Error deleting '{0}' {1}", item.Name, item.GetType().Name), ex);
}
}
}
}
/// <summary>Calculates diskspace used by supplied service items.</summary>
/// <param name="items">Service items to get diskspace usage for.</param>
/// <returns>Calculated disk space usage statistics.</returns>
public override ServiceProviderItemDiskSpace[] GetServiceItemsDiskSpace(ServiceProviderItem[] items)
{
var itemsDiskspace = new List<ServiceProviderItemDiskSpace>();
foreach (ServiceProviderItem item in items)
{
if (item is SharePointSiteCollection)
{
try
{
Log.WriteStart(String.Format("Calculating '{0}' site logs size", item.Name));
SharePointSiteCollection site = GetSiteCollection(item.Name);
var diskspace = new ServiceProviderItemDiskSpace {ItemId = item.Id, DiskSpace = site.Diskspace};
itemsDiskspace.Add(diskspace);
Log.WriteEnd(String.Format("Calculating '{0}' site logs size", item.Name));
}
catch (Exception ex)
{
Log.WriteError(ex);
}
}
}
return itemsDiskspace.ToArray();
}
/// <summary>Checks whether SharePoint 2013 is installed.</summary>
/// <returns>true - if it is installed; false - otherwise.</returns>
private bool IsSharePointInstalled()
{
RegistryKey spKey = Registry.LocalMachine.OpenSubKey(Wss3RegistryKey);
RegistryKey spKey32 = Registry.LocalMachine.OpenSubKey(Wss3Registry32Key);
if (spKey == null && spKey32 == null)
{
return false;
}
var spVal = (string) spKey.GetValue("SharePoint");
return (String.Compare(spVal, "installed", true) == 0);
}
/// <summary>Executes supplied action within separate application domain.</summary>
/// <param name="action">Action to be executed.</param>
/// <returns>Any object that results from action execution or null if nothing is supposed to be returned.</returns>
/// <exception cref="ArgumentNullException">Is thrown in case supplied action is null.</exception>
private static TReturn ExecuteSharePointAction<TReturn>(SharePointAction<TReturn> action)
{
if (action == null)
{
throw new ArgumentNullException("action");
}
AppDomain domain = null;
try
{
Type type = typeof(HostedSharePointServer2013Impl);
var info = new AppDomainSetup { ApplicationBase = Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory), PrivateBinPath = GetPrivateBinPath() };
domain = AppDomain.CreateDomain("WSS30", null, info);
var impl = (HostedSharePointServer2013Impl)domain.CreateInstanceAndUnwrap(type.Assembly.FullName, type.FullName);
return action(impl);
}
finally
{
if (domain != null)
{
AppDomain.Unload(domain);
}
}
throw new ArgumentNullException("action");
}
/// <summary> Getting PrivatePath from web.config. </summary>
/// <returns> The PrivateBinPath.</returns>
private static string GetPrivateBinPath()
{
var lines = new List<string>{ "bin", "bin/debug" };
string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "web.config");
if (File.Exists(path))
{
using (var reader = new StreamReader(path))
{
string content = reader.ReadToEnd();
var pattern = new Regex(@"(?<=probing .*?privatePath\s*=\s*"")[^""]+(?="".*?>)");
Match match = pattern.Match(content);
lines.AddRange(match.Value.Split(';'));
}
}
return string.Join(Path.PathSeparator.ToString(), lines.ToArray());
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
namespace Cat
{
public class CatFxnType : CatTypeKind
{
#region fields
protected CatTypeVector mProd;
protected CatTypeVector mCons;
bool mbSideEffects;
CatFxnType mpParent;
CatTypeVarList mpFreeVars = new CatTypeVarList();
protected int mnId = gnId++;
#endregion
#region static functions
public static CatFxnType PushSomethingType = Create("( -> 'a)");
public static CatFxnType AnyFxnType = Create("('A -> 'B)");
public static CatFxnType PushAnythingType = Create("( -> 'A)");
public static CatFxnType Create(string sType)
{
if (sType.Length == 0)
return null;
Peg.Parser p = new Peg.Parser(sType);
try
{
if (!p.Parse(CatGrammar.FxnType()))
throw new Exception("no additional information");
}
catch (Exception e)
{
throw new Exception(sType + " is not a valid function type ", e);
}
Peg.PegAstNode ast = p.GetAst();
if (ast.GetNumChildren() != 1)
throw new Exception("invalid number of children in abstract syntax tree");
AstFxnType node = new AstFxnType(ast.GetChild(0));
CatFxnType ret = new CatFxnType(node);
return ret;
}
public static CatFxnType ComposeFxnTypes(CatFxnType f, CatFxnType g)
{
CatFxnType ft = CatTypeReconstructor.ComposeTypes(f, g);
return ft;
}
public static CatFxnType Unquote(CatFxnType ft)
{
if (ft == null)
return null;
if (ft.GetCons().GetKinds().Count > 0)
throw new Exception("Can't unquote a function type with a consumption size greater than zero");
if (ft.GetProd().GetKinds().Count != 1)
throw new Exception("Can't unquote a function type which does not produce a single function");
CatKind k = ft.GetProd().GetKinds()[0];
if (!(k is CatFxnType))
throw new Exception("Can't unquote a function type which does not produce a single function");
return k as CatFxnType;
}
#endregion
#region constructors
public CatFxnType(CatTypeVector cons, CatTypeVector prod, bool bSideEffects)
{
mCons = new CatTypeVector(cons);
mProd = new CatTypeVector(prod);
mbSideEffects = bSideEffects;
SetChildFxnParents();
ComputeFreeVars();
}
public CatFxnType()
{
mbSideEffects = false;
mCons = new CatTypeVector();
mProd = new CatTypeVector();
SetChildFxnParents();
ComputeFreeVars();
}
public CatFxnType(AstFxnType node)
{
mbSideEffects = node.HasSideEffects();
mCons = new CatTypeVector(node.mCons);
mProd = new CatTypeVector(node.mProd);
SetChildFxnParents();
ComputeFreeVars();
}
#endregion
#region variable functions
private CatTypeVector AddImplicitRhoVariables(CatTypeVector v)
{
CatTypeVector ret = new CatTypeVector();
foreach (CatKind k in v.GetKinds())
{
if (k is CatFxnType)
ret.Add((k as CatFxnType).AddImplicitRhoVariables());
else if (k is CatTypeVector)
ret.Add(AddImplicitRhoVariables(k as CatTypeVector));
else
ret.Add(k);
}
return ret;
}
public virtual CatFxnType AddImplicitRhoVariables()
{
CatTypeVector cons = AddImplicitRhoVariables(GetCons());
CatTypeVector prod = AddImplicitRhoVariables(GetProd());
if (!(cons.GetBottom() is CatStackVar))
{
CatStackVar rho = CatStackVar.CreateUnique();
cons.PushKindBottom(rho);
prod.PushKindBottom(rho);
}
return new CatFxnType(cons, prod, HasSideEffects());
}
public void RemoveImplicitRhoVariables()
{
// TEMP: TODO: figure out whether or not to remove this.
// RemoveImplicitRhoVariables(this);
}
/// <summary>
/// This function modifies the function
/// </summary>
public void RemoveImplicitRhoVariables(CatFxnType ft)
{
foreach (CatKind k in ft.GetChildKinds())
if (k is CatFxnType)
RemoveImplicitRhoVariables(k as CatFxnType);
if (!ft.GetCons().IsEmpty() && !ft.GetProd().IsEmpty())
{
CatKind k1 = ft.GetCons().GetBottom();
CatKind k2 = ft.GetProd().GetBottom();
// Does both consumption and production share the same
// stack variable at the bottom, if so, then we might have
// an implicit Rho variables
if (k1 is CatStackVar && k1.Equals(k2))
{
// try removing the stack variable
ft.GetCons().GetKinds().RemoveAt(0);
ft.GetProd().GetKinds().RemoveAt(0);
// is the variable used anywhere else?
// if so, then we have to restore it
// otherwise we leave it taken away
if (DoesVarExist(k1))
{
ft.GetCons().GetKinds().Insert(0, k1);
ft.GetProd().GetKinds().Insert(0, k2);
}
}
}
}
public bool DoesVarExist(CatKind k)
{
Trace.Assert(k.IsKindVar());
foreach (CatKind tmp in GetDescendantKinds())
if (tmp.Equals(k))
return true;
return false;
}
public CatTypeVarList GetAllVars()
{
CatTypeVarList ret = new CatTypeVarList();
GetAllVars(ret);
return ret;
}
private void GetAllVars(CatTypeVarList vars)
{
foreach (CatKind k in GetChildKinds())
{
if (k is CatFxnType)
{
(k as CatFxnType).GetAllVars(vars);
}
else if (k.IsKindVar())
{
vars.Add(k);
}
}
}
/* TODO: LOWPRI: remove
private CatTypeVarList GetVarsExcept(CatFxnType except)
{
CatTypeVarList ret = new CatTypeVarList();
GetVarsExcept(except, ret);
return ret;
}
private void GetVarsExcept(CatFxnType except, CatTypeVarList vars)
{
foreach (CatKind k in GetChildKinds())
{
if (k is CatFxnType)
{
CatFxnType ft = k as CatFxnType;
if (ft != except)
ft.GetVarsExcept(except, vars);
}
else
{
if (k.IsKindVar())
vars.Add(k);
}
}
}
*/
/// <summary>
/// Every kind variable has a scope in which it is free.
/// This allows us to compute whether a variable is free or bound.
/// The purpose of figuring whether a variable is free or bound, is so
/// that when we copy a function, we can make sure that any free variables
/// are given new unique names. Basically we want to make new names,
/// but we can't always do that.
/// </summary>
/// <param name="scopes"></param>
private void ComputeVarScopes(CatVarScopes scopes, Stack<CatFxnType> visited)
{
if (visited.Contains(this))
return;
foreach (CatKind k in GetChildKinds())
{
if (k.IsKindVar())
{
scopes.Add(k, this);
}
else if (k is CatFxnType)
{
CatFxnType ft = k as CatFxnType;
visited.Push(ft);
ft.ComputeVarScopes(scopes, visited);
visited.Pop();
}
}
}
private CatVarScopes ComputeVarScopes()
{
CatVarScopes scopes = new CatVarScopes();
ComputeVarScopes(scopes, new Stack<CatFxnType>());
return scopes;
}
private void ComputeFreeVars()
{
CatVarScopes scopes = ComputeVarScopes();
SetFreeVars(scopes, new Stack<CatFxnType>());
// TODO:
// Use the scopes to find out if a function type is well-formed or not.
// i.e. CheckIsWellFormed(scopes);
}
private bool IsFreeVar(CatKind k, CatVarScopes scopes)
{
return scopes.IsFreeVar(this, k);
}
private void SetFreeVars(CatVarScopes scopes, Stack<CatFxnType> visited)
{
if (visited.Contains(this))
return;
foreach (CatKind k in GetDescendantKinds())
{
// iterate over the values
if (IsFreeVar(k, scopes))
mpFreeVars.Add(k);
else if (k is CatFxnType)
{
visited.Push(this);
(k as CatFxnType).SetFreeVars(scopes, visited);
visited.Pop();
}
}
}
public bool IsFreeVar(CatKind var)
{
if (!var.IsKindVar())
return false;
return mpFreeVars.ContainsKey(var.ToString());
}
#endregion
#region production and consumption
public int GetMaxProduction()
{
int nCnt = 0;
List<CatKind> list = mProd.GetKinds();
for (int i = list.Count - 1; i >= 0; --i)
{
CatKind k = list[i];
if (k is CatStackVar)
{
if ((i == 0) && k.Equals(mCons.GetBottom()))
return nCnt;
else
return -1;
}
nCnt++;
}
return nCnt;
}
public int GetMaxConsumption()
{
int nCnt = 0;
List<CatKind> list = mCons.GetKinds();
for (int i = list.Count - 1; i >= 0; --i)
{
CatKind k = list[i];
if (k is CatStackVar)
{
if ((i == 0) && k.Equals(mProd.GetBottom()))
return nCnt;
else
return -1;
}
nCnt++;
}
return nCnt;
}
public CatTypeVector GetProd()
{
return mProd;
}
public CatTypeVector GetCons()
{
return mCons;
}
#endregion
#region string formatting
public override string ToString()
{
if (mbSideEffects)
return "(" + GetCons().ToString() + " ~> " + GetProd().ToString() + ")"; else
return "(" + GetCons().ToString() + " -> " + GetProd().ToString() + ")";
}
public override string ToIdString()
{
string ret = "";
if (mbSideEffects)
ret = "(" + GetCons().ToIdString() + " ~> " + GetProd().ToIdString() + ")"; else
ret = "(" + GetCons().ToIdString() + " -> " + GetProd().ToIdString() + ")";
ret += "_" + mnId.ToString();
return ret;
}
public static string IntToPrettyString(int n)
{
string s = "";
if (n > 26)
s += IntToPrettyString(n / 26);
char c = 'a';
c += (char)(n % 26);
s += c.ToString();
return "'" + s;
}
public static string ToPrettyString(CatTypeVector vec, Dictionary<string, string> dic)
{
string s = "";
for (int i=0; i < vec.GetKinds().Count; ++i)
{
if (i > 0) s += " ";
CatKind k = vec.GetKinds()[i];
if (k.IsKindVar())
{
if (!dic.ContainsKey(k.ToString()))
{
string sNew = IntToPrettyString(dic.Count);
if (k is CatStackVar)
sNew = sNew.ToUpper();
dic.Add(k.ToString(), sNew);
}
s += dic[k.ToString()];
}
else if (k is CatFxnType)
{
s += "(" + ToPrettyString(k as CatFxnType, dic) + ")";
}
else if (k is CatTypeVector)
{
s += ToPrettyString(k as CatFxnType, dic);
}
else
{
s += k.ToString();
}
}
return s;
}
public virtual string ToPrettyString()
{
return "(" + ToPrettyString(this, new Dictionary<string, string>()) + ")";
}
public static string ToPrettyString(CatFxnType ft, Dictionary<string, string> dic)
{
// remove rho variables
ft = ft.Clone();
ft.RemoveImplicitRhoVariables();
string s = ToPrettyString(ft.GetCons(), dic);
if (ft.HasSideEffects())
s += " ~> ";
else
s += " -> ";
s += ToPrettyString(ft.GetProd(), dic);
return s;
}
#endregion
#region comparison functions
/// <summary>
/// This is a raw equivalency check: no normalization is done.
/// To comparse function type normally you would use CompareFxnTypes,
/// which in turn calls this function.
/// </summary>
public override bool Equals(CatKind k)
{
if (!(k is CatFxnType)) return false;
CatFxnType f = k as CatFxnType;
return (GetCons().Equals(f.GetCons()) && GetProd().Equals(f.GetProd())
&& HasSideEffects() == f.HasSideEffects());
}
public override bool IsSubtypeOf(CatKind k)
{
if (k.IsAny() || k.IsDynFxn())
return IsRuntimePolymorphic();
if (k is CatTypeVar)
return true;
if (!(k is CatFxnType))
return false;
CatFxnType f = k as CatFxnType;
bool ret = GetCons().IsSubtypeOf(f.GetCons()) && GetProd().IsSubtypeOf(f.GetProd());
if (HasSideEffects())
ret = ret && f.HasSideEffects();
return ret;
}
/// <summary>
/// Compares two function types, by first normalizing so that they each have
/// names of variables that correspond to the locations in the function
/// </summary>
public static bool CompareFxnTypes(CatFxnType f, CatFxnType g)
{
CatFxnType f2 = CatVarRenamer.RenameVars(f.AddImplicitRhoVariables());
CatFxnType g2 = CatVarRenamer.RenameVars(g.AddImplicitRhoVariables());
return f2.IsSubtypeOf(g2);
}
#endregion
#region verifications
public bool IsValidChildFxn(List<string> varNames, CatFxnType ft)
{
foreach (CatKind k in ft.GetCons().GetKinds())
{
if (k.IsKindVar())
varNames.Add(k.ToString());
}
return IsValidProduction(varNames, ft.GetProd());
}
public void GetConsVarNames(List<string> varNames, CatFxnType ft)
{
foreach (CatKind k in ft.GetCons().GetKinds())
{
if (k.IsKindVar())
varNames.Add(k.ToString());
if (k is CatFxnType)
GetConsVarNames(varNames, k as CatFxnType);
}
}
public bool IsValidProduction(List<string> varNames, CatTypeVector prod)
{
foreach (CatKind k in prod.GetKinds())
if (k is CatFxnType)
GetConsVarNames(varNames, k as CatFxnType);
foreach (CatKind k in prod.GetKinds())
if (k.IsKindVar())
if (!varNames.Contains(k.ToString()))
return false;
return true;
}
public bool IsValid()
{
// TODO : rewrite this function
return true;
/*
// TODO: check that if pure, none of the child functions are impure.
if (!GetCons().IsValid())
return false;
if (!GetProd().IsValid())
return false;
List<string> varNames = new List<string>();
foreach (CatKind k in GetCons().GetDescendantKinds())
{
if (k.IsKindVar())
{
string s = k.ToString();
if (!varNames.Contains(s))
varNames.Add(s);
}
}
if (!IsValidProduction(varNames, GetProd()))
return false;
return true;
*/
}
#endregion
#region utility functions
public CatFxnType Clone()
{
return new CatFxnType(mCons, mProd, mbSideEffects);
}
public bool HasSideEffects()
{
return mbSideEffects;
}
/// <summary>
/// Returns true if this function can be converted to either "any" or a "fxn".
/// </summary>
public bool IsRuntimePolymorphic()
{
return (GetCons().GetKinds().Count == 1) && (GetProd().GetKinds().Count == 1);
}
#endregion
#region parent / child functions
public CatFxnType GetParent()
{
return mpParent;
}
public CatFxnType GetAncestor()
{
if (mpParent == null)
return this;
return mpParent.GetAncestor();
}
public bool DescendentOf(CatFxnType ft)
{
if (this == ft)
return true;
if (mpParent == null)
return false;
return mpParent.DescendentOf(ft);
}
public void SetParent(CatFxnType parent)
{
mpParent = parent;
}
private void SetChildFxnParents()
{
foreach (CatKind k in GetChildKinds())
{
if (k is CatFxnType)
{
CatFxnType ft = k as CatFxnType;
ft.SetChildFxnParents();
ft.SetParent(this);
}
}
}
public override IEnumerable<CatKind> GetChildKinds()
{
foreach (CatKind k in mCons.GetChildKinds())
yield return k;
foreach (CatKind k in mProd.GetChildKinds())
yield return k;
}
public override IEnumerable<CatKind> GetDescendantKinds()
{
foreach (CatKind k in mCons.GetDescendantKinds())
yield return k;
foreach (CatKind k in mProd.GetDescendantKinds())
yield return k;
}
#endregion
}
public class CatQuotedType : CatFxnType
{
public CatQuotedType(CatKind k)
{
GetProd().Add(k);
}
}
public class CatRecursiveType : CatKind
{
public CatRecursiveType()
{
}
public override string ToString()
{
return "self";
}
public override bool Equals(CatKind k)
{
return k is CatRecursiveType;
}
public override IEnumerable<CatKind> GetChildKinds()
{
return new List<CatKind>();
}
public override IEnumerable<CatKind> GetDescendantKinds()
{
return new List<CatKind>();
}
}
}
| |
//
// Copyright (c) 2008-2011, Kenneth Bell
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
namespace DiscUtils.Ntfs
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
/// <summary>
/// Class representing the $MFT file on disk, including mirror.
/// </summary>
/// <remarks>This class only understands basic record structure, and is
/// ignorant of files that span multiple records. This class should only
/// be used by the NtfsFileSystem and File classes.</remarks>
internal class MasterFileTable : IDiagnosticTraceable, IDisposable
{
/// <summary>
/// MFT index of the MFT file itself.
/// </summary>
public const long MftIndex = 0;
/// <summary>
/// MFT index of the MFT Mirror file.
/// </summary>
public const long MftMirrorIndex = 1;
/// <summary>
/// MFT Index of the Log file.
/// </summary>
public const long LogFileIndex = 2;
/// <summary>
/// MFT Index of the Volume file.
/// </summary>
public const long VolumeIndex = 3;
/// <summary>
/// MFT Index of the Attribute Definition file.
/// </summary>
public const long AttrDefIndex = 4;
/// <summary>
/// MFT Index of the Root Directory.
/// </summary>
public const long RootDirIndex = 5;
/// <summary>
/// MFT Index of the Bitmap file.
/// </summary>
public const long BitmapIndex = 6;
/// <summary>
/// MFT Index of the Boot sector(s).
/// </summary>
public const long BootIndex = 7;
/// <summary>
/// MFT Index of the Bad Bluster file.
/// </summary>
public const long BadClusIndex = 8;
/// <summary>
/// MFT Index of the Security Descriptor file.
/// </summary>
public const long SecureIndex = 9;
/// <summary>
/// MFT Index of the Uppercase mapping file.
/// </summary>
public const long UpCaseIndex = 10;
/// <summary>
/// MFT Index of the Optional Extensions directory.
/// </summary>
public const long ExtendIndex = 11;
/// <summary>
/// First MFT Index available for 'normal' files.
/// </summary>
private const uint FirstAvailableMftIndex = 24;
private File _self;
private Bitmap _bitmap;
private Stream _recordStream;
private ObjectCache<long, FileRecord> _recordCache;
private int _recordLength;
private int _bytesPerSector;
public MasterFileTable(INtfsContext context)
{
BiosParameterBlock bpb = context.BiosParameterBlock;
_recordCache = new ObjectCache<long, FileRecord>();
_recordLength = bpb.MftRecordSize;
_bytesPerSector = bpb.BytesPerSector;
// Temporary record stream - until we've bootstrapped the MFT properly
_recordStream = new SubStream(context.RawStream, bpb.MftCluster * bpb.SectorsPerCluster * bpb.BytesPerSector, 24 * _recordLength);
}
public int RecordSize
{
get { return _recordLength; }
}
/// <summary>
/// Gets the MFT records directly from the MFT stream - bypassing the record cache.
/// </summary>
public IEnumerable<FileRecord> Records
{
get
{
using (Stream mftStream = _self.OpenStream(AttributeType.Data, null, FileAccess.Read))
{
uint index = 0;
while (mftStream.Position < mftStream.Length)
{
byte[] recordData = Utilities.ReadFully(mftStream, _recordLength);
if (Utilities.BytesToString(recordData, 0, 4) != "FILE")
{
continue;
}
FileRecord record = new FileRecord(_bytesPerSector);
record.FromBytes(recordData, 0);
record.LoadedIndex = index;
yield return record;
index++;
}
}
}
}
public void Dispose()
{
if (_recordStream != null)
{
_recordStream.Dispose();
_recordStream = null;
}
GC.SuppressFinalize(this);
}
public FileRecord GetBootstrapRecord()
{
_recordStream.Position = 0;
byte[] mftSelfRecordData = Utilities.ReadFully(_recordStream, _recordLength);
FileRecord mftSelfRecord = new FileRecord(_bytesPerSector);
mftSelfRecord.FromBytes(mftSelfRecordData, 0);
_recordCache[MftIndex] = mftSelfRecord;
return mftSelfRecord;
}
public void Initialize(File file)
{
_self = file;
if (_recordStream != null)
{
_recordStream.Dispose();
}
NtfsStream bitmapStream = _self.GetStream(AttributeType.Bitmap, null);
_bitmap = new Bitmap(bitmapStream.Open(FileAccess.ReadWrite), long.MaxValue);
NtfsStream recordsStream = _self.GetStream(AttributeType.Data, null);
_recordStream = recordsStream.Open(FileAccess.ReadWrite);
}
public File InitializeNew(INtfsContext context, long firstBitmapCluster, ulong numBitmapClusters, long firstRecordsCluster, ulong numRecordsClusters)
{
BiosParameterBlock bpb = context.BiosParameterBlock;
FileRecord fileRec = new FileRecord(bpb.BytesPerSector, bpb.MftRecordSize, (uint)MftIndex);
fileRec.Flags = FileRecordFlags.InUse;
fileRec.SequenceNumber = 1;
_recordCache[MftIndex] = fileRec;
_self = new File(context, fileRec);
StandardInformation.InitializeNewFile(_self, FileAttributeFlags.Hidden | FileAttributeFlags.System);
NtfsStream recordsStream = _self.CreateStream(AttributeType.Data, null, firstRecordsCluster, numRecordsClusters, (uint)bpb.BytesPerCluster);
_recordStream = recordsStream.Open(FileAccess.ReadWrite);
Wipe(_recordStream);
NtfsStream bitmapStream = _self.CreateStream(AttributeType.Bitmap, null, firstBitmapCluster, numBitmapClusters, (uint)bpb.BytesPerCluster);
using (Stream s = bitmapStream.Open(FileAccess.ReadWrite))
{
Wipe(s);
s.SetLength(8);
_bitmap = new Bitmap(s, long.MaxValue);
}
_recordLength = context.BiosParameterBlock.MftRecordSize;
_bytesPerSector = context.BiosParameterBlock.BytesPerSector;
_bitmap.MarkPresentRange(0, 1);
// Write the MFT's own record to itself
byte[] buffer = new byte[_recordLength];
fileRec.ToBytes(buffer, 0);
_recordStream.Position = 0;
_recordStream.Write(buffer, 0, _recordLength);
_recordStream.Flush();
return _self;
}
public FileRecord AllocateRecord(FileRecordFlags flags, bool isMft)
{
long index;
if (isMft)
{
// Have to take a lot of care extending the MFT itself, to ensure we never end up unable to
// bootstrap the file system via the MFT itself - hence why special records are reserved
// for MFT's own MFT record overflow.
for (int i = 15; i > 11; --i)
{
FileRecord r = GetRecord(i, false);
if (r.BaseFile.SequenceNumber == 0)
{
r.Reset();
r.Flags |= FileRecordFlags.InUse;
WriteRecord(r);
return r;
}
}
throw new IOException("MFT too fragmented - unable to allocate MFT overflow record");
}
else
{
index = _bitmap.AllocateFirstAvailable(FirstAvailableMftIndex);
}
if (index * _recordLength >= _recordStream.Length)
{
// Note: 64 is significant, since bitmap extends by 8 bytes (=64 bits) at a time.
long newEndIndex = Utilities.RoundUp(index + 1, 64);
_recordStream.SetLength(newEndIndex * _recordLength);
for (long i = index; i < newEndIndex; ++i)
{
FileRecord record = new FileRecord(_bytesPerSector, _recordLength, (uint)i);
WriteRecord(record);
}
}
FileRecord newRecord = GetRecord(index, true);
newRecord.ReInitialize(_bytesPerSector, _recordLength, (uint)index);
_recordCache[index] = newRecord;
newRecord.Flags = FileRecordFlags.InUse | flags;
WriteRecord(newRecord);
_self.UpdateRecordInMft();
return newRecord;
}
public FileRecord AllocateRecord(long index, FileRecordFlags flags)
{
_bitmap.MarkPresent(index);
FileRecord newRecord = new FileRecord(_bytesPerSector, _recordLength, (uint)index);
_recordCache[index] = newRecord;
newRecord.Flags = FileRecordFlags.InUse | flags;
WriteRecord(newRecord);
_self.UpdateRecordInMft();
return newRecord;
}
public void RemoveRecord(FileRecordReference fileRef)
{
FileRecord record = GetRecord(fileRef.MftIndex, false);
record.Reset();
WriteRecord(record);
_recordCache.Remove(fileRef.MftIndex);
_bitmap.MarkAbsent(fileRef.MftIndex);
_self.UpdateRecordInMft();
}
public FileRecord GetRecord(FileRecordReference fileReference)
{
FileRecord result = GetRecord(fileReference.MftIndex, false);
if (result != null)
{
if (fileReference.SequenceNumber != 0 && result.SequenceNumber != 0)
{
if (fileReference.SequenceNumber != result.SequenceNumber)
{
throw new IOException("Attempt to get an MFT record with an old reference");
}
}
}
return result;
}
public FileRecord GetRecord(long index, bool ignoreMagic)
{
return GetRecord(index, ignoreMagic, false);
}
public FileRecord GetRecord(long index, bool ignoreMagic, bool ignoreBitmap)
{
if (ignoreBitmap || _bitmap == null || _bitmap.IsPresent(index))
{
FileRecord result = _recordCache[index];
if (result != null)
{
return result;
}
if ((index + 1) * _recordLength <= _recordStream.Length)
{
_recordStream.Position = index * _recordLength;
byte[] recordBuffer = Utilities.ReadFully(_recordStream, _recordLength);
result = new FileRecord(_bytesPerSector);
result.FromBytes(recordBuffer, 0, ignoreMagic);
result.LoadedIndex = (uint)index;
}
else
{
result = new FileRecord(_bytesPerSector, _recordLength, (uint)index);
}
_recordCache[index] = result;
return result;
}
return null;
}
public void WriteRecord(FileRecord record)
{
int recordSize = record.Size;
if (recordSize > _recordLength)
{
throw new IOException("Attempting to write over-sized MFT record");
}
byte[] buffer = new byte[_recordLength];
record.ToBytes(buffer, 0);
_recordStream.Position = record.MasterFileTableIndex * (long)_recordLength;
_recordStream.Write(buffer, 0, _recordLength);
_recordStream.Flush();
// We may have modified our own meta-data by extending the data stream, so
// make sure our records are up-to-date.
if (_self.MftRecordIsDirty)
{
DirectoryEntry dirEntry = _self.DirectoryEntry;
if (dirEntry != null)
{
dirEntry.UpdateFrom(_self);
}
_self.UpdateRecordInMft();
}
// Need to update Mirror. OpenRaw is OK because this is short duration, and we don't
// extend or otherwise modify any meta-data, just the content of the Data stream.
if (record.MasterFileTableIndex < 4 && _self.Context.GetFileByIndex != null)
{
File mftMirror = _self.Context.GetFileByIndex(MftMirrorIndex);
if (mftMirror != null)
{
using (Stream s = mftMirror.OpenStream(AttributeType.Data, null, FileAccess.ReadWrite))
{
s.Position = record.MasterFileTableIndex * (long)_recordLength;
s.Write(buffer, 0, _recordLength);
}
}
}
}
public long GetRecordOffset(FileRecordReference fileReference)
{
return fileReference.MftIndex * _recordLength;
}
public ClusterMap GetClusterMap()
{
int totalClusters = (int)Utilities.Ceil(_self.Context.BiosParameterBlock.TotalSectors64, _self.Context.BiosParameterBlock.SectorsPerCluster);
ClusterRoles[] clusterToRole = new ClusterRoles[totalClusters];
object[] clusterToFile = new object[totalClusters];
Dictionary<object, string[]> fileToPaths = new Dictionary<object, string[]>();
for (int i = 0; i < totalClusters; ++i)
{
clusterToRole[i] = ClusterRoles.Free;
}
foreach (FileRecord fr in Records)
{
if (fr.BaseFile.Value != 0 || (fr.Flags & FileRecordFlags.InUse) == 0)
{
continue;
}
File f = new File(_self.Context, fr);
foreach (var stream in f.AllStreams)
{
string fileId;
if (stream.AttributeType == AttributeType.Data && !string.IsNullOrEmpty(stream.Name))
{
fileId = f.IndexInMft.ToString(CultureInfo.InvariantCulture) + ":" + stream.Name;
fileToPaths[fileId] = Utilities.Map(f.Names, n => n + ":" + stream.Name);
}
else
{
fileId = f.IndexInMft.ToString(CultureInfo.InvariantCulture);
fileToPaths[fileId] = f.Names.ToArray();
}
ClusterRoles roles = ClusterRoles.None;
if (f.IndexInMft < MasterFileTable.FirstAvailableMftIndex)
{
roles |= ClusterRoles.SystemFile;
if (f.IndexInMft == MasterFileTable.BootIndex)
{
roles |= ClusterRoles.BootArea;
}
}
else
{
roles |= ClusterRoles.DataFile;
}
if (stream.AttributeType != AttributeType.Data)
{
roles |= ClusterRoles.Metadata;
}
foreach (var range in stream.GetClusters())
{
for (long cluster = range.Offset; cluster < range.Offset + range.Count; ++cluster)
{
clusterToRole[cluster] = roles;
clusterToFile[cluster] = fileId;
}
}
}
}
return new ClusterMap(clusterToRole, clusterToFile, fileToPaths);
}
public void Dump(TextWriter writer, string indent)
{
writer.WriteLine(indent + "MASTER FILE TABLE");
writer.WriteLine(indent + " Record Length: " + _recordLength);
foreach (var record in Records)
{
record.Dump(writer, indent + " ");
foreach (AttributeRecord attr in record.Attributes)
{
attr.Dump(writer, indent + " ");
}
}
}
private static void Wipe(Stream s)
{
s.Position = 0;
byte[] buffer = new byte[64 * Sizes.OneKiB];
int numWiped = 0;
while (numWiped < s.Length)
{
int toWrite = (int)Math.Min(buffer.Length, s.Length - s.Position);
s.Write(buffer, 0, toWrite);
numWiped += toWrite;
}
}
}
}
| |
using System;
using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;
#if WINDOWS_PHONE_APP||WINDOWS_APP||NETFX_CORE
using Windows.Web.Http;
using Windows.Web.Http.Filters;
#else
using System.Net;
using System.Net.Http;
using System.Net.Cache;
#endif
namespace Kazyx.ImageStream
{
public class StreamProcessor
{
private const int DEFAULT_REQUEST_TIMEOUT = 5000;
private ConnectionState state = ConnectionState.Closed;
public ConnectionState ConnectionState
{
get { return state; }
}
public event EventHandler Closed;
protected void OnClosed(EventArgs e)
{
if (Closed != null)
{
Closed(this, e);
}
}
public delegate void JpegPacketHandler(object sender, JpegEventArgs e);
public event JpegPacketHandler JpegRetrieved;
protected void OnJpegRetrieved(JpegEventArgs e)
{
if (JpegRetrieved != null)
{
JpegRetrieved(this, e);
}
}
public delegate void FocusFramePacketHandler(object sender, FocusFrameEventArgs e);
public event FocusFramePacketHandler FocusFrameRetrieved;
protected void OnFocusFrameRetrieved(FocusFrameEventArgs e)
{
if (FocusFrameRetrieved != null)
{
FocusFrameRetrieved(this, e);
}
}
public delegate void PlaybackInfoPacketHandler(object sender, PlaybackInfoEventArgs e);
public event PlaybackInfoPacketHandler PlaybackInfoRetrieved;
protected void OnPlaybackInfoRetrieved(PlaybackInfoEventArgs e)
{
if (PlaybackInfoRetrieved != null)
{
PlaybackInfoRetrieved(this, e);
}
}
public async Task<bool> OpenConnection(Uri uri, TimeSpan? timeout = null)
{
if (uri == null)
{
throw new ArgumentNullException();
}
if (state != ConnectionState.Closed)
{
return true;
}
state = ConnectionState.TryingConnection;
#if WINDOWS_PHONE_APP||WINDOWS_APP||NETFX_CORE
var filter = new HttpBaseProtocolFilter();
filter.CacheControl.ReadBehavior = HttpCacheReadBehavior.MostRecent;
var httpClient = new HttpClient(filter);
#else
var httpClient = new HttpClient(new WebRequestHandler
{
CachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore),
});
#endif
var to = (timeout == null) ? TimeSpan.FromMilliseconds(DEFAULT_REQUEST_TIMEOUT) : timeout;
StartTimer((int)to.Value.TotalMilliseconds, httpClient);
try
{
#if WINDOWS_PHONE_APP||WINDOWS_APP||NETFX_CORE
var str = await httpClient.GetInputStreamAsync(uri);
#else
var str = await httpClient.GetStreamAsync(uri);
#endif
state = ConnectionState.Connected;
var task = Task.Factory.StartNew(() =>
{
#if WINDOWS_PHONE_APP||WINDOWS_APP||NETFX_CORE
using (var core = new StreamAnalizer(str.AsStreamForRead()))
#else
using (var core = new StreamAnalizer(str))
#endif
{
core.RunFpsDetector();
core.JpegRetrieved = (packet) => { OnJpegRetrieved(new JpegEventArgs(packet)); };
core.PlaybackInfoRetrieved = (packet) => { OnPlaybackInfoRetrieved(new PlaybackInfoEventArgs(packet)); };
core.FocusFrameRetrieved = (packet) => { OnFocusFrameRetrieved(new FocusFrameEventArgs(packet)); };
while (state == ConnectionState.Connected)
{
try
{
core.ReadNextPayload();
}
catch (Exception e)
{
Log("Caught " + e.GetType() + ": finish reading loop");
break;
}
}
}
Log("End of reading loop");
OnClosed(null);
});
return true;
}
catch (Exception)
{
return false;
}
}
private async void StartTimer(int to, HttpClient client)
{
await Task.Delay(to);
if (state == ConnectionState.TryingConnection)
{
Log("Open request timeout: aborting request.");
try
{
client.Dispose();
}
catch (ObjectDisposedException)
{
Log("Caught ObjectDisposedException");
}
}
}
/// <summary>
/// Forcefully close this connection.
/// </summary>
public void CloseConnection()
{
Log("CloseConnection");
state = ConnectionState.Closed;
}
private static void Log(string message)
{
Log("LvProcessor", message);
}
internal static void Log(string tag, string message)
{
Logger?.Invoke(string.Format("[{0}] {1}", tag, message));
}
public static Action<string> Logger { set; get; } = (s) => Debug.WriteLine(s);
}
public enum ConnectionState
{
Closed,
TryingConnection,
Connected
}
public class JpegEventArgs : EventArgs
{
private readonly JpegPacket packet;
public JpegEventArgs(JpegPacket packet)
{
this.packet = packet;
}
public JpegPacket Packet
{
get { return packet; }
}
}
public class FocusFrameEventArgs : EventArgs
{
private readonly FocusFramePacket packet;
public FocusFrameEventArgs(FocusFramePacket packet)
{
this.packet = packet;
}
public FocusFramePacket Packet
{
get { return packet; }
}
}
public class PlaybackInfoEventArgs : EventArgs
{
private readonly PlaybackInfoPacket packet;
public PlaybackInfoEventArgs(PlaybackInfoPacket packet)
{
this.packet = packet;
}
public PlaybackInfoPacket Packet
{
get { return packet; }
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics.Contracts;
namespace System.Security.Cryptography {
[System.Runtime.InteropServices.ComVisible(true)]
public abstract class SymmetricAlgorithm : IDisposable {
protected int BlockSizeValue;
protected int FeedbackSizeValue;
protected byte[] IVValue;
protected byte[] KeyValue;
protected KeySizes[] LegalBlockSizesValue;
protected KeySizes[] LegalKeySizesValue;
protected int KeySizeValue;
protected CipherMode ModeValue;
protected PaddingMode PaddingValue;
//
// protected constructors
//
protected SymmetricAlgorithm() {
// Default to cipher block chaining (CipherMode.CBC) and
// PKCS-style padding (pad n bytes with value n)
ModeValue = CipherMode.CBC;
PaddingValue = PaddingMode.PKCS7;
}
// SymmetricAlgorithm implements IDisposable
// To keep mscorlib compatibility with Orcas, CoreCLR's SymmetricAlgorithm has an explicit IDisposable
// implementation. Post-Orcas the desktop has an implicit IDispoable implementation.
#if FEATURE_CORECLR
void IDisposable.Dispose()
{
Dispose();
}
#endif // FEATURE_CORECLR
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public void Clear() {
(this as IDisposable).Dispose();
}
protected virtual void Dispose(bool disposing) {
if (disposing) {
// Note: we always want to zeroize the sensitive key material
if (KeyValue != null) {
Array.Clear(KeyValue, 0, KeyValue.Length);
KeyValue = null;
}
if (IVValue != null) {
Array.Clear(IVValue, 0, IVValue.Length);
IVValue = null;
}
}
}
//
// public properties
//
public virtual int BlockSize {
get { return BlockSizeValue; }
set {
int i;
int j;
for (i=0; i<LegalBlockSizesValue.Length; i++) {
// If a cipher has only one valid key size, MinSize == MaxSize and SkipSize will be 0
if (LegalBlockSizesValue[i].SkipSize == 0) {
if (LegalBlockSizesValue[i].MinSize == value) { // assume MinSize = MaxSize
BlockSizeValue = value;
IVValue = null;
return;
}
} else {
for (j = LegalBlockSizesValue[i].MinSize; j<=LegalBlockSizesValue[i].MaxSize;
j += LegalBlockSizesValue[i].SkipSize) {
if (j == value) {
if (BlockSizeValue != value) {
BlockSizeValue = value;
IVValue = null; // Wrong length now
}
return;
}
}
}
}
throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidBlockSize"));
}
}
public virtual int FeedbackSize {
get { return FeedbackSizeValue; }
set {
if (value <= 0 || value > BlockSizeValue || (value % 8) != 0)
throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidFeedbackSize"));
FeedbackSizeValue = value;
}
}
public virtual byte[] IV {
get {
if (IVValue == null) GenerateIV();
return (byte[]) IVValue.Clone();
}
set {
if (value == null) throw new ArgumentNullException("value");
Contract.EndContractBlock();
if (value.Length != BlockSizeValue / 8)
throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidIVSize"));
IVValue = (byte[]) value.Clone();
}
}
public virtual byte[] Key {
get {
if (KeyValue == null) GenerateKey();
return (byte[]) KeyValue.Clone();
}
set {
if (value == null) throw new ArgumentNullException("value");
Contract.EndContractBlock();
if (!ValidKeySize(value.Length * 8))
throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidKeySize"));
// must convert bytes to bits
KeyValue = (byte[]) value.Clone();
KeySizeValue = value.Length * 8;
}
}
public virtual KeySizes[] LegalBlockSizes {
get { return (KeySizes[]) LegalBlockSizesValue.Clone(); }
}
public virtual KeySizes[] LegalKeySizes {
get { return (KeySizes[]) LegalKeySizesValue.Clone(); }
}
public virtual int KeySize {
get { return KeySizeValue; }
set {
if (!ValidKeySize(value))
throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidKeySize"));
KeySizeValue = value;
KeyValue = null;
}
}
public virtual CipherMode Mode {
get { return ModeValue; }
set {
if ((value < CipherMode.CBC) || (CipherMode.CFB < value))
throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidCipherMode"));
ModeValue = value;
}
}
public virtual PaddingMode Padding {
get { return PaddingValue; }
set {
if ((value < PaddingMode.None) || (PaddingMode.ISO10126 < value))
throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidPaddingMode"));
PaddingValue = value;
}
}
//
// public methods
//
// The following method takes a bit length input and returns whether that length is a valid size
// according to LegalKeySizes
public bool ValidKeySize(int bitLength) {
KeySizes[] validSizes = this.LegalKeySizes;
int i,j;
if (validSizes == null) return false;
for (i=0; i< validSizes.Length; i++) {
if (validSizes[i].SkipSize == 0) {
if (validSizes[i].MinSize == bitLength) { // assume MinSize = MaxSize
return true;
}
} else {
for (j = validSizes[i].MinSize; j<= validSizes[i].MaxSize;
j += validSizes[i].SkipSize) {
if (j == bitLength) {
return true;
}
}
}
}
return false;
}
static public SymmetricAlgorithm Create() {
// use the crypto config system to return an instance of
// the default SymmetricAlgorithm on this machine
return Create("System.Security.Cryptography.SymmetricAlgorithm");
}
static public SymmetricAlgorithm Create(String algName) {
return (SymmetricAlgorithm) CryptoConfig.CreateFromName(algName);
}
public virtual ICryptoTransform CreateEncryptor() {
return CreateEncryptor(Key, IV);
}
public abstract ICryptoTransform CreateEncryptor(byte[] rgbKey, byte[] rgbIV);
public virtual ICryptoTransform CreateDecryptor() {
return CreateDecryptor(Key, IV);
}
public abstract ICryptoTransform CreateDecryptor(byte[] rgbKey, byte[] rgbIV);
public abstract void GenerateKey();
public abstract void GenerateIV();
}
}
| |
using System;
using System.Diagnostics;
using System.IO;
namespace Platform.VirtualFileSystem.Providers.Local
{
public class LocalFileSystem
: AbstractFileSystem
{
private FileSystemWatcher fileSystemWatcherFile = null;
private FileSystemWatcher fileSystemWatcherDirectory = null;
internal static event EventHandler<LocalFileSystemEventArgs> DirectoryDeleted;
internal static void OnDirectoryDeleted(LocalFileSystemEventArgs eventArgs)
{
if (DirectoryDeleted != null)
{
DirectoryDeleted(null, eventArgs);
}
}
public override bool SupportsSeeking
{
get
{
return true;
}
}
public override bool SupportsActivityEvents
{
get
{
return true;
}
}
private volatile int activityListenerCount;
public override event FileSystemActivityEventHandler Activity
{
add
{
lock (this)
{
if (!this.fileSystemWatcherInitialised)
{
InitializeFsw();
}
this.ActivityEvent += value;
if (this.activityListenerCount == 0)
{
try
{
this.fileSystemWatcherFile.EnableRaisingEvents = true;
this.fileSystemWatcherDirectory.EnableRaisingEvents = true;
}
catch (Exception)
{
}
}
this.activityListenerCount++;
}
}
remove
{
lock (this)
{
if (!this.fileSystemWatcherInitialised)
{
InitializeFsw();
}
this.ActivityEvent -= value;
this.activityListenerCount--;
if (this.activityListenerCount == 0)
{
this.fileSystemWatcherFile.EnableRaisingEvents = false;
this.fileSystemWatcherDirectory.EnableRaisingEvents = false;
}
}
}
}
private FileSystemActivityEventHandler ActivityEvent;
protected virtual void OnActivityEvent(FileSystemActivityEventArgs eventArgs)
{
if (ActivityEvent != null)
{
if (this.SecurityManager.CurrentContext.IsEmpty)
{
ActivityEvent(this, eventArgs);
}
else
{
INode node;
node = this.Resolve(eventArgs.Path, eventArgs.NodeType);
if (this.SecurityManager.CurrentContext.HasAccess(new AccessVerificationContext(node, FileSystemSecuredOperation.View)))
{
ActivityEvent(this, eventArgs);
}
}
}
}
public LocalFileSystem(INodeAddress rootAddress, FileSystemOptions options)
: base(rootAddress, null, options)
{
}
private volatile bool fileSystemWatcherInitialised = false;
private void InitializeFsw()
{
lock (this)
{
if (this.fileSystemWatcherInitialised)
{
return;
}
WeakReference weakref;
EventHandler<LocalFileSystemEventArgs> handler = null;
weakref = new WeakReference(this);
handler = delegate(object sender, LocalFileSystemEventArgs eventArgs)
{
LocalFileSystem _this = (LocalFileSystem)weakref.Target;
if (_this == null)
{
LocalFileSystem.DirectoryDeleted -= handler;
return;
}
string s;
s = (((LocalDirectory) eventArgs.Directory).directoryInfo.FullName);
if (this.PathsEqual(((LocalNodeAddress)this.RootAddress).AbsoluteNativePath, s, s.Length))
{
// This allows the directory to be deleted
this.fileSystemWatcherDirectory.EnableRaisingEvents = false;
this.fileSystemWatcherFile.EnableRaisingEvents = false;
// TODO: Use file system watcher from level above to allow
// events to still be fired if the directory gets recreated
}
};
LocalFileSystem.DirectoryDeleted += handler;
// We need two different watchers since we need to determine if the renamed/created/deleted events
// occured on a file or a directory.
// Changed events occur on both dirs and files regardless of the NotifyFilters setting so the
// File watcher will be responsible for handling that.
DriveInfo driveInfo;
try
{
driveInfo = new DriveInfo(((LocalNodeAddress) this.RootAddress).AbsoluteNativePath);
}
catch (ArgumentException)
{
driveInfo = null;
}
if (driveInfo == null || (driveInfo != null && driveInfo.DriveType != DriveType.Removable))
{
if (!Directory.Exists(((LocalNodeAddress)this.RootAddress).AbsoluteNativePath))
{
// TODO: Use directory above
return;
}
string path;
path = ((LocalNodeAddress) this.RootAddress).AbsoluteNativePath;
path = path.TrimEnd('/', '\\');
if (Environment.OSVersion.Platform != PlatformID.Unix)
{
if (Path.GetDirectoryName(path) != null)
{
path = Path.GetDirectoryName(path);
}
}
if (!path.EndsWith(Path.DirectorySeparatorChar.ToString()))
{
path += Path.DirectorySeparatorChar;
}
this.fileSystemWatcherFile = new FileSystemWatcher(path);
this.fileSystemWatcherFile.InternalBufferSize = 64 * 1024 /* 128K buffer */;
this.fileSystemWatcherFile.IncludeSubdirectories = true;
this.fileSystemWatcherFile.NotifyFilter =
NotifyFilters.Attributes | NotifyFilters.CreationTime | NotifyFilters.FileName /* Files only */
| NotifyFilters.LastAccess | NotifyFilters.LastWrite /*| NotifyFilters.Security | NotifyFilters.Size*/;
this.fileSystemWatcherFile.Renamed += new RenamedEventHandler(FileSystemWatcher_Renamed);
this.fileSystemWatcherFile.Changed += new FileSystemEventHandler(FileSystemWatcher_Changed);
this.fileSystemWatcherFile.Created += new FileSystemEventHandler(FileSystemWatcher_Created);
this.fileSystemWatcherFile.Deleted += new FileSystemEventHandler(FileSystemWatcher_Deleted);
this.fileSystemWatcherFile.Error += new ErrorEventHandler(FileSystemWatcher_Error);
this.fileSystemWatcherDirectory = new FileSystemWatcher(path);
this.fileSystemWatcherDirectory.InternalBufferSize = 64 * 1024;
this.fileSystemWatcherDirectory.IncludeSubdirectories = true;
this.fileSystemWatcherDirectory.NotifyFilter =
NotifyFilters.Attributes | NotifyFilters.CreationTime | NotifyFilters.DirectoryName /* Dirs only */
| NotifyFilters.LastAccess | NotifyFilters.LastWrite /*| NotifyFilters.Security | NotifyFilters.Size*/;
this.fileSystemWatcherDirectory.Filter = "*";
this.fileSystemWatcherDirectory.Renamed += new RenamedEventHandler(FileSystemWatcher_Renamed);
this.fileSystemWatcherDirectory.Created += new FileSystemEventHandler(FileSystemWatcher_Created);
this.fileSystemWatcherDirectory.Deleted += new FileSystemEventHandler(FileSystemWatcher_Deleted);
//fileSystemWatcherDirectory.Changed += new FileSystemEventHandler(FileSystemWatcher_Changed);
this.fileSystemWatcherDirectory.Error += new ErrorEventHandler(FileSystemWatcher_Error);
this.fileSystemWatcherInitialised = true;
}
}
}
private object fileSystemMonitorLock = new object();
private void FileSystemWatcher_Error(object sender, ErrorEventArgs e)
{
Trace.WriteLine("FileSystemWatcher generated an error: " + e.GetException().Message, "FileSystemWatcher");
}
public override int MaximumPathLength
{
get
{
switch (Environment.OSVersion.Platform)
{
case PlatformID.Win32NT:
return 255 - ((LocalNodeAddress)this.RootAddress).RootPart.Length - 1;
case PlatformID.Win32S:
case PlatformID.Win32Windows:
case PlatformID.WinCE:
default:
return 255 - ((LocalNodeAddress)this.RootAddress).RootPart.Length - 1;
}
}
}
private void FileSystemWatcher_Renamed(object sender, RenamedEventArgs e)
{
if (ActivityEvent != null)
{
NodeType nodeType;
if (!e.FullPath.StartsWith(((LocalNodeAddress) this.RootAddress).AbsoluteNativePath))
{
return;
}
nodeType = (sender == this.fileSystemWatcherFile) ? NodeType.File : NodeType.Directory;
OnActivityEvent(new FileSystemRenamedActivityEventArgs(FileSystemActivity.Renamed,
nodeType,
Path.GetFileName(e.OldName),
StringUriUtils.NormalizePath(
e.OldFullPath.Substring(
this.fileSystemWatcherFile.Path.Length - 1)),
Path.GetFileName(e.Name),
StringUriUtils.NormalizePath(
e.FullPath.Substring(
((LocalNodeAddress) this.RootAddress).AbsoluteNativePath.
Length - 1))));
}
}
private void FileSystemWatcher_Changed(object sender, FileSystemEventArgs e)
{
if (ActivityEvent != null)
{
NodeType nodeType;
if (!e.FullPath.StartsWith(((LocalNodeAddress) this.RootAddress).AbsoluteNativePath))
{
return;
}
/*
* There is a race here between when the watcher sees the event and when it is processed
* which may mean that a changed event meant for a dir goes to a file (or vice versa).
* There's nothing we can do about it but since the Changed event is pretty opaque
* (users will have to figure what has changed anyway) it doesn't matter too much.
*/
nodeType = GetNodeType(e.FullPath.Substring(((LocalNodeAddress) this.RootAddress).AbsoluteNativePath.Length - 1));
if (nodeType == NodeType.None)
{
OnActivityEvent(new FileSystemActivityEventArgs(FileSystemActivity.Changed, NodeType.File, e.Name,
StringUriUtils.NormalizePath(
e.FullPath.Substring(
((LocalNodeAddress) this.RootAddress).AbsoluteNativePath.Length -
1))));
OnActivityEvent(new FileSystemActivityEventArgs(FileSystemActivity.Changed, NodeType.Directory, e.Name,
StringUriUtils.NormalizePath(
e.FullPath.Substring(
((LocalNodeAddress) this.RootAddress).AbsoluteNativePath.Length -
1))));
return;
}
else
{
OnActivityEvent(new FileSystemActivityEventArgs(FileSystemActivity.Changed, nodeType, e.Name,
StringUriUtils.NormalizePath(
e.FullPath.Substring(
((LocalNodeAddress) this.RootAddress).AbsoluteNativePath.Length -
1))));
}
}
}
private void FileSystemWatcher_Created(object sender, FileSystemEventArgs e)
{
if (ActivityEvent != null)
{
NodeType nodeType;
if (!e.FullPath.StartsWith(((LocalNodeAddress) this.RootAddress).AbsoluteNativePath))
{
return;
}
nodeType = (sender == this.fileSystemWatcherFile) ? NodeType.File : NodeType.Directory;
OnActivityEvent(new FileSystemActivityEventArgs(FileSystemActivity.Created, nodeType, e.Name,
StringUriUtils.NormalizePath(
e.FullPath.Substring(
((LocalNodeAddress) this.RootAddress).AbsoluteNativePath.Length -
1))));
}
}
private void FileSystemWatcher_Deleted(object sender, FileSystemEventArgs e)
{
if (ActivityEvent != null)
{
NodeType nodeType;
if (!e.FullPath.StartsWith(((LocalNodeAddress) this.RootAddress).AbsoluteNativePath))
{
return;
}
nodeType = (sender == this.fileSystemWatcherFile) ? NodeType.File : NodeType.Directory;
OnActivityEvent(new FileSystemActivityEventArgs(FileSystemActivity.Deleted, nodeType, e.Name,
StringUriUtils.NormalizePath(
e.FullPath.Substring(
((LocalNodeAddress) this.RootAddress).AbsoluteNativePath.Length -
1))));
}
}
public override INode Resolve(INodeAddress address, NodeType nodeType)
{
if (nodeType == NodeType.Any)
{
INode node;
node = Resolve(address, NodeType.File);
if (node.Exists)
{
return node;
}
node = Resolve(address, NodeType.Directory);
if (node.Exists)
{
return node;
}
return base.Resolve(address, NodeType.File);
}
// LocalFileSystem always refreshes node before returning it
return base.Resolve(address, nodeType).Refresh();
}
/// <summary>
/// <see cref="INode.Resolve(string, NodeType, AddressScope)"/>
/// </summary>
protected override INode CreateNode(INodeAddress address, NodeType nodeType)
{
if (nodeType == NodeType.File)
{
return new LocalFile(this, (LocalNodeAddress)address);
}
else if (nodeType == NodeType.Directory)
{
return new LocalDirectory(this, (LocalNodeAddress)address);
}
else if (nodeType == NodeType.Any)
{
if (Directory.Exists(address.RootUri + address.AbsolutePath))
{
return new LocalDirectory(this, (LocalNodeAddress)address);
}
else
{
return new LocalFile(this, (LocalNodeAddress)address);
}
}
else
{
throw new NodeTypeNotSupportedException(nodeType);
}
}
public override bool PathsEqual(string path1, string path2, int length)
{
if (Environment.OSVersion.Platform == PlatformID.Unix)
{
if (length > path1.Length || length > path2.Length)
{
return false;
}
for (int i = 0; i < length; i++)
{
if (!path1[i].Equals(path2[i]))
{
return false;
}
}
return true;
}
else
{
return base.PathsEqual(path1, path2, length);
}
}
private volatile bool disposed;
internal protected virtual void CheckDisposed()
{
if (this.disposed)
{
throw new ObjectDisposedException("LocalFileSystem: " + this.RootAddress.Uri);
}
}
public override bool IsDisposed
{
get
{
return this.disposed;
}
}
protected override void Dispose(bool disposing)
{
try
{
this.disposed = true;
this.fileSystemWatcherDirectory.EnableRaisingEvents = false;
this.fileSystemWatcherFile.EnableRaisingEvents = false;
}
catch
{
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
namespace MvcMeublatexApp.Models
{
#region Models
[PropertiesMustMatch("NewPassword", "ConfirmPassword", ErrorMessage = "The new password and confirmation password do not match.")]
public class ChangePasswordModel
{
[Required]
[DataType(DataType.Password)]
[DisplayName("Current password")]
public string OldPassword { get; set; }
[Required]
[ValidatePasswordLength]
[DataType(DataType.Password)]
[DisplayName("New password")]
public string NewPassword { get; set; }
[Required]
[DataType(DataType.Password)]
[DisplayName("Confirm new password")]
public string ConfirmPassword { get; set; }
}
public class LogOnModel
{
[Required]
[DisplayName("User name")]
public string UserName { get; set; }
[Required]
[DataType(DataType.Password)]
[DisplayName("Password")]
public string Password { get; set; }
[DisplayName("Remember me?")]
public bool RememberMe { get; set; }
}
[PropertiesMustMatch("Password", "ConfirmPassword", ErrorMessage = "The password and confirmation password do not match.")]
public class RegisterModel
{
[Required]
[DisplayName("User name")]
public string UserName { get; set; }
[Required]
[DataType(DataType.EmailAddress)]
[DisplayName("Email address")]
public string Email { get; set; }
[Required]
[ValidatePasswordLength]
[DataType(DataType.Password)]
[DisplayName("Password")]
public string Password { get; set; }
[Required]
[DataType(DataType.Password)]
[DisplayName("Confirm password")]
public string ConfirmPassword { get; set; }
}
#endregion
#region Services
// The FormsAuthentication type is sealed and contains static members, so it is difficult to
// unit test code that calls its members. The interface and helper class below demonstrate
// how to create an abstract wrapper around such a type in order to make the AccountController
// code unit testable.
public interface IMembershipService
{
int MinPasswordLength { get; }
bool ValidateUser(string userName, string password);
MembershipCreateStatus CreateUser(string userName, string password, string email);
bool ChangePassword(string userName, string oldPassword, string newPassword);
}
public class AccountMembershipService : IMembershipService
{
private readonly MembershipProvider _provider;
public AccountMembershipService()
: this(null)
{
}
public AccountMembershipService(MembershipProvider provider)
{
_provider = provider ?? Membership.Provider;
}
public int MinPasswordLength
{
get
{
return _provider.MinRequiredPasswordLength;
}
}
public bool ValidateUser(string userName, string password)
{
if (String.IsNullOrEmpty(userName)) throw new ArgumentException("Value cannot be null or empty.", "userName");
if (String.IsNullOrEmpty(password)) throw new ArgumentException("Value cannot be null or empty.", "password");
return _provider.ValidateUser(userName, password);
}
public MembershipCreateStatus CreateUser(string userName, string password, string email)
{
if (String.IsNullOrEmpty(userName)) throw new ArgumentException("Value cannot be null or empty.", "userName");
if (String.IsNullOrEmpty(password)) throw new ArgumentException("Value cannot be null or empty.", "password");
if (String.IsNullOrEmpty(email)) throw new ArgumentException("Value cannot be null or empty.", "email");
MembershipCreateStatus status;
_provider.CreateUser(userName, password, email, null, null, true, null, out status);
return status;
}
public bool ChangePassword(string userName, string oldPassword, string newPassword)
{
if (String.IsNullOrEmpty(userName)) throw new ArgumentException("Value cannot be null or empty.", "userName");
if (String.IsNullOrEmpty(oldPassword)) throw new ArgumentException("Value cannot be null or empty.", "oldPassword");
if (String.IsNullOrEmpty(newPassword)) throw new ArgumentException("Value cannot be null or empty.", "newPassword");
// The underlying ChangePassword() will throw an exception rather
// than return false in certain failure scenarios.
try
{
MembershipUser currentUser = _provider.GetUser(userName, true /* userIsOnline */);
return currentUser.ChangePassword(oldPassword, newPassword);
}
catch (ArgumentException)
{
return false;
}
catch (MembershipPasswordException)
{
return false;
}
}
}
public interface IFormsAuthenticationService
{
void SignIn(string userName, bool createPersistentCookie);
void SignOut();
}
public class FormsAuthenticationService : IFormsAuthenticationService
{
public void SignIn(string userName, bool createPersistentCookie)
{
if (String.IsNullOrEmpty(userName)) throw new ArgumentException("Value cannot be null or empty.", "userName");
FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);
}
public void SignOut()
{
FormsAuthentication.SignOut();
}
}
#endregion
#region Validation
public static class AccountValidation
{
public static string ErrorCodeToString(MembershipCreateStatus createStatus)
{
// See http://go.microsoft.com/fwlink/?LinkID=177550 for
// a full list of status codes.
switch (createStatus)
{
case MembershipCreateStatus.DuplicateUserName:
return "Username already exists. Please enter a different user name.";
case MembershipCreateStatus.DuplicateEmail:
return "A username for that e-mail address already exists. Please enter a different e-mail address.";
case MembershipCreateStatus.InvalidPassword:
return "The password provided is invalid. Please enter a valid password value.";
case MembershipCreateStatus.InvalidEmail:
return "The e-mail address provided is invalid. Please check the value and try again.";
case MembershipCreateStatus.InvalidAnswer:
return "The password retrieval answer provided is invalid. Please check the value and try again.";
case MembershipCreateStatus.InvalidQuestion:
return "The password retrieval question provided is invalid. Please check the value and try again.";
case MembershipCreateStatus.InvalidUserName:
return "The user name provided is invalid. Please check the value and try again.";
case MembershipCreateStatus.ProviderError:
return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
case MembershipCreateStatus.UserRejected:
return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
default:
return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
}
}
}
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)]
public sealed class PropertiesMustMatchAttribute : ValidationAttribute
{
private const string _defaultErrorMessage = "'{0}' and '{1}' do not match.";
private readonly object _typeId = new object();
public PropertiesMustMatchAttribute(string originalProperty, string confirmProperty)
: base(_defaultErrorMessage)
{
OriginalProperty = originalProperty;
ConfirmProperty = confirmProperty;
}
public string ConfirmProperty { get; private set; }
public string OriginalProperty { get; private set; }
public override object TypeId
{
get
{
return _typeId;
}
}
public override string FormatErrorMessage(string name)
{
return String.Format(CultureInfo.CurrentUICulture, ErrorMessageString,
OriginalProperty, ConfirmProperty);
}
public override bool IsValid(object value)
{
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(value);
object originalValue = properties.Find(OriginalProperty, true /* ignoreCase */).GetValue(value);
object confirmValue = properties.Find(ConfirmProperty, true /* ignoreCase */).GetValue(value);
return Object.Equals(originalValue, confirmValue);
}
}
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public sealed class ValidatePasswordLengthAttribute : ValidationAttribute
{
private const string _defaultErrorMessage = "'{0}' must be at least {1} characters long.";
private readonly int _minCharacters = Membership.Provider.MinRequiredPasswordLength;
public ValidatePasswordLengthAttribute()
: base(_defaultErrorMessage)
{
}
public override string FormatErrorMessage(string name)
{
return String.Format(CultureInfo.CurrentUICulture, ErrorMessageString,
name, _minCharacters);
}
public override bool IsValid(object value)
{
string valueAsString = value as string;
return (valueAsString != null && valueAsString.Length >= _minCharacters);
}
}
#endregion
}
| |
using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
using Microsoft.IdentityModel.Tokens;
using Microsoft.SharePoint.Client;
using System;
using System.Net;
using System.Security.Principal;
using System.Web;
using System.Web.Configuration;
namespace SPO_MasterPages
{
/// <summary>
/// Encapsulates all the information from SharePoint.
/// </summary>
public abstract class SharePointContext
{
public const string SPHostUrlKey = "SPHostUrl";
public const string SPAppWebUrlKey = "SPAppWebUrl";
public const string SPLanguageKey = "SPLanguage";
public const string SPClientTagKey = "SPClientTag";
public const string SPProductNumberKey = "SPProductNumber";
protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0);
private readonly Uri spHostUrl;
private readonly Uri spAppWebUrl;
private readonly string spLanguage;
private readonly string spClientTag;
private readonly string spProductNumber;
// <AccessTokenString, UtcExpiresOn>
protected Tuple<string, DateTime> userAccessTokenForSPHost;
protected Tuple<string, DateTime> userAccessTokenForSPAppWeb;
protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost;
protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb;
/// <summary>
/// Gets the SharePoint host url from QueryString of the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The specified HTTP request.</param>
/// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
public static Uri GetSPHostUrl(HttpRequestBase httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentNullException("httpRequest");
}
string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]);
Uri spHostUrl;
if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) &&
(spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps))
{
return spHostUrl;
}
return null;
}
/// <summary>
/// Gets the SharePoint host url from QueryString of the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The specified HTTP request.</param>
/// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
public static Uri GetSPHostUrl(HttpRequest httpRequest)
{
return GetSPHostUrl(new HttpRequestWrapper(httpRequest));
}
/// <summary>
/// The SharePoint host url.
/// </summary>
public Uri SPHostUrl
{
get { return this.spHostUrl; }
}
/// <summary>
/// The SharePoint app web url.
/// </summary>
public Uri SPAppWebUrl
{
get { return this.spAppWebUrl; }
}
/// <summary>
/// The SharePoint language.
/// </summary>
public string SPLanguage
{
get { return this.spLanguage; }
}
/// <summary>
/// The SharePoint client tag.
/// </summary>
public string SPClientTag
{
get { return this.spClientTag; }
}
/// <summary>
/// The SharePoint product number.
/// </summary>
public string SPProductNumber
{
get { return this.spProductNumber; }
}
/// <summary>
/// The user access token for the SharePoint host.
/// </summary>
public abstract string UserAccessTokenForSPHost
{
get;
}
/// <summary>
/// The user access token for the SharePoint app web.
/// </summary>
public abstract string UserAccessTokenForSPAppWeb
{
get;
}
/// <summary>
/// The app only access token for the SharePoint host.
/// </summary>
public abstract string AppOnlyAccessTokenForSPHost
{
get;
}
/// <summary>
/// The app only access token for the SharePoint app web.
/// </summary>
public abstract string AppOnlyAccessTokenForSPAppWeb
{
get;
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="spHostUrl">The SharePoint host url.</param>
/// <param name="spAppWebUrl">The SharePoint app web url.</param>
/// <param name="spLanguage">The SharePoint language.</param>
/// <param name="spClientTag">The SharePoint client tag.</param>
/// <param name="spProductNumber">The SharePoint product number.</param>
protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber)
{
if (spHostUrl == null)
{
throw new ArgumentNullException("spHostUrl");
}
if (string.IsNullOrEmpty(spLanguage))
{
throw new ArgumentNullException("spLanguage");
}
if (string.IsNullOrEmpty(spClientTag))
{
throw new ArgumentNullException("spClientTag");
}
if (string.IsNullOrEmpty(spProductNumber))
{
throw new ArgumentNullException("spProductNumber");
}
this.spHostUrl = spHostUrl;
this.spAppWebUrl = spAppWebUrl;
this.spLanguage = spLanguage;
this.spClientTag = spClientTag;
this.spProductNumber = spProductNumber;
}
/// <summary>
/// Creates a user ClientContext for the SharePoint host.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateUserClientContextForSPHost()
{
return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost);
}
/// <summary>
/// Creates a user ClientContext for the SharePoint app web.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateUserClientContextForSPAppWeb()
{
return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb);
}
/// <summary>
/// Creates app only ClientContext for the SharePoint host.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateAppOnlyClientContextForSPHost()
{
return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost);
}
/// <summary>
/// Creates an app only ClientContext for the SharePoint app web.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateAppOnlyClientContextForSPAppWeb()
{
return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb);
}
/// <summary>
/// Gets the database connection string from SharePoint for autohosted app.
/// This method is deprecated because the autohosted option is no longer available.
/// </summary>
[ObsoleteAttribute("This method is deprecated because the autohosted option is no longer available.", true)]
public string GetDatabaseConnectionString()
{
throw new NotSupportedException("This method is deprecated because the autohosted option is no longer available.");
}
/// <summary>
/// Determines if the specified access token is valid.
/// It considers an access token as not valid if it is null, or it has expired.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <returns>True if the access token is valid.</returns>
protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken)
{
return accessToken != null &&
!string.IsNullOrEmpty(accessToken.Item1) &&
accessToken.Item2 > DateTime.UtcNow;
}
/// <summary>
/// Creates a ClientContext with the specified SharePoint site url and the access token.
/// </summary>
/// <param name="spSiteUrl">The site url.</param>
/// <param name="accessToken">The access token.</param>
/// <returns>A ClientContext instance.</returns>
private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken)
{
if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken))
{
return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken);
}
return null;
}
}
/// <summary>
/// Redirection status.
/// </summary>
public enum RedirectionStatus
{
Ok,
ShouldRedirect,
CanNotRedirect
}
/// <summary>
/// Provides SharePointContext instances.
/// </summary>
public abstract class SharePointContextProvider
{
private static SharePointContextProvider current;
/// <summary>
/// The current SharePointContextProvider instance.
/// </summary>
public static SharePointContextProvider Current
{
get { return SharePointContextProvider.current; }
}
/// <summary>
/// Initializes the default SharePointContextProvider instance.
/// </summary>
static SharePointContextProvider()
{
if (!TokenHelper.IsHighTrustApp())
{
SharePointContextProvider.current = new SharePointAcsContextProvider();
}
else
{
SharePointContextProvider.current = new SharePointHighTrustContextProvider();
}
}
/// <summary>
/// Registers the specified SharePointContextProvider instance as current.
/// It should be called by Application_Start() in Global.asax.
/// </summary>
/// <param name="provider">The SharePointContextProvider to be set as current.</param>
public static void Register(SharePointContextProvider provider)
{
if (provider == null)
{
throw new ArgumentNullException("provider");
}
SharePointContextProvider.current = provider;
}
/// <summary>
/// Checks if it is necessary to redirect to SharePoint for user to authenticate.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
/// <returns>Redirection status.</returns>
public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
redirectUrl = null;
bool contextTokenExpired = false;
try
{
if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null)
{
return RedirectionStatus.Ok;
}
}
catch (SecurityTokenExpiredException)
{
contextTokenExpired = true;
}
const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint";
if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey]) && !contextTokenExpired)
{
return RedirectionStatus.CanNotRedirect;
}
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
if (spHostUrl == null)
{
return RedirectionStatus.CanNotRedirect;
}
if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST"))
{
return RedirectionStatus.CanNotRedirect;
}
Uri requestUrl = httpContext.Request.Url;
var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query);
// Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string.
queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey);
queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey);
queryNameValueCollection.Remove(SharePointContext.SPLanguageKey);
queryNameValueCollection.Remove(SharePointContext.SPClientTagKey);
queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey);
// Adds SPHasRedirectedToSharePoint=1.
queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1");
UriBuilder returnUrlBuilder = new UriBuilder(requestUrl);
returnUrlBuilder.Query = queryNameValueCollection.ToString();
// Inserts StandardTokens.
const string StandardTokens = "{StandardTokens}";
string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri;
returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&");
// Constructs redirect url.
string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString));
redirectUrl = new Uri(redirectUrlString, UriKind.Absolute);
return RedirectionStatus.ShouldRedirect;
}
/// <summary>
/// Checks if it is necessary to redirect to SharePoint for user to authenticate.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
/// <returns>Redirection status.</returns>
public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl)
{
return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl);
}
/// <summary>
/// Creates a SharePointContext instance with the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentNullException("httpRequest");
}
// SPHostUrl
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest);
if (spHostUrl == null)
{
return null;
}
// SPAppWebUrl
string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]);
Uri spAppWebUrl;
if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) ||
!(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps))
{
spAppWebUrl = null;
}
// SPLanguage
string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey];
if (string.IsNullOrEmpty(spLanguage))
{
return null;
}
// SPClientTag
string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey];
if (string.IsNullOrEmpty(spClientTag))
{
return null;
}
// SPProductNumber
string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey];
if (string.IsNullOrEmpty(spProductNumber))
{
return null;
}
return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest);
}
/// <summary>
/// Creates a SharePointContext instance with the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
public SharePointContext CreateSharePointContext(HttpRequest httpRequest)
{
return CreateSharePointContext(new HttpRequestWrapper(httpRequest));
}
/// <summary>
/// Gets a SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns>
public SharePointContext GetSharePointContext(HttpContextBase httpContext)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
if (spHostUrl == null)
{
return null;
}
SharePointContext spContext = LoadSharePointContext(httpContext);
if (spContext == null || !ValidateSharePointContext(spContext, httpContext))
{
spContext = CreateSharePointContext(httpContext.Request);
if (spContext != null)
{
SaveSharePointContext(spContext, httpContext);
}
}
return spContext;
}
/// <summary>
/// Gets a SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns>
public SharePointContext GetSharePointContext(HttpContext httpContext)
{
return GetSharePointContext(new HttpContextWrapper(httpContext));
}
/// <summary>
/// Creates a SharePointContext instance.
/// </summary>
/// <param name="spHostUrl">The SharePoint host url.</param>
/// <param name="spAppWebUrl">The SharePoint app web url.</param>
/// <param name="spLanguage">The SharePoint language.</param>
/// <param name="spClientTag">The SharePoint client tag.</param>
/// <param name="spProductNumber">The SharePoint product number.</param>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest);
/// <summary>
/// Validates if the given SharePointContext can be used with the specified HTTP context.
/// </summary>
/// <param name="spContext">The SharePointContext.</param>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns>
protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
/// <summary>
/// Loads the SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns>
protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext);
/// <summary>
/// Saves the specified SharePointContext instance associated with the specified HTTP context.
/// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context.
/// </summary>
/// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param>
/// <param name="httpContext">The HTTP context.</param>
protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
}
#region ACS
/// <summary>
/// Encapsulates all the information from SharePoint in ACS mode.
/// </summary>
public class SharePointAcsContext : SharePointContext
{
private readonly string contextToken;
private readonly SharePointContextToken contextTokenObj;
/// <summary>
/// The context token.
/// </summary>
public string ContextToken
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; }
}
/// <summary>
/// The context token's "CacheKey" claim.
/// </summary>
public string CacheKey
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; }
}
/// <summary>
/// The context token's "refreshtoken" claim.
/// </summary>
public string RefreshToken
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; }
}
public override string UserAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.userAccessTokenForSPHost,
() => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority));
}
}
public override string UserAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb,
() => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority));
}
}
public override string AppOnlyAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost,
() => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl)));
}
}
public override string AppOnlyAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb,
() => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl)));
}
}
public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj)
: base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
{
if (string.IsNullOrEmpty(contextToken))
{
throw new ArgumentNullException("contextToken");
}
if (contextTokenObj == null)
{
throw new ArgumentNullException("contextTokenObj");
}
this.contextToken = contextToken;
this.contextTokenObj = contextTokenObj;
}
/// <summary>
/// Ensures the access token is valid and returns it.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
/// <returns>The access token string.</returns>
private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler)
{
RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);
return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null;
}
/// <summary>
/// Renews the access token if it is not valid.
/// </summary>
/// <param name="accessToken">The access token to renew.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler)
{
if (IsAccessTokenValid(accessToken))
{
return;
}
try
{
OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler();
DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn;
if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance)
{
// Make the access token get renewed a bit earlier than the time when it expires
// so that the calls to SharePoint with it will have enough time to complete successfully.
expiresOn -= AccessTokenLifetimeTolerance;
}
accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn);
}
catch (WebException)
{
}
}
}
/// <summary>
/// Default provider for SharePointAcsContext.
/// </summary>
public class SharePointAcsContextProvider : SharePointContextProvider
{
private const string SPContextKey = "SPContext";
private const string SPCacheKeyKey = "SPCacheKey";
protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest)
{
string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest);
if (string.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = null;
try
{
contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority);
}
catch (WebException)
{
return null;
}
catch (AudienceUriValidationFailedException)
{
return null;
}
return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken);
}
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointAcsContext spAcsContext = spContext as SharePointAcsContext;
if (spAcsContext != null)
{
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request);
HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey];
string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null;
return spHostUrl == spAcsContext.SPHostUrl &&
!string.IsNullOrEmpty(spAcsContext.CacheKey) &&
spCacheKey == spAcsContext.CacheKey &&
!string.IsNullOrEmpty(spAcsContext.ContextToken) &&
(string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken);
}
return false;
}
protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext)
{
return httpContext.Session[SPContextKey] as SharePointAcsContext;
}
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointAcsContext spAcsContext = spContext as SharePointAcsContext;
if (spAcsContext != null)
{
HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey)
{
Value = spAcsContext.CacheKey,
Secure = true,
HttpOnly = true
};
httpContext.Response.AppendCookie(spCacheKeyCookie);
}
httpContext.Session[SPContextKey] = spAcsContext;
}
}
#endregion ACS
#region HighTrust
/// <summary>
/// Encapsulates all the information from SharePoint in HighTrust mode.
/// </summary>
public class SharePointHighTrustContext : SharePointContext
{
private readonly WindowsIdentity logonUserIdentity;
/// <summary>
/// The Windows identity for the current user.
/// </summary>
public WindowsIdentity LogonUserIdentity
{
get { return this.logonUserIdentity; }
}
public override string UserAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.userAccessTokenForSPHost,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity));
}
}
public override string UserAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity));
}
}
public override string AppOnlyAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null));
}
}
public override string AppOnlyAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null));
}
}
public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity)
: base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
{
if (logonUserIdentity == null)
{
throw new ArgumentNullException("logonUserIdentity");
}
this.logonUserIdentity = logonUserIdentity;
}
/// <summary>
/// Ensures the access token is valid and returns it.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
/// <returns>The access token string.</returns>
private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
{
RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);
return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null;
}
/// <summary>
/// Renews the access token if it is not valid.
/// </summary>
/// <param name="accessToken">The access token to renew.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
{
if (IsAccessTokenValid(accessToken))
{
return;
}
DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime);
if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance)
{
// Make the access token get renewed a bit earlier than the time when it expires
// so that the calls to SharePoint with it will have enough time to complete successfully.
expiresOn -= AccessTokenLifetimeTolerance;
}
accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn);
}
}
/// <summary>
/// Default provider for SharePointHighTrustContext.
/// </summary>
public class SharePointHighTrustContextProvider : SharePointContextProvider
{
private const string SPContextKey = "SPContext";
protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest)
{
WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity;
if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null)
{
return null;
}
return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity);
}
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext;
if (spHighTrustContext != null)
{
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity;
return spHostUrl == spHighTrustContext.SPHostUrl &&
logonUserIdentity != null &&
logonUserIdentity.IsAuthenticated &&
!logonUserIdentity.IsGuest &&
logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User;
}
return false;
}
protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext)
{
return httpContext.Session[SPContextKey] as SharePointHighTrustContext;
}
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext;
}
}
#endregion HighTrust
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System;
using System.IO;
using System.Collections; // for IDictionary;
using System.Compiler;
using System.Diagnostics.Contracts;
using System.Diagnostics;
using Microsoft.Win32;
namespace Microsoft.Contracts.Foxtrot.Driver
{
/// <summary>
/// Main program for Foxtrot.
/// </summary>
public sealed class Program
{
// Private fields
private static TypeNode userSpecifiedContractType;
private static ContractNodes DefaultContractLibrary;
private static ContractNodes BackupContractLibrary;
private static string originalAssemblyName = null;
private static FoxtrotOptions options;
private const int LeaderBoard_RewriterId = 0x1;
private const int LeaderBoardFeatureMask_Rewriter = LeaderBoard_RewriterId << 12;
[Flags]
private enum LeaderBoardFeatureId
{
StandardMode = 0x10,
ThrowOnFailure = 0x20,
}
private static int LeaderBoardFeature(FoxtrotOptions options)
{
Contract.Requires(options != null);
var result = options.level | LeaderBoardFeatureMask_Rewriter;
if (options.assemblyMode == FoxtrotOptions.AssemblyMode.standard)
{
result |= (int) LeaderBoardFeatureId.StandardMode;
}
if (options.throwOnFailure)
{
result |= (int) LeaderBoardFeatureId.ThrowOnFailure;
}
return result;
}
/// <summary>
/// Parses command line arguments and extracts, verifies, and/or rewrites a given assembly.
/// </summary>
/// <param name="args">Command line arguments, or <c>null</c> for help to be written to the console.</param>
public static int Main(string[] args)
{
var stopWatch = new Stopwatch();
stopWatch.Start();
try
{
var r = InternalMain(args);
return r;
}
finally
{
var delta = stopWatch.Elapsed;
Console.WriteLine("elapsed time: {0}ms", delta.TotalMilliseconds);
}
}
private static int InternalMain(string[] args)
{
options = new FoxtrotOptions();
options.Parse(args);
if (!options.nologo)
{
var version = typeof (FoxtrotOptions).Assembly.GetName().Version;
Console.WriteLine("Microsoft (R) .NET Contract Rewriter Version {0}", version);
Console.WriteLine("Copyright (C) Microsoft Corporation. All rights reserved.");
Console.WriteLine("");
}
if (options.HasErrors)
{
options.PrintErrorsAndExit(Console.Out);
return -1;
}
if (options.HelpRequested)
{
options.PrintOptions("", Console.Out);
return 0;
}
if (options.breakIntoDebugger)
{
Debugger.Launch();
}
#if DEBUG
if (options.nobox)
{
Debug.Listeners.Clear();
// listen for failed assertions
Debug.Listeners.Add(new ExitTraceListener());
}
#else
Debug.Listeners.Clear();
#endif
if (options.repro)
{
WriteReproFile(args);
}
var resolver = new AssemblyResolver(
options.resolvedPaths, options.libpaths, options.debug,
options.shortBranches, options.verbose > 2,
PostLoadExtractionHook);
GlobalAssemblyCache.probeGAC = options.useGAC;
// Connect to LeaderBoard
SendLeaderBoardRewriterFeature(options);
int errorReturnValue = -1;
IDictionary assemblyCache = new Hashtable();
// Trigger static initializer of SystemTypes
var savedGACFlag = GlobalAssemblyCache.probeGAC;
GlobalAssemblyCache.probeGAC = false;
TypeNode dummy = SystemTypes.Object;
TargetPlatform.Clear();
TargetPlatform.AssemblyReferenceFor = null;
GlobalAssemblyCache.probeGAC = savedGACFlag;
try
{
// Validate the command-line arguments.
if (options.output != "same")
{
if (!Path.IsPathRooted(options.output))
{
string s = Directory.GetCurrentDirectory();
options.output = Path.Combine(s, options.output);
}
}
if (options.assembly == null && options.GeneralArguments.Count == 1)
{
options.assembly = options.GeneralArguments[0];
}
if (!File.Exists(options.assembly))
{
throw new FileNotFoundException(String.Format("The given assembly '{0}' does not exist.", options.assembly));
}
InitializePlatform(resolver, assemblyCache);
if (options.passthrough)
{
options.rewrite = false;
}
if (!(options.rewrite || options.passthrough))
{
Console.WriteLine("Error: Need to specify at least one of: /rewrite, /pass");
options.PrintOptions("", Console.Out);
return errorReturnValue;
}
if (options.extractSourceText && !options.debug)
{
Console.WriteLine("Error: Cannot specify /sourceText without also specifying /debug");
options.PrintOptions("", Console.Out);
return errorReturnValue;
}
if (!(0 <= options.level && options.level <= 4))
{
Console.WriteLine("Error: incorrect /level: {0}. /level must be between 0 and 4 (inclusive)", options.level);
return errorReturnValue;
}
if (options.automaticallyLookForOOBs && options.contracts != null && 0 < options.contracts.Count)
{
Console.WriteLine("Error: Out of band contracts are being automatically applied, all files specified using the contracts option are ignored.");
return errorReturnValue;
}
// Sanity check: just make sure that all files specified for out-of-band contracts actually exist
bool atLeastOneOobNotFound = false;
if (options.contracts != null)
{
foreach (string oob in options.contracts)
{
bool found = false;
if (File.Exists(oob)) found = true;
if (!found)
{
if (options.libpaths != null)
{
foreach (string dir in options.libpaths)
{
if (File.Exists(Path.Combine(dir, oob)))
{
found = true;
break;
}
}
}
if (!found)
{
Console.WriteLine("Error: Contract file '" + oob + "' could not be found");
atLeastOneOobNotFound = true;
}
}
}
}
if (atLeastOneOobNotFound)
{
return errorReturnValue;
}
// Load the assembly to be rewritten
originalAssemblyName = Path.GetFileNameWithoutExtension(options.assembly);
AssemblyNode assemblyNode = AssemblyNode.GetAssembly(options.assembly,
TargetPlatform.StaticAssemblyCache, true, options.debug, true, options.shortBranches
, delegate(AssemblyNode a)
{
//Console.WriteLine("Loaded '" + a.Name + "' from '" + a.Location.ToString() + "'");
PossiblyLoadOOB(resolver, a, originalAssemblyName);
});
if (assemblyNode == null)
throw new FileLoadException("The given assembly could not be loaded.", options.assembly);
// Check to see if any metadata errors were reported
if (assemblyNode.MetadataImportWarnings != null && assemblyNode.MetadataImportWarnings.Count > 0)
{
string msg = "\tThere were warnings reported in " + assemblyNode.Name + "'s metadata.\n";
foreach (Exception e in assemblyNode.MetadataImportWarnings)
{
msg += "\t" + e.Message;
}
Console.WriteLine(msg);
}
if (assemblyNode.MetadataImportErrors != null && assemblyNode.MetadataImportErrors.Count > 0)
{
string msg = "\tThere were errors reported in " + assemblyNode.Name + "'s metadata.\n";
foreach (Exception e in assemblyNode.MetadataImportErrors)
{
msg += "\t" + e.Message;
}
Console.WriteLine(msg);
throw new InvalidOperationException("Foxtrot: " + msg);
}
else
{
//Console.WriteLine("\tThere were no errors reported in {0}'s metadata.", assemblyNode.Name);
}
// Load the rewriter assembly if any
AssemblyNode rewriterMethodAssembly = null;
if (options.rewriterMethods != null && 0 < options.rewriterMethods.Length)
{
string[] pieces = options.rewriterMethods.Split(',');
if (!(pieces.Length == 2 || pieces.Length == 3))
{
Console.WriteLine("Error: Need to provide two or three comma separated arguments to /rewriterMethods");
options.PrintOptions("", Console.Out);
return errorReturnValue;
}
string assemName = pieces[0];
rewriterMethodAssembly = resolver.ProbeForAssembly(assemName, null, resolver.AllExt);
if (rewriterMethodAssembly == null)
{
Console.WriteLine("Error: Could not open assembly '" + assemName + "'");
return errorReturnValue;
}
string nameSpaceName = null;
string bareClassName = null;
if (pieces.Length == 2)
{
// interpret A.B.C as namespace A.B and class C
// no nested classes allowed.
string namespaceAndClassName = pieces[1];
int lastDot = namespaceAndClassName.LastIndexOf('.');
nameSpaceName = lastDot == -1 ? "" : namespaceAndClassName.Substring(0, lastDot);
bareClassName = namespaceAndClassName.Substring(lastDot + 1);
userSpecifiedContractType = rewriterMethodAssembly.GetType(Identifier.For(nameSpaceName),
Identifier.For(bareClassName));
}
else
{
// pieces.Length == 3
// namespace can be A.B and class can be C.D
nameSpaceName = pieces[1];
bareClassName = pieces[2];
userSpecifiedContractType = GetPossiblyNestedType(rewriterMethodAssembly, nameSpaceName, bareClassName);
}
if (userSpecifiedContractType == null)
{
Console.WriteLine("Error: Could not find type '" + bareClassName + "' in the namespace '" +
nameSpaceName + "' in the assembly '" + assemName + "'");
return errorReturnValue;
}
}
// Load the ASTs for all of the contract methods
AssemblyNode contractAssembly = null;
if (!options.passthrough)
{
// The contract assembly should be determined in the following order:
// 0. if the option contractLibrary was specified, use that.
// 1. the assembly being rewritten
// 2. the system assembly
// 3. the microsoft.contracts library
if (options.contractLibrary != null)
{
contractAssembly = resolver.ProbeForAssembly(options.contractLibrary,
Path.GetDirectoryName(options.assembly), resolver.EmptyAndDllExt);
if (contractAssembly != null)
DefaultContractLibrary = ContractNodes.GetContractNodes(contractAssembly, options.EmitError);
if (contractAssembly == null || DefaultContractLibrary == null)
{
Console.WriteLine("Error: could not load Contracts API from assembly '{0}'", options.contractLibrary);
return -1;
}
}
else
{
if (DefaultContractLibrary == null)
{
// See if contracts are in the assembly we're rewriting
DefaultContractLibrary = ContractNodes.GetContractNodes(assemblyNode, options.EmitError);
}
if (DefaultContractLibrary == null)
{
// See if contracts are in Mscorlib
DefaultContractLibrary = ContractNodes.GetContractNodes(SystemTypes.SystemAssembly,
options.EmitError);
}
// try to load Microsoft.Contracts.dll
var microsoftContractsLibrary = resolver.ProbeForAssembly("Microsoft.Contracts",
Path.GetDirectoryName(options.assembly), resolver.DllExt);
if (microsoftContractsLibrary != null)
{
BackupContractLibrary = ContractNodes.GetContractNodes(microsoftContractsLibrary, options.EmitError);
}
if (DefaultContractLibrary == null && BackupContractLibrary != null)
{
DefaultContractLibrary = BackupContractLibrary;
}
}
}
if (DefaultContractLibrary == null)
{
if (options.output == "same")
{
Console.WriteLine(
"Warning: Runtime Contract Checking requested, but contract class could not be found. Did you forget to reference the contracts assembly?");
return 0; // Returning success so that it doesn't break any build processes.
}
else
{
// Then an output file was specified (assume it is not the same as the input assembly, but that could be checked here).
// In that case, consider it an error to not have found a contract class.
// No prinicpled reason, but this is a common pitfall that several users have run into and the rewriter just
// didn't do anything without giving any reason.
Console.WriteLine(
"Error: Runtime Contract Checking requested, but contract class could not be found. Did you forget to reference the contracts assembly?");
return errorReturnValue;
}
}
if (0 < options.verbose)
{
Console.WriteLine("Trace: Using '" + DefaultContractLibrary.ContractClass.DeclaringModule.Location +
"' for the definition of the contract class");
}
// Make sure we extract contracts from the system assembly and the system.dll assemblies.
// As they are already loaded, they will never trigger the post assembly load event.
// But even if we are rewriting one of these assemblies (and so *not* trying to extract
// the contracts at this point), still need to hook up our resolver to them. If this
// isn't done, then any references chased down from them might not get resolved.
bool isPreloadedAssembly = false;
CheckIfPreloaded(resolver, assemblyNode, SystemTypes.SystemAssembly, ref isPreloadedAssembly);
CheckIfPreloaded(resolver, assemblyNode, SystemTypes.SystemDllAssembly, ref isPreloadedAssembly);
//CheckIfPreloaded(resolver, assemblyNode, SystemTypes.SystemRuntimeWindowsRuntimeAssembly, ref isPreloadedAssembly);
//CheckIfPreloaded(resolver, assemblyNode, SystemTypes.SystemRuntimeWindowsRuntimeUIXamlAssembly, ref isPreloadedAssembly);
if (!isPreloadedAssembly)
{
assemblyNode.AssemblyReferenceResolution += resolver.ResolveAssemblyReference;
}
MikesArchitecture(resolver, assemblyNode, DefaultContractLibrary, BackupContractLibrary);
return options.GetErrorCount();
}
catch (Exception exception)
{
SendLeaderBoardFailure();
// Redirect the exception message to the console and quit.
Console.Error.WriteLine(new System.CodeDom.Compiler.CompilerError(exception.Source, 0, 0, null, exception.Message));
return errorReturnValue;
}
finally
{
// Reset statics
userSpecifiedContractType = null;
DefaultContractLibrary = null;
BackupContractLibrary = null;
originalAssemblyName = null;
options = null;
// eagerly close all assemblies due to pdb file locking issues
DisposeAssemblies(assemblyCache.Values);
// copy needed since Dispose actually removes things from the StaticAssemblyCache
object[] assemblies = new object[TargetPlatform.StaticAssemblyCache.Values.Count];
TargetPlatform.StaticAssemblyCache.Values.CopyTo(assemblies, 0);
DisposeAssemblies(assemblies);
}
}
private static void CheckIfPreloaded(AssemblyResolver resolver, AssemblyNode assemblyNode,
AssemblyNode preloaded, ref bool isPreloadedAssembly)
{
Contract.Requires(preloaded == null || resolver != null);
if (preloaded == null) return;
resolver.PostLoadHook(preloaded);
if (assemblyNode == preloaded)
{
isPreloadedAssembly = true;
}
}
private static void InitializePlatform(AssemblyResolver resolver, System.Collections.IDictionary assemblyCache)
{
// Initialize CCI's platform if necessary
if (options.targetplatform != null && options.targetplatform != "")
{
string platformDir = Path.GetDirectoryName(options.targetplatform);
if (platformDir == "")
{
platformDir = ".";
}
if (!Directory.Exists(platformDir))
throw new ArgumentException("Directory '" + platformDir + "' doesn't exist.");
if (!File.Exists(options.targetplatform))
throw new ArgumentException("Cannot find the file '" + options.targetplatform +
"' to use as the system assembly.");
TargetPlatform.GetDebugInfo = options.debug;
switch (options.framework)
{
case "v4.5":
TargetPlatform.SetToV4_5(platformDir);
break;
case "v4.0":
TargetPlatform.SetToV4(platformDir);
break;
case "v3.5":
case "v3.0":
case "v2.0":
TargetPlatform.SetToV2(platformDir);
break;
default:
if (platformDir.Contains("v4.0"))
{
TargetPlatform.SetToV4(platformDir);
}
else if (platformDir.Contains("v4.5"))
{
TargetPlatform.SetToV4_5(platformDir);
}
else if (platformDir.Contains("v3.5"))
{
TargetPlatform.SetToV2(platformDir);
}
else
{
TargetPlatform.SetToPostV2(platformDir);
}
break;
}
SystemAssemblyLocation.Location = options.targetplatform;
// When rewriting the framework assemblies, it might not be the case that the input assembly (e.g., System.dll)
// is in the same directory as the target platform that the rewriter has been asked to run on.
SystemRuntimeWindowsRuntimeAssemblyLocation.Location =
SetPlatformAssemblyLocation("System.Runtime.WindowsRuntime.dll");
SystemRuntimeWindowsRuntimeUIXamlAssemblyLocation.Location =
SetPlatformAssemblyLocation("System.Runtime.WindowsRuntime.UI.Xaml.dll");
SystemDllAssemblyLocation.Location = SetPlatformAssemblyLocation("System.dll");
SystemAssemblyLocation.SystemAssemblyCache = assemblyCache;
}
else
{
if (options.resolvedPaths != null)
{
foreach (var path in options.resolvedPaths)
{
if (path == null) continue;
if (string.IsNullOrEmpty(path.Trim())) continue;
var candidate = Path.GetFullPath(path);
if (candidate.EndsWith(@"\mscorlib.dll", StringComparison.OrdinalIgnoreCase) &&
File.Exists(candidate))
{
// found our platform
var dir = Path.Combine(Path.GetPathRoot(candidate), Path.GetDirectoryName(candidate));
SelectPlatform(assemblyCache, dir, candidate);
goto doneWithLibPaths;
}
}
}
if (options.libpaths != null)
{
// try to infer platform from libpaths
foreach (var path in options.libpaths)
{
if (path == "") continue;
var corlib = Path.Combine(path, "mscorlib.dll");
if (File.Exists(corlib))
{
// this should be our platform mscorlib.dll
SelectPlatform(assemblyCache, path, corlib);
goto doneWithLibPaths;
}
}
}
}
doneWithLibPaths:
;
if (string.IsNullOrEmpty(options.targetplatform))
{
SystemTypes.Initialize(false, true);
// try to use mscorlib of assembly to rewrite
AssemblyNode target = AssemblyNode.GetAssembly(options.assembly, TargetPlatform.StaticAssemblyCache,
true, false, true);
if (target != null)
{
var majorTargetVersion = target.MetadataFormatMajorVersion;
var corlib = SystemTypes.SystemAssembly.Location;
var path = Path.GetDirectoryName(corlib);
if (SystemTypes.SystemAssembly.Version.Major != majorTargetVersion)
{
var versionDir = String.Format(@"..\{0}", target.TargetRuntimeVersion);
path = Path.Combine(path, versionDir);
corlib = Path.Combine(path, "mscorlib.dll");
if (!File.Exists(corlib))
{
throw new ArgumentException(
"Cannot determine target runtime version. Please specify /resolvedPaths, /libpaths or /targetplatform");
}
}
if (majorTargetVersion == 2)
{
TargetPlatform.SetToV2(path);
}
else
{
TargetPlatform.SetToV4(path);
}
SystemAssemblyLocation.Location = corlib;
Contract.Assume(path != null);
SystemDllAssemblyLocation.Location = Path.Combine(path, "System.dll");
SystemRuntimeWindowsRuntimeAssemblyLocation.Location = Path.Combine(path,
"System.Runtime.WindowsRuntime.dll");
SystemRuntimeWindowsRuntimeUIXamlAssemblyLocation.Location = Path.Combine(path,
"System.Runtime.WindowsRuntime.UI.Xaml.dll");
SystemAssemblyLocation.SystemAssemblyCache = assemblyCache;
options.targetplatform = corlib;
}
}
// always make sure we have the platform assemblies loaded
if (TargetPlatform.PlatformAssembliesLocation == null)
{
throw new ArgumentException("Could not find the platform assemblies.");
}
if (!string.IsNullOrEmpty(options.targetplatform))
{
TargetPlatform.AssemblyReferenceFor = null;
assemblyCache.Clear();
SystemTypes.Initialize(false, true, resolver.PostLoadHook);
}
// Force SystemTypes.Initialize() to be run before attaching any out-of-band contracts
// Otherwise, if there is an out-of-band contract for mscorlib, then types in SystemTypes
// get loaded twice.
AssemblyNode corlibAssembly = SystemTypes.SystemAssembly;
// Add the system assembly to the cache so if we rewrite it itself we won't load it twice
TargetPlatform.UseGenerics = true;
TargetPlatform.StaticAssemblyCache.Add(corlibAssembly.Name, corlibAssembly);
}
private static string SetPlatformAssemblyLocation(string platformAssemblyName)
{
Contract.Requires(platformAssemblyName != null);
var result = Path.Combine(Path.GetDirectoryName(options.targetplatform), platformAssemblyName);
;
var assemblyFileName = Path.GetFileName(options.assembly);
if (assemblyFileName.Equals(platformAssemblyName, StringComparison.OrdinalIgnoreCase) &&
File.Exists(options.assembly))
{
result = options.assembly;
}
return result;
}
private static void SelectPlatform(IDictionary assemblyCache, string path, string corlib)
{
Contract.Requires(corlib != null);
Contract.Requires(path != null);
Debug.Assert(corlib.StartsWith(path));
SystemTypes.Clear();
TargetPlatform.GetDebugInfo = options.debug;
TargetPlatform.Clear();
if (path.Contains("v4.0") || path.Contains("v4.5"))
{
TargetPlatform.SetToV4(path);
}
else
{
TargetPlatform.SetToV2(path);
}
SystemAssemblyLocation.Location = corlib;
SystemRuntimeWindowsRuntimeAssemblyLocation.Location = Path.Combine(path,
"System.Runtime.WindowsRuntime.dll");
SystemRuntimeWindowsRuntimeUIXamlAssemblyLocation.Location = Path.Combine(path,
"System.Runtime.WindowsRuntime.UI.Xaml.dll");
SystemDllAssemblyLocation.Location = Path.Combine(path, "System.dll");
SystemAssemblyLocation.SystemAssemblyCache = assemblyCache;
options.targetplatform = corlib;
}
private static void SendLeaderBoardFailure()
{
#if LeaderBoard
var version = typeof(FoxtrotOptions).Assembly.GetName().Version;
LeaderBoard.LeaderBoardAPI.SendLeaderBoardFailure(LeaderBoard_RewriterId, version);
#endif
}
private static void SendLeaderBoardRewriterFeature(FoxtrotOptions options)
{
#if LeaderBoard
LeaderBoard.LeaderBoardAPI.SendLeaderBoardFeatureUse(LeaderBoardFeature(options));
#endif
}
private static void WriteReproFile(string[] args)
{
try
{
var file = new StreamWriter("repro.bat");
#if false
file.Write(@"c:\users\maf\cci1\foxtrot\driver\bin\debug\foxtrot.exe ");
foreach (var arg in args)
{
file.Write("\"{0}\" ", arg);
}
#else
file.Write(Environment.CommandLine.Replace("-repro", ""));
#endif
file.WriteLine(" %1 %2 %3 %4 %5");
file.Close();
}
catch
{
}
}
private static TypeNode GetPossiblyNestedType(AssemblyNode assem, string namespaceName, string className)
{
Contract.Requires(assem != null);
Contract.Requires(className != null);
var ns = Identifier.For(namespaceName);
string[] pieces = className.Split('.');
// Get outermost type
string outerMost = pieces[0];
TypeNode t = assem.GetType(ns, Identifier.For(outerMost));
if (t == null) return null;
for (int i = 1; i < pieces.Length; i++)
{
var piece = pieces[i];
t = t.GetNestedType(Identifier.For(piece));
if (t == null) return null;
}
return t;
}
private static void DisposeAssemblies(IEnumerable assemblies)
{
try
{
Contract.Assume(assemblies != null);
foreach (Module assembly in assemblies)
{
if (assembly != null)
{
assembly.Dispose();
}
}
}
catch
{
}
}
#if false
/// <summary>
/// Resolves assembly references based on the library paths specified.
/// Tries to resolve to ".dll" or ".exe". First found wins.
/// </summary>
/// <param name="assemblyReference">Reference to resolve.</param>
/// <param name="referencingModule">Referencing module.</param>
/// <returns>The resolved assembly node (null if not found).</returns>
private static AssemblyNode AssemblyReferenceResolution (AssemblyReference assemblyReference, Module referencingModule) {
AssemblyNode a = ProbeForAssembly(assemblyReference.Name, referencingModule.Directory, DllAndExeExt);
return a;
}
private static AssemblyNode ProbeForAssemblyWithExtension(string directory, string assemblyName, string[] exts)
{
do
{
var result = ProbeForAssemblyWithExtensionAtomic(directory, assemblyName, exts);
if (result != null) return result;
if (directory.EndsWith("CodeContracts")) return null;
// if directory is a profile directory, we need to look in parent directory too
if (directory.Contains("Profile") || directory.Contains("profile"))
{
try
{
var parent = Directory.GetParent(directory);
directory = parent.FullName;
}
catch
{
break;
}
}
else
{
break;
}
}
while (!String.IsNullOrWhiteSpace(directory));
return null;
}
private static AssemblyNode ProbeForAssemblyWithExtensionAtomic(string directory, string assemblyName, string[] exts)
{
foreach (string ext in exts)
{
bool tempDebugInfo = options.debug;
string fullName = Path.Combine(directory, assemblyName + ext);
LoadTracing("Attempting load from:");
LoadTracing(fullName);
if (File.Exists(fullName))
{
if (tempDebugInfo)
{
// Don't pass the debugInfo flag to GetAssembly unless the PDB file exists.
string pdbFullName;
if (ext == "")
{
pdbFullName = Path.Combine(directory, Path.GetFileNameWithoutExtension(assemblyName) + ".pdb");
}
else
{
pdbFullName = Path.Combine(directory, assemblyName + ".pdb");
}
if (!File.Exists(pdbFullName))
{
Trace.WriteLine(String.Format("Can not find PDB file. Debug info will not be available for assembly '{0}'.", assemblyName));
tempDebugInfo = false;
}
}
Trace.WriteLine(string.Format("Resolved assembly reference '{0}' to '{1}'. (Using directory {2})", assemblyName, fullName, directory));
var result = AssemblyNode.GetAssembly(
fullName, // path to assembly
TargetPlatform.StaticAssemblyCache, // global cache to use for assemblies
true, // doNotLockFile
tempDebugInfo, // getDebugInfo
true, // useGlobalCache
options.shortBranches, // preserveShortBranches
PostLoadExtractionHook
);
return result;
}
}
return null;
}
private static void LoadTracing(string msg)
{
if (options.verbose > 2)
{
Console.WriteLine("Trace: {0}", msg);
}
Trace.WriteLine(msg);
}
static string[] EmptyExt = new[] { "" };
static string[] DllExt = new[] { ".dll", ".winmd" };
static string[] DllAndExeExt = new[] { ".dll", ".winmd", ".exe" };
static string[] EmptyAndDllExt = new[] { "", ".dll", ".winmd" };
static string[] AllExt = new[] { "", ".dll", ".winmd", ".exe" };
private static AssemblyNode ProbeForAssembly (string assemblyName, string referencingModuleDirectory, string[] exts) {
AssemblyNode a = null;
try {
LoadTracing("Attempting to load");
LoadTracing(assemblyName);
// Location Priority (in decreasing order):
// 0. list of candidate full paths specified by client
// 1. list of directories specified by client
// 2. referencing Module's directory
// 3. directory original assembly was in
//
// Extension Priority (in decreasing order):
// dll, exe, (any others?)
// Check user-supplied candidate paths
LoadTracing("AssemblyResolver: Attempting user-supplied candidates.");
if (options.resolvedPaths != null)
{
foreach (string candidate in options.resolvedPaths)
{
var candidateAssemblyName = Path.GetFileNameWithoutExtension(candidate);
if (String.Compare(candidateAssemblyName, assemblyName, StringComparison.OrdinalIgnoreCase) != 0) continue;
if (File.Exists(candidate))
{
a = ProbeForAssemblyWithExtension("", candidate, EmptyExt);
break;
}
}
}
else
{
Trace.WriteLine("\tAssemblyResolver: No user-supplied resolvedPaths.");
}
if (a == null)
{
if (options.resolvedPaths != null)
{
Trace.WriteLine("\tAssemblyResolver: Did not find assembly in user-supplied resolvedPaths candidates.");
}
}
else
{
goto End;
}
// Check user-supplied search directories
LoadTracing("AssemblyResolver: Attempting user-supplied directories.");
if (options.libpaths != null)
{
foreach (string dir in options.libpaths)
{
a = ProbeForAssemblyWithExtension(dir, assemblyName, exts);
if (a != null)
break;
}
}
else
{
Trace.WriteLine("\tAssemblyResolver: No user-supplied directories.");
}
if (a == null)
{
if (options.libpaths != null)
{
Trace.WriteLine("\tAssemblyResolver: Did not find assembly in user-supplied directories.");
}
}
else
{
goto End;
}
// Check referencing module's directory
Trace.WriteLine("\tAssemblyResolver: Attempting referencing assembly's directory.");
if (referencingModuleDirectory != null) {
a = ProbeForAssemblyWithExtension(referencingModuleDirectory, assemblyName, exts);
}
else
{
Trace.WriteLine("\t\tAssemblyResolver: Referencing assembly's directory is null.");
}
if (a == null) {
if (referencingModuleDirectory != null) {
Trace.WriteLine("\tAssemblyResolver: Did not find assembly in referencing assembly's directory.");
}
} else {
goto End;
}
// Check input directory
Trace.WriteLine("\tAssemblyResolver: Attempting input directory.");
a = ProbeForAssemblyWithExtension("", assemblyName, exts);
if (a == null) {
Trace.WriteLine("\tAssemblyResolver: Did not find assembly in input directory.");
} else {
goto End;
}
End:
if (a == null)
{
Trace.WriteLine("AssemblyResolver: Unable to resolve reference. (It still might be found, e.g., in the GAC.)");
}
} catch (Exception e) {
Trace.WriteLine("AssemblyResolver: Exception occurred. Unable to resolve reference.");
Trace.WriteLine("Inner exception: " + e.ToString());
}
return a;
}
#endif
/// <summary>
/// Moves external resource files referenced in an assembly node to the specified path.
/// </summary>
/// <param name="assemblyNode">Assembly node containing the resource references.</param>
/// <param name="path">Directory to move the external files to.</param>
private static void MoveModuleResources(AssemblyNode assemblyNode, string directory)
{
Contract.Requires(assemblyNode != null);
for (int i = 0, n = assemblyNode.Resources == null ? 0 : assemblyNode.Resources.Count; i < n; i++)
{
Resource r = assemblyNode.Resources[i];
if (r.Data != null) continue; // not an external resource
if (r.DefiningModule == null) continue; // error? should have a defining module that represents the file
string newPath = Path.Combine(directory, r.Name);
if (!directory.Equals(r.DefiningModule.Directory, StringComparison.OrdinalIgnoreCase))
{
if (File.Exists(newPath))
{
Console.WriteLine("The file '" + newPath +
"' already exists, so is not being copied. Make sure this is okay!");
}
else
{
File.Copy(r.DefiningModule.Location, newPath);
}
}
r.DefiningModule.Location = newPath;
}
}
#if KAEL
private static void KaelsArchitecture(AssemblyNode assemblyNode) {
// Finish decompiling expressions where CCI left off.
new Abnormalizer().Visit(assemblyNode);
// Check and extract all inline foxtrot contracts and place them in the object model.
Checker checker = new Checker(new ContractNodes(assemblyNode));
bool errorFound = false;
checker.ErrorFound += delegate(System.CodeDom.Compiler.CompilerError error) {
if (!error.IsWarning || warningLevel > 0) {
Console.WriteLine(error.ToString());
}
errorFound |= !error.IsWarning;
};
checker.Visit(assemblyNode);
if (errorFound)
return;
if (verify) {
throw new NotImplementedException("Static verification is not yet implemented.");
}
// Write out the assembly, possibly injecting the runtime checks
if (rewrite || passthrough) {
// Reload the assembly to flush out the abnormalized contracts since the rewriter can't handle them yet.
assemblyNode = LoadAssembly();
if (!passthrough) {
// Rewrite the assembly in memory.
Rewriter rewriter = new Rewriter(new ContractNodes(assemblyNode));
rewriter.InlinePreconditions = false;
rewriter.InlinePostconditions = false;
rewriter.InlineInvariant = false;
rewriter.Verbose = verbose;
rewriter.Decompile = decompile;
rewriter.Visit(assemblyNode);
}
if (output == "same") {
// Save the rewritten assembly to a temporary location.
output = Path.Combine(Path.GetTempPath(), Path.GetFileName(assembly));
// Re-attach external file resources to the new output assembly.
MoveModuleResources(assemblyNode, output);
// Save the rewritten assembly.
assemblyNode.WriteModule(output, debug);
// Make a copy of the original assembly and PDB.
File.Delete(assembly + ".original");
File.Delete(Path.ChangeExtension(assembly, ".pdb") + ".original");
File.Move(assembly, assembly + ".original");
File.Move(Path.ChangeExtension(assembly, ".pdb"), Path.ChangeExtension(assembly, ".pdb") + ".original");
// Move the rewritten assembly and PDB to the original location.
File.Move(output, assembly);
File.Move(Path.ChangeExtension(output, ".pdb"), Path.ChangeExtension(assembly, ".pdb"));
} else {
// Re-attach external file resources to the new output assembly.
MoveModuleResources(assemblyNode, output);
// Save the rewritten assembly.
assemblyNode.WriteModule(output, debug);
}
}
}
#endif
private static void LogFileLoads(AssemblyNode assemblyNode)
{
if (options.verbose > 0 && assemblyNode != null)
{
Console.WriteLine("Trace: Assembly '{0}' loaded from '{1}'", assemblyNode.Name, assemblyNode.Location);
}
}
private static void PossiblyLoadOOB(AssemblyResolver resolver, AssemblyNode assemblyNode, string originalAssemblyName)
{
Contract.Requires(assemblyNode != null);
Contract.Requires(originalAssemblyName != null);
// Do NOT automatically attach an out-of-band contract to the main assembly being worked on,
// but only for the assemblies it references.
// That is because there might be a contract assembly X.Contracts for an assembly X that contains
// contracts and we don't want to be confused or get duplicate contracts if that contract assembly
// is found the next time X is rewritten.
// So attach the contract only if it is explicitly listed in the options
if (assemblyNode.Name.ToLower() == originalAssemblyName.ToLower())
{
assemblyNode.AssemblyReferenceResolution +=
new Module.AssemblyReferenceResolver(resolver.ResolveAssemblyReference);
LogFileLoads(assemblyNode);
return;
}
resolver.PostLoadHook(assemblyNode);
}
private static void PostLoadExtractionHook(AssemblyResolver resolver, AssemblyNode assemblyNode)
{
Contract.Requires(assemblyNode != null);
LogFileLoads(assemblyNode);
// If ends in ".Contracts", no need to do anything. Just return
if (assemblyNode.Name.EndsWith(".Contracts")) return;
// Possibly load OOB contract assembly for assemblyNode. If found, run extractor on the pair.
if (options.automaticallyLookForOOBs)
{
string contractFileName = Path.GetFileNameWithoutExtension(assemblyNode.Location) + ".Contracts";
// if (contractFileName != null)
{
AssemblyNode contractAssembly = resolver.ProbeForAssembly(contractFileName, assemblyNode.Directory, resolver.DllExt);
if (contractAssembly != null)
{
ContractNodes usedContractNodes;
Extractor.ExtractContracts(assemblyNode, contractAssembly, DefaultContractLibrary,
BackupContractLibrary, DefaultContractLibrary, out usedContractNodes, null, false);
}
}
}
else
{
// use only if specified
if (options.contracts != null)
{
foreach (var contractAssemblyName in options.contracts)
{
string contractFileName = Path.GetFileNameWithoutExtension(contractAssemblyName);
var assemblyName = assemblyNode.Name + ".Contracts";
if (contractFileName == assemblyName)
{
AssemblyNode contractAssembly = resolver.ProbeForAssembly(assemblyName, assemblyNode.Directory, resolver.DllExt);
if (contractAssembly != null)
{
ContractNodes usedContractNodes;
Extractor.ExtractContracts(assemblyNode, contractAssembly, DefaultContractLibrary,
BackupContractLibrary, DefaultContractLibrary, out usedContractNodes, null, false);
}
break; // only do the one
}
}
}
}
}
private static int PEVerify(string assemblyFile)
{
var path = Path.GetDirectoryName(assemblyFile);
var file = Path.GetFileName(assemblyFile);
if (file == "mscorlib.dll") return -1; // peverify returns 0 for mscorlib without verifying.
var oldCWD = Environment.CurrentDirectory;
if (string.IsNullOrEmpty(path)) path = oldCWD;
try
{
Environment.CurrentDirectory = path;
object winsdkfolder =
Registry.GetValue(
@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SDKs\Windows\v7.0A\WinSDK-NetFx40Tools",
"InstallationFolder", null);
if (winsdkfolder == null)
{
winsdkfolder = Registry.GetValue(@"HKEY_LOCAL_MACHINE\Software\Microsoft\Microsoft SDKs\Windows",
"CurrentInstallFolder", null);
}
string peVerifyPath = null;
if (winsdkfolder != null)
{
peVerifyPath = (string) winsdkfolder + @"\peverify.exe";
if (!File.Exists(peVerifyPath))
{
peVerifyPath = (string) winsdkfolder + @"\bin\peverify.exe";
}
if (!File.Exists(peVerifyPath))
{
peVerifyPath = null;
}
}
if (peVerifyPath == null)
{
peVerifyPath =
Environment.ExpandEnvironmentVariables(
@"%ProgramFiles%\Microsoft Visual Studio 8\Common7\IDE\PEVerify.exe");
}
if (String.IsNullOrEmpty(peVerifyPath) || !File.Exists(peVerifyPath))
{
return -2;
}
ProcessStartInfo i = new ProcessStartInfo(peVerifyPath, "/unique \"" + file + "\"");
i.RedirectStandardOutput = true;
i.UseShellExecute = false;
i.ErrorDialog = false;
i.CreateNoWindow = true;
using (Process p = Process.Start(i))
{
if (!(p.WaitForExit(10000))) return -1;
#if false
if (p.ExitCode != 0)
{
var s = p.StandardOutput.ReadToEnd();
Console.WriteLine("{0}", s);
}
#endif
return p.ExitCode;
}
}
catch
{
return -1;
}
finally
{
Environment.CurrentDirectory = oldCWD;
}
}
private static void MikesArchitecture(AssemblyResolver resolver, AssemblyNode assemblyNode,
ContractNodes contractNodes, ContractNodes backupContracts)
{
#if false
var originalsourceDir = Path.GetDirectoryName(assemblyNode.Location);
int oldPeVerifyCode = options.verify ? PEVerify(assemblyNode.Location, originalsourceDir) : -1;
#endif
// Check to see if the assembly has already been rewritten
if (!options.passthrough)
{
if (ContractNodes.IsAlreadyRewritten(assemblyNode))
{
if (!options.allowRewritten)
{
Console.WriteLine("Assembly '" + assemblyNode.Name +
"' has already been rewritten. I, your poor humble servant, cannot rewrite it. Instead I must give up without rewriting it. Help!");
}
return;
}
}
// Extract the contracts from the code (includes checking the contracts)
if (!options.passthrough)
{
string contractFileName = Path.GetFileNameWithoutExtension(assemblyNode.Location) + ".Contracts";
if (options.contracts == null || options.contracts.Count <= 0) contractFileName = null;
if (options.contracts != null &&
!options.contracts.Exists(
name => name.Equals(assemblyNode.Name + ".Contracts.dll", StringComparison.OrdinalIgnoreCase)))
contractFileName = null;
AssemblyNode contractAssembly = null;
if (contractFileName != null)
{
contractAssembly = resolver.ProbeForAssembly(contractFileName, assemblyNode.Directory,
resolver.DllExt);
}
ContractNodes usedContractNodes;
Extractor.ExtractContracts(assemblyNode, contractAssembly, contractNodes, backupContracts, contractNodes,
out usedContractNodes, options.EmitError, false);
// important to extract source before we perform any more traversals due to contract instantiation. Otherwise,
// we might get copies of contracts due to instantiation that have no source text yet.
// Extract the text from the sources (optional)
if (usedContractNodes != null && options.extractSourceText)
{
GenerateDocumentationFromPDB gd = new GenerateDocumentationFromPDB(contractNodes);
gd.VisitForDoc(assemblyNode);
}
// After all contracts have been extracted in assembly, do some post-extractor checks
// we run these even if no contracts were extracted due to checks having to do with overrides
var contractNodesForChecks = usedContractNodes != null ? usedContractNodes : contractNodes;
if (contractNodesForChecks != null)
{
PostExtractorChecker pec = new PostExtractorChecker(contractNodesForChecks, options.EmitError, false,
options.fSharp, options.IsLegacyModeAssembly, options.addInterfaceWrappersWhenNeeded,
options.level);
if (contractAssembly != null)
{
pec.VisitForPostCheck(contractAssembly);
}
else
{
pec.VisitForPostCheck(assemblyNode);
}
}
// don't really need to test, since if they are the same, the assignment doesn't change that
// but this is to emphasize that the nodes used in the AST by the extractor are different
// than what we thought we were using.
if (options.GetErrorCount() > 0)
{
// we are done.
// But first, report any metadata errors so they are not masked by the errors
CheckForMetaDataErrors(assemblyNode);
return;
}
}
// If we have metadata errors, cop out
{
#if false
for (int i = 0; i < assemblyNode.ModuleReferences.Count; i++)
{
Module m = assemblyNode.ModuleReferences[i].Module;
Console.WriteLine("Location for referenced module '{0}' is '{1}'", m.Name, m.Location);
}
#endif
if (CheckForMetaDataErrors(assemblyNode))
{
throw new Exception("Rewrite aborted due to metadata errors. Check output window");
}
for (int i = 0; i < assemblyNode.AssemblyReferences.Count; i++)
{
AssemblyNode aref = assemblyNode.AssemblyReferences[i].Assembly;
if (CheckForMetaDataErrors(aref))
{
throw new Exception("Rewrite aborted due to metadata errors. Check output window");
}
}
}
// Inject the contracts into the code (optional)
if (options.rewrite && !options.passthrough)
{
// Rewrite the assembly in memory.
ContractNodes cnForRuntime = null;
// make sure to use the correct contract nodes for runtime code generation. We may have Contractnodes pointing to microsoft.Contracts even though
// the code relies on mscorlib to provide the contracts. So make sure the code references the contract nodes first.
if (contractNodes != null && contractNodes.ContractClass != null &&
contractNodes.ContractClass.DeclaringModule != SystemTypes.SystemAssembly)
{
string assemblyNameContainingContracts = contractNodes.ContractClass.DeclaringModule.Name;
for (int i = 0; i < assemblyNode.AssemblyReferences.Count; i++)
{
if (assemblyNode.AssemblyReferences[i].Name == assemblyNameContainingContracts)
{
cnForRuntime = contractNodes;
break; // runtime actually references the contract library
}
}
}
if (cnForRuntime == null)
{
// try to grab the system assembly contracts
cnForRuntime = ContractNodes.GetContractNodes(SystemTypes.SystemAssembly, null);
}
if (cnForRuntime == null)
{
// Can happen if the assembly does not use contracts directly, but inherits them from some other place
// Use the normal contractNodes in this case (actually we should generate whatever we grab from ContractNodes)
cnForRuntime = contractNodes;
}
RuntimeContractMethods runtimeContracts =
new RuntimeContractMethods(userSpecifiedContractType,
cnForRuntime, assemblyNode, options.throwOnFailure, options.level, options.publicSurfaceOnly,
options.callSiteRequires,
options.recursionGuard, options.hideFromDebugger, options.IsLegacyModeAssembly);
Rewriter rewriter = new Rewriter(assemblyNode, runtimeContracts, options.EmitError,
options.inheritInvariants, options.skipQuantifiers);
rewriter.Verbose = 0 < options.verbose;
rewriter.Visit(assemblyNode);
}
//Console.WriteLine(">>>Finished Rewriting<<<");
// Set metadata version for target the same as for the source
TargetPlatform.TargetRuntimeVersion = assemblyNode.TargetRuntimeVersion;
// Write out the assembly (optional)
if (options.rewrite || options.passthrough)
{
bool updateInPlace = options.output == "same";
string pdbFile = Path.ChangeExtension(options.assembly, ".pdb");
bool pdbExists = File.Exists(pdbFile);
string backupAssembly = options.assembly + ".original";
string backupPDB = pdbFile + ".original";
if (updateInPlace)
{
// Write the rewritten assembly in a temporary location.
options.output = options.assembly;
MoveAssemblyFileAndPDB(options.output, pdbFile, pdbExists, backupAssembly, backupPDB);
}
// Write the assembly.
// Don't pass the debugInfo flag to WriteModule unless the PDB file exists.
assemblyNode.WriteModule(options.output, options.debug && pdbExists && options.writePDBFile);
string outputDir = updateInPlace
? Path.GetDirectoryName(options.assembly)
: Path.GetDirectoryName(options.output);
// Re-attach external file resources to the new output assembly.
MoveModuleResources(assemblyNode, outputDir);
#if false
if (oldPeVerifyCode == 0)
{
var newPeVerifyCode = PEVerify(assemblyNode.Location, originalsourceDir);
if (newPeVerifyCode > 0)
{
if (updateInPlace)
{
// move original back in place
MoveAssemblyFileAndPDB(backupAssembly, backupPDB, pdbExists, options.output, pdbFile);
}
throw new Exception("Rewrite failed to produce verifiable assembly");
}
else if (newPeVerifyCode == 0)
{
Console.WriteLine("rewriter output verified");
}
}
#endif
if (updateInPlace)
{
if (!options.keepOriginalFiles)
{
try
{
File.Delete(backupAssembly);
}
catch
{
// there are situations where the exe is still in use
}
if (options.debug && pdbExists && options.writePDBFile)
{
try
{
File.Delete(backupPDB);
}
catch
{
// I know this is stupid, but somehow on some machines we get an AccessError trying to delete the pdb.
// so we leave it in place.
}
}
}
}
}
}
private static void MoveAssemblyFileAndPDB(string sourceAssembly, string sourcePDB, bool pdbExists,
string targetAssembly, string targetPDB)
{
// delete targets
try
{
Contract.Assume(!String.IsNullOrEmpty(sourceAssembly));
Contract.Assume(!String.IsNullOrEmpty(targetAssembly));
File.Delete(targetAssembly);
if (options.debug && pdbExists && options.writePDBFile)
{
File.Delete(targetPDB);
}
}
catch
{
}
// move things to target
try
{
File.Move(sourceAssembly, targetAssembly);
if (options.debug && pdbExists && options.writePDBFile)
{
Contract.Assume(!String.IsNullOrEmpty(sourcePDB));
File.Move(sourcePDB, targetPDB);
}
}
catch
{
}
}
private static bool CheckForMetaDataErrors(AssemblyNode aref)
{
Contract.Requires(aref != null);
if (aref.MetadataImportWarnings != null && aref.MetadataImportWarnings.Count > 0)
{
Console.WriteLine("Assembly '{0}' from '{1}' was skipped due to non-critical warnings.", aref.Name, aref.Location);
foreach (Exception e in aref.MetadataImportWarnings)
{
Console.WriteLine("\t" + e.Message);
}
}
bool result = false;
if (aref.MetadataImportErrors != null && aref.MetadataImportErrors.Count > 0)
{
Console.WriteLine("Reading assembly '{0}' from '{1}' resulted in errors.", aref.Name, aref.Location);
foreach (Exception ex in aref.MetadataImportErrors)
{
Console.WriteLine("\t" + ex.Message);
result = true;
}
}
if (options.ignoreMetadataErrors)
{
return false;
}
return result;
}
}
}
| |
//for details on this class see my article 'The Helper Trinity' at http://www.codeproject.com/csharp/thehelpertrinity.asp
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using System.Text;
using SyNet.BindingHelpers;
namespace SyNet
{
using System;
/// <summary>
/// Provides helper methods for raising events.
/// </summary>
/// <remarks>
/// <para>
/// The <c>EventHelper</c> class provides methods that can be used to raise events. It avoids the need for explicitly
/// checking event sinks for <see langword="null"/> before raising the event.
/// </para>
/// </remarks>
/// <example>
/// The following example shows how a non-generic event can be raised:
/// <code>
/// public event EventHandler Changed;
///
/// protected void OnChanged()
/// {
/// EventHelper.Raise(Changed, this);
/// }
/// </code>
/// </example>
/// <example>
/// The following example shows how a non-generic event can be raised where the event type requires a specific
/// <c>EventArgs</c> subclass:
/// <code>
/// public event PropertyChangedEventHandler PropertyChanged;
///
/// protected void OnPropertyChanged(PropertyChangedEventArgs e)
/// {
/// EventHelper.Raise(PropertyChanged, this, e);
/// }
/// </code>
/// </example>
/// <example>
/// The following example shows how a generic event can be raised:
/// <code>
/// public event EventHandler<EventArgs> Changed;
///
/// protected void OnChanged()
/// {
/// EventHelper.Raise(Changed, this, EventArgs.Empty);
/// }
/// </code>
/// </example>
/// <example>
/// The following example shows how a generic event with custom event arguments can be raised:
/// <code>
/// public event EventHandler<MyEventArgs> MyEvent;
///
/// protected void OnMyEvent(MyEventArgs e)
/// {
/// EventHelper.Raise(MyEventArgs, this, e);
/// }
/// </code>
/// </example>
/// <example>
/// The following example raises a generic event, but does not create the event arguments unless there is at least one
/// handler for the event:
/// <code>
/// public event EventHandler<MyEventArgs> MyEvent;
///
/// protected void OnMyEvent(int someData)
/// {
/// EventHelper.Raise(MyEvent, this, delegate
/// {
/// return new MyEventArgs(someData);
/// });
/// }
/// </code>
/// </example>
public static class EventHelper
{
/// <summary>
/// Raises a non-generic event.
/// </summary>
/// <remarks>
/// This method raises the specified non-generic event and passes in <c>EventArgs.Empty</c> as the event arguments.
/// </remarks>
/// <param name="handler">
/// The event to be raised.
/// </param>
/// <param name="sender">
/// The sender of the event.
/// </param>
[SuppressMessage("Microsoft.Design", "CA1030", Justification = "False positive - the Raise method overloads are supposed to raise an event on behalf of a client, not on behalf of its declaring class.")]
[DebuggerHidden]
public static void Raise(EventHandler handler, object sender)
{
if (handler != null)
{
#if DEBUG
RaiseWithDiagnostics(handler, sender, EventArgs.Empty);
#else
handler(sender, EventArgs.Empty);
#endif
}
}
/// <summary>
/// Raises a non-generic event.
/// </summary>
/// <remarks>
/// This method can be used to raise a non-generic event that needs a specific <see cref="EventArgs"/> subclass as its
/// second parameter. This method assumes that <paramref name="handler"/> points to a method that conforms to the
/// standard .NET event signature. That is, it takes an <see cref="object"/> as its first parameter and an
/// <see cref="EventArgs"/> instance as its second.
/// </remarks>
/// <param name="handler">
/// The event handler.
/// </param>
/// <param name="sender">
/// The sender of the event.
/// </param>
/// <param name="e">
/// The arguments for the event.
/// </param>
/// <exception cref="TargetParameterCountException">
/// If <paramref name="handler"/> does not contain the correct number of arguments or contains arguments of the wrong
/// type or in the wrong order.
/// </exception>
[SuppressMessage("Microsoft.Design", "CA1030", Justification = "False positive - the Raise method overloads are supposed to raise an event on behalf of a client, not on behalf of its declaring class.")]
[DebuggerHidden]
public static void Raise(Delegate handler, object sender, EventArgs e)
{
if (handler != null)
{
#if DEBUG
RaiseWithDiagnostics(handler, sender, e);
#else
handler.DynamicInvoke(sender, e);
#endif
}
}
/// <summary>
/// Raises a generic event.
/// </summary>
/// <remarks>
/// This method raises a generic event, passing in the specified event arguments.
/// </remarks>
/// <typeparam name="T">
/// The event arguments type.
/// </typeparam>
/// <param name="handler">
/// The event to be raised.
/// </param>
/// <param name="sender">
/// The sender of the event.
/// </param>
/// <param name="e">
/// The arguments for the event.
/// </param>
[SuppressMessage("Microsoft.Design", "CA1030", Justification = "False positive - the Raise method overloads are supposed to raise an event on behalf of a client, not on behalf of its declaring class.")]
[DebuggerHidden]
public static void Raise<T>(EventHandler<T> handler, object sender, T e)
where T : EventArgs
{
if (handler != null)
{
#if DEBUG
RaiseWithDiagnostics(handler, sender, e);
#else
handler(sender, e);
#endif
}
}
/// <summary>
/// Raises a generic event, but does not create the event arguments unless there is at least one handler for the event.
/// </summary>
/// <typeparam name="T">
/// The event arguments type.
/// </typeparam>
/// <param name="handler">
/// The event to be raised.
/// </param>
/// <param name="sender">
/// The sender of the event.
/// </param>
/// <param name="createEventArguments">
/// The delegate to invoke when an event arguments instance is needed.
/// </param>
/// <exception cref="ArgumentNullException">
/// If <paramref name="createEventArguments"/> is <see langword="null"/>.
/// </exception>
[SuppressMessage("Microsoft.Design", "CA1030", Justification = "False positive - the Raise method overloads are supposed to raise an event on behalf of a client, not on behalf of its declaring class.")]
[DebuggerHidden]
public static void Raise<T>(EventHandler<T> handler, object sender, CreateEventArguments<T> createEventArguments)
where T : EventArgs
{
ArgumentHelper.AssertNotNull(createEventArguments, "createEventArguments");
if (handler != null)
{
#if DEBUG
RaiseWithDiagnostics(handler, sender, createEventArguments());
#else
handler(sender, createEventArguments());
#endif
}
}
#if DEBUG
/// <summary>
/// A method used by debug builds to raise events and log diagnostic information in the process.
/// </summary>
/// <remarks>
/// This method is only called in debug builds. It logs details about raised events and any exceptions thrown by event
/// handlers.
/// </remarks>
/// <param name="handler">
/// The event handler.
/// </param>
/// <param name="parameters">
/// Parameters to the event handler.
/// </param>
private static void RaiseWithDiagnostics(Delegate handler, params object[] parameters)
{
Debug.Assert(handler != null);
string threadName = System.Threading.Thread.CurrentThread.Name;
// Debug.WriteLine(string.Format("Event being raised by thread '{0}'.", threadName));
foreach (Delegate del in handler.GetInvocationList())
{
try
{
// Debug.WriteLine(string.Format(" Calling method '{0}.{1}'.", del.Method.DeclaringType.FullName, del.Method.Name));
del.DynamicInvoke(parameters);
}
catch (Exception ex)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine(" An exception occurred in the event handler:");
while (ex != null)
{
sb.Append(" ").AppendLine(ex.Message);
sb.AppendLine(ex.StackTrace);
ex = ex.InnerException;
if (ex != null)
{
sb.AppendLine("--- INNER EXCEPTION ---");
}
}
Debug.WriteLine(sb.ToString());
//the exception isn't swallowed - just logged
throw;
}
}
// Debug.WriteLine(string.Format("Finished raising event by thread '{0}'.", threadName));
}
#endif
/// <summary>
/// A handler used to create an event arguments instance for the
/// <see cref="Raise<T>(EventHandler<T>, object, CreateEventArguments<T>)"/> method.
/// </summary>
/// <remarks>
/// This delegate is invoked by the
/// <see cref="Raise<T>(EventHandler<T>, object, CreateEventArguments<T>)"/> method to create the
/// event arguments instance. The handler should create the instance and return it.
/// </remarks>
/// <typeparam name="T">
/// The event arguments type.
/// </typeparam>
/// <returns>
/// The event arguments instance.
/// </returns>
public delegate T CreateEventArguments<T>()
where T : EventArgs;
}
}
| |
namespace Mapack
{
using System;
/// <summary>LU decomposition of a rectangular matrix.</summary>
/// <remarks>
/// For an m-by-n matrix <c>A</c> with m >= n, the LU decomposition is an m-by-n
/// unit lower triangular matrix <c>L</c>, an n-by-n upper triangular matrix <c>U</c>,
/// and a permutation vector <c>piv</c> of length m so that <c>A(piv)=L*U</c>.
/// If m < n, then <c>L</c> is m-by-m and <c>U</c> is m-by-n.
/// The LU decompostion with pivoting always exists, even if the matrix is
/// singular, so the constructor will never fail. The primary use of the
/// LU decomposition is in the solution of square systems of simultaneous
/// linear equations. This will fail if <see cref="NonSingular"/> returns <see langword="false"/>.
/// </remarks>
public class LuDecomposition
{
private Matrix LU;
private int pivotSign;
private int[] pivotVector;
/// <summary>Construct a LU decomposition.</summary>
public LuDecomposition(Matrix value)
{
if (value == null)
{
throw new ArgumentNullException("value");
}
this.LU = (Matrix) value.Clone();
double[][] lu = LU.Array;
int rows = value.Rows;
int columns = value.Columns;
pivotVector = new int[rows];
for (int i = 0; i < rows; i++)
{
pivotVector[i] = i;
}
pivotSign = 1;
double[] LUrowi;
double[] LUcolj = new double[rows];
// Outer loop.
for (int j = 0; j < columns; j++)
{
// Make a copy of the j-th column to localize references.
for (int i = 0; i < rows; i++)
{
LUcolj[i] = lu[i][j];
}
// Apply previous transformations.
for (int i = 0; i < rows; i++)
{
LUrowi = lu[i];
// Most of the time is spent in the following dot product.
int kmax = Math.Min(i,j);
double s = 0.0;
for (int k = 0; k < kmax; k++)
{
s += LUrowi[k]*LUcolj[k];
}
LUrowi[j] = LUcolj[i] -= s;
}
// Find pivot and exchange if necessary.
int p = j;
for (int i = j+1; i < rows; i++)
{
if (Math.Abs(LUcolj[i]) > Math.Abs(LUcolj[p]))
{
p = i;
}
}
if (p != j)
{
for (int k = 0; k < columns; k++)
{
double t = lu[p][k];
lu[p][k] = lu[j][k];
lu[j][k] = t;
}
int v = pivotVector[p];
pivotVector[p] = pivotVector[j];
pivotVector[j] = v;
pivotSign = - pivotSign;
}
// Compute multipliers.
if (j < rows & lu[j][j] != 0.0)
{
for (int i = j+1; i < rows; i++)
{
lu[i][j] /= lu[j][j];
}
}
}
}
/// <summary>Returns if the matrix is non-singular.</summary>
public bool NonSingular
{
get
{
for (int j = 0; j < LU.Columns; j++)
if (LU[j, j] == 0)
return false;
return true;
}
}
/// <summary>Returns the determinant of the matrix.</summary>
public double Determinant
{
get
{
if (LU.Rows != LU.Columns) throw new ArgumentException("Matrix must be square.");
double determinant = (double) pivotSign;
for (int j = 0; j < LU.Columns; j++)
determinant *= LU[j, j];
return determinant;
}
}
/// <summary>Returns the lower triangular factor <c>L</c> with <c>A=LU</c>.</summary>
public Matrix LowerTriangularFactor
{
get
{
int rows = LU.Rows;
int columns = LU.Columns;
Matrix X = new Matrix(rows, columns);
for (int i = 0; i < rows; i++)
for (int j = 0; j < columns; j++)
if (i > j)
X[i,j] = LU[i,j];
else if (i == j)
X[i,j] = 1.0;
else
X[i,j] = 0.0;
return X;
}
}
/// <summary>Returns the lower triangular factor <c>L</c> with <c>A=LU</c>.</summary>
public Matrix UpperTriangularFactor
{
get
{
int rows = LU.Rows;
int columns = LU.Columns;
Matrix X = new Matrix(rows, columns);
for (int i = 0; i < rows; i++)
for (int j = 0; j < columns; j++)
if (i <= j)
X[i,j] = LU[i,j];
else
X[i,j] = 0.0;
return X;
}
}
/// <summary>Returns the pivot permuation vector.</summary>
public double[] PivotPermutationVector
{
get
{
int rows = LU.Rows;
double[] p = new double[rows];
for (int i = 0; i < rows; i++)
{
p[i] = (double) this.pivotVector[i];
}
return p;
}
}
/// <summary>Solves a set of equation systems of type <c>A * X = B</c>.</summary>
/// <param name="value">Right hand side matrix with as many rows as <c>A</c> and any number of columns.</param>
/// <returns>Matrix <c>X</c> so that <c>L * U * X = B</c>.</returns>
public Matrix Solve(Matrix value)
{
if (value == null)
{
throw new ArgumentNullException("value");
}
if (value.Rows != this.LU.Rows)
{
throw new ArgumentException("Invalid matrix dimensions.", "value");
}
if (!this.NonSingular)
{
throw new InvalidOperationException("Matrix is singular");
}
// Copy right hand side with pivoting
int count = value.Columns;
Matrix X = value.Submatrix(pivotVector, 0, count-1);
int rows = LU.Rows;
int columns = LU.Columns;
double[][] lu = LU.Array;
// Solve L*Y = B(piv,:)
for (int k = 0; k < columns; k++)
{
for (int i = k + 1; i < columns; i++)
{
for (int j = 0; j < count; j++)
{
X[i,j] -= X[k,j] * lu[i][k];
}
}
}
// Solve U*X = Y;
for (int k = columns - 1; k >= 0; k--)
{
for (int j = 0; j < count; j++)
{
X[k,j] /= lu[k][k];
}
for (int i = 0; i < k; i++)
{
for (int j = 0; j < count; j++)
{
X[i,j] -= X[k,j] * lu[i][k];
}
}
}
return X;
}
}
}
| |
// 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.Binary;
using System.Collections;
using System.Diagnostics;
using System.Reflection;
using System.Text;
namespace System.Security.Cryptography
{
internal static class XmlKeyHelper
{
internal static ParseState ParseDocument(string xmlString)
{
if (xmlString == null)
{
throw new ArgumentNullException(nameof(xmlString));
}
try
{
return ParseState.ParseDocument(xmlString);
}
catch (Exception e)
{
throw new CryptographicException(SR.Cryptography_FromXmlParseError, e);
}
}
internal static bool HasElement(ref ParseState state, string name)
{
return state.HasElement(name);
}
internal static byte[] ReadCryptoBinary(ref ParseState state, string name, int sizeHint = -1)
{
string value = state.GetValue(name);
if (value == null)
{
return null;
}
if (value.Length == 0)
{
return Array.Empty<byte>();
}
if (sizeHint < 0)
{
return Convert.FromBase64String(value);
}
byte[] ret = new byte[sizeHint];
if (Convert.TryFromBase64Chars(value.AsSpan(), ret, out int written))
{
if (written == sizeHint)
{
return ret;
}
int shift = sizeHint - written;
Buffer.BlockCopy(ret, 0, ret, shift, written);
ret.AsSpan(0, shift).Clear();
return ret;
}
// It didn't fit, so let FromBase64String figure out how big it should be.
// This is almost certainly going to result in throwing from ImportParameters,
// but that's where the exception belongs.
//
// Alternatively, this is where we get the exception that the base64 value was
// corrupt.
return Convert.FromBase64String(value);
}
internal static int ReadCryptoBinaryInt32(byte[] buf)
{
Debug.Assert(buf != null);
int val = 0;
int idx = Math.Max(0, buf.Length - sizeof(int));
// This is like BinaryPrimitives.ReadBigEndianInt32, except it works
// on trimmed inputs and skips to the end.
//
// This is compatible with what .NET Framework does (Utils.ConvertByteArrayToInt)
for (; idx < buf.Length; idx++)
{
val <<= 8;
val |= buf[idx];
}
return val;
}
internal static void WriteCryptoBinary(string name, int value, StringBuilder builder)
{
// NetFX compat
if (value == 0)
{
Span<byte> single = stackalloc byte[1];
single[0] = 0;
WriteCryptoBinary(name, single, builder);
return;
}
Span<byte> valBuf = stackalloc byte[sizeof(int)];
BinaryPrimitives.WriteInt32BigEndian(valBuf, value);
// NetFX does write the counter value as CryptoBinary, so do the leading-byte trim here.
int start = 0;
// Guaranteed not to go out of bounds by the == 0 check above.
while (valBuf[start] == 0)
{
start++;
}
WriteCryptoBinary(name, valBuf.Slice(start, valBuf.Length - start), builder);
}
internal static void WriteCryptoBinary(string name, ReadOnlySpan<byte> value, StringBuilder builder)
{
Debug.Assert(name.Length > 0);
Debug.Assert(value.Length > 0);
Debug.Assert(builder != null);
builder.Append('<');
builder.Append(name);
builder.Append('>');
int offset = 0;
int length = value.Length;
// If we wanted to produce a ds:CryptoBinary instead of an xml:base64Binary,
// we'd skip all leading zeroes (increase offset, decrease length) before moving on
const int StackChars = 256;
const int ByteLimit = StackChars / 4 * 3;
Span<char> base64 = stackalloc char[StackChars];
while (length > 0)
{
int localLength = Math.Min(ByteLimit, length);
if (!Convert.TryToBase64Chars(value.Slice(offset, localLength), base64, out int written))
{
Debug.Fail($"Convert.TryToBase64Chars failed with {localLength} bytes to {StackChars} chars");
throw new CryptographicException();
}
builder.Append(base64.Slice(0, written));
length -= localLength;
offset += localLength;
}
builder.Append('<');
builder.Append('/');
builder.Append(name);
builder.Append('>');
}
internal struct ParseState
{
private IEnumerable _enumerable;
private IEnumerator _enumerator;
private int _index;
internal static ParseState ParseDocument(string xmlString)
{
object rootElement = Functions.ParseDocument(xmlString);
return new ParseState
{
_enumerable = Functions.GetElements(rootElement),
_enumerator = null,
_index = -1,
};
}
internal bool HasElement(string localName)
{
string value = GetValue(localName);
bool ret = value != null;
if (ret)
{
// Make it so that if GetValue is called on
// this name it'll advance into it correctly.
_index--;
}
return ret;
}
internal string GetValue(string localName)
{
if (_enumerable == null)
{
return null;
}
if (_enumerator == null)
{
_enumerator = _enumerable.GetEnumerator();
}
int origIdx = _index;
int idx = origIdx;
if (!_enumerator.MoveNext())
{
idx = -1;
_enumerator = _enumerable.GetEnumerator();
if (!_enumerator.MoveNext())
{
_enumerable = null;
return null;
}
}
idx++;
while (idx != origIdx)
{
string curName = Functions.GetLocalName(_enumerator.Current);
if (localName == curName)
{
_index = idx;
return Functions.GetValue(_enumerator.Current);
}
if (!_enumerator.MoveNext())
{
idx = -1;
if (origIdx < 0)
{
_enumerator = null;
return null;
}
_enumerator = _enumerable.GetEnumerator();
if (!_enumerator.MoveNext())
{
Debug.Fail("Original enumerator had elements, new one does not");
_enumerable = null;
return null;
}
}
idx++;
}
return null;
}
private static class Functions
{
private static readonly Type s_xDocument = Type.GetType("System.Xml.Linq.XDocument, System.Private.Xml.Linq, Version=4.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51");
private static readonly Func<string, object> s_xDocumentCreate =
(Func<string, object>)s_xDocument.GetMethod(
"Parse",
BindingFlags.Static | BindingFlags.Public,
null,
new[] { typeof(string) },
null).CreateDelegate(typeof(Func<string, object>));
private static readonly PropertyInfo s_docRootProperty = s_xDocument.GetProperty("Root");
private static readonly MethodInfo s_getElementsMethod = s_docRootProperty.PropertyType.GetMethod(
"Elements",
BindingFlags.Instance | BindingFlags.Public,
null,
Array.Empty<Type>(),
null);
private static readonly PropertyInfo s_elementNameProperty = s_docRootProperty.PropertyType.GetProperty("Name");
private static readonly PropertyInfo s_nameNameProperty = s_elementNameProperty.PropertyType.GetProperty("LocalName");
private static readonly PropertyInfo s_elementValueProperty = s_docRootProperty.PropertyType.GetProperty("Value");
internal static object ParseDocument(string xmlString) =>
s_docRootProperty.GetValue(s_xDocumentCreate(xmlString));
internal static IEnumerable GetElements(object element) =>
(IEnumerable)s_getElementsMethod.Invoke(element, Array.Empty<object>());
internal static string GetLocalName(object element) =>
(string)s_nameNameProperty.GetValue(s_elementNameProperty.GetValue(element));
internal static string GetValue(object element) =>
(string)s_elementValueProperty.GetValue(element);
}
}
}
}
| |
/*
* Color.cs - Implementation of the "System.Drawing.Color" class.
*
* Copyright (C) 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.Drawing
{
using System.Runtime.InteropServices;
using System.ComponentModel;
using System.Drawing.Design;
using System.Drawing.Toolkit;
using System.Text;
#if !ECMA_COMPAT
[Serializable]
[ComVisible(true)]
#endif
#if CONFIG_COMPONENT_MODEL_DESIGN
[TypeConverter(typeof(ColorConverter))]
[Editor("System.Drawing.Design.ColorEditor, System.Drawing.Design",
typeof(UITypeEditor))]
#endif
public struct Color
{
// The empty color.
public static readonly Color Empty;
// Internal state.
private uint value;
private short knownColor;
private bool resolved;
// Constructors.
internal Color(KnownColor knownColor)
{
this.value = 0;
this.knownColor = (short)knownColor;
this.resolved = false;
}
private Color(uint value)
{
this.value = value;
this.knownColor = (short)0;
this.resolved = true;
}
// Get the color components.
public byte R
{
get
{
if(!resolved)
{
Resolve();
}
return (byte)(value >> 16);
}
}
public byte G
{
get
{
if(!resolved)
{
Resolve();
}
return (byte)(value >> 8);
}
}
public byte B
{
get
{
if(!resolved)
{
Resolve();
}
return (byte)value;
}
}
public byte A
{
get
{
if(!resolved)
{
Resolve();
}
return (byte)(value >> 24);
}
}
// Determine if this is the empty color value.
public bool IsEmpty
{
get
{
return (knownColor == 0 && !resolved);
}
}
// Determine if this is a known color value.
public bool IsKnownColor
{
get
{
return (knownColor != 0);
}
}
// Determine if this is a named color value.
public bool IsNamedColor
{
get
{
// Because we only support known color names,
// this is identical in behaviour to "IsKnownColor".
return (knownColor != 0);
}
}
// Determine if this is a system color value.
public bool IsSystemColor
{
get
{
return (knownColor >= (int)(KnownColor.ActiveBorder) &&
knownColor <= (int)(KnownColor.WindowText));
}
}
// Get the color's name.
public String Name
{
get
{
if(knownColor != 0)
{
return ((KnownColor)knownColor).ToString();
}
else
{
return String.Format("{0:x}", value);
}
}
}
// Determine if this object is equal to another.
public override bool Equals(Object obj)
{
if(obj is Color)
{
Color other = (Color)obj;
if(other.knownColor != 0)
{
return (other.knownColor == knownColor);
}
else if(knownColor != 0)
{
return false;
}
else
{
return (other.value == value);
}
}
else
{
return false;
}
}
// Convert an ARGB value into a color.
public static Color FromArgb(int argb)
{
return new Color((uint)argb);
}
public static Color FromArgb(int alpha, Color baseColor)
{
if(alpha < 0 || alpha > 255)
{
throw new ArgumentException
(S._("Arg_ColorComponent"), "alpha");
}
if(!(baseColor.resolved))
{
baseColor.Resolve();
}
return new Color((baseColor.value & 0x00FFFFFF) |
(uint)(alpha << 24));
}
public static Color FromArgb(int red, int green, int blue)
{
if(red < 0 || red > 255)
{
throw new ArgumentException
(S._("Arg_ColorComponent"), "red");
}
if(green < 0 || green > 255)
{
throw new ArgumentException
(S._("Arg_ColorComponent"), "green");
}
if(blue < 0 || blue > 255)
{
throw new ArgumentException
(S._("Arg_ColorComponent"), "blue");
}
return new Color(((uint)((red << 16) | (green << 8) | blue)) |
0xFF000000);
}
public static Color FromArgb(int alpha, int red, int green, int blue)
{
if(alpha < 0 || alpha > 255)
{
throw new ArgumentException
(S._("Arg_ColorComponent"), "alpha");
}
if(red < 0 || red > 255)
{
throw new ArgumentException
(S._("Arg_ColorComponent"), "red");
}
if(green < 0 || green > 255)
{
throw new ArgumentException
(S._("Arg_ColorComponent"), "green");
}
if(blue < 0 || blue > 255)
{
throw new ArgumentException
(S._("Arg_ColorComponent"), "blue");
}
return new Color((uint)((alpha << 24) | (red << 16) |
(green << 8) | blue));
}
// Convert a known color value into a color value.
public static Color FromKnownColor(KnownColor color)
{
return new Color(color);
}
// Convert a color name into a color value.
public static Color FromName(String name)
{
try
{
KnownColor value;
value = (KnownColor)
(Enum.Parse(typeof(KnownColor), name, true));
return new Color(value);
}
catch(ArgumentException)
{
// Unknown color name.
return Empty;
}
}
// Get the hash code for this object.
public override int GetHashCode()
{
return (int)value;
}
// Get the HSV values from this color.
public float GetHue()
{
// Calculate the minimum and maximum components.
int red = R;
int green = G;
int blue = B;
if (red == green && green == blue)
return 0.0f;
int min, max;
min = red;
if(min > green)
{
min = green;
}
if(min > blue)
{
min = blue;
}
max = red;
if(max < green)
{
max = green;
}
if(max < blue)
{
max = blue;
}
float hue;
if(red == max)
{
hue = (float)(green - blue) / (float)(max - min);
}
else if(green == max)
{
hue = 2.0f + (float)(blue - red) / (float)(max - min);
}
else
{
hue = 4.0f + (float)(red - green) / (float)(max - min);
}
hue *= 60.0f;
if(hue < 0.0f)
{
hue += 360.0f;
}
return hue;
}
public float GetSaturation()
{
int red = R;
int green = G;
int blue = B;
int min, max;
min = red;
if(min > green)
{
min = green;
}
if(min > blue)
{
min = blue;
}
max = red;
if(max < green)
{
max = green;
}
if(max < blue)
{
max = blue;
}
if(max == min)
{
return 0.0f;
}
else
{
if (max + min < 256)
return (float)(max - min)/(float)(max + min);
else
return (float)(max - min) / (float)( 510 - max - min);
}
}
public float GetBrightness()
{
// The brightness is the average of the maximum and minimum of the
// components.
int red = R;
int min = R;
int green = G;
int blue = B;
if(red < green)
{
red = green;
}
if(red < blue)
{
red = blue;
}
if (min > green)
{
min = green;
}
if (min > blue)
{
min = blue;
}
return (float)(red + min) / 510.0f;
}
// Get the ARGB value for a color.
public int ToArgb()
{
if(!resolved)
{
Resolve();
}
return (int)value;
}
// Get the known color value within this structure.
public KnownColor ToKnownColor()
{
return (KnownColor)knownColor;
}
// Convert this object into a string.
public override String ToString()
{
StringBuilder builder = new StringBuilder();
builder.Append("Color [");
if(knownColor != 0)
{
builder.Append(((KnownColor)knownColor).ToString());
}
else
{
builder.Append("A=");
builder.Append(A);
builder.Append(", R=");
builder.Append(R);
builder.Append(", G=");
builder.Append(G);
builder.Append(", B=");
builder.Append(B);
}
builder.Append(']');
return builder.ToString();
}
// Equality and inequality testing.
public static bool operator==(Color left, Color right)
{
return left.Equals(right);
}
public static bool operator!=(Color left, Color right)
{
return !(left.Equals(right));
}
// Resolve a color to its ARGB value.
private void Resolve()
{
KnownColor known = (KnownColor)knownColor;
if(known >= KnownColor.ActiveBorder &&
known <= KnownColor.WindowText)
{
int rgb = ToolkitManager.Toolkit.ResolveSystemColor(known);
if(rgb != -1)
{
value = ((uint)rgb) | ((uint)0xFF000000);
// We don't set "resolved" to true, because the system
// color may change between now and the next call.
}
else
{
value = specificColors[((int)known)];
resolved = true;
}
}
else if(known >= KnownColor.Transparent &&
known <= KnownColor.YellowGreen)
{
// A known color that has a fixed value.
value = specificColors[((int)known)];
resolved = true;
}
}
// Builtin color table.
private static readonly uint[] specificColors = {
// Placeholder for KnownColor value of zero.
0x00000000,
// Special colors - may be overridden by profiles.
0xFFD4D0C8,
0xFF0A246A,
0xFFFFFFFF,
0xFF808080,
0xFFD4D0C8,
0xFF808080,
0xFF404040,
0xFFD4D0C8,
0xFFFFFFFF,
0xFF000000,
0xFF3A6EA5,
0xFF808080,
0xFF0A246A,
0xFFFFFFFF,
0xFF0000FF,
0xFFD4D0C8,
0xFF808080,
0xFFD4D0C8,
0xFFFFFFE1,
0xFF000000,
0xFFD4D0C8,
0xFF000000,
0xFFD4D0C8,
0xFFFFFFFF,
0xFF000000,
0xFF000000,
// Specific colors with fixed values.
0x00FFFFFF,
0xFFF0F8FF,
0xFFFAEBD7,
0xFF00FFFF,
0xFF7FFFD4,
0xFFF0FFFF,
0xFFF5F5DC,
0xFFFFE4C4,
0xFF000000,
0xFFFFEBCD,
0xFF0000FF,
0xFF8A2BE2,
0xFFA52A2A,
0xFFDEB887,
0xFF5F9EA0,
0xFF7FFF00,
0xFFD2691E,
0xFFFF7F50,
0xFF6495ED,
0xFFFFF8DC,
0xFFDC143C,
0xFF00FFFF,
0xFF00008B,
0xFF008B8B,
0xFFB8860B,
0xFFA9A9A9,
0xFF006400,
0xFFBDB76B,
0xFF8B008B,
0xFF556B2F,
0xFFFF8C00,
0xFF9932CC,
0xFF8B0000,
0xFFE9967A,
0xFF8FBC8B,
0xFF483D8B,
0xFF2F4F4F,
0xFF00CED1,
0xFF9400D3,
0xFFFF1493,
0xFF00BFFF,
0xFF696969,
0xFF1E90FF,
0xFFB22222,
0xFFFFFAF0,
0xFF228B22,
0xFFFF00FF,
0xFFDCDCDC,
0xFFF8F8FF,
0xFFFFD700,
0xFFDAA520,
0xFF808080,
0xFF008000,
0xFFADFF2F,
0xFFF0FFF0,
0xFFFF69B4,
0xFFCD5C5C,
0xFF4B0082,
0xFFFFFFF0,
0xFFF0E68C,
0xFFE6E6FA,
0xFFFFF0F5,
0xFF7CFC00,
0xFFFFFACD,
0xFFADD8E6,
0xFFF08080,
0xFFE0FFFF,
0xFFFAFAD2,
0xFFD3D3D3,
0xFF90EE90,
0xFFFFB6C1,
0xFFFFA07A,
0xFF20B2AA,
0xFF87CEFA,
0xFF778899,
0xFFB0C4DE,
0xFFFFFFE0,
0xFF00FF00,
0xFF32CD32,
0xFFFAF0E6,
0xFFFF00FF,
0xFF800000,
0xFF66CDAA,
0xFF0000CD,
0xFFBA55D3,
0xFF9370DB,
0xFF3CB371,
0xFF7B68EE,
0xFF00FA9A,
0xFF48D1CC,
0xFFC71585,
0xFF191970,
0xFFF5FFFA,
0xFFFFE4E1,
0xFFFFE4B5,
0xFFFFDEAD,
0xFF000080,
0xFFFDF5E6,
0xFF808000,
0xFF6B8E23,
0xFFFFA500,
0xFFFF4500,
0xFFDA70D6,
0xFFEEE8AA,
0xFF98FB98,
0xFFAFEEEE,
0xFFDB7093,
0xFFFFEFD5,
0xFFFFDAB9,
0xFFCD853F,
0xFFFFC0CB,
0xFFDDA0DD,
0xFFB0E0E6,
0xFF800080,
0xFFFF0000,
0xFFBC8F8F,
0xFF4169E1,
0xFF8B4513,
0xFFFA8072,
0xFFF4A460,
0xFF2E8B57,
0xFFFFF5EE,
0xFFA0522D,
0xFFC0C0C0,
0xFF87CEEB,
0xFF6A5ACD,
0xFF708090,
0xFFFFFAFA,
0xFF00FF7F,
0xFF4682B4,
0xFFD2B48C,
0xFF008080,
0xFFD8BFD8,
0xFFFF6347,
0xFF40E0D0,
0xFFEE82EE,
0xFFF5DEB3,
0xFFFFFFFF,
0xFFF5F5F5,
0xFFFFFF00,
0xFF9ACD32,
};
// Pre-defined colors as static properties.
public static Color Transparent
{
get
{
return new Color(KnownColor.Transparent);
}
}
public static Color AliceBlue
{
get
{
return new Color(KnownColor.AliceBlue);
}
}
public static Color AntiqueWhite
{
get
{
return new Color(KnownColor.AntiqueWhite);
}
}
public static Color Aqua
{
get
{
return new Color(KnownColor.Aqua);
}
}
public static Color Aquamarine
{
get
{
return new Color(KnownColor.Aquamarine);
}
}
public static Color Azure
{
get
{
return new Color(KnownColor.Azure);
}
}
public static Color Beige
{
get
{
return new Color(KnownColor.Beige);
}
}
public static Color Bisque
{
get
{
return new Color(KnownColor.Bisque);
}
}
public static Color Black
{
get
{
return new Color(KnownColor.Black);
}
}
public static Color BlanchedAlmond
{
get
{
return new Color(KnownColor.BlanchedAlmond);
}
}
public static Color Blue
{
get
{
return new Color(KnownColor.Blue);
}
}
public static Color BlueViolet
{
get
{
return new Color(KnownColor.BlueViolet);
}
}
public static Color Brown
{
get
{
return new Color(KnownColor.Brown);
}
}
public static Color BurlyWood
{
get
{
return new Color(KnownColor.BurlyWood);
}
}
public static Color CadetBlue
{
get
{
return new Color(KnownColor.CadetBlue);
}
}
public static Color Chartreuse
{
get
{
return new Color(KnownColor.Chartreuse);
}
}
public static Color Chocolate
{
get
{
return new Color(KnownColor.Chocolate);
}
}
public static Color Coral
{
get
{
return new Color(KnownColor.Coral);
}
}
public static Color CornflowerBlue
{
get
{
return new Color(KnownColor.CornflowerBlue);
}
}
public static Color Cornsilk
{
get
{
return new Color(KnownColor.Cornsilk);
}
}
public static Color Crimson
{
get
{
return new Color(KnownColor.Crimson);
}
}
public static Color Cyan
{
get
{
return new Color(KnownColor.Cyan);
}
}
public static Color DarkBlue
{
get
{
return new Color(KnownColor.DarkBlue);
}
}
public static Color DarkCyan
{
get
{
return new Color(KnownColor.DarkCyan);
}
}
public static Color DarkGoldenrod
{
get
{
return new Color(KnownColor.DarkGoldenrod);
}
}
public static Color DarkGray
{
get
{
return new Color(KnownColor.DarkGray);
}
}
public static Color DarkGreen
{
get
{
return new Color(KnownColor.DarkGreen);
}
}
public static Color DarkKhaki
{
get
{
return new Color(KnownColor.DarkKhaki);
}
}
public static Color DarkMagenta
{
get
{
return new Color(KnownColor.DarkMagenta);
}
}
public static Color DarkOliveGreen
{
get
{
return new Color(KnownColor.DarkOliveGreen);
}
}
public static Color DarkOrange
{
get
{
return new Color(KnownColor.DarkOrange);
}
}
public static Color DarkOrchid
{
get
{
return new Color(KnownColor.DarkOrchid);
}
}
public static Color DarkRed
{
get
{
return new Color(KnownColor.DarkRed);
}
}
public static Color DarkSalmon
{
get
{
return new Color(KnownColor.DarkSalmon);
}
}
public static Color DarkSeaGreen
{
get
{
return new Color(KnownColor.DarkSeaGreen);
}
}
public static Color DarkSlateBlue
{
get
{
return new Color(KnownColor.DarkSlateBlue);
}
}
public static Color DarkSlateGray
{
get
{
return new Color(KnownColor.DarkSlateGray);
}
}
public static Color DarkTurquoise
{
get
{
return new Color(KnownColor.DarkTurquoise);
}
}
public static Color DarkViolet
{
get
{
return new Color(KnownColor.DarkViolet);
}
}
public static Color DeepPink
{
get
{
return new Color(KnownColor.DeepPink);
}
}
public static Color DeepSkyBlue
{
get
{
return new Color(KnownColor.DeepSkyBlue);
}
}
public static Color DimGray
{
get
{
return new Color(KnownColor.DimGray);
}
}
public static Color DodgerBlue
{
get
{
return new Color(KnownColor.DodgerBlue);
}
}
public static Color Firebrick
{
get
{
return new Color(KnownColor.Firebrick);
}
}
public static Color FloralWhite
{
get
{
return new Color(KnownColor.FloralWhite);
}
}
public static Color ForestGreen
{
get
{
return new Color(KnownColor.ForestGreen);
}
}
public static Color Fuchsia
{
get
{
return new Color(KnownColor.Fuchsia);
}
}
public static Color Gainsboro
{
get
{
return new Color(KnownColor.Gainsboro);
}
}
public static Color GhostWhite
{
get
{
return new Color(KnownColor.GhostWhite);
}
}
public static Color Gold
{
get
{
return new Color(KnownColor.Gold);
}
}
public static Color Goldenrod
{
get
{
return new Color(KnownColor.Goldenrod);
}
}
public static Color Gray
{
get
{
return new Color(KnownColor.Gray);
}
}
public static Color Green
{
get
{
return new Color(KnownColor.Green);
}
}
public static Color GreenYellow
{
get
{
return new Color(KnownColor.GreenYellow);
}
}
public static Color Honeydew
{
get
{
return new Color(KnownColor.Honeydew);
}
}
public static Color HotPink
{
get
{
return new Color(KnownColor.HotPink);
}
}
public static Color IndianRed
{
get
{
return new Color(KnownColor.IndianRed);
}
}
public static Color Indigo
{
get
{
return new Color(KnownColor.Indigo);
}
}
public static Color Ivory
{
get
{
return new Color(KnownColor.Ivory);
}
}
public static Color Khaki
{
get
{
return new Color(KnownColor.Khaki);
}
}
public static Color Lavender
{
get
{
return new Color(KnownColor.Lavender);
}
}
public static Color LavenderBlush
{
get
{
return new Color(KnownColor.LavenderBlush);
}
}
public static Color LawnGreen
{
get
{
return new Color(KnownColor.LawnGreen);
}
}
public static Color LemonChiffon
{
get
{
return new Color(KnownColor.LemonChiffon);
}
}
public static Color LightBlue
{
get
{
return new Color(KnownColor.LightBlue);
}
}
public static Color LightCoral
{
get
{
return new Color(KnownColor.LightCoral);
}
}
public static Color LightCyan
{
get
{
return new Color(KnownColor.LightCyan);
}
}
public static Color LightGoldenrodYellow
{
get
{
return new Color(KnownColor.LightGoldenrodYellow);
}
}
public static Color LightGray
{
get
{
return new Color(KnownColor.LightGray);
}
}
public static Color LightGreen
{
get
{
return new Color(KnownColor.LightGreen);
}
}
public static Color LightPink
{
get
{
return new Color(KnownColor.LightPink);
}
}
public static Color LightSalmon
{
get
{
return new Color(KnownColor.LightSalmon);
}
}
public static Color LightSeaGreen
{
get
{
return new Color(KnownColor.LightSeaGreen);
}
}
public static Color LightSkyBlue
{
get
{
return new Color(KnownColor.LightSkyBlue);
}
}
public static Color LightSlateGray
{
get
{
return new Color(KnownColor.LightSlateGray);
}
}
public static Color LightSteelBlue
{
get
{
return new Color(KnownColor.LightSteelBlue);
}
}
public static Color LightYellow
{
get
{
return new Color(KnownColor.LightYellow);
}
}
public static Color Lime
{
get
{
return new Color(KnownColor.Lime);
}
}
public static Color LimeGreen
{
get
{
return new Color(KnownColor.LimeGreen);
}
}
public static Color Linen
{
get
{
return new Color(KnownColor.Linen);
}
}
public static Color Magenta
{
get
{
return new Color(KnownColor.Magenta);
}
}
public static Color Maroon
{
get
{
return new Color(KnownColor.Maroon);
}
}
public static Color MediumAquamarine
{
get
{
return new Color(KnownColor.MediumAquamarine);
}
}
public static Color MediumBlue
{
get
{
return new Color(KnownColor.MediumBlue);
}
}
public static Color MediumOrchid
{
get
{
return new Color(KnownColor.MediumOrchid);
}
}
public static Color MediumPurple
{
get
{
return new Color(KnownColor.MediumPurple);
}
}
public static Color MediumSeaGreen
{
get
{
return new Color(KnownColor.MediumSeaGreen);
}
}
public static Color MediumSlateBlue
{
get
{
return new Color(KnownColor.MediumSlateBlue);
}
}
public static Color MediumSpringGreen
{
get
{
return new Color(KnownColor.MediumSpringGreen);
}
}
public static Color MediumTurquoise
{
get
{
return new Color(KnownColor.MediumTurquoise);
}
}
public static Color MediumVioletRed
{
get
{
return new Color(KnownColor.MediumVioletRed);
}
}
public static Color MidnightBlue
{
get
{
return new Color(KnownColor.MidnightBlue);
}
}
public static Color MintCream
{
get
{
return new Color(KnownColor.MintCream);
}
}
public static Color MistyRose
{
get
{
return new Color(KnownColor.MistyRose);
}
}
public static Color Moccasin
{
get
{
return new Color(KnownColor.Moccasin);
}
}
public static Color NavajoWhite
{
get
{
return new Color(KnownColor.NavajoWhite);
}
}
public static Color Navy
{
get
{
return new Color(KnownColor.Navy);
}
}
public static Color OldLace
{
get
{
return new Color(KnownColor.OldLace);
}
}
public static Color Olive
{
get
{
return new Color(KnownColor.Olive);
}
}
public static Color OliveDrab
{
get
{
return new Color(KnownColor.OliveDrab);
}
}
public static Color Orange
{
get
{
return new Color(KnownColor.Orange);
}
}
public static Color OrangeRed
{
get
{
return new Color(KnownColor.OrangeRed);
}
}
public static Color Orchid
{
get
{
return new Color(KnownColor.Orchid);
}
}
public static Color PaleGoldenrod
{
get
{
return new Color(KnownColor.PaleGoldenrod);
}
}
public static Color PaleGreen
{
get
{
return new Color(KnownColor.PaleGreen);
}
}
public static Color PaleTurquoise
{
get
{
return new Color(KnownColor.PaleTurquoise);
}
}
public static Color PaleVioletRed
{
get
{
return new Color(KnownColor.PaleVioletRed);
}
}
public static Color PapayaWhip
{
get
{
return new Color(KnownColor.PapayaWhip);
}
}
public static Color PeachPuff
{
get
{
return new Color(KnownColor.PeachPuff);
}
}
public static Color Peru
{
get
{
return new Color(KnownColor.Peru);
}
}
public static Color Pink
{
get
{
return new Color(KnownColor.Pink);
}
}
public static Color Plum
{
get
{
return new Color(KnownColor.Plum);
}
}
public static Color PowderBlue
{
get
{
return new Color(KnownColor.PowderBlue);
}
}
public static Color Purple
{
get
{
return new Color(KnownColor.Purple);
}
}
public static Color Red
{
get
{
return new Color(KnownColor.Red);
}
}
public static Color RosyBrown
{
get
{
return new Color(KnownColor.RosyBrown);
}
}
public static Color RoyalBlue
{
get
{
return new Color(KnownColor.RoyalBlue);
}
}
public static Color SaddleBrown
{
get
{
return new Color(KnownColor.SaddleBrown);
}
}
public static Color Salmon
{
get
{
return new Color(KnownColor.Salmon);
}
}
public static Color SandyBrown
{
get
{
return new Color(KnownColor.SandyBrown);
}
}
public static Color SeaGreen
{
get
{
return new Color(KnownColor.SeaGreen);
}
}
public static Color SeaShell
{
get
{
return new Color(KnownColor.SeaShell);
}
}
public static Color Sienna
{
get
{
return new Color(KnownColor.Sienna);
}
}
public static Color Silver
{
get
{
return new Color(KnownColor.Silver);
}
}
public static Color SkyBlue
{
get
{
return new Color(KnownColor.SkyBlue);
}
}
public static Color SlateBlue
{
get
{
return new Color(KnownColor.SlateBlue);
}
}
public static Color SlateGray
{
get
{
return new Color(KnownColor.SlateGray);
}
}
public static Color Snow
{
get
{
return new Color(KnownColor.Snow);
}
}
public static Color SpringGreen
{
get
{
return new Color(KnownColor.SpringGreen);
}
}
public static Color SteelBlue
{
get
{
return new Color(KnownColor.SteelBlue);
}
}
public static Color Tan
{
get
{
return new Color(KnownColor.Tan);
}
}
public static Color Teal
{
get
{
return new Color(KnownColor.Teal);
}
}
public static Color Thistle
{
get
{
return new Color(KnownColor.Thistle);
}
}
public static Color Tomato
{
get
{
return new Color(KnownColor.Tomato);
}
}
public static Color Turquoise
{
get
{
return new Color(KnownColor.Turquoise);
}
}
public static Color Violet
{
get
{
return new Color(KnownColor.Violet);
}
}
public static Color Wheat
{
get
{
return new Color(KnownColor.Wheat);
}
}
public static Color White
{
get
{
return new Color(KnownColor.White);
}
}
public static Color WhiteSmoke
{
get
{
return new Color(KnownColor.WhiteSmoke);
}
}
public static Color Yellow
{
get
{
return new Color(KnownColor.Yellow);
}
}
public static Color YellowGreen
{
get
{
return new Color(KnownColor.YellowGreen);
}
}
}; // struct Color
}; // namespace System.Drawing
| |
using System;
using System.IO;
using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Security;
namespace Org.BouncyCastle.Crypto.Tls
{
/// <summary>
/// TLS 1.0 DH key exchange.
/// </summary>
internal class TlsDHKeyExchange
: TlsKeyExchange
{
protected TlsClientContext context;
protected KeyExchangeAlgorithm keyExchange;
protected TlsSigner tlsSigner;
protected AsymmetricKeyParameter serverPublicKey = null;
protected DHPublicKeyParameters dhAgreeServerPublicKey = null;
protected TlsAgreementCredentials agreementCredentials;
protected DHPrivateKeyParameters dhAgreeClientPrivateKey = null;
internal TlsDHKeyExchange(TlsClientContext context, KeyExchangeAlgorithm keyExchange)
{
switch (keyExchange)
{
case KeyExchangeAlgorithm.DH_RSA:
case KeyExchangeAlgorithm.DH_DSS:
this.tlsSigner = null;
break;
case KeyExchangeAlgorithm.DHE_RSA:
this.tlsSigner = new TlsRsaSigner();
break;
case KeyExchangeAlgorithm.DHE_DSS:
this.tlsSigner = new TlsDssSigner();
break;
default:
throw new ArgumentException("unsupported key exchange algorithm", "keyExchange");
}
this.context = context;
this.keyExchange = keyExchange;
}
public virtual void SkipServerCertificate()
{
throw new TlsFatalAlert(AlertDescription.unexpected_message);
}
public virtual void ProcessServerCertificate(Certificate serverCertificate)
{
X509CertificateStructure x509Cert = serverCertificate.certs[0];
SubjectPublicKeyInfo keyInfo = x509Cert.SubjectPublicKeyInfo;
try
{
this.serverPublicKey = PublicKeyFactory.CreateKey(keyInfo);
}
catch (Exception)
{
throw new TlsFatalAlert(AlertDescription.unsupported_certificate);
}
if (tlsSigner == null)
{
try
{
this.dhAgreeServerPublicKey = ValidateDHPublicKey((DHPublicKeyParameters)this.serverPublicKey);
}
catch (InvalidCastException)
{
throw new TlsFatalAlert(AlertDescription.certificate_unknown);
}
TlsUtilities.ValidateKeyUsage(x509Cert, KeyUsage.KeyAgreement);
}
else
{
if (!tlsSigner.IsValidPublicKey(this.serverPublicKey))
{
throw new TlsFatalAlert(AlertDescription.certificate_unknown);
}
TlsUtilities.ValidateKeyUsage(x509Cert, KeyUsage.DigitalSignature);
}
// TODO
/*
* Perform various checks per RFC2246 7.4.2: "Unless otherwise specified, the
* signing algorithm for the certificate must be the same as the algorithm for the
* certificate key."
*/
}
public virtual void SkipServerKeyExchange()
{
// OK
}
public virtual void ProcessServerKeyExchange(Stream input)
{
throw new TlsFatalAlert(AlertDescription.unexpected_message);
}
public virtual void ValidateCertificateRequest(CertificateRequest certificateRequest)
{
ClientCertificateType[] types = certificateRequest.CertificateTypes;
foreach (ClientCertificateType type in types)
{
switch (type)
{
case ClientCertificateType.rsa_sign:
case ClientCertificateType.dss_sign:
case ClientCertificateType.rsa_fixed_dh:
case ClientCertificateType.dss_fixed_dh:
case ClientCertificateType.ecdsa_sign:
break;
default:
throw new TlsFatalAlert(AlertDescription.illegal_parameter);
}
}
}
public virtual void SkipClientCredentials()
{
this.agreementCredentials = null;
}
public virtual void ProcessClientCredentials(TlsCredentials clientCredentials)
{
if (clientCredentials is TlsAgreementCredentials)
{
// TODO Validate client cert has matching parameters (see 'areCompatibleParameters')?
this.agreementCredentials = (TlsAgreementCredentials)clientCredentials;
}
else if (clientCredentials is TlsSignerCredentials)
{
// OK
}
else
{
throw new TlsFatalAlert(AlertDescription.internal_error);
}
}
public virtual void GenerateClientKeyExchange(Stream output)
{
/*
* RFC 2246 7.4.7.2 If the client certificate already contains a suitable
* Diffie-Hellman key, then Yc is implicit and does not need to be sent again. In
* this case, the Client Key Exchange message will be sent, but will be empty.
*/
if (agreementCredentials == null)
{
GenerateEphemeralClientKeyExchange(dhAgreeServerPublicKey.Parameters, output);
}
}
public virtual byte[] GeneratePremasterSecret()
{
if (agreementCredentials != null)
{
return agreementCredentials.GenerateAgreement(dhAgreeServerPublicKey);
}
return CalculateDHBasicAgreement(dhAgreeServerPublicKey, dhAgreeClientPrivateKey);
}
protected virtual bool AreCompatibleParameters(DHParameters a, DHParameters b)
{
return a.P.Equals(b.P) && a.G.Equals(b.G);
}
protected virtual byte[] CalculateDHBasicAgreement(DHPublicKeyParameters publicKey,
DHPrivateKeyParameters privateKey)
{
return TlsDHUtilities.CalculateDHBasicAgreement(publicKey, privateKey);
}
protected virtual AsymmetricCipherKeyPair GenerateDHKeyPair(DHParameters dhParams)
{
return TlsDHUtilities.GenerateDHKeyPair(context.SecureRandom, dhParams);
}
protected virtual void GenerateEphemeralClientKeyExchange(DHParameters dhParams, Stream output)
{
this.dhAgreeClientPrivateKey = TlsDHUtilities.GenerateEphemeralClientKeyExchange(
context.SecureRandom, dhParams, output);
}
protected virtual DHPublicKeyParameters ValidateDHPublicKey(DHPublicKeyParameters key)
{
return TlsDHUtilities.ValidateDHPublicKey(key);
}
}
}
| |
//
// 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.SiteRecovery;
using Microsoft.Azure.Management.SiteRecovery.Models;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.SiteRecovery
{
/// <summary>
/// Definition of Logical Network operations for the Site Recovery
/// extension.
/// </summary>
internal partial class LogicalNetworkOperations : IServiceOperations<SiteRecoveryManagementClient>, ILogicalNetworkOperations
{
/// <summary>
/// Initializes a new instance of the LogicalNetworkOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal LogicalNetworkOperations(SiteRecoveryManagementClient client)
{
this._client = client;
}
private SiteRecoveryManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.SiteRecovery.SiteRecoveryManagementClient.
/// </summary>
public SiteRecoveryManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Gets a VM logical network.
/// </summary>
/// <param name='fabricName'>
/// Required. Fabric unique name.
/// </param>
/// <param name='logicalNetworkName'>
/// Required. Network name.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the Logical Network object.
/// </returns>
public async Task<LogicalNetworkResponse> GetAsync(string fabricName, string logicalNetworkName, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken)
{
// Validate
if (fabricName == null)
{
throw new ArgumentNullException("fabricName");
}
if (logicalNetworkName == null)
{
throw new ArgumentNullException("logicalNetworkName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("fabricName", fabricName);
tracingParameters.Add("logicalNetworkName", logicalNetworkName);
tracingParameters.Add("customRequestHeaders", customRequestHeaders);
TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/Subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(this.Client.ResourceGroupName);
url = url + "/providers/";
url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
url = url + "/";
url = url + Uri.EscapeDataString(this.Client.ResourceType);
url = url + "/";
url = url + Uri.EscapeDataString(this.Client.ResourceName);
url = url + "/replicationFabrics/";
url = url + Uri.EscapeDataString(fabricName);
url = url + "/replicationLogicalNetworks/";
url = url + Uri.EscapeDataString(logicalNetworkName);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-11-10");
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
httpRequest.Headers.Add("Accept-Language", customRequestHeaders.Culture);
httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId);
httpRequest.Headers.Add("x-ms-version", "2015-01-01");
// 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
LogicalNetworkResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new LogicalNetworkResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
LogicalNetwork logicalNetworkInstance = new LogicalNetwork();
result.LogicalNetwork = logicalNetworkInstance;
JToken propertiesValue = responseDoc["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
LogicalNetworkProperties propertiesInstance = new LogicalNetworkProperties();
logicalNetworkInstance.Properties = propertiesInstance;
JToken friendlyNameValue = propertiesValue["friendlyName"];
if (friendlyNameValue != null && friendlyNameValue.Type != JTokenType.Null)
{
string friendlyNameInstance = ((string)friendlyNameValue);
propertiesInstance.FriendlyName = friendlyNameInstance;
}
JToken logicalNetworkDefinitionsStatusValue = propertiesValue["logicalNetworkDefinitionsStatus"];
if (logicalNetworkDefinitionsStatusValue != null && logicalNetworkDefinitionsStatusValue.Type != JTokenType.Null)
{
string logicalNetworkDefinitionsStatusInstance = ((string)logicalNetworkDefinitionsStatusValue);
propertiesInstance.LogicalNetworkDefinitionsStatus = logicalNetworkDefinitionsStatusInstance;
}
JToken networkVirtualizationStatusValue = propertiesValue["networkVirtualizationStatus"];
if (networkVirtualizationStatusValue != null && networkVirtualizationStatusValue.Type != JTokenType.Null)
{
string networkVirtualizationStatusInstance = ((string)networkVirtualizationStatusValue);
propertiesInstance.NetworkVirtualizationStatus = networkVirtualizationStatusInstance;
}
JToken logicalNetworkUsageValue = propertiesValue["logicalNetworkUsage"];
if (logicalNetworkUsageValue != null && logicalNetworkUsageValue.Type != JTokenType.Null)
{
string logicalNetworkUsageInstance = ((string)logicalNetworkUsageValue);
propertiesInstance.LogicalNetworkUsage = logicalNetworkUsageInstance;
}
}
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
logicalNetworkInstance.Id = idInstance;
}
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
logicalNetworkInstance.Name = nameInstance;
}
JToken typeValue = responseDoc["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
logicalNetworkInstance.Type = typeInstance;
}
JToken locationValue = responseDoc["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
logicalNetworkInstance.Location = locationInstance;
}
JToken tagsSequenceElement = ((JToken)responseDoc["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey = ((string)property.Name);
string tagsValue = ((string)property.Value);
logicalNetworkInstance.Tags.Add(tagsKey, tagsValue);
}
}
JToken clientRequestIdValue = responseDoc["ClientRequestId"];
if (clientRequestIdValue != null && clientRequestIdValue.Type != JTokenType.Null)
{
string clientRequestIdInstance = ((string)clientRequestIdValue);
result.ClientRequestId = clientRequestIdInstance;
}
JToken correlationRequestIdValue = responseDoc["CorrelationRequestId"];
if (correlationRequestIdValue != null && correlationRequestIdValue.Type != JTokenType.Null)
{
string correlationRequestIdInstance = ((string)correlationRequestIdValue);
result.CorrelationRequestId = correlationRequestIdInstance;
}
JToken dateValue = responseDoc["Date"];
if (dateValue != null && dateValue.Type != JTokenType.Null)
{
string dateInstance = ((string)dateValue);
result.Date = dateInstance;
}
JToken contentTypeValue = responseDoc["ContentType"];
if (contentTypeValue != null && contentTypeValue.Type != JTokenType.Null)
{
string contentTypeInstance = ((string)contentTypeValue);
result.ContentType = contentTypeInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Content != null && httpResponse.Content.Headers.Contains("Content-Type"))
{
result.ContentType = httpResponse.Content.Headers.GetValues("Content-Type").FirstOrDefault();
}
if (httpResponse.Headers.Contains("Date"))
{
result.Date = httpResponse.Headers.GetValues("Date").FirstOrDefault();
}
if (httpResponse.Headers.Contains("x-ms-client-request-id"))
{
result.ClientRequestId = httpResponse.Headers.GetValues("x-ms-client-request-id").FirstOrDefault();
}
if (httpResponse.Headers.Contains("x-ms-correlation-request-id"))
{
result.CorrelationRequestId = httpResponse.Headers.GetValues("x-ms-correlation-request-id").FirstOrDefault();
}
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>
/// Get list of Logical Networks.
/// </summary>
/// <param name='fabricName'>
/// Required. Fabric unique name.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the list of Logical Networks.
/// </returns>
public async Task<LogicalNetworksListResponse> ListAsync(string fabricName, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken)
{
// Validate
if (fabricName == null)
{
throw new ArgumentNullException("fabricName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("fabricName", fabricName);
tracingParameters.Add("customRequestHeaders", customRequestHeaders);
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(this.Client.ResourceGroupName);
url = url + "/providers/";
url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
url = url + "/";
url = url + Uri.EscapeDataString(this.Client.ResourceType);
url = url + "/";
url = url + Uri.EscapeDataString(this.Client.ResourceName);
url = url + "/replicationFabrics/";
url = url + Uri.EscapeDataString(fabricName);
url = url + "/replicationLogicalNetworks";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-11-10");
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
httpRequest.Headers.Add("Accept-Language", customRequestHeaders.Culture);
httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId);
httpRequest.Headers.Add("x-ms-version", "2015-01-01");
// 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
LogicalNetworksListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new LogicalNetworksListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
LogicalNetwork logicalNetworkInstance = new LogicalNetwork();
result.LogicalNetworks.Add(logicalNetworkInstance);
JToken propertiesValue = valueValue["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
LogicalNetworkProperties propertiesInstance = new LogicalNetworkProperties();
logicalNetworkInstance.Properties = propertiesInstance;
JToken friendlyNameValue = propertiesValue["friendlyName"];
if (friendlyNameValue != null && friendlyNameValue.Type != JTokenType.Null)
{
string friendlyNameInstance = ((string)friendlyNameValue);
propertiesInstance.FriendlyName = friendlyNameInstance;
}
JToken logicalNetworkDefinitionsStatusValue = propertiesValue["logicalNetworkDefinitionsStatus"];
if (logicalNetworkDefinitionsStatusValue != null && logicalNetworkDefinitionsStatusValue.Type != JTokenType.Null)
{
string logicalNetworkDefinitionsStatusInstance = ((string)logicalNetworkDefinitionsStatusValue);
propertiesInstance.LogicalNetworkDefinitionsStatus = logicalNetworkDefinitionsStatusInstance;
}
JToken networkVirtualizationStatusValue = propertiesValue["networkVirtualizationStatus"];
if (networkVirtualizationStatusValue != null && networkVirtualizationStatusValue.Type != JTokenType.Null)
{
string networkVirtualizationStatusInstance = ((string)networkVirtualizationStatusValue);
propertiesInstance.NetworkVirtualizationStatus = networkVirtualizationStatusInstance;
}
JToken logicalNetworkUsageValue = propertiesValue["logicalNetworkUsage"];
if (logicalNetworkUsageValue != null && logicalNetworkUsageValue.Type != JTokenType.Null)
{
string logicalNetworkUsageInstance = ((string)logicalNetworkUsageValue);
propertiesInstance.LogicalNetworkUsage = logicalNetworkUsageInstance;
}
}
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
logicalNetworkInstance.Id = idInstance;
}
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
logicalNetworkInstance.Name = nameInstance;
}
JToken typeValue = valueValue["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
logicalNetworkInstance.Type = typeInstance;
}
JToken locationValue = valueValue["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
logicalNetworkInstance.Location = locationInstance;
}
JToken tagsSequenceElement = ((JToken)valueValue["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey = ((string)property.Name);
string tagsValue = ((string)property.Value);
logicalNetworkInstance.Tags.Add(tagsKey, tagsValue);
}
}
}
}
JToken nextLinkValue = responseDoc["nextLink"];
if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
{
string nextLinkInstance = ((string)nextLinkValue);
result.NextLink = nextLinkInstance;
}
JToken clientRequestIdValue = responseDoc["ClientRequestId"];
if (clientRequestIdValue != null && clientRequestIdValue.Type != JTokenType.Null)
{
string clientRequestIdInstance = ((string)clientRequestIdValue);
result.ClientRequestId = clientRequestIdInstance;
}
JToken correlationRequestIdValue = responseDoc["CorrelationRequestId"];
if (correlationRequestIdValue != null && correlationRequestIdValue.Type != JTokenType.Null)
{
string correlationRequestIdInstance = ((string)correlationRequestIdValue);
result.CorrelationRequestId = correlationRequestIdInstance;
}
JToken dateValue = responseDoc["Date"];
if (dateValue != null && dateValue.Type != JTokenType.Null)
{
string dateInstance = ((string)dateValue);
result.Date = dateInstance;
}
JToken contentTypeValue = responseDoc["ContentType"];
if (contentTypeValue != null && contentTypeValue.Type != JTokenType.Null)
{
string contentTypeInstance = ((string)contentTypeValue);
result.ContentType = contentTypeInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Content != null && httpResponse.Content.Headers.Contains("Content-Type"))
{
result.ContentType = httpResponse.Content.Headers.GetValues("Content-Type").FirstOrDefault();
}
if (httpResponse.Headers.Contains("Date"))
{
result.Date = httpResponse.Headers.GetValues("Date").FirstOrDefault();
}
if (httpResponse.Headers.Contains("x-ms-client-request-id"))
{
result.ClientRequestId = httpResponse.Headers.GetValues("x-ms-client-request-id").FirstOrDefault();
}
if (httpResponse.Headers.Contains("x-ms-correlation-request-id"))
{
result.CorrelationRequestId = httpResponse.Headers.GetValues("x-ms-correlation-request-id").FirstOrDefault();
}
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();
}
}
}
}
}
| |
using System.Collections.Generic;
using System.Reflection.Metadata;
using Microsoft.CodeAnalysis;
using Wyam.Common.Documents;
namespace Wyam.CodeAnalysis
{
/// <summary>
/// Common metadata keys for code analysis modules.
/// </summary>
public static class CodeAnalysisKeys
{
// Note that if we ever introduce code analysis for other formats (such as Java or CSS), the metadata should be kept as similar as possible
/// <summary>
/// The name of the assembly for each input document. Used to group input documents by assembly (if provided). If this is
/// not provided for each input source document, then analysis that depends on both source files and assemblies may not
/// correctly bind symbols across multiple inputs.
/// </summary>
/// <type><see cref="string"/></type>
public const string AssemblyName = nameof(AssemblyName);
/// <summary>
/// By default only certain symbols are processed as part of the initial
/// result set(such as those that match the specified predicate). If this value is <c>true</c>, then this
/// symbol was part of the initial result set. If it is <c>false</c>, the symbol was lazily processed later
/// while fetching related symbols and may not contain the full set of metadata.
/// </summary>
/// <type><see cref="bool"/></type>
public const string IsResult = nameof(IsResult);
/// <summary>
/// A unique ID that identifies the symbol (can be used for generating folder paths, for example).
/// </summary>
/// <type><see cref="string"/></type>
public const string SymbolId = nameof(SymbolId);
/// <summary>
/// The Roslyn <c>ISymbol</c> from which this document is derived. If the document represents a namespace, this metadata might contain more than one
/// symbol since the namespaces documents consolidate same-named namespaces across input code and assemblies.
/// </summary>
/// <type><see cref="ISymbol"/> (or <see cref="IEnumerable{ISymbol}"/> if a namespace)</type>
public const string Symbol = nameof(Symbol);
/// <summary>
/// The name of the symbol, or an empty string if the symbol has no name (like the global namespace).
/// </summary>
/// <type><see cref="string"/></type>
public const string Name = nameof(Name);
/// <summary>
/// The full name of the symbol. For namespaces, this is the name of the namespace. For types, this includes all generic type parameters.
/// </summary>
/// <type><see cref="string"/></type>
public const string FullName = nameof(FullName);
/// <summary>
/// The qualified name of the symbol which includes all containing namespaces.
/// </summary>
/// <type><see cref="string"/></type>
public const string QualifiedName = nameof(QualifiedName);
/// <summary>
/// A display name for the symbol. For namespaces, this is the same as <see cref="QualifiedName"/>.
/// For types, this is the same as <see cref="FullName"/>.
/// </summary>
/// <type><see cref="string"/></type>
public const string DisplayName = nameof(DisplayName);
/// <summary>
/// This is the general kind of symbol. For example, the for a namespace this is "Namespace" and for a type this is "NamedType".
/// </summary>
/// <type><see cref="string"/></type>
public const string Kind = nameof(Kind);
/// <summary>
/// The more specific kind of the symbol ("Class", "Struct", etc.) This is the same as <c>Kind</c> if there is no more specific kind.
/// </summary>
/// <type><see cref="string"/></type>
public const string SpecificKind = nameof(SpecificKind);
/// <summary>
/// The document that represents the containing namespace (or null if this symbol is not nested).
/// </summary>
/// <type><see cref="IDocument"/></type>
public const string ContainingNamespace = nameof(ContainingNamespace);
/// <summary>
/// The document that represents the containing assembly (or null if this symbol is not from an assembly).
/// </summary>
/// <type><see cref="IDocument"/></type>
public const string ContainingAssembly = nameof(ContainingAssembly);
/// <summary>
/// Indicates if the symbol is static.
/// </summary>
/// <type><see cref="bool"/></type>
public const string IsStatic = nameof(IsStatic);
/// <summary>
/// Indicates if the symbol is abstract.
/// </summary>
/// <type><see cref="bool"/></type>
public const string IsAbstract = nameof(IsAbstract);
/// <summary>
/// Indicates if the symbol is virtual.
/// </summary>
/// <type><see cref="bool"/></type>
public const string IsVirtual = nameof(IsVirtual);
/// <summary>
/// Indicates if the symbol is an override.
/// </summary>
/// <type><see cref="bool"/></type>
public const string IsOverride = nameof(IsOverride);
/// <summary>
/// A unique ID that identifies the symbol for documentation purposes.
/// </summary>
/// <type><see cref="string"/></type>
public const string CommentId = nameof(CommentId);
/// <summary>
/// This is available for namespace and type symbols and contains a collection of the documents that represent all member types.
/// It only contains direct children (as opposed to all nested types).
/// </summary>
/// <type><c>IReadOnlyList<IDocument></c></type>
public const string MemberTypes = nameof(MemberTypes);
/// <summary>
/// This is available for namespace symbols and contains a collection of the documents that represent all member namespaces.
/// The collection is empty if there are no member namespaces.
/// </summary>
/// <type><c>IReadOnlyList<IDocument></c></type>
public const string MemberNamespaces = nameof(MemberNamespaces);
/// <summary>
/// This is available for type, method, field, event, property, and parameter symbols and contains a document
/// representing the containing type(or<c>null</c> if no containing type).
/// </summary>
/// <type><see cref="IDocument"/></type>
public const string ContainingType = nameof(ContainingType);
/// <summary>
/// This is available for type symbols and contains a collection of the documents that represent all base types (inner-most first).
/// </summary>
/// <type><c>IReadOnlyList<IDocument></c></type>
public const string BaseTypes = nameof(BaseTypes);
/// <summary>
/// This is available for type symbols and contains a collection of the documents that represent all implemented interfaces. The collection
/// is empty if the type doesn't implement any interfaces.
/// </summary>
/// <type><c>IReadOnlyList<IDocument></c></type>
public const string AllInterfaces = nameof(AllInterfaces);
/// <summary>
/// This is available for type symbols and contains a collection of the documents that represent all members of the type, including inherited ones. The collection
/// is empty if the type doesn't have any members.
/// </summary>
/// <type><c>IReadOnlyList<IDocument></c></type>
public const string Members = nameof(Members);
/// <summary>
/// This is available for type symbols and contains a collection of the documents that represent all operators of the type, including inherited ones. The collection
/// is empty if the type doesn't have any operators.
/// </summary>
/// <type><c>IReadOnlyList<IDocument></c></type>
public const string Operators = nameof(Operators);
/// <summary>
/// This is available for type symbols and contains a collection of the documents that represent all extension members applicable to the type.
/// </summary>
/// <type><c>IReadOnlyList<IDocument></c></type>
public const string ExtensionMethods = nameof(ExtensionMethods);
/// <summary>
/// This is available for type symbols and contains a collection of the documents that represent all types derived from the type. The collection
/// is empty if the type doesn't have any derived types.
/// </summary>
/// <type><c>IReadOnlyList<IDocument></c></type>
public const string DerivedTypes = nameof(DerivedTypes);
/// <summary>
/// This is available for interface symbols and contains a collection of the documents that represent all types that implement the interface. The collection
/// is empty if no other types implement the interface.
/// </summary>
/// <type><c>IReadOnlyList<IDocument></c></type>
public const string ImplementingTypes = nameof(ImplementingTypes);
/// <summary>
/// This is available for type symbols and contains a collection of the documents that represent all constructors of the type. The collection
/// is empty if the type doesn't have any explicit constructors.
/// </summary>
/// <type><c>IReadOnlyList<IDocument></c></type>
public const string Constructors = nameof(Constructors);
/// <summary>
/// This is available for type and method symbols and contains a collection of the documents that represent all generic type parameters of the type or method. The collection
/// is empty if the type or method doesn't have any generic type parameters.
/// </summary>
/// <type><c>IReadOnlyList<IDocument></c></type>
public const string TypeParameters = nameof(TypeParameters);
/// <summary>
/// This is available for type, method, field, event, and property symbols and contains the declared accessibility of the symbol.
/// </summary>
/// <type><see cref="string"/></type>
public const string Accessibility = nameof(Accessibility);
/// <summary>
/// This is available for type, method, field, event, property, parameter, and type parameter symbols and contains the type symbol documents for attributes applied to the symbol.
/// </summary>
/// <type><c>IReadOnlyList<IDocument></c></type>
public const string Attributes = nameof(Attributes);
/// <summary>
/// This is available for method and property (I.e., indexer) symbols and contains a collection of the documents that represent the parameters of the method or property.
/// </summary>
/// <type><c>IReadOnlyList<IDocument></c></type>
public const string Parameters = nameof(Parameters);
/// <summary>
/// This is available for method symbols and contains a document that represents the return type of the method (or <c>null</c> if the method returns <c>void</c>).
/// </summary>
/// <type><see cref="IDocument"/></type>
public const string ReturnType = nameof(ReturnType);
/// <summary>
/// This is available for method symbols and contains a document that represents the method being overridden (or <c>null</c> if no method is overriden by this one).
/// </summary>
/// <type><see cref="IDocument"/></type>
public const string OverriddenMethod = nameof(OverriddenMethod);
/// <summary>
/// This is available for field, event, property, and parameter symbols and contains the document that represents the type of the symbol.
/// </summary>
/// <type><see cref="IDocument"/></type>
public const string Type = nameof(Type);
/// <summary>
/// This is available for field symbols and indicates whether a constant value is available for the field.
/// </summary>
/// <type><see cref="bool"/></type>
public const string HasConstantValue = nameof(HasConstantValue);
/// <summary>
/// This is available for field symbols and contains the constant value (if one exists).
/// </summary>
/// <type><see cref="object"/></type>
public const string ConstantValue = nameof(ConstantValue);
/// <summary>
/// This is available for type parameter symbols and contains a document that represents the declaring type of the type parameter.
/// </summary>
/// <type><see cref="IDocument"/></type>
public const string DeclaringType = nameof(DeclaringType);
/// <summary>
/// This is available for attribute symbols and contains the Roslyn <see cref="Microsoft.CodeAnalysis.AttributeData"/> instance for the attribute.
/// </summary>
/// <type><see cref="Microsoft.CodeAnalysis.AttributeData"/></type>
public const string AttributeData = nameof(AttributeData);
// Documentation keys (not present for external symbols)
/// <summary>
/// This is available for documents in the initial result set (<see cref="IsResult"/> is <c>true</c>) and contains
/// the full unprocessed XML documentation comments content for this symbol. In addition, special metadata keys
/// may be added for custom comment elements with the name <c>[ElementName]Comments</c>. These special metadata
/// keys contain a <see cref="OtherComment"/> instance with the rendered HTML content (and any attributes) of the
/// custom XML documentation comments with the given <c>[ElementName]</c>.
/// </summary>
/// <type><see cref="string"/></type>
public const string CommentXml = nameof(CommentXml);
/// <summary>
/// This is available for documents in the initial result set (<see cref="IsResult"/> is <c>true</c>) and contains
/// the rendered HTML content from all<c>example</c> XML documentation comments for this symbol.
/// </summary>
/// <type><see cref="string"/></type>
public const string Example = nameof(Example);
/// <summary>
/// This is available for documents in the initial result set (<see cref="IsResult"/> is <c>true</c>) and contains
/// the rendered HTML content from all<c>remarks</c> XML documentation comments for this symbol.
/// </summary>
/// <type><see cref="string"/></type>
public const string Remarks = nameof(Remarks);
/// <summary>
/// This is available for documents in the initial result set (<see cref="IsResult"/> is <c>true</c>) and contains
/// the rendered HTML content from all<c>summary</c> XML documentation comments for this symbol.
/// </summary>
/// <type><see cref="string"/></type>
public const string Summary = nameof(Summary);
/// <summary>
/// This is available for documents in the initial result set (<see cref="IsResult"/> is <c>true</c>) and contains
/// the rendered HTML content from all<c>returns</c> XML documentation comments for this symbol.
/// </summary>
/// <type><see cref="string"/></type>
public const string Returns = nameof(Returns);
/// <summary>
/// This is available for documents in the initial result set (<see cref="IsResult"/> is <c>true</c>) and contains
/// the rendered HTML content from all<c>value</c> XML documentation comments for this symbol.
/// </summary>
/// <type><see cref="string"/></type>
public const string Value = nameof(Value);
/// <summary>
/// This is available for documents in the initial result set (<see cref="IsResult"/> is <c>true</c>) and contains
/// a collection of all<c>exception</c> XML documentation comments for this symbol with their name, link, and/or rendered HTML content.
/// </summary>
/// <type><see cref="IReadOnlyList{ReferenceComment}"/></type>
public const string Exceptions = nameof(Exceptions);
/// <summary>
/// This is available for documents in the initial result set (<see cref="IsResult"/> is <c>true</c>) and contains
/// a collection of all<c>permission</c> XML documentation comments for this symbol with their name, link, and/or rendered HTML content.
/// </summary>
/// <type><see cref="IReadOnlyList{ReferenceComment}"/></type>
public const string Permissions = nameof(Permissions);
/// <summary>
/// This is available for documents in the initial result set (<see cref="IsResult"/> is <c>true</c>) and contains
/// a collection of all<c>param</c> XML documentation comments for this symbol with their name, link, and/or rendered HTML content.
/// </summary>
/// <type><see cref="IReadOnlyList{ReferenceComment}"/></type>
public const string Params = nameof(Params);
/// <summary>
/// This is available for documents in the initial result set (<see cref="IsResult"/> is <c>true</c>) and contains
/// a collection of all<c>typeparam</c> XML documentation comments for this symbol with their name, link, and/or rendered HTML content.
/// </summary>
/// <type><see cref="IReadOnlyList{ReferenceComment}"/></type>
public const string TypeParams = nameof(TypeParams);
/// <summary>
/// This is available for documents in the initial result set (<see cref="IsResult"/> is <c>true</c>) and contains
/// a collection of all<c>seealso</c> XML documentation comments for this symbol with their rendered HTML link (or just name if no link could be generated).
/// </summary>
/// <type><c>IReadOnlyList<string></c></type>
public const string SeeAlso = nameof(SeeAlso);
/// <summary>
/// This is available for documents in the initial result set (<see cref="IsResult"/> is <c>true</c>) and contains
/// a generated syntax example for the symbol.
/// </summary>
/// <type><see cref="string"/></type>
public const string Syntax = nameof(Syntax);
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Xunit;
namespace NuGet.Test
{
public class PathResolverTest
{
[Fact]
public void GetPathToEnumerateReturnsSearchPathIfSearchPathIsNotUnderBasePath()
{
// Arrange
var basePath = @"c:\packages\bin";
var searchPath = @"d:\work\projects\project1\bin\*\*.dll";
// Act
var result = PathResolver.GetPathToEnumerateFrom(basePath, searchPath);
// Assert
Assert.Equal(@"d:\work\projects\project1\bin", result);
}
[Fact]
public void GetPathToEnumerateReturnsSearchPathIfSearchPathIsUnderBasePath()
{
// Arrange
var basePath = @"d:\work";
var searchPath = @"d:\work\projects\project1\bin\*\*.dll";
// Act
var result = PathResolver.GetPathToEnumerateFrom(basePath, searchPath);
// Assert
Assert.Equal(@"d:\work\projects\project1\bin", result);
}
[Fact]
public void GetPathToEnumerateReturnsSearchPathIfItIsANetworkPath()
{
// Arrange
var basePath = @"c:\work";
var searchPath = @"\\build-vm\shared\drops\nuget.*";
// Act
var result = PathResolver.GetPathToEnumerateFrom(basePath, searchPath);
// Assert
Assert.Equal(@"\\build-vm\shared\drops", result);
}
[Fact]
public void GetPathToEnumerateReturnsCombinedPathFromBaseForSearchWithWildcardFileName()
{
// Arrange
var basePath = @"c:\work\projects\my-project";
var searchPath = @"bin\debug\*.dll";
// Act
var result = PathResolver.GetPathToEnumerateFrom(basePath, searchPath);
// Assert
Assert.Equal(@"c:\work\projects\my-project\bin\debug", result);
}
[Fact]
public void GetPathToEnumerateReturnsCombinedPathFromBaseForSearchWithWildcardInPath()
{
// Arrange
var basePath = @"c:\work\projects\my-project";
var searchPath = @"output\*\binaries\NuGet.dll";
// Act
var result = PathResolver.GetPathToEnumerateFrom(basePath, searchPath);
// Assert
Assert.Equal(@"c:\work\projects\my-project\output", result);
}
[Fact]
public void GetPathToEnumerateReturnsBasePathIfSearchPathStartsWithRecursiveWildcard()
{
// Arrange
var basePath = @"c:\work\projects\my-project";
var searchPath = @"**\*.dll";
// Act
var result = PathResolver.GetPathToEnumerateFrom(basePath, searchPath);
// Assert
Assert.Equal(@"c:\work\projects\my-project", result);
}
[Fact]
public void GetPathToEnumerateReturnsBasePathIfSearchPathStartsWithWildcard()
{
// Arrange
var basePath = @"c:\work\projects\my-project\bin";
var searchPath = @"*.dll";
// Act
var result = PathResolver.GetPathToEnumerateFrom(basePath, searchPath);
// Assert
Assert.Equal(@"c:\work\projects\my-project\bin", result);
}
[Fact]
public void GetPathToEnumerateReturnsFullPathIfSearchPathDoesNotContainWildCards()
{
// Arrange
var basePath = @"c:\work\projects\my-project\";
var searchPath = @"bin\release\SuperBin.dll";
// Act
var result = PathResolver.GetPathToEnumerateFrom(basePath, searchPath);
// Assert
Assert.Equal(@"c:\work\projects\my-project\bin\release", result);
}
[Fact]
public void ResolvePackagePathPreservesPortionOfWildCardInPackagePath()
{
// Arrange
var basePath = @"c:\work\projects\my-project\";
var searchPattern = @"bin\release\**\*.dll";
var fullPath = @"c:\work\projects\my-project\bin\release\net40\foo.dll";
var targetPath = @"lib";
// Act
var basePathToEnumerate = PathResolver.GetPathToEnumerateFrom(basePath, searchPattern);
var result = PathResolver.ResolvePackagePath(basePathToEnumerate, searchPattern, fullPath, targetPath);
// Assert
Assert.Equal(@"lib\net40\foo.dll", result);
}
[Fact]
public void ResolvePackagePathAppendsFullTargetPathToPortionOfWildCardInPackagePath()
{
// Arrange
var basePath = @"c:\work\projects\my-project\";
var searchPattern = @"bin\release\**\*.dll";
var fullPath = @"c:\work\projects\my-project\bin\release\net40\foo.dll";
var targetPath = @"lib\assemblies\";
// Act
var basePathToEnumerate = PathResolver.GetPathToEnumerateFrom(basePath, searchPattern);
var result = PathResolver.ResolvePackagePath(basePathToEnumerate, searchPattern, fullPath, targetPath);
// Assert
Assert.Equal(@"lib\assemblies\net40\foo.dll", result);
}
[Fact]
public void ResolvePackagePathAppendsFileNameToTargetForWildCardInExtension()
{
// Arrange
var basePath = @"c:\work\projects\my-project\";
var searchPattern = @"bin\release\NuGet.*";
var fullPath = @"c:\work\projects\my-project\bin\release\NuGet.pdb";
var targetPath = @"lib\";
// Act
var basePathToEnumerate = PathResolver.GetPathToEnumerateFrom(basePath, searchPattern);
var result = PathResolver.ResolvePackagePath(basePathToEnumerate, searchPattern, fullPath, targetPath);
// Assert
Assert.Equal(@"lib\NuGet.pdb", result);
}
[Fact]
public void ResolvePackagePathAppendsFileNameToTargetForWildCardInFileName()
{
// Arrange
var basePath = @"c:\work\projects\my-project\";
var searchPattern = @"bin\release\*.dll";
var fullPath = @"c:\work\projects\my-project\bin\release\NuGet.dll";
var targetPath = @"lib\net40";
// Act
var basePathToEnumerate = PathResolver.GetPathToEnumerateFrom(basePath, searchPattern);
var result = PathResolver.ResolvePackagePath(basePathToEnumerate, searchPattern, fullPath, targetPath);
// Assert
Assert.Equal(@"lib\net40\NuGet.dll", result);
}
[Fact]
public void ResolvePackagePathAppendsFileNameToTargetForWildCardInPath()
{
// Arrange
var basePath = @"c:\work\projects\my-project\";
var searchPattern = @"out\*\NuGet*.dll";
var fullPath = @"c:\work\projects\my-project\out\NuGet.Core\NuGet.dll";
var targetPath = @"lib\net35";
// Act
var basePathToEnumerate = PathResolver.GetPathToEnumerateFrom(basePath, searchPattern);
var result = PathResolver.ResolvePackagePath(basePathToEnumerate, searchPattern, fullPath, targetPath);
// Assert
Assert.Equal(@"lib\net35\NuGet.dll", result);
}
[Fact]
public void ResolvePackagePathAppendsFileNameToTargetForMultipleWildCardInPath()
{
// Arrange
var basePath = @"c:\work\";
var searchPattern = @"src\Nu*\bin\*\NuGet*.dll";
var fullPath = @"c:\My Documents\Temporary Internet Files\NuGet\src\NuGet.Core\bin\release\NuGet.dll";
var targetPath = @"lib";
// Act
var basePathToEnumerate = PathResolver.GetPathToEnumerateFrom(basePath, searchPattern);
var result = PathResolver.ResolvePackagePath(basePathToEnumerate, searchPattern, fullPath, targetPath);
// Assert
Assert.Equal(@"lib\NuGet.dll", result);
}
[Fact]
public void ResolvePackagePathReturnsTargetPathIfNoWildCardIsPresentInSearchPatternAndTargetPathHasSameExtension()
{
// Arrange
var basePath = @"c:\work\";
var searchPattern = @"site\css\main.css";
var fullPath = @"c:\work\site\css\main.css";
var targetPath = @"content\css\site.css";
// Act
var basePathToEnumerate = PathResolver.GetPathToEnumerateFrom(basePath, searchPattern);
var result = PathResolver.ResolvePackagePath(basePathToEnumerate, searchPattern, fullPath, targetPath);
// Assert
Assert.Equal(@"content\css\site.css", result);
}
[Fact]
public void GetMatchesFiltersByWildCards()
{
// Arrange
var files = new[] {
new PhysicalPackageFile { SourcePath = @"content\1.txt" },
new PhysicalPackageFile { SourcePath = @"content\foo\bar.txt" },
new PhysicalPackageFile { SourcePath = @"baz.pdb" },
};
// Act
var matches = PathResolver.GetMatches(files, f => f.SourcePath, new[] { @"content\*.txt", "*.pdb" });
// Assert
Assert.Equal(2, matches.Count());
Assert.Equal(@"content\1.txt", matches.ElementAt(0).SourcePath);
Assert.Equal(@"baz.pdb", matches.ElementAt(1).SourcePath);
}
[Fact]
public void GetMatchesAllowsRecursiveWildcardMatches()
{
// Arrange
var files = new[] {
new PhysicalPackageFile { SourcePath = @"content\1.txt" },
new PhysicalPackageFile { SourcePath = @"content\foo\bar.txt" },
new PhysicalPackageFile { SourcePath = @"lib\baz.pdb" },
new PhysicalPackageFile { SourcePath = @"baz.dll" },
};
// Act
var matches = PathResolver.GetMatches(files, f => f.SourcePath, new[] { @"content\**\.txt", "**.pdb" });
// Assert
Assert.Equal(3, matches.Count());
Assert.Equal(@"content\1.txt", matches.ElementAt(0).SourcePath);
Assert.Equal(@"content\foo\bar.txt", matches.ElementAt(1).SourcePath);
Assert.Equal(@"lib\baz.pdb", matches.ElementAt(2).SourcePath);
}
[Fact]
public void GetMatchesAgainstUnixStylePaths()
{
// Arrange
var files = new[] {
new PhysicalPackageFile { SourcePath = @"content\1.txt" },
new PhysicalPackageFile { SourcePath = @"content\foo\bar.txt" },
new PhysicalPackageFile { SourcePath = @"lib\baz.pdb" },
new PhysicalPackageFile { SourcePath = @"baz.dll" },
};
// Act
var matches = PathResolver.GetMatches(files, f => f.SourcePath, new[] { @"content/**/.txt", "**.pdb" });
// Assert
Assert.Equal(3, matches.Count());
Assert.Equal(@"content\1.txt", matches.ElementAt(0).SourcePath);
Assert.Equal(@"content\foo\bar.txt", matches.ElementAt(1).SourcePath);
Assert.Equal(@"lib\baz.pdb", matches.ElementAt(2).SourcePath);
}
[Fact]
public void GetMatchesPerformsRecursiveWildcardSearch()
{
// Arrange
var files = new[] {
new PhysicalPackageFile { SourcePath = @"content\1.txt" },
new PhysicalPackageFile { SourcePath = @"content\foo\bar.txt" },
new PhysicalPackageFile { SourcePath = @"lib\baz.pdb" },
new PhysicalPackageFile { SourcePath = @"baz.dll" },
};
// Act
var matches = PathResolver.GetMatches(files, f => f.SourcePath, new[] { @"content\**\.txt", "**.pdb" });
// Assert
Assert.Equal(3, matches.Count());
Assert.Equal(@"content\1.txt", matches.ElementAt(0).SourcePath);
Assert.Equal(@"content\foo\bar.txt", matches.ElementAt(1).SourcePath);
Assert.Equal(@"lib\baz.pdb", matches.ElementAt(2).SourcePath);
}
[Fact]
public void GetMatchesPerformsExactMatches()
{
// Arrange
var files = new[] {
new PhysicalPackageFile { SourcePath = @"foo.dll" },
new PhysicalPackageFile { SourcePath = @"content\foo.dll" },
new PhysicalPackageFile { SourcePath = @"bin\debug\baz.dll" },
new PhysicalPackageFile { SourcePath = @"bin\debug\notbaz.dll" },
};
// Act
var matches = PathResolver.GetMatches(files, f => f.SourcePath, new[] { @"foo.dll", @"bin\*\b*.dll" });
// Assert
Assert.Equal(2, matches.Count());
Assert.Equal(@"foo.dll", matches.ElementAt(0).SourcePath);
Assert.Equal(@"bin\debug\baz.dll", matches.ElementAt(1).SourcePath);
}
[Fact]
public void FilterPathRemovesItemsThatMatchWildcard()
{
// Arrange
var files = new List<IPackageFile>(new[] {
new PhysicalPackageFile { TargetPath = @"foo.dll" },
new PhysicalPackageFile { TargetPath = @"content\foo.dll" },
new PhysicalPackageFile { TargetPath = @"bin\debug\baz.dll" },
new PhysicalPackageFile { TargetPath = @"bin\debug\notbaz.dll" },
new PhysicalPackageFile { TargetPath = @"bin\debug\baz.pdb" },
new PhysicalPackageFile { TargetPath = @"bin\debug\notbaz.pdb" },
});
// Act
PathResolver.FilterPackageFiles(files, f => f.Path, new[] { @"**\f*.dll", @"**\*.pdb" });
// Assert
Assert.Equal(2, files.Count());
Assert.Equal(@"bin\debug\baz.dll", files[0].Path);
Assert.Equal(@"bin\debug\notbaz.dll", files[1].Path);
}
}
}
| |
// 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.Linq;
using System.Runtime.InteropServices;
using Xunit;
using Windows.Storage;
namespace System.IO.Tests
{
[PlatformSpecific(TestPlatforms.Windows)]
[SkipOnTargetFramework(~(TargetFrameworkMonikers.Uap | TargetFrameworkMonikers.UapAot))]
public partial class WinRT_BrokeredFunctions : FileSystemTest
{
private static string s_musicFolder = StorageLibrary.GetLibraryAsync(KnownLibraryId.Music).AsTask().Result.SaveFolder.Path;
[Fact]
public void CopyFile_ToBrokeredLocation()
{
string testFile = GetTestFilePath();
File.Create(testFile).Dispose();
string destination = Path.Combine(s_musicFolder, "CopyToBrokeredLocation_" + Path.GetRandomFileName());
try
{
Assert.False(File.Exists(destination), "destination shouldn't exist before copying");
File.Copy(testFile, destination);
Assert.True(File.Exists(testFile), "testFile should exist after copying");
Assert.True(File.Exists(destination), "destination should exist after copying");
}
finally
{
File.Delete(destination);
}
}
[Fact]
public void CreateDirectory()
{
string testFolder = Path.Combine(s_musicFolder, "CreateDirectory_" + Path.GetRandomFileName());
try
{
Assert.False(Directory.Exists(testFolder), "destination shouldn't exist");
Directory.CreateDirectory(testFolder);
Assert.True(Directory.Exists(testFolder), "destination should exist");
}
finally
{
Directory.Delete(testFolder);
}
}
[Fact]
public void DeleteFile()
{
string testFile = Path.Combine(s_musicFolder, "DeleteFile_" + Path.GetRandomFileName());
CreateFileInBrokeredLocation(testFile);
Assert.True(File.Exists(testFile), "testFile should exist before deleting");
File.Delete(testFile);
Assert.False(File.Exists(testFile), "testFile shouldn't exist after deleting");
}
[Fact]
public void FindFirstFile()
{
string subFolder = Path.Combine(s_musicFolder, "FindFirstFile_SubFolder_" + Path.GetRandomFileName());
Directory.CreateDirectory(subFolder);
string testFile = null;
try
{
testFile = Path.Combine(subFolder, "FindFirstFile_SubFile_" + Path.GetRandomFileName());
CreateFileInBrokeredLocation(testFile);
Assert.True(File.Exists(testFile), "testFile should exist");
}
finally
{
Directory.Delete(subFolder, true);
}
Assert.False(File.Exists(testFile), "testFile shouldn't exist after a recursive delete");
Assert.False(Directory.Exists(subFolder), "subFolder shouldn't exist after a recursive delete");
}
[Fact]
[ActiveIssue(23444)]
public void GetFileAttributesEx()
{
string destination = Path.Combine(s_musicFolder, "GetFileAttributesEx_" + Path.GetRandomFileName());
CreateFileInBrokeredLocation(destination);
try
{
FileAttributes attr = File.GetAttributes(destination);
Assert.False((attr & FileAttributes.ReadOnly) == 0, "new file in brokered location should not be readonly");
}
finally
{
File.Delete(destination);
}
}
[Fact]
public void MoveFile()
{
string testFile = GetTestFilePath();
File.Create(testFile).Dispose();
string destination = Path.Combine(s_musicFolder, "MoveFile_" + Path.GetRandomFileName());
try
{
Assert.False(File.Exists(destination), "destination shouldn't exist before moving");
File.Move(testFile, destination);
Assert.False(File.Exists(testFile), "testFile shouldn't exist after moving");
Assert.True(File.Exists(destination), "destination should exist after moving");
}
finally
{
File.Delete(destination);
}
}
[Fact]
public void RemoveDirectory()
{
string testFolder = Path.Combine(s_musicFolder, "CreateDirectory_" + Path.GetRandomFileName());
Assert.False(Directory.Exists(testFolder), "destination shouldn't exist");
Directory.CreateDirectory(testFolder);
Assert.True(Directory.Exists(testFolder), "destination should exist");
Directory.Delete(testFolder);
Assert.False(Directory.Exists(testFolder), "destination shouldn't exist");
}
[Fact]
public void ReplaceFile()
{
string testFile = GetTestFilePath();
File.Create(testFile).Dispose();
string destination = Path.Combine(s_musicFolder, "ReplaceFile_" + Path.GetRandomFileName());
File.Copy(testFile, destination);
// Need to be on the same drive
Assert.Equal(testFile[0], destination[0]);
string destinationBackup = Path.Combine(s_musicFolder, "ReplaceFile_" + Path.GetRandomFileName());
try
{
Assert.True(File.Exists(destination), "destination should exist before replacing");
Assert.False(File.Exists(destinationBackup), "destination shouldn't exist before replacing");
File.Replace(testFile, destination, destinationBackup);
Assert.False(File.Exists(testFile), "testFile shouldn't exist after replacing");
Assert.True(File.Exists(destination), "destination should exist after replacing");
Assert.True(File.Exists(destinationBackup), "destinationBackup should exist after replacing");
}
finally
{
File.Delete(destination);
File.Delete(destinationBackup);
}
}
[Fact]
[ActiveIssue(23444)]
public void SetFileAttributes()
{
string destination = Path.Combine(s_musicFolder, "SetFileAttributes_" + Path.GetRandomFileName());
CreateFileInBrokeredLocation(destination);
FileAttributes attr = File.GetAttributes(destination);
try
{
Assert.False(((attr & FileAttributes.ReadOnly) > 0), "new file in brokered location should not be readonly");
File.SetAttributes(destination, attr | FileAttributes.ReadOnly);
Assert.True(((File.GetAttributes(destination) & FileAttributes.ReadOnly) > 0), "file in brokered location should be readonly after setting FileAttributes");
}
finally
{
File.SetAttributes(destination, attr);
Assert.False(((File.GetAttributes(destination) & FileAttributes.ReadOnly) > 0), "file in brokered location should NOT be readonly after setting FileAttributes");
File.Delete(destination);
}
}
private void CreateFileInBrokeredLocation(string path)
{
// Temporary hack until FileStream is updated to support brokering
string testFile = GetTestFilePath();
File.WriteAllText(testFile, "CoreFX test file");
File.Copy(testFile, path);
}
// Temporarily blocking until the CoreCLR change is made [Fact]
public void WriteReadAllText()
{
string destination = Path.Combine(s_musicFolder, "WriteReadAllText_" + Path.GetRandomFileName());
string content = "WriteReadAllText";
File.WriteAllText(destination, content);
try
{
Assert.True(File.Exists(destination));
Assert.Equal(content, File.ReadAllText(destination));
}
finally
{
File.Delete(destination);
}
}
}
}
| |
#region File Description
//-----------------------------------------------------------------------------
// SampleCamera.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.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Storage;
#endregion
namespace PerPixelLightingSample
{
public enum SampleArcBallCameraMode
{
/// <summary>
/// A totally free-look arcball that orbits relative
/// to its orientation
/// </summary>
Free = 0,
/// <summary>
/// A camera constrained by roll so that orbits only
/// occur on latitude and longitude
/// </summary>
RollConstrained = 1
}
/// <summary>
/// An example arc ball camera
/// </summary>
public class SampleArcBallCamera
{
#region Helper Functions
/// <summary>
/// Uses a pair of keys to simulate a positive or negative axis input.
/// </summary>
public static float ReadKeyboardAxis(KeyboardState keyState, Keys downKey,
Keys upKey)
{
float value = 0;
if (keyState.IsKeyDown(downKey))
value -= 1.0f;
if (keyState.IsKeyDown(upKey))
value += 1.0f;
return value;
}
#endregion
#region Fields
/// <summary>
/// The location of the look-at target
/// </summary>
private Vector3 targetValue;
/// <summary>
/// The distance between the camera and the target
/// </summary>
private float distanceValue;
/// <summary>
/// The orientation of the camera relative to the target
/// </summary>
private Quaternion orientation;
private float inputDistanceRateValue;
private const float InputTurnRate = 3.0f;
private SampleArcBallCameraMode mode;
private float yaw, pitch;
#endregion
#region Constructors
/// <summary>
/// Create an arcball camera that allows free orbit around a target point.
/// </summary>
public SampleArcBallCamera(SampleArcBallCameraMode controlMode)
{
//orientation quaternion assumes a Pi rotation so you're facing the "front"
//of the model (looking down the +Z axis)
orientation = Quaternion.CreateFromAxisAngle(Vector3.Up, MathHelper.Pi);
mode = controlMode;
inputDistanceRateValue = 4.0f;
yaw = MathHelper.Pi;
pitch = 0;
}
#endregion
#region Calculated Camera Properties
/// <summary>
/// Get the forward direction vector of the camera.
/// </summary>
public Vector3 Direction
{
get
{
//R v R' where v = (0,0,-1,0)
//The equation can be reduced because we know the following things:
// 1. We're using unit quaternions
// 2. The initial aspect does not change
//The reduced form of the same equation follows
Vector3 dir = Vector3.Zero;
dir.X = -2.0f *
((orientation.X * orientation.Z) + (orientation.W * orientation.Y));
dir.Y = 2.0f *
((orientation.W * orientation.X) - (orientation.Y * orientation.Z));
dir.Z =
((orientation.X * orientation.X) + (orientation.Y * orientation.Y)) -
((orientation.Z * orientation.Z) + (orientation.W * orientation.W));
Vector3.Normalize(ref dir, out dir);
return dir;
}
}
/// <summary>
/// Get the right direction vector of the camera.
/// </summary>
public Vector3 Right
{
get
{
//R v R' where v = (1,0,0,0)
//The equation can be reduced because we know the following things:
// 1. We're using unit quaternions
// 2. The initial aspect does not change
//The reduced form of the same equation follows
Vector3 right = Vector3.Zero;
right.X =
((orientation.X * orientation.X) + (orientation.W * orientation.W)) -
((orientation.Z * orientation.Z) + (orientation.Y * orientation.Y));
right.Y = 2.0f *
((orientation.X * orientation.Y) + (orientation.Z * orientation.W));
right.Z = 2.0f *
((orientation.X * orientation.Z) - (orientation.Y * orientation.W));
return right;
}
}
/// <summary>
/// Get the up direction vector of the camera.
/// </summary>
public Vector3 Up
{
get
{
//R v R' where v = (0,1,0,0)
//The equation can be reduced because we know the following things:
// 1. We're using unit quaternions
// 2. The initial aspect does not change
//The reduced form of the same equation follows
Vector3 up = Vector3.Zero;
up.X = 2.0f *
((orientation.X * orientation.Y) - (orientation.Z * orientation.W));
up.Y =
((orientation.Y * orientation.Y) + (orientation.W * orientation.W)) -
((orientation.Z * orientation.Z) + (orientation.X * orientation.X));
up.Z = 2.0f *
((orientation.Y * orientation.Z) + (orientation.X * orientation.W));
return up;
}
}
/// <summary>
/// Get the View (look at) Matrix defined by the camera
/// </summary>
public Matrix ViewMatrix
{
get
{
return Matrix.CreateLookAt(targetValue -
(Direction * distanceValue), targetValue, Up);
}
}
public SampleArcBallCameraMode ControlMode
{
get { return mode; }
set
{
if (value != mode)
{
mode = value;
SetCamera(targetValue - (Direction* distanceValue),
targetValue, Vector3.Up);
}
}
}
#endregion
#region Position Controls
/// <summary>
/// Get or Set the current target of the camera
/// </summary>
public Vector3 Target
{
get
{ return targetValue; }
set
{ targetValue = value; }
}
/// <summary>
/// Get or Set the camera's distance to the target.
/// </summary>
public float Distance
{
get
{ return distanceValue; }
set
{ distanceValue = value; }
}
/// <summary>
/// Sets the rate of distance change
/// when automatically handling input
/// </summary>
public float InputDistanceRate
{
get
{ return inputDistanceRateValue; }
set
{ inputDistanceRateValue = value; }
}
/// <summary>
/// Get/Set the camera's current postion.
/// </summary>
public Vector3 Position
{
get
{
return targetValue - (Direction * Distance);
}
set
{
SetCamera(value, targetValue, Vector3.Up);
}
}
#endregion
#region Orbit Controls
/// <summary>
/// Orbit directly upwards in Free camera or on
/// the longitude line when roll constrained
/// </summary>
public void OrbitUp(float angle)
{
switch (mode)
{
case SampleArcBallCameraMode.Free:
//rotate the aspect by the angle
orientation = orientation *
Quaternion.CreateFromAxisAngle(Vector3.Right, -angle);
//normalize to reduce errors
Quaternion.Normalize(ref orientation, out orientation);
break;
case SampleArcBallCameraMode.RollConstrained:
//update the yaw
pitch -= angle;
//constrain pitch to vertical to avoid confusion
pitch = MathHelper.Clamp(pitch, -(MathHelper.PiOver2) + .0001f,
(MathHelper.PiOver2) - .0001f);
//create a new aspect based on pitch and yaw
orientation = Quaternion.CreateFromAxisAngle(Vector3.Up, -yaw) *
Quaternion.CreateFromAxisAngle(Vector3.Right, pitch);
break;
}
}
/// <summary>
/// Orbit towards the Right vector in Free camera
/// or on the latitude line when roll constrained
/// </summary>
public void OrbitRight(float angle)
{
switch (mode)
{
case SampleArcBallCameraMode.Free:
//rotate the aspect by the angle
orientation = orientation *
Quaternion.CreateFromAxisAngle(Vector3.Up, angle);
//normalize to reduce errors
Quaternion.Normalize(ref orientation, out orientation);
break;
case SampleArcBallCameraMode.RollConstrained:
//update the yaw
yaw -= angle;
//float mod yaw to avoid eventual precision errors
//as we move away from 0
yaw = yaw % MathHelper.TwoPi;
//create a new aspect based on pitch and yaw
orientation = Quaternion.CreateFromAxisAngle(Vector3.Up, -yaw) *
Quaternion.CreateFromAxisAngle(Vector3.Right, pitch);
//normalize to reduce errors
Quaternion.Normalize(ref orientation, out orientation);
break;
}
}
/// <summary>
/// Rotate around the Forward vector
/// in free-look camera only
/// </summary>
public void RotateClockwise(float angle)
{
switch (mode)
{
case SampleArcBallCameraMode.Free:
//rotate the orientation around the direction vector
orientation = orientation *
Quaternion.CreateFromAxisAngle(Vector3.Forward, angle);
Quaternion.Normalize(ref orientation, out orientation);
break;
case SampleArcBallCameraMode.RollConstrained:
//Do nothing, we don't want to roll at all to stay consistent
break;
}
}
/// <summary>
/// Sets up a quaternion & position from vector camera components
/// and oriented the camera up
/// </summary>
/// <param name="eye">The camera position</param>
/// <param name="lookAt">The camera's look-at point</param>
/// <param name="up"></param>
public void SetCamera(Vector3 position, Vector3 target, Vector3 up)
{
//Create a look at matrix, to simplify matters a bit
Matrix temp = Matrix.CreateLookAt(position, target, up);
//invert the matrix, since we're determining the
//orientation from the rotation matrix in RH coords
temp = Matrix.Invert(temp);
//set the postion
targetValue = target;
//create the new aspect from the look-at matrix
orientation = Quaternion.CreateFromRotationMatrix(temp);
//When setting a new eye-view direction
//in one of the gimble-locked modes, the yaw and
//pitch gimble must be calculated.
if (mode != SampleArcBallCameraMode.Free)
{
//first, get the direction projected on the x/z plne
Vector3 dir = Direction;
dir.Y = 0;
if (dir.Length() == 0f)
{
dir = Vector3.Forward;
}
dir.Normalize();
//find the yaw of the direction on the x/z plane
//and use the sign of the x-component since we have 360 degrees
//of freedom
yaw = (float)(Math.Acos(-dir.Z) * Math.Sign(dir.X));
//Get the pitch from the angle formed by the Up vector and the
//the forward direction, then subtracting Pi / 2, since
//we pitch is zero at Forward, not Up.
pitch = (float)-(Math.Acos(Vector3.Dot(Vector3.Up, Direction))
- MathHelper.PiOver2);
}
}
#endregion
#region Input Handlers
/// <summary>
/// Handle default keyboard input for a camera
/// </summary>
public void HandleDefaultKeyboardControls(KeyboardState kbState,
GameTime gameTime)
{
if (gameTime == null)
{
throw new ArgumentNullException("gameTime",
"GameTime parameter cannot be null.");
}
float elapsedTime = (float)gameTime.ElapsedGameTime.TotalSeconds;
float dX = elapsedTime * ReadKeyboardAxis(
kbState, Keys.A, Keys.D) * InputTurnRate;
float dY = elapsedTime * ReadKeyboardAxis(
kbState, Keys.S, Keys.W) * InputTurnRate;
if (dY != 0) OrbitUp(dY);
if (dX != 0) OrbitRight(dX);
distanceValue += ReadKeyboardAxis(kbState, Keys.Z, Keys.X)
* inputDistanceRateValue * elapsedTime;
if (distanceValue < .001f) distanceValue = .001f;
if (mode != SampleArcBallCameraMode.Free)
{
float dR = elapsedTime * ReadKeyboardAxis(
kbState, Keys.Q, Keys.E) * InputTurnRate;
if (dR != 0) RotateClockwise(dR);
}
}
/// <summary>
/// Handle default gamepad input for a camera
/// </summary>
public void HandleDefaultGamepadControls(GamePadState gpState, GameTime gameTime)
{
if (gameTime == null)
{
throw new ArgumentNullException("gameTime",
"GameTime parameter cannot be null.");
}
if (gpState.IsConnected)
{
float elapsedTime = (float)gameTime.ElapsedGameTime.TotalSeconds;
float dX = gpState.ThumbSticks.Right.X * elapsedTime * InputTurnRate;
float dY = gpState.ThumbSticks.Right.Y * elapsedTime * InputTurnRate;
float dR = gpState.Triggers.Right * elapsedTime * InputTurnRate;
dR-= gpState.Triggers.Left * elapsedTime * InputTurnRate;
//change orientation if necessary
if(dY != 0) OrbitUp(dY);
if(dX != 0) OrbitRight(dX);
if (dR != 0) RotateClockwise(dR);
//decrease distance to target (move forward)
if (gpState.Buttons.A == ButtonState.Pressed)
{
distanceValue -= elapsedTime * inputDistanceRateValue;
}
//increase distance to target (move back)
if (gpState.Buttons.B == ButtonState.Pressed)
{
distanceValue += elapsedTime * inputDistanceRateValue;
}
if (distanceValue < .001f) distanceValue = .001f;
}
}
#endregion
#region Misc Camera Controls
/// <summary>
/// Reset the camera to the defaults set in the constructor
/// </summary>
public void Reset()
{
//orientation quaternion assumes a Pi rotation so you're facing the "front"
//of the model (looking down the +Z axis)
orientation = Quaternion.CreateFromAxisAngle(Vector3.Up, MathHelper.Pi);
distanceValue = 3f;
targetValue = Vector3.Zero;
yaw = MathHelper.Pi;
pitch = 0;
}
#endregion
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="GraphDsl.cs" company="Akka.NET Project">
// Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Linq;
using Akka.Streams.Implementation;
using Akka.Streams.Implementation.Fusing;
namespace Akka.Streams.Dsl
{
/// <summary>
/// TBD
/// </summary>
public static partial class GraphDsl
{
/// <summary>
/// TBD
/// </summary>
/// <typeparam name="T">TBD</typeparam>
public sealed class Builder<T>
{
#region internal API
/// <summary>
/// TBD
/// </summary>
internal Builder() { }
private IModule _moduleInProgress = EmptyModule.Instance;
/// <summary>
/// TBD
/// </summary>
/// <typeparam name="T1">TBD</typeparam>
/// <typeparam name="T2">TBD</typeparam>
/// <param name="from">TBD</param>
/// <param name="to">TBD</param>
internal void AddEdge<T1, T2>(Outlet<T1> from, Inlet<T2> to) where T2 : T1
{
_moduleInProgress = _moduleInProgress.Wire(from, to);
}
/// <summary>
/// INTERNAL API.
/// This is only used by the materialization-importing apply methods of Source,
/// Flow, Sink and Graph.
/// </summary>
/// <typeparam name="TShape">TBD</typeparam>
/// <typeparam name="TMat">TBD</typeparam>
/// <typeparam name="TMat2">TBD</typeparam>
/// <param name="graph">TBD</param>
/// <param name="transform">TBD</param>
/// <returns>TBD</returns>
internal TShape Add<TShape, TMat, TMat2>(IGraph<TShape, TMat> graph, Func<TMat, TMat2> transform) where TShape : Shape
{
if (StreamLayout.IsDebug)
StreamLayout.Validate(graph.Module);
var copy = graph.Module.CarbonCopy();
_moduleInProgress = _moduleInProgress.Compose<TMat,TMat2,TMat2>(copy.TransformMaterializedValue(transform), Keep.Right);
return (TShape)graph.Shape.CopyFromPorts(copy.Shape.Inlets, copy.Shape.Outlets);
}
/// <summary>
/// INTERNAL API.
/// This is only used by the materialization-importing apply methods of Source,
/// Flow, Sink and Graph.
/// </summary>
/// <typeparam name="TShape">TBD</typeparam>
/// <typeparam name="TMat1">TBD</typeparam>
/// <typeparam name="TMat2">TBD</typeparam>
/// <typeparam name="TMat3">TBD</typeparam>
/// <param name="graph">TBD</param>
/// <param name="combine">TBD</param>
/// <returns>TBD</returns>
internal TShape Add<TShape, TMat1, TMat2, TMat3>(IGraph<TShape> graph, Func<TMat1, TMat2, TMat3> combine) where TShape : Shape
{
if (StreamLayout.IsDebug)
StreamLayout.Validate(graph.Module);
var copy = graph.Module.CarbonCopy();
_moduleInProgress = _moduleInProgress.Compose(copy, combine);
return (TShape)graph.Shape.CopyFromPorts(copy.Shape.Inlets, copy.Shape.Outlets);
}
#endregion
/// <summary>
/// Import a graph into this module, performing a deep copy, discarding its
/// materialized value and returning the copied Ports that are now to be connected.
/// </summary>
/// <typeparam name="TShape">TBD</typeparam>
/// <typeparam name="TMat">TBD</typeparam>
/// <param name="graph">TBD</param>
/// <returns>TBD</returns>
public TShape Add<TShape, TMat>(IGraph<TShape, TMat> graph)
where TShape : Shape
{
if (StreamLayout.IsDebug)
StreamLayout.Validate(graph.Module);
var copy = graph.Module.CarbonCopy();
_moduleInProgress = _moduleInProgress.Compose<object, TMat, object>(copy, Keep.Left);
return (TShape)graph.Shape.CopyFromPorts(copy.Shape.Inlets, copy.Shape.Outlets);
}
/// <summary>
/// Returns an <see cref="Outlet{T}"/> that gives access to the materialized value of this graph. Once the graph is materialized
/// this outlet will emit exactly one element which is the materialized value. It is possible to expose this
/// outlet as an externally accessible outlet of a <see cref="Source{TOut,TMat}"/>, <see cref="Sink{TIn,TMat}"/>,
/// <see cref="Flow{TIn,TOut,TMat}"/> or <see cref="BidiFlow{TIn1,TOut1,TIn2,TOut2,TMat}"/>.
///
/// It is possible to call this method multiple times to get multiple <see cref="Outlet{T}"/> instances if necessary. All of
/// the outlets will emit the materialized value.
///
/// Be careful to not to feed the result of this outlet to a stage that produces the materialized value itself (for
/// example to a <see cref="Sink.Aggregate{TIn,TOut}"/> that contributes to the materialized value) since that might lead to an unresolvable
/// dependency cycle.
/// </summary>
public Outlet<T> MaterializedValue
{
get
{
/*
* This brings the graph into a homogenous shape: if only one `add` has
* been performed so far, the moduleInProgress will be a CopiedModule
* that upon the next `composeNoMat` will be wrapped together with the
* MaterializedValueSource into a CompositeModule, leading to its
* relevant computation being an Atomic() for the CopiedModule. This is
* what we must reference, and we can only get this reference if we
* create that computation up-front: just making one up will not work
* because that computation node would not be part of the tree and
* the source would not be triggered.
*/
if (_moduleInProgress is CopiedModule)
_moduleInProgress = CompositeModule.Create((Module) _moduleInProgress, _moduleInProgress.Shape);
var source = new MaterializedValueSource<T>(_moduleInProgress.MaterializedValueComputation);
_moduleInProgress = _moduleInProgress.ComposeNoMaterialized(source.Module);
return source.Outlet;
}
}
/// <summary>
/// TBD
/// </summary>
public IModule Module => _moduleInProgress;
/// <summary>
/// TBD
/// </summary>
/// <typeparam name="TOut">TBD</typeparam>
/// <param name="outlet">TBD</param>
/// <returns>TBD</returns>
public ForwardOps<TOut, T> From<TOut>(Outlet<TOut> outlet)
{
return new ForwardOps<TOut, T>(this, outlet);
}
/// <summary>
/// TBD
/// </summary>
/// <typeparam name="TOut">TBD</typeparam>
/// <param name="source">TBD</param>
/// <returns>TBD</returns>
public ForwardOps<TOut, T> From<TOut>(SourceShape<TOut> source)
{
return new ForwardOps<TOut, T>(this, source.Outlet);
}
/// <summary>
/// TBD
/// </summary>
/// <typeparam name="TOut">TBD</typeparam>
/// <param name="source">TBD</param>
/// <returns>TBD</returns>
public ForwardOps<TOut, T> From<TOut>(IGraph<SourceShape<TOut>, T> source)
{
return new ForwardOps<TOut, T>(this, Add(source).Outlet);
}
/// <summary>
/// TBD
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <typeparam name="TOut">TBD</typeparam>
/// <param name="flow">TBD</param>
/// <returns>TBD</returns>
public ForwardOps<TOut, T> From<TIn, TOut>(FlowShape<TIn, TOut> flow)
{
return new ForwardOps<TOut, T>(this, flow.Outlet);
}
/// <summary>
/// TBD
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <typeparam name="TOut">TBD</typeparam>
/// <param name="flow">TBD</param>
/// <returns>TBD</returns>
public ForwardOps<TOut, T> From<TIn, TOut>(IGraph<FlowShape<TIn, TOut>, T> flow)
{
return new ForwardOps<TOut, T>(this, Add(flow).Outlet);
}
/// <summary>
/// TBD
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <typeparam name="TOut">TBD</typeparam>
/// <param name="fanIn">TBD</param>
/// <returns>TBD</returns>
public ForwardOps<TOut, T> From<TIn, TOut>(UniformFanInShape<TIn, TOut> fanIn)
{
return new ForwardOps<TOut, T>(this, fanIn.Out);
}
/// <summary>
/// TBD
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <typeparam name="TOut">TBD</typeparam>
/// <param name="fanOut">TBD</param>
/// <returns>TBD</returns>
public ForwardOps<TOut, T> From<TIn, TOut>(UniformFanOutShape<TIn, TOut> fanOut)
{
return new ForwardOps<TOut, T>(this, FindOut(this, fanOut, 0));
}
/// <summary>
/// TBD
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <param name="inlet">TBD</param>
/// <returns>TBD</returns>
public ReverseOps<TIn, T> To<TIn>(Inlet<TIn> inlet)
{
return new ReverseOps<TIn, T>(this, inlet);
}
/// <summary>
/// TBD
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <param name="sink">TBD</param>
/// <returns>TBD</returns>
public ReverseOps<TIn, T> To<TIn>(SinkShape<TIn> sink)
{
return new ReverseOps<TIn, T>(this, sink.Inlet);
}
/// <summary>
/// TBD
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <typeparam name="TMat">TBD</typeparam>
/// <param name="sink">TBD</param>
/// <returns>TBD</returns>
public ReverseOps<TIn, T> To<TIn, TMat>(IGraph<SinkShape<TIn>, TMat> sink)
{
return new ReverseOps<TIn, T>(this, Add(sink).Inlet);
}
/// <summary>
/// TBD
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <typeparam name="TOut">TBD</typeparam>
/// <typeparam name="TMat">TBD</typeparam>
/// <param name="flow">TBD</param>
/// <returns>TBD</returns>
public ReverseOps<TIn, T> To<TIn, TOut, TMat>(IGraph<FlowShape<TIn, TOut>, TMat> flow)
{
return new ReverseOps<TIn, T>(this, Add(flow).Inlet);
}
/// <summary>
/// TBD
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <typeparam name="TOut">TBD</typeparam>
/// <param name="flow">TBD</param>
/// <returns>TBD</returns>
public ReverseOps<TIn, T> To<TIn, TOut>(FlowShape<TIn, TOut> flow)
{
return new ReverseOps<TIn, T>(this, flow.Inlet);
}
/// <summary>
/// TBD
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <typeparam name="TOut">TBD</typeparam>
/// <param name="fanOut">TBD</param>
/// <returns>TBD</returns>
public ReverseOps<TIn, T> To<TIn, TOut>(UniformFanOutShape<TIn, TOut> fanOut)
{
return new ReverseOps<TIn, T>(this, fanOut.In);
}
/// <summary>
/// TBD
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <typeparam name="TOut">TBD</typeparam>
/// <param name="fanOut">TBD</param>
/// <returns>TBD</returns>
public ReverseOps<TIn, T> To<TIn, TOut>(UniformFanInShape<TIn, TOut> fanOut)
{
return new ReverseOps<TIn, T>(this, FindIn(this, fanOut, 0));
}
}
/// <summary>
/// TBD
/// </summary>
/// <typeparam name="TOut">TBD</typeparam>
/// <typeparam name="TMat">TBD</typeparam>
public sealed class ForwardOps<TOut, TMat>
{
/// <summary>
/// TBD
/// </summary>
internal readonly Builder<TMat> Builder;
/// <summary>
/// TBD
/// </summary>
/// <param name="builder">TBD</param>
/// <param name="outlet">TBD</param>
public ForwardOps(Builder<TMat> builder, Outlet<TOut> outlet)
{
Builder = builder;
Out = outlet;
}
/// <summary>
/// TBD
/// </summary>
public Outlet<TOut> Out { get; }
}
/// <summary>
/// TBD
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <typeparam name="TMat">TBD</typeparam>
public sealed class ReverseOps<TIn, TMat>
{
/// <summary>
/// TBD
/// </summary>
internal readonly Builder<TMat> Builder;
/// <summary>
/// TBD
/// </summary>
/// <param name="builder">TBD</param>
/// <param name="inlet">TBD</param>
public ReverseOps(Builder<TMat> builder, Inlet<TIn> inlet)
{
Builder = builder;
In = inlet;
}
/// <summary>
/// TBD
/// </summary>
public Inlet<TIn> In { get; }
}
/// <summary>
/// TBD
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <typeparam name="TOut">TBD</typeparam>
/// <typeparam name="T">TBD</typeparam>
/// <param name="builder">TBD</param>
/// <param name="junction">TBD</param>
/// <param name="n">TBD</param>
/// <exception cref="ArgumentException">TBD</exception>
/// <returns>TBD</returns>
internal static Outlet<TOut> FindOut<TIn, TOut, T>(Builder<T> builder, UniformFanOutShape<TIn, TOut> junction, int n)
{
var count = junction.Outlets.Count();
while (n < count)
{
var outlet = junction.Out(n);
if (builder.Module.Downstreams.ContainsKey(outlet)) n++;
else return outlet;
}
throw new ArgumentException("No more outlets on junction");
}
/// <summary>
/// TBD
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <typeparam name="TOut">TBD</typeparam>
/// <typeparam name="T">TBD</typeparam>
/// <param name="builder">TBD</param>
/// <param name="junction">TBD</param>
/// <param name="n">TBD</param>
/// <exception cref="ArgumentException">TBD</exception>
/// <returns>TBD</returns>
internal static Inlet<TIn> FindIn<TIn, TOut, T>(Builder<T> builder, UniformFanInShape<TIn, TOut> junction, int n)
{
var count = junction.Inlets.Count();
while (n < count)
{
var inlet = junction.In(n);
if (builder.Module.Upstreams.ContainsKey(inlet)) n++;
else return inlet;
}
throw new ArgumentException("No more inlets on junction");
}
}
/// <summary>
/// TBD
/// </summary>
public static class ForwardOps
{
/// <summary>
/// TBD
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <typeparam name="TOut">TBD</typeparam>
/// <typeparam name="TMat">TBD</typeparam>
/// <param name="ops">TBD</param>
/// <param name="inlet">TBD</param>
/// <returns>TBD</returns>
public static GraphDsl.Builder<TMat> To<TIn, TOut, TMat>(this GraphDsl.ForwardOps<TOut, TMat> ops, Inlet<TIn> inlet)
where TIn : TOut
{
ops.Builder.AddEdge(ops.Out, inlet);
return ops.Builder;
}
/// <summary>
/// TBD
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <typeparam name="TOut">TBD</typeparam>
/// <typeparam name="TMat">TBD</typeparam>
/// <param name="ops">TBD</param>
/// <param name="sink">TBD</param>
/// <returns>TBD</returns>
public static GraphDsl.Builder<TMat> To<TIn, TOut, TMat>(this GraphDsl.ForwardOps<TOut, TMat> ops, SinkShape<TIn> sink)
where TIn : TOut
{
var b = ops.Builder;
b.AddEdge(ops.Out, sink.Inlet);
return b;
}
/// <summary>
/// TBD
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <typeparam name="TOut">TBD</typeparam>
/// <typeparam name="TMat">TBD</typeparam>
/// <param name="ops">TBD</param>
/// <param name="flow">TBD</param>
/// <returns>TBD</returns>
public static GraphDsl.Builder<TMat> To<TIn, TOut, TMat>(this GraphDsl.ForwardOps<TOut, TMat> ops, FlowShape<TIn, TOut> flow)
where TIn : TOut
{
var b = ops.Builder;
b.AddEdge(ops.Out, flow.Inlet);
return b;
}
/// <summary>
/// TBD
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <typeparam name="TOut">TBD</typeparam>
/// <typeparam name="TMat">TBD</typeparam>
/// <typeparam name="TMat2">TBD</typeparam>
/// <param name="ops">TBD</param>
/// <param name="sink">TBD</param>
/// <returns>TBD</returns>
public static GraphDsl.Builder<TMat> To<TIn, TOut, TMat, TMat2>(this GraphDsl.ForwardOps<TOut, TMat> ops, IGraph<SinkShape<TIn>, TMat2> sink)
where TIn : TOut
{
var b = ops.Builder;
b.AddEdge(ops.Out, b.Add(sink).Inlet);
return b;
}
/// <summary>
/// TBD
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <typeparam name="TOut1">TBD</typeparam>
/// <typeparam name="TOut2">TBD</typeparam>
/// <typeparam name="TMat">TBD</typeparam>
/// <param name="ops">TBD</param>
/// <param name="junction">TBD</param>
/// <returns>TBD</returns>
public static GraphDsl.Builder<TMat> To<TIn, TOut1, TOut2, TMat>(this GraphDsl.ForwardOps<TOut1, TMat> ops, UniformFanInShape<TIn, TOut2> junction)
where TIn : TOut1
{
var b = ops.Builder;
var inlet = GraphDsl.FindIn(b, junction, 0);
b.AddEdge(ops.Out, inlet);
return b;
}
/// <summary>
/// TBD
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <typeparam name="TOut1">TBD</typeparam>
/// <typeparam name="TOut2">TBD</typeparam>
/// <typeparam name="TMat">TBD</typeparam>
/// <param name="ops">TBD</param>
/// <param name="junction">TBD</param>
/// <exception cref="ArgumentException">TBD</exception>
/// <returns>TBD</returns>
public static GraphDsl.Builder<TMat> To<TIn, TOut1, TOut2, TMat>(this GraphDsl.ForwardOps<TOut1, TMat> ops, UniformFanOutShape<TIn, TOut2> junction)
where TIn : TOut1
{
var b = ops.Builder;
if (!b.Module.Upstreams.ContainsKey(junction.In))
{
b.AddEdge(ops.Out, junction.In);
return b;
}
throw new ArgumentException("No more inlets free on junction", nameof(junction));
}
private static Outlet<TOut2> Bind<TIn, TOut1, TOut2, TMat>(GraphDsl.ForwardOps<TOut1, TMat> ops, UniformFanOutShape<TIn, TOut2> junction) where TIn : TOut1
{
var b = ops.Builder;
b.AddEdge(ops.Out, junction.In);
return GraphDsl.FindOut(b, junction, 0);
}
/// <summary>
/// TBD
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <typeparam name="TOut1">TBD</typeparam>
/// <typeparam name="TOut2">TBD</typeparam>
/// <typeparam name="TMat">TBD</typeparam>
/// <param name="ops">TBD</param>
/// <param name="flow">TBD</param>
/// <returns>TBD</returns>
public static GraphDsl.ForwardOps<TOut2, TMat> Via<TIn, TOut1, TOut2, TMat>(this GraphDsl.ForwardOps<TOut1, TMat> ops, FlowShape<TIn, TOut2> flow)
where TIn : TOut1
{
var b = ops.Builder;
b.AddEdge(ops.Out, flow.Inlet);
return new GraphDsl.ForwardOps<TOut2, TMat>(b, flow.Outlet);
}
/// <summary>
/// TBD
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <typeparam name="TOut1">TBD</typeparam>
/// <typeparam name="TOut2">TBD</typeparam>
/// <typeparam name="TMat">TBD</typeparam>
/// <param name="ops">TBD</param>
/// <param name="flow">TBD</param>
/// <returns>TBD</returns>
public static GraphDsl.ForwardOps<TOut2, TMat> Via<TIn, TOut1, TOut2, TMat>(this GraphDsl.ForwardOps<TOut1, TMat> ops, IGraph<FlowShape<TIn, TOut2>, NotUsed> flow)
where TIn : TOut1
{
var b = ops.Builder;
var s = b.Add(flow);
b.AddEdge(ops.Out, s.Inlet);
return new GraphDsl.ForwardOps<TOut2, TMat>(b, s.Outlet);
}
/// <summary>
/// TBD
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <typeparam name="TOut1">TBD</typeparam>
/// <typeparam name="TOut2">TBD</typeparam>
/// <typeparam name="TMat">TBD</typeparam>
/// <param name="ops">TBD</param>
/// <param name="junction">TBD</param>
/// <returns>TBD</returns>
public static GraphDsl.ForwardOps<TOut2, TMat> Via<TIn, TOut1, TOut2, TMat>(this GraphDsl.ForwardOps<TOut1, TMat> ops, UniformFanInShape<TIn, TOut2> junction)
where TIn : TOut1
{
var b = To(ops, junction);
return b.From(junction.Out);
}
/// <summary>
/// TBD
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <typeparam name="TOut1">TBD</typeparam>
/// <typeparam name="TOut2">TBD</typeparam>
/// <typeparam name="TMat">TBD</typeparam>
/// <param name="ops">TBD</param>
/// <param name="junction">TBD</param>
/// <returns>TBD</returns>
public static GraphDsl.ForwardOps<TOut2, TMat> Via<TIn, TOut1, TOut2, TMat>(this GraphDsl.ForwardOps<TOut1, TMat> ops, UniformFanOutShape<TIn, TOut2> junction)
where TIn : TOut1
{
var outlet = Bind(ops, junction);
return ops.Builder.From(outlet);
}
}
/// <summary>
/// TBD
/// </summary>
public static class ReverseOps
{
/// <summary>
/// TBD
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <typeparam name="TOut">TBD</typeparam>
/// <typeparam name="TMat">TBD</typeparam>
/// <param name="ops">TBD</param>
/// <param name="outlet">TBD</param>
/// <returns>TBD</returns>
public static GraphDsl.Builder<TMat> From<TIn, TOut, TMat>(this GraphDsl.ReverseOps<TIn, TMat> ops, Outlet<TOut> outlet)
where TIn : TOut
{
var b = ops.Builder;
b.AddEdge(outlet, ops.In);
return b;
}
/// <summary>
/// TBD
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <typeparam name="TOut">TBD</typeparam>
/// <typeparam name="TMat">TBD</typeparam>
/// <param name="ops">TBD</param>
/// <param name="source">TBD</param>
/// <returns>TBD</returns>
public static GraphDsl.Builder<TMat> From<TIn, TOut, TMat>(this GraphDsl.ReverseOps<TIn, TMat> ops, SourceShape<TOut> source)
where TIn : TOut
{
var b = ops.Builder;
b.AddEdge(source.Outlet, ops.In);
return b;
}
/// <summary>
/// TBD
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <typeparam name="TOut">TBD</typeparam>
/// <typeparam name="TMat">TBD</typeparam>
/// <param name="ops">TBD</param>
/// <param name="source">TBD</param>
/// <returns>TBD</returns>
public static GraphDsl.Builder<TMat> From<TIn, TOut, TMat>(this GraphDsl.ReverseOps<TIn, TMat> ops, IGraph<SourceShape<TOut>, TMat> source)
where TIn : TOut
{
var b = ops.Builder;
var s = b.Add(source);
b.AddEdge(s.Outlet, ops.In);
return b;
}
/// <summary>
/// TBD
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <typeparam name="TOut">TBD</typeparam>
/// <typeparam name="TMat">TBD</typeparam>
/// <param name="ops">TBD</param>
/// <param name="flow">TBD</param>
/// <returns>TBD</returns>
public static GraphDsl.Builder<TMat> From<TIn, TOut, TMat>(this GraphDsl.ReverseOps<TIn, TMat> ops, FlowShape<TIn, TOut> flow)
where TIn : TOut
{
var b = ops.Builder;
b.AddEdge(flow.Outlet, ops.In);
return b;
}
/// <summary>
/// TBD
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <typeparam name="TOut">TBD</typeparam>
/// <typeparam name="TMat">TBD</typeparam>
/// <param name="ops">TBD</param>
/// <param name="junction">TBD</param>
/// <returns>TBD</returns>
public static GraphDsl.Builder<TMat> From<TIn, TOut, TMat>(this GraphDsl.ReverseOps<TIn, TMat> ops, UniformFanInShape<TIn, TOut> junction)
where TIn : TOut
{
Bind(ops, junction);
return ops.Builder;
}
private static Inlet<TIn> Bind<TIn, TOut, TMat>(GraphDsl.ReverseOps<TIn, TMat> ops, UniformFanInShape<TIn, TOut> junction)
where TIn : TOut
{
var b = ops.Builder;
b.AddEdge(junction.Out, ops.In);
return GraphDsl.FindIn(b, junction, 0);
}
/// <summary>
/// TBD
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <typeparam name="TOut1">TBD</typeparam>
/// <typeparam name="TOut2">TBD</typeparam>
/// <typeparam name="TMat">TBD</typeparam>
/// <param name="ops">TBD</param>
/// <param name="junction">TBD</param>
/// <exception cref="ArgumentException">TBD</exception>
/// <returns>TBD</returns>
public static GraphDsl.Builder<TMat> From<TIn, TOut1, TOut2, TMat>(this GraphDsl.ReverseOps<TIn, TMat> ops, UniformFanOutShape<TOut1, TOut2> junction)
where TIn : TOut2
{
var b = ops.Builder;
var count = junction.Outlets.Count();
for (var n = 0; n < count; n++)
{
var outlet = junction.Out(n);
if (!b.Module.Downstreams.ContainsKey(outlet))
{
b.AddEdge(outlet, ops.In);
return b;
}
}
throw new ArgumentException("No more inlets free on junction", nameof(junction));
}
/// <summary>
/// TBD
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <typeparam name="TOut1">TBD</typeparam>
/// <typeparam name="TOut2">TBD</typeparam>
/// <typeparam name="TMat">TBD</typeparam>
/// <param name="ops">TBD</param>
/// <param name="flow">TBD</param>
/// <returns>TBD</returns>
public static GraphDsl.ReverseOps<TOut1, TMat> Via<TIn, TOut1, TOut2, TMat>(this GraphDsl.ReverseOps<TIn, TMat> ops, FlowShape<TOut1, TOut2> flow)
where TIn : TOut2
{
var b = ops.Builder;
b.AddEdge(flow.Outlet, ops.In);
return new GraphDsl.ReverseOps<TOut1, TMat>(b, flow.Inlet);
}
/// <summary>
/// TBD
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <typeparam name="TOut1">TBD</typeparam>
/// <typeparam name="TOut2">TBD</typeparam>
/// <typeparam name="TMat">TBD</typeparam>
/// <param name="ops">TBD</param>
/// <param name="flow">TBD</param>
/// <returns>TBD</returns>
public static GraphDsl.ReverseOps<TOut1, TMat> Via<TIn, TOut1, TOut2, TMat>(this GraphDsl.ReverseOps<TIn, TMat> ops, IGraph<FlowShape<TOut1, TOut2>, TMat> flow)
where TIn : TOut2
{
var b = ops.Builder;
var f = b.Add(flow);
b.AddEdge(f.Outlet, ops.In);
return new GraphDsl.ReverseOps<TOut1, TMat>(b, f.Inlet);
}
/// <summary>
/// TBD
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <typeparam name="TOut">TBD</typeparam>
/// <typeparam name="TMat">TBD</typeparam>
/// <param name="ops">TBD</param>
/// <param name="junction">TBD</param>
/// <returns>TBD</returns>
public static GraphDsl.ReverseOps<TIn, TMat> Via<TIn, TOut, TMat>(this GraphDsl.ReverseOps<TIn, TMat> ops, UniformFanInShape<TIn, TOut> junction)
where TIn : TOut
{
var inlet = Bind(ops, junction);
return ops.Builder.To(inlet);
}
/// <summary>
/// TBD
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <typeparam name="TOut">TBD</typeparam>
/// <typeparam name="TMat">TBD</typeparam>
/// <param name="ops">TBD</param>
/// <param name="junction">TBD</param>
/// <returns>TBD</returns>
public static GraphDsl.ReverseOps<TIn, TMat> Via<TIn, TOut, TMat>(this GraphDsl.ReverseOps<TIn, TMat> ops, UniformFanOutShape<TIn, TOut> junction)
where TIn : TOut
{
var b = From(ops, junction);
return b.To(junction.In);
}
}
}
| |
using System;
using System.Net;
using System.Threading.Tasks;
using AspNetCore_netcoreapp3._0_TestApp.Endpoints;
using AspNetCore_netcoreapp3_0_TestApp.Authentication;
using AspNetCore_netcoreapp3_0_TestApp.Middleware;
using AspNetCore_netcoreapp3_0_TestApp.Services;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Primitives;
using tusdotnet;
using tusdotnet.Helpers;
using tusdotnet.Models;
using tusdotnet.Models.Concatenation;
using tusdotnet.Models.Configuration;
using tusdotnet.Models.Expiration;
using tusdotnet.Stores;
namespace AspNetCore_netcoreapp3._0_TestApp
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
services.AddSingleton(CreateTusConfiguration);
services.AddHostedService<ExpiredFilesCleanupService>();
services.AddAuthentication("BasicAuthentication")
.AddScheme<AuthenticationSchemeOptions, BasicAuthenticationHandler>("BasicAuthentication", null);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.Use((context, next) =>
{
// Default limit was changed some time ago. Should work by setting MaxRequestBodySize to null using ConfigureKestrel but this does not seem to work for IISExpress.
// Source: https://github.com/aspnet/Announcements/issues/267
context.Features.Get<IHttpMaxRequestBodySizeFeature>().MaxRequestBodySize = null;
return next.Invoke();
});
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseSimpleExceptionHandler();
app.UseAuthentication();
app.UseDefaultFiles();
app.UseStaticFiles();
app.UseHttpsRedirection();
app.UseCors(builder => builder
.AllowAnyHeader()
.AllowAnyMethod()
.AllowAnyOrigin()
.WithExposedHeaders(CorsHelper.GetExposedHeaders()));
// httpContext parameter can be used to create a tus configuration based on current user, domain, host, port or whatever.
// In this case we just return the same configuration for everyone.
app.UseTus(httpContext => Task.FromResult(httpContext.RequestServices.GetService<DefaultTusConfiguration>()));
app.UseRouting();
// All GET requests to tusdotnet are forwarded so that you can handle file downloads.
// This is done because the file's metadata is domain specific and thus cannot be handled
// in a generic way by tusdotnet.
app.UseEndpoints(endpoints => endpoints.MapGet("/files/{fileId}", DownloadFileEndpoint.HandleRoute));
}
private DefaultTusConfiguration CreateTusConfiguration(IServiceProvider serviceProvider)
{
var logger = serviceProvider.GetService<ILoggerFactory>().CreateLogger<Startup>();
// Change the value of EnableOnAuthorize in appsettings.json to enable or disable
// the new authorization event.
var enableAuthorize = Configuration.GetValue<bool>("EnableOnAuthorize");
return new DefaultTusConfiguration
{
UrlPath = "/files",
Store = new TusDiskStore(@"C:\tusfiles\"),
MetadataParsingStrategy = MetadataParsingStrategy.AllowEmptyValues,
Events = new Events
{
OnAuthorizeAsync = ctx =>
{
if (!enableAuthorize)
return Task.CompletedTask;
if (!ctx.HttpContext.User.Identity.IsAuthenticated)
{
ctx.HttpContext.Response.Headers.Add("WWW-Authenticate", new StringValues("Basic realm=tusdotnet-test-netcoreapp2.2"));
ctx.FailRequest(HttpStatusCode.Unauthorized);
return Task.CompletedTask;
}
if (ctx.HttpContext.User.Identity.Name != "test")
{
ctx.FailRequest(HttpStatusCode.Forbidden, "'test' is the only allowed user");
return Task.CompletedTask;
}
// Do other verification on the user; claims, roles, etc.
// Verify different things depending on the intent of the request.
// E.g.:
// Does the file about to be written belong to this user?
// Is the current user allowed to create new files or have they reached their quota?
// etc etc
switch (ctx.Intent)
{
case IntentType.CreateFile:
break;
case IntentType.ConcatenateFiles:
break;
case IntentType.WriteFile:
break;
case IntentType.DeleteFile:
break;
case IntentType.GetFileInfo:
break;
case IntentType.GetOptions:
break;
default:
break;
}
return Task.CompletedTask;
},
OnBeforeCreateAsync = ctx =>
{
// Partial files are not complete so we do not need to validate
// the metadata in our example.
if (ctx.FileConcatenation is FileConcatPartial)
{
return Task.CompletedTask;
}
if (!ctx.Metadata.ContainsKey("name") || ctx.Metadata["name"].HasEmptyValue)
{
ctx.FailRequest("name metadata must be specified. ");
}
if (!ctx.Metadata.ContainsKey("contentType") || ctx.Metadata["contentType"].HasEmptyValue)
{
ctx.FailRequest("contentType metadata must be specified. ");
}
return Task.CompletedTask;
},
OnCreateCompleteAsync = ctx =>
{
logger.LogInformation($"Created file {ctx.FileId} using {ctx.Store.GetType().FullName}");
return Task.CompletedTask;
},
OnBeforeDeleteAsync = ctx =>
{
// Can the file be deleted? If not call ctx.FailRequest(<message>);
return Task.CompletedTask;
},
OnDeleteCompleteAsync = ctx =>
{
logger.LogInformation($"Deleted file {ctx.FileId} using {ctx.Store.GetType().FullName}");
return Task.CompletedTask;
},
OnFileCompleteAsync = ctx =>
{
logger.LogInformation($"Upload of {ctx.FileId} completed using {ctx.Store.GetType().FullName}");
// If the store implements ITusReadableStore one could access the completed file here.
// The default TusDiskStore implements this interface:
//var file = await ctx.GetFileAsync();
return Task.CompletedTask;
}
},
// Set an expiration time where incomplete files can no longer be updated.
// This value can either be absolute or sliding.
// Absolute expiration will be saved per file on create
// Sliding expiration will be saved per file on create and updated on each patch/update.
Expiration = new AbsoluteExpiration(TimeSpan.FromMinutes(5))
};
}
}
}
| |
namespace DeOps.Services.Plan
{
partial class GoalPanel
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
DeOps.Interface.TLVex.ToggleColumnHeader toggleColumnHeader1 = new DeOps.Interface.TLVex.ToggleColumnHeader();
DeOps.Interface.TLVex.ToggleColumnHeader toggleColumnHeader2 = new DeOps.Interface.TLVex.ToggleColumnHeader();
DeOps.Interface.TLVex.ToggleColumnHeader toggleColumnHeader3 = new DeOps.Interface.TLVex.ToggleColumnHeader();
DeOps.Interface.TLVex.ToggleColumnHeader toggleColumnHeader4 = new DeOps.Interface.TLVex.ToggleColumnHeader();
DeOps.Interface.TLVex.ToggleColumnHeader toggleColumnHeader5 = new DeOps.Interface.TLVex.ToggleColumnHeader();
DeOps.Interface.TLVex.ToggleColumnHeader toggleColumnHeader6 = new DeOps.Interface.TLVex.ToggleColumnHeader();
DeOps.Interface.TLVex.ToggleColumnHeader toggleColumnHeader7 = new DeOps.Interface.TLVex.ToggleColumnHeader();
this.splitContainer1 = new System.Windows.Forms.SplitContainer();
this.MineOnly = new System.Windows.Forms.CheckBox();
this.DelegateLink = new System.Windows.Forms.LinkLabel();
this.GoalTree = new DeOps.Interface.TLVex.TreeListViewEx();
this.AddItemLink = new System.Windows.Forms.LinkLabel();
this.PlanList = new DeOps.Interface.TLVex.ContainerListViewEx();
this.splitContainer1.Panel1.SuspendLayout();
this.splitContainer1.Panel2.SuspendLayout();
this.splitContainer1.SuspendLayout();
this.SuspendLayout();
//
// splitContainer1
//
this.splitContainer1.Dock = System.Windows.Forms.DockStyle.Fill;
this.splitContainer1.Location = new System.Drawing.Point(0, 0);
this.splitContainer1.Name = "splitContainer1";
this.splitContainer1.Orientation = System.Windows.Forms.Orientation.Horizontal;
//
// splitContainer1.Panel1
//
this.splitContainer1.Panel1.BackColor = System.Drawing.Color.White;
this.splitContainer1.Panel1.Controls.Add(this.MineOnly);
this.splitContainer1.Panel1.Controls.Add(this.DelegateLink);
this.splitContainer1.Panel1.Controls.Add(this.GoalTree);
//
// splitContainer1.Panel2
//
this.splitContainer1.Panel2.BackColor = System.Drawing.Color.White;
this.splitContainer1.Panel2.Controls.Add(this.AddItemLink);
this.splitContainer1.Panel2.Controls.Add(this.PlanList);
this.splitContainer1.Size = new System.Drawing.Size(469, 343);
this.splitContainer1.SplitterDistance = 212;
this.splitContainer1.TabIndex = 0;
//
// MineOnly
//
this.MineOnly.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.MineOnly.AutoSize = true;
this.MineOnly.Location = new System.Drawing.Point(359, 197);
this.MineOnly.Name = "MineOnly";
this.MineOnly.Size = new System.Drawing.Size(112, 17);
this.MineOnly.TabIndex = 2;
this.MineOnly.Text = "My Branches Only";
this.MineOnly.UseVisualStyleBackColor = true;
this.MineOnly.CheckedChanged += new System.EventHandler(this.MineOnly_CheckedChanged);
//
// DelegateLink
//
this.DelegateLink.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.DelegateLink.LinkBehavior = System.Windows.Forms.LinkBehavior.HoverUnderline;
this.DelegateLink.Location = new System.Drawing.Point(3, 198);
this.DelegateLink.Name = "DelegateLink";
this.DelegateLink.Size = new System.Drawing.Size(350, 13);
this.DelegateLink.TabIndex = 1;
this.DelegateLink.TabStop = true;
this.DelegateLink.Text = "Delegate Responsibility";
this.DelegateLink.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.DelegateLink_LinkClicked);
//
// GoalTree
//
this.GoalTree.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.GoalTree.BackColor = System.Drawing.SystemColors.Window;
this.GoalTree.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
toggleColumnHeader1.Hovered = false;
toggleColumnHeader1.Image = null;
toggleColumnHeader1.Index = 0;
toggleColumnHeader1.Pressed = false;
toggleColumnHeader1.ScaleStyle = DeOps.Interface.TLVex.ColumnScaleStyle.Spring;
toggleColumnHeader1.Selected = false;
toggleColumnHeader1.Text = "Goal";
toggleColumnHeader1.TextAlign = System.Windows.Forms.HorizontalAlignment.Left;
toggleColumnHeader1.Visible = true;
toggleColumnHeader1.Width = 129;
toggleColumnHeader2.Hovered = false;
toggleColumnHeader2.Image = null;
toggleColumnHeader2.Index = 0;
toggleColumnHeader2.Pressed = false;
toggleColumnHeader2.ScaleStyle = DeOps.Interface.TLVex.ColumnScaleStyle.Slide;
toggleColumnHeader2.Selected = false;
toggleColumnHeader2.Text = "Person";
toggleColumnHeader2.TextAlign = System.Windows.Forms.HorizontalAlignment.Left;
toggleColumnHeader2.Visible = true;
toggleColumnHeader2.Width = 110;
toggleColumnHeader3.Hovered = false;
toggleColumnHeader3.Image = null;
toggleColumnHeader3.Index = 0;
toggleColumnHeader3.Pressed = false;
toggleColumnHeader3.ScaleStyle = DeOps.Interface.TLVex.ColumnScaleStyle.Slide;
toggleColumnHeader3.Selected = false;
toggleColumnHeader3.Text = "All Progress";
toggleColumnHeader3.TextAlign = System.Windows.Forms.HorizontalAlignment.Left;
toggleColumnHeader3.Visible = true;
toggleColumnHeader3.Width = 140;
toggleColumnHeader4.Hovered = false;
toggleColumnHeader4.Image = null;
toggleColumnHeader4.Index = 0;
toggleColumnHeader4.Pressed = false;
toggleColumnHeader4.ScaleStyle = DeOps.Interface.TLVex.ColumnScaleStyle.Slide;
toggleColumnHeader4.Selected = false;
toggleColumnHeader4.Text = "Deadline";
toggleColumnHeader4.TextAlign = System.Windows.Forms.HorizontalAlignment.Left;
toggleColumnHeader4.Visible = true;
this.GoalTree.Columns.AddRange(new DeOps.Interface.TLVex.ToggleColumnHeader[] {
toggleColumnHeader1,
toggleColumnHeader2,
toggleColumnHeader3,
toggleColumnHeader4});
this.GoalTree.ColumnSortColor = System.Drawing.Color.Gainsboro;
this.GoalTree.ColumnTrackColor = System.Drawing.Color.WhiteSmoke;
this.GoalTree.DisableHorizontalScroll = true;
this.GoalTree.GridLineColor = System.Drawing.Color.WhiteSmoke;
this.GoalTree.HeaderMenu = null;
this.GoalTree.HideSelection = false;
this.GoalTree.ItemHeight = 20;
this.GoalTree.ItemMenu = null;
this.GoalTree.LabelEdit = false;
this.GoalTree.Location = new System.Drawing.Point(0, 0);
this.GoalTree.Name = "GoalTree";
this.GoalTree.RowSelectColor = System.Drawing.SystemColors.Highlight;
this.GoalTree.RowTrackColor = System.Drawing.Color.WhiteSmoke;
this.GoalTree.ShowLines = true;
this.GoalTree.Size = new System.Drawing.Size(471, 214);
this.GoalTree.SmallImageList = null;
this.GoalTree.StateImageList = null;
this.GoalTree.TabIndex = 0;
this.GoalTree.MouseClick += new System.Windows.Forms.MouseEventHandler(this.GoalTree_MouseClick);
this.GoalTree.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler(this.GoalTree_MouseDoubleClick);
this.GoalTree.SelectedItemChanged += new System.EventHandler(this.GoalTree_SelectedItemChanged);
//
// AddItemLink
//
this.AddItemLink.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.AddItemLink.LinkBehavior = System.Windows.Forms.LinkBehavior.HoverUnderline;
this.AddItemLink.Location = new System.Drawing.Point(3, 112);
this.AddItemLink.Name = "AddItemLink";
this.AddItemLink.Size = new System.Drawing.Size(463, 13);
this.AddItemLink.TabIndex = 5;
this.AddItemLink.TabStop = true;
this.AddItemLink.Text = "Add Item to My Plan";
this.AddItemLink.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.AddItemLink_LinkClicked);
//
// PlanList
//
this.PlanList.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.PlanList.BackColor = System.Drawing.SystemColors.Window;
this.PlanList.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
toggleColumnHeader5.Hovered = false;
toggleColumnHeader5.Image = null;
toggleColumnHeader5.Index = 0;
toggleColumnHeader5.Pressed = false;
toggleColumnHeader5.ScaleStyle = DeOps.Interface.TLVex.ColumnScaleStyle.Spring;
toggleColumnHeader5.Selected = false;
toggleColumnHeader5.Text = "Plan";
toggleColumnHeader5.TextAlign = System.Windows.Forms.HorizontalAlignment.Left;
toggleColumnHeader5.Visible = true;
toggleColumnHeader5.Width = 207;
toggleColumnHeader6.Hovered = false;
toggleColumnHeader6.Image = null;
toggleColumnHeader6.Index = 0;
toggleColumnHeader6.Pressed = false;
toggleColumnHeader6.ScaleStyle = DeOps.Interface.TLVex.ColumnScaleStyle.Slide;
toggleColumnHeader6.Selected = false;
toggleColumnHeader6.Text = "Time Estimate";
toggleColumnHeader6.TextAlign = System.Windows.Forms.HorizontalAlignment.Left;
toggleColumnHeader6.Visible = true;
toggleColumnHeader7.Hovered = false;
toggleColumnHeader7.Image = null;
toggleColumnHeader7.Index = 0;
toggleColumnHeader7.Pressed = false;
toggleColumnHeader7.ScaleStyle = DeOps.Interface.TLVex.ColumnScaleStyle.Slide;
toggleColumnHeader7.Selected = false;
toggleColumnHeader7.Text = "Progress";
toggleColumnHeader7.TextAlign = System.Windows.Forms.HorizontalAlignment.Left;
toggleColumnHeader7.Visible = true;
toggleColumnHeader7.Width = 170;
this.PlanList.Columns.AddRange(new DeOps.Interface.TLVex.ToggleColumnHeader[] {
toggleColumnHeader5,
toggleColumnHeader6,
toggleColumnHeader7});
this.PlanList.ColumnSortColor = System.Drawing.Color.Gainsboro;
this.PlanList.ColumnTrackColor = System.Drawing.Color.WhiteSmoke;
this.PlanList.DisableHorizontalScroll = true;
this.PlanList.GridLineColor = System.Drawing.Color.WhiteSmoke;
this.PlanList.HeaderMenu = null;
this.PlanList.ItemMenu = null;
this.PlanList.LabelEdit = false;
this.PlanList.Location = new System.Drawing.Point(0, 0);
this.PlanList.Name = "PlanList";
this.PlanList.RowSelectColor = System.Drawing.SystemColors.Highlight;
this.PlanList.RowTrackColor = System.Drawing.Color.WhiteSmoke;
this.PlanList.Size = new System.Drawing.Size(469, 127);
this.PlanList.SmallImageList = null;
this.PlanList.StateImageList = null;
this.PlanList.TabIndex = 4;
this.PlanList.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler(this.PlanList_MouseDoubleClick);
this.PlanList.MouseClick += new System.Windows.Forms.MouseEventHandler(this.PlanList_MouseClick);
this.PlanList.SelectedIndexChanged += new System.EventHandler(this.PlanList_SelectedIndexChanged);
//
// GoalPanel
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.Color.WhiteSmoke;
this.Controls.Add(this.splitContainer1);
this.Name = "GoalPanel";
this.Size = new System.Drawing.Size(469, 343);
this.splitContainer1.Panel1.ResumeLayout(false);
this.splitContainer1.Panel1.PerformLayout();
this.splitContainer1.Panel2.ResumeLayout(false);
this.splitContainer1.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.SplitContainer splitContainer1;
private System.Windows.Forms.LinkLabel DelegateLink;
public DeOps.Interface.TLVex.TreeListViewEx GoalTree;
private System.Windows.Forms.CheckBox MineOnly;
private System.Windows.Forms.LinkLabel AddItemLink;
private DeOps.Interface.TLVex.ContainerListViewEx PlanList;
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#region Using directives
using System.Collections.Generic;
using System.Globalization;
using System.Management.Automation;
using System.Text;
#endregion
namespace Microsoft.Management.Infrastructure.CimCmdlets
{
/// <summary>
/// A class used to add pstypename to partial ciminstance
/// for <see cref="GetCimInstanceCommand"/>, if -KeyOnly
/// or -SelectProperties is been specified, then add a pstypename:
/// "Microsoft.Management.Infrastructure.CimInstance#__PartialCIMInstance"
/// </summary>
internal class FormatPartialCimInstance : IObjectPreProcess
{
/// <summary>
/// Partial ciminstance pstypename.
/// </summary>
internal const string PartialPSTypeName = @"Microsoft.Management.Infrastructure.CimInstance#__PartialCIMInstance";
/// <summary>
/// Add pstypename to the resultobject if necessary.
/// </summary>
/// <param name="resultObject"></param>
/// <returns></returns>
public object Process(object resultObject)
{
if (resultObject is CimInstance)
{
PSObject obj = PSObject.AsPSObject(resultObject);
obj.TypeNames.Insert(0, PartialPSTypeName);
return obj;
}
return resultObject;
}
}
/// <summary>
/// <para>
/// Implements operations of get-ciminstance cmdlet.
/// </para>
/// </summary>
internal class CimGetInstance : CimAsyncOperation
{
/// <summary>
/// Initializes a new instance of the <see cref="CimGetInstance"/> class.
/// <para>
/// Constructor
/// </para>
/// </summary>
public CimGetInstance() : base()
{
}
/// <summary>
/// <para>
/// Base on parametersetName to retrieve ciminstances
/// </para>
/// </summary>
/// <param name="cmdlet"><see cref="GetCimInstanceCommand"/> object.</param>
public void GetCimInstance(GetCimInstanceCommand cmdlet)
{
GetCimInstanceInternal(cmdlet);
}
/// <summary>
/// <para>
/// Refactor to be reused by Get-CimInstance;Remove-CimInstance;Set-CimInstance
/// </para>
/// </summary>
/// <param name="cmdlet"></param>
protected void GetCimInstanceInternal(CimBaseCommand cmdlet)
{
IEnumerable<string> computerNames = ConstValue.GetComputerNames(
GetComputerName(cmdlet));
string nameSpace;
List<CimSessionProxy> proxys = new();
bool isGetCimInstanceCommand = cmdlet is GetCimInstanceCommand;
CimInstance targetCimInstance = null;
switch (cmdlet.ParameterSetName)
{
case CimBaseCommand.CimInstanceComputerSet:
foreach (string computerName in computerNames)
{
targetCimInstance = GetCimInstanceParameter(cmdlet);
CimSessionProxy proxy = CreateSessionProxy(computerName, targetCimInstance, cmdlet);
if (isGetCimInstanceCommand)
{
SetPreProcess(proxy, cmdlet as GetCimInstanceCommand);
}
proxys.Add(proxy);
}
break;
case CimBaseCommand.ClassNameComputerSet:
case CimBaseCommand.QueryComputerSet:
case CimBaseCommand.ResourceUriComputerSet:
foreach (string computerName in computerNames)
{
CimSessionProxy proxy = CreateSessionProxy(computerName, cmdlet);
if (isGetCimInstanceCommand)
{
SetPreProcess(proxy, cmdlet as GetCimInstanceCommand);
}
proxys.Add(proxy);
}
break;
case CimBaseCommand.ClassNameSessionSet:
case CimBaseCommand.CimInstanceSessionSet:
case CimBaseCommand.QuerySessionSet:
case CimBaseCommand.ResourceUriSessionSet:
foreach (CimSession session in GetCimSession(cmdlet))
{
CimSessionProxy proxy = CreateSessionProxy(session, cmdlet);
if (isGetCimInstanceCommand)
{
SetPreProcess(proxy, cmdlet as GetCimInstanceCommand);
}
proxys.Add(proxy);
}
break;
default:
break;
}
switch (cmdlet.ParameterSetName)
{
case CimBaseCommand.ClassNameComputerSet:
case CimBaseCommand.ClassNameSessionSet:
nameSpace = ConstValue.GetNamespace(GetNamespace(cmdlet));
if (IsClassNameQuerySet(cmdlet))
{
string query = CreateQuery(cmdlet);
DebugHelper.WriteLogEx(@"Query = {0}", 1, query);
foreach (CimSessionProxy proxy in proxys)
{
proxy.QueryInstancesAsync(nameSpace,
ConstValue.GetQueryDialectWithDefault(GetQueryDialect(cmdlet)),
query);
}
}
else
{
foreach (CimSessionProxy proxy in proxys)
{
proxy.EnumerateInstancesAsync(nameSpace, GetClassName(cmdlet));
}
}
break;
case CimBaseCommand.CimInstanceComputerSet:
case CimBaseCommand.CimInstanceSessionSet:
{
CimInstance instance = GetCimInstanceParameter(cmdlet);
nameSpace = ConstValue.GetNamespace(instance.CimSystemProperties.Namespace);
foreach (CimSessionProxy proxy in proxys)
{
proxy.GetInstanceAsync(nameSpace, instance);
}
}
break;
case CimBaseCommand.QueryComputerSet:
case CimBaseCommand.QuerySessionSet:
nameSpace = ConstValue.GetNamespace(GetNamespace(cmdlet));
foreach (CimSessionProxy proxy in proxys)
{
proxy.QueryInstancesAsync(nameSpace,
ConstValue.GetQueryDialectWithDefault(GetQueryDialect(cmdlet)),
GetQuery(cmdlet));
}
break;
case CimBaseCommand.ResourceUriSessionSet:
case CimBaseCommand.ResourceUriComputerSet:
foreach (CimSessionProxy proxy in proxys)
{
proxy.EnumerateInstancesAsync(GetNamespace(cmdlet), GetClassName(cmdlet));
}
break;
default:
break;
}
}
#region bridge methods to read properties from cmdlet
protected static string[] GetComputerName(CimBaseCommand cmdlet)
{
if (cmdlet is GetCimInstanceCommand)
{
return (cmdlet as GetCimInstanceCommand).ComputerName;
}
else if (cmdlet is RemoveCimInstanceCommand)
{
return (cmdlet as RemoveCimInstanceCommand).ComputerName;
}
else if (cmdlet is SetCimInstanceCommand)
{
return (cmdlet as SetCimInstanceCommand).ComputerName;
}
return null;
}
protected static string GetNamespace(CimBaseCommand cmdlet)
{
if (cmdlet is GetCimInstanceCommand)
{
return (cmdlet as GetCimInstanceCommand).Namespace;
}
else if (cmdlet is RemoveCimInstanceCommand)
{
return (cmdlet as RemoveCimInstanceCommand).Namespace;
}
else if (cmdlet is SetCimInstanceCommand)
{
return (cmdlet as SetCimInstanceCommand).Namespace;
}
return null;
}
protected static CimSession[] GetCimSession(CimBaseCommand cmdlet)
{
if (cmdlet is GetCimInstanceCommand)
{
return (cmdlet as GetCimInstanceCommand).CimSession;
}
else if (cmdlet is RemoveCimInstanceCommand)
{
return (cmdlet as RemoveCimInstanceCommand).CimSession;
}
else if (cmdlet is SetCimInstanceCommand)
{
return (cmdlet as SetCimInstanceCommand).CimSession;
}
return null;
}
protected static string GetClassName(CimBaseCommand cmdlet)
{
if (cmdlet is GetCimInstanceCommand)
{
return (cmdlet as GetCimInstanceCommand).ClassName;
}
return null;
}
protected static string GetQuery(CimBaseCommand cmdlet)
{
if (cmdlet is GetCimInstanceCommand)
{
return (cmdlet as GetCimInstanceCommand).Query;
}
else if (cmdlet is RemoveCimInstanceCommand)
{
return (cmdlet as RemoveCimInstanceCommand).Query;
}
else if (cmdlet is SetCimInstanceCommand)
{
return (cmdlet as SetCimInstanceCommand).Query;
}
return null;
}
internal static bool IsClassNameQuerySet(CimBaseCommand cmdlet)
{
DebugHelper.WriteLogEx();
GetCimInstanceCommand cmd = cmdlet as GetCimInstanceCommand;
if (cmd != null)
{
if (cmd.QueryDialect != null || cmd.SelectProperties != null || cmd.Filter != null)
{
return true;
}
}
return false;
}
protected static string CreateQuery(CimBaseCommand cmdlet)
{
DebugHelper.WriteLogEx();
GetCimInstanceCommand cmd = cmdlet as GetCimInstanceCommand;
if (cmd != null)
{
StringBuilder propertyList = new();
if (cmd.SelectProperties == null)
{
propertyList.Append('*');
}
else
{
foreach (string property in cmd.SelectProperties)
{
if (propertyList.Length > 0)
{
propertyList.Append(',');
}
propertyList.Append(property);
}
}
return (cmd.Filter == null) ?
string.Format(CultureInfo.CurrentUICulture, queryWithoutWhere, propertyList, cmd.ClassName) :
string.Format(CultureInfo.CurrentUICulture, queryWithWhere, propertyList, cmd.ClassName, cmd.Filter);
}
return null;
}
protected static string GetQueryDialect(CimBaseCommand cmdlet)
{
if (cmdlet is GetCimInstanceCommand)
{
return (cmdlet as GetCimInstanceCommand).QueryDialect;
}
else if (cmdlet is RemoveCimInstanceCommand)
{
return (cmdlet as RemoveCimInstanceCommand).QueryDialect;
}
else if (cmdlet is SetCimInstanceCommand)
{
return (cmdlet as SetCimInstanceCommand).QueryDialect;
}
return null;
}
protected static CimInstance GetCimInstanceParameter(CimBaseCommand cmdlet)
{
if (cmdlet is GetCimInstanceCommand)
{
return (cmdlet as GetCimInstanceCommand).CimInstance;
}
else if (cmdlet is RemoveCimInstanceCommand)
{
return (cmdlet as RemoveCimInstanceCommand).CimInstance;
}
else if (cmdlet is SetCimInstanceCommand)
{
return (cmdlet as SetCimInstanceCommand).CimInstance;
}
return null;
}
#endregion
#region help methods
/// <summary>
/// <para>
/// Set <see cref="CimSessionProxy"/> properties
/// </para>
/// </summary>
/// <param name="proxy"></param>
/// <param name="cmdlet"></param>
private static void SetSessionProxyProperties(
ref CimSessionProxy proxy,
CimBaseCommand cmdlet)
{
if (cmdlet is GetCimInstanceCommand)
{
GetCimInstanceCommand getCimInstance = cmdlet as GetCimInstanceCommand;
proxy.KeyOnly = getCimInstance.KeyOnly;
proxy.Shallow = getCimInstance.Shallow;
proxy.OperationTimeout = getCimInstance.OperationTimeoutSec;
if (getCimInstance.ResourceUri != null)
{
proxy.ResourceUri = getCimInstance.ResourceUri;
}
}
else if (cmdlet is RemoveCimInstanceCommand)
{
RemoveCimInstanceCommand removeCimInstance = cmdlet as RemoveCimInstanceCommand;
proxy.OperationTimeout = removeCimInstance.OperationTimeoutSec;
if (removeCimInstance.ResourceUri != null)
{
proxy.ResourceUri = removeCimInstance.ResourceUri;
}
CimRemoveCimInstanceContext context = new(
ConstValue.GetNamespace(removeCimInstance.Namespace),
proxy);
proxy.ContextObject = context;
}
else if (cmdlet is SetCimInstanceCommand)
{
SetCimInstanceCommand setCimInstance = cmdlet as SetCimInstanceCommand;
proxy.OperationTimeout = setCimInstance.OperationTimeoutSec;
if (setCimInstance.ResourceUri != null)
{
proxy.ResourceUri = setCimInstance.ResourceUri;
}
CimSetCimInstanceContext context = new(
ConstValue.GetNamespace(setCimInstance.Namespace),
setCimInstance.Property,
proxy,
cmdlet.ParameterSetName,
setCimInstance.PassThru);
proxy.ContextObject = context;
}
}
/// <summary>
/// <para>
/// Create <see cref="CimSessionProxy"/> and set properties.
/// </para>
/// </summary>
/// <param name="computerName"></param>
/// <param name="cmdlet"></param>
/// <returns></returns>
protected CimSessionProxy CreateSessionProxy(
string computerName,
CimBaseCommand cmdlet)
{
CimSessionProxy proxy = CreateCimSessionProxy(computerName);
SetSessionProxyProperties(ref proxy, cmdlet);
return proxy;
}
/// <summary>
/// <para>
/// Create <see cref="CimSessionProxy"/> and set properties.
/// </para>
/// </summary>
/// <param name="computerName"></param>
/// <param name="cimInstance"></param>
/// <param name="cmdlet"></param>
/// <returns></returns>
protected CimSessionProxy CreateSessionProxy(
string computerName,
CimInstance cimInstance,
CimBaseCommand cmdlet,
bool passThru)
{
CimSessionProxy proxy = CreateCimSessionProxy(computerName, cimInstance, passThru);
SetSessionProxyProperties(ref proxy, cmdlet);
return proxy;
}
/// <summary>
/// Create <see cref="CimSessionProxy"/> and set properties.
/// </summary>
/// <param name="session"></param>
/// <param name="cmdlet"></param>
/// <returns></returns>
protected CimSessionProxy CreateSessionProxy(
CimSession session,
CimBaseCommand cmdlet)
{
CimSessionProxy proxy = CreateCimSessionProxy(session);
SetSessionProxyProperties(ref proxy, cmdlet);
return proxy;
}
/// <summary>
/// <para>
/// Create <see cref="CimSessionProxy"/> and set properties
/// </para>
/// </summary>
/// <param name="computerName"></param>
/// <param name="cimInstance"></param>
/// <param name="cmdlet"></param>
/// <returns></returns>
protected CimSessionProxy CreateSessionProxy(
string computerName,
CimInstance cimInstance,
CimBaseCommand cmdlet)
{
CimSessionProxy proxy = CreateCimSessionProxy(computerName, cimInstance);
SetSessionProxyProperties(ref proxy, cmdlet);
return proxy;
}
/// <summary>
/// Create <see cref="CimSessionProxy"/> and set properties.
/// </summary>
/// <param name="session"></param>
/// <param name="cmdlet"></param>
/// <returns></returns>
protected CimSessionProxy CreateSessionProxy(
CimSession session,
CimBaseCommand cmdlet,
bool passThru)
{
CimSessionProxy proxy = CreateCimSessionProxy(session, passThru);
SetSessionProxyProperties(ref proxy, cmdlet);
return proxy;
}
/// <summary>
/// Set <see cref="IObjectPreProcess"/> object to proxy to pre-process
/// the result object if necessary.
/// </summary>
/// <param name="proxy"></param>
/// <param name="cmdlet"></param>
private static void SetPreProcess(CimSessionProxy proxy, GetCimInstanceCommand cmdlet)
{
if (cmdlet.KeyOnly || (cmdlet.SelectProperties != null))
{
proxy.ObjectPreProcess = new FormatPartialCimInstance();
}
}
#endregion
#region const strings
/// <summary>
/// Wql query format with where clause.
/// </summary>
private const string queryWithWhere = @"SELECT {0} FROM {1} WHERE {2}";
/// <summary>
/// Wql query format without where clause.
/// </summary>
private const string queryWithoutWhere = @"SELECT {0} FROM {1}";
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.16.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Network
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// Extension methods for ExpressRouteCircuitAuthorizationsOperations.
/// </summary>
public static partial class ExpressRouteCircuitAuthorizationsOperationsExtensions
{
/// <summary>
/// The delete authorization operation deletes the specified authorization
/// from the specified ExpressRouteCircuit.
/// </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='authorizationName'>
/// The name of the authorization.
/// </param>
public static void Delete(this IExpressRouteCircuitAuthorizationsOperations operations, string resourceGroupName, string circuitName, string authorizationName)
{
Task.Factory.StartNew(s => ((IExpressRouteCircuitAuthorizationsOperations)s).DeleteAsync(resourceGroupName, circuitName, authorizationName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The delete authorization operation deletes the specified authorization
/// from the specified ExpressRouteCircuit.
/// </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='authorizationName'>
/// The name of the authorization.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this IExpressRouteCircuitAuthorizationsOperations operations, string resourceGroupName, string circuitName, string authorizationName, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.DeleteWithHttpMessagesAsync(resourceGroupName, circuitName, authorizationName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// The delete authorization operation deletes the specified authorization
/// from the specified ExpressRouteCircuit.
/// </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='authorizationName'>
/// The name of the authorization.
/// </param>
public static void BeginDelete(this IExpressRouteCircuitAuthorizationsOperations operations, string resourceGroupName, string circuitName, string authorizationName)
{
Task.Factory.StartNew(s => ((IExpressRouteCircuitAuthorizationsOperations)s).BeginDeleteAsync(resourceGroupName, circuitName, authorizationName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The delete authorization operation deletes the specified authorization
/// from the specified ExpressRouteCircuit.
/// </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='authorizationName'>
/// The name of the authorization.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginDeleteAsync(this IExpressRouteCircuitAuthorizationsOperations operations, string resourceGroupName, string circuitName, string authorizationName, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, circuitName, authorizationName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// The GET authorization operation retrieves the specified authorization from
/// the specified ExpressRouteCircuit.
/// </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='authorizationName'>
/// The name of the authorization.
/// </param>
public static ExpressRouteCircuitAuthorization Get(this IExpressRouteCircuitAuthorizationsOperations operations, string resourceGroupName, string circuitName, string authorizationName)
{
return Task.Factory.StartNew(s => ((IExpressRouteCircuitAuthorizationsOperations)s).GetAsync(resourceGroupName, circuitName, authorizationName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The GET authorization operation retrieves the specified authorization from
/// the specified ExpressRouteCircuit.
/// </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='authorizationName'>
/// The name of the authorization.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ExpressRouteCircuitAuthorization> GetAsync(this IExpressRouteCircuitAuthorizationsOperations operations, string resourceGroupName, string circuitName, string authorizationName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, circuitName, authorizationName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// The Put Authorization operation creates/updates an authorization in the
/// specified ExpressRouteCircuits
/// </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='authorizationName'>
/// The name of the authorization.
/// </param>
/// <param name='authorizationParameters'>
/// Parameters supplied to the create/update ExpressRouteCircuitAuthorization
/// operation
/// </param>
public static ExpressRouteCircuitAuthorization CreateOrUpdate(this IExpressRouteCircuitAuthorizationsOperations operations, string resourceGroupName, string circuitName, string authorizationName, ExpressRouteCircuitAuthorization authorizationParameters)
{
return Task.Factory.StartNew(s => ((IExpressRouteCircuitAuthorizationsOperations)s).CreateOrUpdateAsync(resourceGroupName, circuitName, authorizationName, authorizationParameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Put Authorization operation creates/updates an authorization in the
/// specified ExpressRouteCircuits
/// </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='authorizationName'>
/// The name of the authorization.
/// </param>
/// <param name='authorizationParameters'>
/// Parameters supplied to the create/update ExpressRouteCircuitAuthorization
/// operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ExpressRouteCircuitAuthorization> CreateOrUpdateAsync(this IExpressRouteCircuitAuthorizationsOperations operations, string resourceGroupName, string circuitName, string authorizationName, ExpressRouteCircuitAuthorization authorizationParameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, circuitName, authorizationName, authorizationParameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// The Put Authorization operation creates/updates an authorization in the
/// specified ExpressRouteCircuits
/// </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='authorizationName'>
/// The name of the authorization.
/// </param>
/// <param name='authorizationParameters'>
/// Parameters supplied to the create/update ExpressRouteCircuitAuthorization
/// operation
/// </param>
public static ExpressRouteCircuitAuthorization BeginCreateOrUpdate(this IExpressRouteCircuitAuthorizationsOperations operations, string resourceGroupName, string circuitName, string authorizationName, ExpressRouteCircuitAuthorization authorizationParameters)
{
return Task.Factory.StartNew(s => ((IExpressRouteCircuitAuthorizationsOperations)s).BeginCreateOrUpdateAsync(resourceGroupName, circuitName, authorizationName, authorizationParameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Put Authorization operation creates/updates an authorization in the
/// specified ExpressRouteCircuits
/// </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='authorizationName'>
/// The name of the authorization.
/// </param>
/// <param name='authorizationParameters'>
/// Parameters supplied to the create/update ExpressRouteCircuitAuthorization
/// operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ExpressRouteCircuitAuthorization> BeginCreateOrUpdateAsync(this IExpressRouteCircuitAuthorizationsOperations operations, string resourceGroupName, string circuitName, string authorizationName, ExpressRouteCircuitAuthorization authorizationParameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, circuitName, authorizationName, authorizationParameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// The List authorization operation retrieves all the authorizations in an
/// ExpressRouteCircuit.
/// </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 circuit.
/// </param>
public static IPage<ExpressRouteCircuitAuthorization> List(this IExpressRouteCircuitAuthorizationsOperations operations, string resourceGroupName, string circuitName)
{
return Task.Factory.StartNew(s => ((IExpressRouteCircuitAuthorizationsOperations)s).ListAsync(resourceGroupName, circuitName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The List authorization operation retrieves all the authorizations in an
/// ExpressRouteCircuit.
/// </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 circuit.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<ExpressRouteCircuitAuthorization>> ListAsync(this IExpressRouteCircuitAuthorizationsOperations 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>
/// The List authorization operation retrieves all the authorizations in an
/// ExpressRouteCircuit.
/// </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<ExpressRouteCircuitAuthorization> ListNext(this IExpressRouteCircuitAuthorizationsOperations operations, string nextPageLink)
{
return Task.Factory.StartNew(s => ((IExpressRouteCircuitAuthorizationsOperations)s).ListNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The List authorization operation retrieves all the authorizations in an
/// ExpressRouteCircuit.
/// </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<ExpressRouteCircuitAuthorization>> ListNextAsync(this IExpressRouteCircuitAuthorizationsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Jint.Native.Object;
using Jint.Native.RegExp;
using Jint.Runtime;
using Jint.Runtime.Descriptors;
namespace Jint.Native.Iterator
{
internal class IteratorInstance : ObjectInstance
{
private readonly IEnumerator<JsValue> _enumerable;
public IteratorInstance(Engine engine)
: this(engine, Enumerable.Empty<JsValue>())
{
}
public IteratorInstance(
Engine engine,
IEnumerable<JsValue> enumerable) : base(engine, ObjectClass.Iterator)
{
_enumerable = enumerable.GetEnumerator();
}
public override object ToObject()
{
ExceptionHelper.ThrowNotImplementedException();
return null;
}
public override bool Equals(JsValue other)
{
return false;
}
public virtual bool TryIteratorStep(out ObjectInstance nextItem)
{
if (_enumerable.MoveNext())
{
nextItem = new ValueIteratorPosition(_engine, _enumerable.Current);
return true;
}
nextItem = ValueIteratorPosition.Done(_engine);
return false;
}
public virtual void Close(CompletionType completion)
{
}
/// <summary>
/// https://tc39.es/ecma262/#sec-createiterresultobject
/// </summary>
private ObjectInstance CreateIterResultObject(JsValue value, bool done)
{
return new IteratorResult(_engine, value, done ? JsBoolean.True : JsBoolean.False);
}
internal sealed class KeyValueIteratorPosition : ObjectInstance
{
internal static ObjectInstance Done(Engine engine) => new KeyValueIteratorPosition(engine, null, null);
public KeyValueIteratorPosition(Engine engine, JsValue key, JsValue value) : base(engine)
{
var done = ReferenceEquals(null, key) && ReferenceEquals(null, value);
if (!done)
{
var arrayInstance = engine.Realm.Intrinsics.Array.ArrayCreate(2);
arrayInstance.SetIndexValue(0, key, false);
arrayInstance.SetIndexValue(1, value, false);
SetProperty("value", new PropertyDescriptor(arrayInstance, PropertyFlag.AllForbidden));
}
SetProperty("done", done ? PropertyDescriptor.AllForbiddenDescriptor.BooleanTrue : PropertyDescriptor.AllForbiddenDescriptor.BooleanFalse);
}
}
internal sealed class ValueIteratorPosition : ObjectInstance
{
internal static ObjectInstance Done(Engine engine) => new ValueIteratorPosition(engine, Undefined, true);
public ValueIteratorPosition(Engine engine, JsValue value, bool? done = null) : base(engine)
{
if (value is not null)
{
SetProperty("value", new PropertyDescriptor(value, PropertyFlag.AllForbidden));
}
SetProperty("done", new PropertyDescriptor(done ?? value is null, PropertyFlag.AllForbidden));
}
}
public sealed class ListIterator : IteratorInstance
{
private readonly List<JsValue> _values;
private int _position;
private bool _closed;
public ListIterator(Engine engine, List<JsValue> values) : base(engine)
{
_values = values;
_position = 0;
}
public override bool TryIteratorStep(out ObjectInstance nextItem)
{
if (!_closed && _position < _values.Count)
{
var value = _values[_position];
_position++;
nextItem = new ValueIteratorPosition(_engine, value);
return true;
}
_closed = true;
nextItem = KeyValueIteratorPosition.Done(_engine);
return false;
}
}
internal sealed class ObjectIterator : IteratorInstance
{
private readonly ObjectInstance _target;
private readonly ICallable _nextMethod;
public ObjectIterator(ObjectInstance target) : base(target.Engine)
{
_target = target;
_nextMethod = target.Get(CommonProperties.Next, target) as ICallable;
if (_nextMethod is null)
{
ExceptionHelper.ThrowTypeError(target.Engine.Realm);
}
}
public override bool TryIteratorStep(out ObjectInstance result)
{
result = IteratorNext();
var done = result.Get(CommonProperties.Done);
if (!done.IsUndefined() && TypeConverter.ToBoolean(done))
{
return false;
}
return true;
}
private ObjectInstance IteratorNext()
{
var jsValue = _nextMethod.Call(_target, Arguments.Empty);
var instance = jsValue as ObjectInstance;
if (instance is null)
{
ExceptionHelper.ThrowTypeError(_target.Engine.Realm, "Iterator result " + jsValue + " is not an object");
}
return instance;
}
public override void Close(CompletionType completion)
{
if (!_target.TryGetValue(CommonProperties.Return, out var func)
|| func.IsNullOrUndefined())
{
return;
}
var callable = func as ICallable;
if (callable is null)
{
ExceptionHelper.ThrowTypeError(_target.Engine.Realm, func + " is not a function");
}
var innerResult = Undefined;
try
{
innerResult = callable.Call(_target, Arguments.Empty);
}
catch
{
if (completion != CompletionType.Throw)
{
throw;
}
}
if (completion != CompletionType.Throw && !innerResult.IsObject())
{
ExceptionHelper.ThrowTypeError(_target.Engine.Realm, "Iterator returned non-object");
}
}
}
internal sealed class StringIterator : IteratorInstance
{
private readonly TextElementEnumerator _iterator;
public StringIterator(Engine engine, string str) : base(engine)
{
_iterator = StringInfo.GetTextElementEnumerator(str);
}
public override bool TryIteratorStep(out ObjectInstance nextItem)
{
if (_iterator.MoveNext())
{
nextItem = new ValueIteratorPosition(_engine, (string) _iterator.Current);
return true;
}
nextItem = KeyValueIteratorPosition.Done(_engine);
return false;
}
}
internal sealed class RegExpStringIterator : IteratorInstance
{
private readonly RegExpInstance _iteratingRegExp;
private readonly string _s;
private readonly bool _global;
private readonly bool _unicode;
private bool _done;
public RegExpStringIterator(Engine engine, ObjectInstance iteratingRegExp, string iteratedString, bool global, bool unicode) : base(engine)
{
var r = iteratingRegExp as RegExpInstance;
if (r is null)
{
ExceptionHelper.ThrowTypeError(engine.Realm);
}
_iteratingRegExp = r;
_s = iteratedString;
_global = global;
_unicode = unicode;
}
public override bool TryIteratorStep(out ObjectInstance nextItem)
{
if (_done)
{
nextItem = CreateIterResultObject(Undefined, true);
return false;
}
var match = RegExpPrototype.RegExpExec(_iteratingRegExp, _s);
if (match.IsNull())
{
_done = true;
nextItem = CreateIterResultObject(Undefined, true);
return false;
}
if (_global)
{
var macthStr = TypeConverter.ToString(match.Get(JsString.NumberZeroString));
if (macthStr == "")
{
var thisIndex = TypeConverter.ToLength(_iteratingRegExp.Get(RegExpInstance.PropertyLastIndex));
var nextIndex = thisIndex + 1;
_iteratingRegExp.Set(RegExpInstance.PropertyLastIndex, nextIndex, true);
}
}
else
{
_done = true;
}
nextItem = CreateIterResultObject(match, false);
return false;
}
}
}
}
| |
//*********************************************************//
// Copyright (c) Microsoft. All rights reserved.
//
// Apache 2.0 License
//
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License.
//
//*********************************************************//
using System;
using System.Collections.Generic;
using System.ComponentModel.Design;
using System.Diagnostics;
using System.Threading;
using Microsoft.VisualStudio.Language.Intellisense;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using VSConstants = Microsoft.VisualStudio.VSConstants;
namespace Microsoft.VisualStudioTools.Navigation {
/// <summary>
/// Single node inside the tree of the libraries in the object browser or class view.
/// </summary>
class LibraryNode : SimpleObjectList<LibraryNode>, IVsNavInfo, IVsNavInfoNode, ISimpleObject {
private string _name, _fullname;
private readonly LibraryNode _parent;
private LibraryNodeCapabilities _capabilities;
private readonly LibraryNodeType _type;
private readonly CommandID _contextMenuID;
private readonly string _tooltip;
private readonly Dictionary<LibraryNodeType, LibraryNode> _filteredView;
private readonly Dictionary<string, LibraryNode[]> _childrenByName;
private bool _duplicatedByName;
public LibraryNode(LibraryNode parent, string name, string fullname, LibraryNodeType type)
: this(parent, name, fullname, type, LibraryNodeCapabilities.None, null) { }
public LibraryNode(LibraryNode parent, string name, string fullname, LibraryNodeType type, LibraryNodeCapabilities capabilities, CommandID contextMenuID) {
Debug.Assert(name != null);
_parent = parent;
_capabilities = capabilities;
_contextMenuID = contextMenuID;
_name = name;
_fullname = fullname;
_tooltip = name;
_type = type;
_filteredView = new Dictionary<LibraryNodeType, LibraryNode>();
_childrenByName = new Dictionary<string, LibraryNode[]>();
}
protected LibraryNode(LibraryNode node)
: this(node, node.FullName) {
}
protected LibraryNode(LibraryNode node, string newFullName) {
_parent = node._parent;
_capabilities = node._capabilities;
_contextMenuID = node._contextMenuID;
_name = node._name;
_tooltip = node._tooltip;
_type = node._type;
_fullname = newFullName;
Children.AddRange(node.Children);
_childrenByName = new Dictionary<string, LibraryNode[]>(node._childrenByName);
_filteredView = new Dictionary<LibraryNodeType, LibraryNode>();
}
protected void SetCapabilityFlag(LibraryNodeCapabilities flag, bool value) {
if (value) {
_capabilities |= flag;
} else {
_capabilities &= ~flag;
}
}
public LibraryNode Parent {
get { return _parent; }
}
/// <summary>
/// Get or Set if the node can be deleted.
/// </summary>
public bool CanDelete {
get { return (0 != (_capabilities & LibraryNodeCapabilities.AllowDelete)); }
set { SetCapabilityFlag(LibraryNodeCapabilities.AllowDelete, value); }
}
/// <summary>
/// Get or Set if the node can be associated with some source code.
/// </summary>
public bool CanGoToSource {
get { return (0 != (_capabilities & LibraryNodeCapabilities.HasSourceContext)); }
set { SetCapabilityFlag(LibraryNodeCapabilities.HasSourceContext, value); }
}
/// <summary>
/// Get or Set if the node can be renamed.
/// </summary>
public bool CanRename {
get { return (0 != (_capabilities & LibraryNodeCapabilities.AllowRename)); }
set { SetCapabilityFlag(LibraryNodeCapabilities.AllowRename, value); }
}
/// <summary>
///
/// </summary>
public override uint Capabilities { get { return (uint)_capabilities; } }
public string TooltipText {
get { return _tooltip; }
}
internal void AddNode(LibraryNode node) {
lock (Children) {
Children.Add(node);
LibraryNode[] nodes;
if (!_childrenByName.TryGetValue(node.Name, out nodes)) {
// common case, no duplicates by name
_childrenByName[node.Name] = new[] { node };
} else {
// uncommon case, duplicated by name
_childrenByName[node.Name] = nodes = nodes.Append(node);
foreach (var dupNode in nodes) {
dupNode.DuplicatedByName = true;
}
}
}
Update();
}
internal void RemoveNode(LibraryNode node) {
if (node != null) {
lock (Children) {
Children.Remove(node);
LibraryNode[] items;
if (_childrenByName.TryGetValue(node.Name, out items)) {
if (items.Length == 1) {
System.Diagnostics.Debug.Assert(items[0] == node);
_childrenByName.Remove(node.Name);
} else {
var newItems = new LibraryNode[items.Length - 1];
for (int i = 0, write = 0; i < items.Length; i++) {
if (items[i] != node) {
newItems[write++] = items[i];
}
}
_childrenByName[node.Name] = newItems;
}
}
}
Update();
}
}
public virtual object BrowseObject {
get { return null; }
}
public override uint CategoryField(LIB_CATEGORY category) {
uint fieldValue = 0;
switch (category) {
case (LIB_CATEGORY)_LIB_CATEGORY2.LC_PHYSICALCONTAINERTYPE:
fieldValue = (uint)_LIBCAT_PHYSICALCONTAINERTYPE.LCPT_PROJECT;
break;
case LIB_CATEGORY.LC_NODETYPE:
fieldValue = (uint)_LIBCAT_NODETYPE.LCNT_SYMBOL;
break;
case LIB_CATEGORY.LC_LISTTYPE: {
LibraryNodeType subTypes = LibraryNodeType.None;
foreach (LibraryNode node in Children) {
subTypes |= node._type;
}
fieldValue = (uint)subTypes;
}
break;
case (LIB_CATEGORY)_LIB_CATEGORY2.LC_HIERARCHYTYPE:
fieldValue = (uint)_LIBCAT_HIERARCHYTYPE.LCHT_UNKNOWN;
break;
case LIB_CATEGORY.LC_VISIBILITY:
fieldValue = (uint)_LIBCAT_VISIBILITY.LCV_VISIBLE;
break;
case LIB_CATEGORY.LC_MEMBERTYPE:
fieldValue = (uint)_LIBCAT_MEMBERTYPE.LCMT_METHOD;
break;
case LIB_CATEGORY.LC_MEMBERACCESS:
fieldValue = (uint)_LIBCAT_MEMBERACCESS.LCMA_PUBLIC;
break;
default:
throw new NotImplementedException();
}
return fieldValue;
}
public virtual LibraryNode Clone() {
return new LibraryNode(this);
}
public virtual LibraryNode Clone(string newFullName) {
return new LibraryNode(this, newFullName);
}
/// <summary>
/// Performs the operations needed to delete this node.
/// </summary>
public virtual void Delete() {
}
/// <summary>
/// Perform a Drag and Drop operation on this node.
/// </summary>
public virtual void DoDragDrop(OleDataObject dataObject, uint keyState, uint effect) {
}
public virtual uint EnumClipboardFormats(_VSOBJCFFLAGS flags, VSOBJCLIPFORMAT[] formats) {
return 0;
}
public virtual void FillDescription(_VSOBJDESCOPTIONS flags, IVsObjectBrowserDescription3 description) {
description.ClearDescriptionText();
description.AddDescriptionText3(_name, VSOBDESCRIPTIONSECTION.OBDS_NAME, null);
}
public IVsSimpleObjectList2 FilterView(uint filterType) {
var libraryNodeType = (LibraryNodeType)filterType;
LibraryNode filtered = null;
if (_filteredView.TryGetValue(libraryNodeType, out filtered)) {
return filtered as IVsSimpleObjectList2;
}
filtered = this.Clone();
for (int i = 0; i < filtered.Children.Count; ) {
if (0 == (filtered.Children[i]._type & libraryNodeType)) {
filtered.Children.RemoveAt(i);
} else {
i += 1;
}
}
_filteredView.Add(libraryNodeType, filtered);
return filtered as IVsSimpleObjectList2;
}
public virtual void GotoSource(VSOBJGOTOSRCTYPE gotoType) {
// Do nothing.
}
public virtual string Name {
get {
return _name;
}
}
public virtual string GetTextRepresentation(VSTREETEXTOPTIONS options) {
return Name;
}
public LibraryNodeType NodeType {
get { return _type; }
}
/// <summary>
/// Finds the source files associated with this node.
/// </summary>
/// <param name="hierarchy">The hierarchy containing the items.</param>
/// <param name="itemId">The item id of the item.</param>
/// <param name="itemsCount">Number of items.</param>
public virtual void SourceItems(out IVsHierarchy hierarchy, out uint itemId, out uint itemsCount) {
hierarchy = null;
itemId = 0;
itemsCount = 0;
}
public virtual void Rename(string newName, uint flags) {
this._name = newName;
}
public virtual string UniqueName {
get { return Name; }
}
public string FullName {
get {
return _fullname;
}
}
public CommandID ContextMenuID {
get {
return _contextMenuID;
}
}
public virtual StandardGlyphGroup GlyphType {
get {
return StandardGlyphGroup.GlyphGroupModule;
}
}
public virtual VSTREEDISPLAYDATA DisplayData {
get {
var res = new VSTREEDISPLAYDATA();
res.Image = res.SelectedImage = (ushort)GlyphType;
return res;
}
}
public virtual IVsSimpleObjectList2 DoSearch(VSOBSEARCHCRITERIA2 criteria) {
return null;
}
public override void Update() {
base.Update();
_filteredView.Clear();
}
/// <summary>
/// Visit this node and its children.
/// </summary>
/// <param name="visitor">Visitor to invoke methods on when visiting the nodes.</param>
public void Visit(ILibraryNodeVisitor visitor, CancellationToken ct = default(CancellationToken)) {
if (ct.IsCancellationRequested) {
visitor.LeaveNode(this, ct);
return;
}
if (visitor.EnterNode(this, ct)) {
lock (Children) {
foreach (var child in Children) {
if (ct.IsCancellationRequested) {
visitor.LeaveNode(this, ct);
return;
}
child.Visit(visitor, ct);
}
}
}
visitor.LeaveNode(this, ct);
}
#region IVsNavInfoNode Members
int IVsNavInfoNode.get_Name(out string pbstrName) {
pbstrName = UniqueName;
return VSConstants.S_OK;
}
int IVsNavInfoNode.get_Type(out uint pllt) {
pllt = (uint)_type;
return VSConstants.S_OK;
}
#endregion
/// <summary>
/// Enumeration of the capabilities of a node. It is possible to combine different values
/// to support more capabilities.
/// This enumeration is a copy of _LIB_LISTCAPABILITIES with the Flags attribute set.
/// </summary>
[Flags()]
public enum LibraryNodeCapabilities {
None = _LIB_LISTCAPABILITIES.LLC_NONE,
HasBrowseObject = _LIB_LISTCAPABILITIES.LLC_HASBROWSEOBJ,
HasDescriptionPane = _LIB_LISTCAPABILITIES.LLC_HASDESCPANE,
HasSourceContext = _LIB_LISTCAPABILITIES.LLC_HASSOURCECONTEXT,
HasCommands = _LIB_LISTCAPABILITIES.LLC_HASCOMMANDS,
AllowDragDrop = _LIB_LISTCAPABILITIES.LLC_ALLOWDRAGDROP,
AllowRename = _LIB_LISTCAPABILITIES.LLC_ALLOWRENAME,
AllowDelete = _LIB_LISTCAPABILITIES.LLC_ALLOWDELETE,
AllowSourceControl = _LIB_LISTCAPABILITIES.LLC_ALLOWSCCOPS,
}
public bool DuplicatedByName { get { return _duplicatedByName; } private set { _duplicatedByName = value; } }
#region IVsNavInfo
private class VsEnumNavInfoNodes : IVsEnumNavInfoNodes {
private readonly IEnumerator<IVsNavInfoNode> _nodeEnum;
public VsEnumNavInfoNodes(IEnumerator<IVsNavInfoNode> nodeEnum) {
_nodeEnum = nodeEnum;
}
public int Clone(out IVsEnumNavInfoNodes ppEnum) {
ppEnum = new VsEnumNavInfoNodes(_nodeEnum);
return VSConstants.S_OK;
}
public int Next(uint celt, IVsNavInfoNode[] rgelt, out uint pceltFetched) {
for (pceltFetched = 0; pceltFetched < celt; ++pceltFetched) {
if (!_nodeEnum.MoveNext()) {
return VSConstants.S_FALSE;
}
rgelt[pceltFetched] = _nodeEnum.Current;
}
return VSConstants.S_OK;
}
public int Reset() {
throw new NotImplementedException();
}
public int Skip(uint celt) {
while (celt-- > 0) {
if (!_nodeEnum.MoveNext()) {
return VSConstants.S_FALSE;
}
}
return VSConstants.S_OK;
}
}
public virtual int GetLibGuid(out Guid pGuid) {
pGuid = Guid.Empty;
return VSConstants.E_NOTIMPL;
}
public int EnumCanonicalNodes(out IVsEnumNavInfoNodes ppEnum) {
return EnumPresentationNodes(0, out ppEnum);
}
public int EnumPresentationNodes(uint dwFlags, out IVsEnumNavInfoNodes ppEnum) {
var path = new Stack<LibraryNode>();
for (LibraryNode node = this; node != null; node = node.Parent) {
path.Push(node);
}
ppEnum = new VsEnumNavInfoNodes(path.GetEnumerator());
return VSConstants.S_OK;
}
public int GetSymbolType(out uint pdwType) {
pdwType = (uint)_type;
return VSConstants.S_OK;
}
#endregion
}
/// <summary>
/// Enumeration of the possible types of node. The type of a node can be the combination
/// of one of more of these values.
/// This is actually a copy of the _LIB_LISTTYPE enumeration with the difference that the
/// Flags attribute is set so that it is possible to specify more than one value.
/// </summary>
[Flags()]
enum LibraryNodeType {
None = 0,
Hierarchy = _LIB_LISTTYPE.LLT_HIERARCHY,
Namespaces = _LIB_LISTTYPE.LLT_NAMESPACES,
Classes = _LIB_LISTTYPE.LLT_CLASSES,
Members = _LIB_LISTTYPE.LLT_MEMBERS,
Package = _LIB_LISTTYPE.LLT_PACKAGE,
PhysicalContainer = _LIB_LISTTYPE.LLT_PHYSICALCONTAINERS,
Containment = _LIB_LISTTYPE.LLT_CONTAINMENT,
ContainedBy = _LIB_LISTTYPE.LLT_CONTAINEDBY,
UsesClasses = _LIB_LISTTYPE.LLT_USESCLASSES,
UsedByClasses = _LIB_LISTTYPE.LLT_USEDBYCLASSES,
NestedClasses = _LIB_LISTTYPE.LLT_NESTEDCLASSES,
InheritedInterface = _LIB_LISTTYPE.LLT_INHERITEDINTERFACES,
InterfaceUsedByClasses = _LIB_LISTTYPE.LLT_INTERFACEUSEDBYCLASSES,
Definitions = _LIB_LISTTYPE.LLT_DEFINITIONS,
References = _LIB_LISTTYPE.LLT_REFERENCES,
DeferExpansion = _LIB_LISTTYPE.LLT_DEFEREXPANSION,
}
/// <summary>
/// Visitor interface used to enumerate all <see cref="LibraryNode"/>s in the library.
/// </summary>
interface ILibraryNodeVisitor {
/// <summary>
/// Called on each node before any of its child nodes are visited.
/// </summary>
/// <param name="node">The node that is being visited.</param>
/// <returns><c>true</c> if children of this node should be visited, otherwise <c>false</c>.</returns>
bool EnterNode(LibraryNode node, CancellationToken ct);
/// <summary>
/// Called on each node after all its child nodes were visited.
/// </summary>
/// <param name="node">The node that was being visited.</param>
void LeaveNode(LibraryNode node, CancellationToken ct);
}
}
| |
/*
Copyright (c) 2003-2006 Niels Kokholm and Peter Sestoft
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 C5;
using NUnit.Framework;
using SCG = System.Collections.Generic;
namespace C5UnitTests.hashtable.set
{
using CollectionOfInt = HashSet<int>;
[TestFixture]
public class GenericTesters
{
[Test]
public void TestEvents()
{
Fun<CollectionOfInt> factory = delegate() { return new CollectionOfInt(TenEqualityComparer.Default); };
new C5UnitTests.Templates.Events.CollectionTester<CollectionOfInt>().Test(factory);
}
[Test]
public void Extensible()
{
C5UnitTests.Templates.Extensible.Clone.Tester<CollectionOfInt>();
C5UnitTests.Templates.Extensible.Serialization.Tester<CollectionOfInt>();
}
}
static class Factory
{
public static ICollection<T> New<T>() { return new HashSet<T>(); }
}
namespace Enumerable
{
[TestFixture]
public class Multiops
{
private HashSet<int> list;
private Fun<int, bool> always, never, even;
[SetUp]
public void Init()
{
list = new HashSet<int>();
always = delegate { return true; };
never = delegate { return false; };
even = delegate(int i) { return i % 2 == 0; };
}
[Test]
public void All()
{
Assert.IsTrue(list.All(always));
Assert.IsTrue(list.All(never));
Assert.IsTrue(list.All(even));
list.Add(0);
Assert.IsTrue(list.All(always));
Assert.IsFalse(list.All(never));
Assert.IsTrue(list.All(even));
list.Add(5);
Assert.IsTrue(list.All(always));
Assert.IsFalse(list.All(never));
Assert.IsFalse(list.All(even));
}
[Test]
public void Exists()
{
Assert.IsFalse(list.Exists(always));
Assert.IsFalse(list.Exists(never));
Assert.IsFalse(list.Exists(even));
list.Add(5);
Assert.IsTrue(list.Exists(always));
Assert.IsFalse(list.Exists(never));
Assert.IsFalse(list.Exists(even));
list.Add(8);
Assert.IsTrue(list.Exists(always));
Assert.IsFalse(list.Exists(never));
Assert.IsTrue(list.Exists(even));
}
[Test]
public void Apply()
{
int sum = 0;
Act<int> a = delegate(int i) { sum = i + 10 * sum; };
list.Apply(a);
Assert.AreEqual(0, sum);
sum = 0;
list.Add(5); list.Add(8); list.Add(7); list.Add(5);
list.Apply(a);
Assert.AreEqual(758, sum);
}
[TearDown]
public void Dispose() { list = null; }
}
[TestFixture]
public class GetEnumerator
{
private HashSet<int> hashset;
[SetUp]
public void Init() { hashset = new HashSet<int>(); }
[Test]
public void Empty()
{
SCG.IEnumerator<int> e = hashset.GetEnumerator();
Assert.IsFalse(e.MoveNext());
}
[Test]
public void Normal()
{
hashset.Add(5);
hashset.Add(8);
hashset.Add(5);
hashset.Add(5);
hashset.Add(10);
hashset.Add(1);
hashset.Add(16);
hashset.Add(18);
hashset.Add(17);
hashset.Add(33);
Assert.IsTrue(IC.seteq(hashset, 1, 5, 8, 10, 16, 17, 18, 33));
}
[Test]
public void DoDispose()
{
hashset.Add(5);
hashset.Add(8);
hashset.Add(5);
SCG.IEnumerator<int> e = hashset.GetEnumerator();
e.MoveNext();
e.MoveNext();
e.Dispose();
}
[Test]
[ExpectedException(typeof(CollectionModifiedException))]
public void MoveNextAfterUpdate()
{
hashset.Add(5);
hashset.Add(8);
hashset.Add(5);
SCG.IEnumerator<int> e = hashset.GetEnumerator();
e.MoveNext();
hashset.Add(99);
e.MoveNext();
}
[TearDown]
public void Dispose() { hashset = null; }
}
}
namespace CollectionOrSink
{
[TestFixture]
public class Formatting
{
ICollection<int> coll;
IFormatProvider rad16;
[SetUp]
public void Init() { coll = Factory.New<int>(); rad16 = new RadixFormatProvider(16); }
[TearDown]
public void Dispose() { coll = null; rad16 = null; }
[Test]
public void Format()
{
Assert.AreEqual("{ }", coll.ToString());
coll.AddAll<int>(new int[] { -4, 28, 129, 65530 });
Assert.AreEqual("{ 65530, -4, 28, 129 }", coll.ToString());
Assert.AreEqual("{ FFFA, -4, 1C, 81 }", coll.ToString(null, rad16));
Assert.AreEqual("{ 65530, -4, ... }", coll.ToString("L14", null));
Assert.AreEqual("{ FFFA, -4, ... }", coll.ToString("L14", rad16));
}
}
[TestFixture]
public class CollectionOrSink
{
private HashSet<int> hashset;
[SetUp]
public void Init() { hashset = new HashSet<int>(); }
[Test]
public void Choose()
{
hashset.Add(7);
Assert.AreEqual(7, hashset.Choose());
}
[Test]
[ExpectedException(typeof(NoSuchItemException))]
public void BadChoose()
{
hashset.Choose();
}
[Test]
public void CountEtAl()
{
Assert.AreEqual(0, hashset.Count);
Assert.IsTrue(hashset.IsEmpty);
Assert.IsFalse(hashset.AllowsDuplicates);
Assert.IsTrue(hashset.Add(0));
Assert.AreEqual(1, hashset.Count);
Assert.IsFalse(hashset.IsEmpty);
Assert.IsTrue(hashset.Add(5));
Assert.AreEqual(2, hashset.Count);
Assert.IsFalse(hashset.Add(5));
Assert.AreEqual(2, hashset.Count);
Assert.IsFalse(hashset.IsEmpty);
Assert.IsTrue(hashset.Add(8));
Assert.AreEqual(3, hashset.Count);
}
[Test]
public void AddAll()
{
hashset.Add(3); hashset.Add(4); hashset.Add(5);
HashSet<int> hashset2 = new HashSet<int>();
hashset2.AddAll(hashset);
Assert.IsTrue(IC.seteq(hashset2, 3, 4, 5));
hashset.Add(9);
hashset.AddAll(hashset2);
Assert.IsTrue(IC.seteq(hashset2, 3, 4, 5));
Assert.IsTrue(IC.seteq(hashset, 3, 4, 5, 9));
}
[TearDown]
public void Dispose() { hashset = null; }
}
[TestFixture]
public class FindPredicate
{
private HashSet<int> list;
Fun<int, bool> pred;
[SetUp]
public void Init()
{
list = new HashSet<int>(TenEqualityComparer.Default);
pred = delegate(int i) { return i % 5 == 0; };
}
[TearDown]
public void Dispose() { list = null; }
[Test]
public void Find()
{
int i;
Assert.IsFalse(list.Find(pred, out i));
list.AddAll<int>(new int[] { 4, 22, 67, 37 });
Assert.IsFalse(list.Find(pred, out i));
list.AddAll<int>(new int[] { 45, 122, 675, 137 });
Assert.IsTrue(list.Find(pred, out i));
Assert.AreEqual(45, i);
}
}
[TestFixture]
public class UniqueItems
{
private HashSet<int> list;
[SetUp]
public void Init() { list = new HashSet<int>(); }
[TearDown]
public void Dispose() { list = null; }
[Test]
public void Test()
{
Assert.IsTrue(IC.seteq(list.UniqueItems()));
Assert.IsTrue(IC.seteq(list.ItemMultiplicities()));
list.AddAll<int>(new int[] { 7, 9, 7 });
Assert.IsTrue(IC.seteq(list.UniqueItems(), 7, 9));
Assert.IsTrue(IC.seteq(list.ItemMultiplicities(), 7, 1, 9, 1));
}
}
[TestFixture]
public class ArrayTest
{
private HashSet<int> hashset;
int[] a;
[SetUp]
public void Init()
{
hashset = new HashSet<int>();
a = new int[10];
for (int i = 0; i < 10; i++)
a[i] = 1000 + i;
}
[TearDown]
public void Dispose() { hashset = null; }
private string aeq(int[] a, params int[] b)
{
if (a.Length != b.Length)
return "Lengths differ: " + a.Length + " != " + b.Length;
for (int i = 0; i < a.Length; i++)
if (a[i] != b[i])
return String.Format("{0}'th elements differ: {1} != {2}", i, a[i], b[i]);
return "Alles klar";
}
[Test]
public void ToArray()
{
Assert.AreEqual("Alles klar", aeq(hashset.ToArray()));
hashset.Add(7);
hashset.Add(3);
hashset.Add(10);
int[] r = hashset.ToArray();
Array.Sort(r);
Assert.AreEqual("Alles klar", aeq(r, 3, 7, 10));
}
[Test]
public void CopyTo()
{
//Note: for small ints the itemequalityComparer is the identity!
hashset.CopyTo(a, 1);
Assert.AreEqual("Alles klar", aeq(a, 1000, 1001, 1002, 1003, 1004, 1005, 1006, 1007, 1008, 1009));
hashset.Add(6);
hashset.CopyTo(a, 2);
Assert.AreEqual("Alles klar", aeq(a, 1000, 1001, 6, 1003, 1004, 1005, 1006, 1007, 1008, 1009));
hashset.Add(4);
hashset.Add(9);
hashset.CopyTo(a, 4);
//TODO: make test independent on onterequalityComparer
Assert.AreEqual("Alles klar", aeq(a, 1000, 1001, 6, 1003, 6, 9, 4, 1007, 1008, 1009));
hashset.Clear();
hashset.Add(7);
hashset.CopyTo(a, 9);
Assert.AreEqual("Alles klar", aeq(a, 1000, 1001, 6, 1003, 6, 9, 4, 1007, 1008, 7));
}
[Test]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void CopyToBad()
{
hashset.CopyTo(a, 11);
}
[Test]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void CopyToBad2()
{
hashset.CopyTo(a, -1);
}
[Test]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void CopyToTooFar()
{
hashset.Add(3);
hashset.Add(8);
hashset.CopyTo(a, 9);
}
}
}
namespace EditableCollection
{
[TestFixture]
public class Collision
{
HashSet<int> hashset;
[SetUp]
public void Init()
{
hashset = new HashSet<int>();
}
[Test]
public void SingleCollision()
{
hashset.Add(7);
hashset.Add(7 - 1503427877);
//foreach (int cell in hashset) Console.WriteLine("A: {0}", cell);
hashset.Remove(7);
Assert.IsTrue(hashset.Contains(7 - 1503427877));
}
[TearDown]
public void Dispose()
{
hashset = null;
}
}
[TestFixture]
public class Searching
{
private HashSet<int> hashset;
[SetUp]
public void Init() { hashset = new HashSet<int>(); }
[Test]
[ExpectedException(typeof(NullReferenceException))]
public void NullEqualityComparerinConstructor1()
{
new HashSet<int>(null);
}
[Test]
[ExpectedException(typeof(NullReferenceException))]
public void NullEqualityComparerinConstructor2()
{
new HashSet<int>(5, null);
}
[Test]
[ExpectedException(typeof(NullReferenceException))]
public void NullEqualityComparerinConstructor3()
{
new HashSet<int>(5, 0.5, null);
}
[Test]
public void Contains()
{
Assert.IsFalse(hashset.Contains(5));
hashset.Add(5);
Assert.IsTrue(hashset.Contains(5));
Assert.IsFalse(hashset.Contains(7));
hashset.Add(8);
hashset.Add(10);
Assert.IsTrue(hashset.Contains(5));
Assert.IsFalse(hashset.Contains(7));
Assert.IsTrue(hashset.Contains(8));
Assert.IsTrue(hashset.Contains(10));
hashset.Remove(8);
Assert.IsTrue(hashset.Contains(5));
Assert.IsFalse(hashset.Contains(7));
Assert.IsFalse(hashset.Contains(8));
Assert.IsTrue(hashset.Contains(10));
hashset.Add(0); hashset.Add(16); hashset.Add(32); hashset.Add(48); hashset.Add(64);
Assert.IsTrue(hashset.Contains(0));
Assert.IsTrue(hashset.Contains(16));
Assert.IsTrue(hashset.Contains(32));
Assert.IsTrue(hashset.Contains(48));
Assert.IsTrue(hashset.Contains(64));
Assert.IsTrue(hashset.Check());
int i = 0, j = i;
Assert.IsTrue(hashset.Find(ref i));
Assert.AreEqual(j, i);
j = i = 16;
Assert.IsTrue(hashset.Find(ref i));
Assert.AreEqual(j, i);
j = i = 32;
Assert.IsTrue(hashset.Find(ref i));
Assert.AreEqual(j, i);
j = i = 48;
Assert.IsTrue(hashset.Find(ref i));
Assert.AreEqual(j, i);
j = i = 64;
Assert.IsTrue(hashset.Find(ref i));
Assert.AreEqual(j, i);
j = i = 80;
Assert.IsFalse(hashset.Find(ref i));
Assert.AreEqual(j, i);
}
[Test]
public void Many()
{
int j = 7373;
int[] a = new int[j];
for (int i = 0; i < j; i++)
{
hashset.Add(3 * i + 1);
a[i] = 3 * i + 1;
}
Assert.IsTrue(IC.seteq(hashset, a));
}
[Test]
public void ContainsCount()
{
Assert.AreEqual(0, hashset.ContainsCount(5));
hashset.Add(5);
Assert.AreEqual(1, hashset.ContainsCount(5));
Assert.AreEqual(0, hashset.ContainsCount(7));
hashset.Add(8);
Assert.AreEqual(1, hashset.ContainsCount(5));
Assert.AreEqual(0, hashset.ContainsCount(7));
Assert.AreEqual(1, hashset.ContainsCount(8));
hashset.Add(5);
Assert.AreEqual(1, hashset.ContainsCount(5));
Assert.AreEqual(0, hashset.ContainsCount(7));
Assert.AreEqual(1, hashset.ContainsCount(8));
}
[Test]
public void RemoveAllCopies()
{
hashset.Add(5); hashset.Add(7); hashset.Add(5);
Assert.AreEqual(1, hashset.ContainsCount(5));
Assert.AreEqual(1, hashset.ContainsCount(7));
hashset.RemoveAllCopies(5);
Assert.AreEqual(0, hashset.ContainsCount(5));
Assert.AreEqual(1, hashset.ContainsCount(7));
hashset.Add(5); hashset.Add(8); hashset.Add(5);
hashset.RemoveAllCopies(8);
Assert.IsTrue(IC.eq(hashset, 7, 5));
}
[Test]
public void ContainsAll()
{
HashSet<int> list2 = new HashSet<int>();
Assert.IsTrue(hashset.ContainsAll(list2));
list2.Add(4);
Assert.IsFalse(hashset.ContainsAll(list2));
hashset.Add(4);
Assert.IsTrue(hashset.ContainsAll(list2));
hashset.Add(5);
Assert.IsTrue(hashset.ContainsAll(list2));
list2.Add(20);
Assert.IsFalse(hashset.ContainsAll(list2));
hashset.Add(20);
Assert.IsTrue(hashset.ContainsAll(list2));
}
[Test]
public void RetainAll()
{
HashSet<int> list2 = new HashSet<int>();
hashset.Add(4); hashset.Add(5); hashset.Add(6);
list2.Add(5); list2.Add(4); list2.Add(7);
hashset.RetainAll(list2);
Assert.IsTrue(IC.seteq(hashset, 4, 5));
hashset.Add(6);
list2.Clear();
list2.Add(7); list2.Add(8); list2.Add(9);
hashset.RetainAll(list2);
Assert.IsTrue(IC.seteq(hashset));
}
//Bug in RetainAll reported by Chris Fesler
//The result has different bitsc
[Test]
public void RetainAll2()
{
int LARGE_ARRAY_SIZE = 30;
int LARGE_ARRAY_MID = 15;
string[] _largeArrayOne = new string[LARGE_ARRAY_SIZE];
string[] _largeArrayTwo = new string[LARGE_ARRAY_SIZE];
for (int i = 0; i < LARGE_ARRAY_SIZE; i++)
{
_largeArrayOne[i] = "" + i;
_largeArrayTwo[i] = "" + (i + LARGE_ARRAY_MID);
}
HashSet<string> setOne = new HashSet<string>();
setOne.AddAll(_largeArrayOne);
HashSet<string> setTwo = new HashSet<string>();
setTwo.AddAll(_largeArrayTwo);
setOne.RetainAll(setTwo);
Assert.IsTrue(setOne.Check(),"setOne check fails");
for (int i = LARGE_ARRAY_MID; i < LARGE_ARRAY_SIZE; i++)
Assert.IsTrue(setOne.Contains(_largeArrayOne[i]), "missing " + i);
}
[Test]
public void RemoveAll()
{
HashSet<int> list2 = new HashSet<int>();
hashset.Add(4); hashset.Add(5); hashset.Add(6);
list2.Add(5); list2.Add(7); list2.Add(4);
hashset.RemoveAll(list2);
Assert.IsTrue(IC.eq(hashset, 6));
hashset.Add(5); hashset.Add(4);
list2.Clear();
list2.Add(6); list2.Add(5);
hashset.RemoveAll(list2);
Assert.IsTrue(IC.eq(hashset, 4));
list2.Clear();
list2.Add(7); list2.Add(8); list2.Add(9);
hashset.RemoveAll(list2);
Assert.IsTrue(IC.eq(hashset, 4));
}
[Test]
public void Remove()
{
hashset.Add(4); hashset.Add(4); hashset.Add(5); hashset.Add(4); hashset.Add(6);
Assert.IsFalse(hashset.Remove(2));
Assert.IsTrue(hashset.Remove(4));
Assert.IsTrue(IC.seteq(hashset, 5, 6));
hashset.Add(7);
hashset.Add(21); hashset.Add(37); hashset.Add(53); hashset.Add(69); hashset.Add(85);
Assert.IsTrue(hashset.Remove(5));
Assert.IsTrue(IC.seteq(hashset, 6, 7, 21, 37, 53, 69, 85));
Assert.IsFalse(hashset.Remove(165));
Assert.IsTrue(IC.seteq(hashset, 6, 7, 21, 37, 53, 69, 85));
Assert.IsTrue(hashset.Remove(53));
Assert.IsTrue(IC.seteq(hashset, 6, 7, 21, 37, 69, 85));
Assert.IsTrue(hashset.Remove(37));
Assert.IsTrue(IC.seteq(hashset, 6, 7, 21, 69, 85));
Assert.IsTrue(hashset.Remove(85));
Assert.IsTrue(IC.seteq(hashset, 6, 7, 21, 69));
}
[Test]
public void Clear()
{
hashset.Add(7); hashset.Add(7);
hashset.Clear();
Assert.IsTrue(hashset.IsEmpty);
}
[TearDown]
public void Dispose() { hashset = null; }
}
[TestFixture]
public class Combined
{
private ICollection<KeyValuePair<int, int>> lst;
[SetUp]
public void Init()
{
lst = new HashSet<KeyValuePair<int, int>>(new KeyValuePairEqualityComparer<int, int>());
for (int i = 0; i < 10; i++)
lst.Add(new KeyValuePair<int, int>(i, i + 30));
}
[TearDown]
public void Dispose() { lst = null; }
[Test]
public void Find()
{
KeyValuePair<int, int> p = new KeyValuePair<int, int>(3, 78);
Assert.IsTrue(lst.Find(ref p));
Assert.AreEqual(3, p.Key);
Assert.AreEqual(33, p.Value);
p = new KeyValuePair<int, int>(13, 78);
Assert.IsFalse(lst.Find(ref p));
}
[Test]
public void FindOrAdd()
{
KeyValuePair<int, int> p = new KeyValuePair<int, int>(3, 78);
KeyValuePair<int, int> q = new KeyValuePair<int, int>();
Assert.IsTrue(lst.FindOrAdd(ref p));
Assert.AreEqual(3, p.Key);
Assert.AreEqual(33, p.Value);
p = new KeyValuePair<int, int>(13, 79);
Assert.IsFalse(lst.FindOrAdd(ref p));
q.Key = 13;
Assert.IsTrue(lst.Find(ref q));
Assert.AreEqual(13, q.Key);
Assert.AreEqual(79, q.Value);
}
[Test]
public void Update()
{
KeyValuePair<int, int> p = new KeyValuePair<int, int>(3, 78);
KeyValuePair<int, int> q = new KeyValuePair<int, int>();
Assert.IsTrue(lst.Update(p));
q.Key = 3;
Assert.IsTrue(lst.Find(ref q));
Assert.AreEqual(3, q.Key);
Assert.AreEqual(78, q.Value);
p = new KeyValuePair<int, int>(13, 78);
Assert.IsFalse(lst.Update(p));
}
[Test]
public void UpdateOrAdd1()
{
KeyValuePair<int, int> p = new KeyValuePair<int, int>(3, 78);
KeyValuePair<int, int> q = new KeyValuePair<int, int>();
Assert.IsTrue(lst.UpdateOrAdd(p));
q.Key = 3;
Assert.IsTrue(lst.Find(ref q));
Assert.AreEqual(3, q.Key);
Assert.AreEqual(78, q.Value);
p = new KeyValuePair<int, int>(13, 79);
Assert.IsFalse(lst.UpdateOrAdd(p));
q.Key = 13;
Assert.IsTrue(lst.Find(ref q));
Assert.AreEqual(13, q.Key);
Assert.AreEqual(79, q.Value);
}
[Test]
public void UpdateOrAdd2()
{
ICollection<String> coll = new HashSet<String>();
// s1 and s2 are distinct objects but contain the same text:
String old, s1 = "abc", s2 = ("def" + s1).Substring(3);
Assert.IsFalse(coll.UpdateOrAdd(s1, out old));
Assert.AreEqual(null, old);
Assert.IsTrue(coll.UpdateOrAdd(s2, out old));
Assert.IsTrue(Object.ReferenceEquals(s1, old));
Assert.IsFalse(Object.ReferenceEquals(s2, old));
}
[Test]
public void RemoveWithReturn()
{
KeyValuePair<int, int> p = new KeyValuePair<int, int>(3, 78);
//KeyValuePair<int,int> q = new KeyValuePair<int,int>();
Assert.IsTrue(lst.Remove(p, out p));
Assert.AreEqual(3, p.Key);
Assert.AreEqual(33, p.Value);
p = new KeyValuePair<int, int>(13, 78);
Assert.IsFalse(lst.Remove(p, out p));
}
}
}
namespace HashingAndEquals
{
[TestFixture]
public class IEditableCollection
{
private ICollection<int> dit, dat, dut;
[SetUp]
public void Init()
{
dit = new HashSet<int>();
dat = new HashSet<int>();
dut = new HashSet<int>();
}
[Test]
public void EmptyEmpty()
{
Assert.IsTrue(dit.UnsequencedEquals(dat));
}
[Test]
public void EmptyNonEmpty()
{
dit.Add(3);
Assert.IsFalse(dit.UnsequencedEquals(dat));
Assert.IsFalse(dat.UnsequencedEquals(dit));
}
[Test]
public void HashVal()
{
Assert.AreEqual(CHC.unsequencedhashcode(), dit.GetUnsequencedHashCode());
dit.Add(3);
Assert.AreEqual(CHC.unsequencedhashcode(3), dit.GetUnsequencedHashCode());
dit.Add(7);
Assert.AreEqual(CHC.unsequencedhashcode(3, 7), dit.GetUnsequencedHashCode());
Assert.AreEqual(CHC.unsequencedhashcode(), dut.GetUnsequencedHashCode());
dut.Add(3);
Assert.AreEqual(CHC.unsequencedhashcode(3), dut.GetUnsequencedHashCode());
dut.Add(7);
Assert.AreEqual(CHC.unsequencedhashcode(7, 3), dut.GetUnsequencedHashCode());
}
[Test]
public void EqualHashButDifferent()
{
dit.Add(-1657792980); dit.Add(-1570288808);
dat.Add(1862883298); dat.Add(-272461342);
Assert.AreEqual(dit.GetUnsequencedHashCode(), dat.GetUnsequencedHashCode());
Assert.IsFalse(dit.UnsequencedEquals(dat));
}
[Test]
public void Normal()
{
dit.Add(3);
dit.Add(7);
dat.Add(3);
Assert.IsFalse(dit.UnsequencedEquals(dat));
Assert.IsFalse(dat.UnsequencedEquals(dit));
dat.Add(7);
Assert.IsTrue(dit.UnsequencedEquals(dat));
Assert.IsTrue(dat.UnsequencedEquals(dit));
}
[Test]
public void WrongOrder()
{
dit.Add(3);
dut.Add(3);
Assert.IsTrue(dit.UnsequencedEquals(dut));
Assert.IsTrue(dut.UnsequencedEquals(dit));
dit.Add(7);
dut.Add(7);
Assert.IsTrue(dit.UnsequencedEquals(dut));
Assert.IsTrue(dut.UnsequencedEquals(dit));
}
[Test]
public void Reflexive()
{
Assert.IsTrue(dit.UnsequencedEquals(dit));
dit.Add(3);
Assert.IsTrue(dit.UnsequencedEquals(dit));
dit.Add(7);
Assert.IsTrue(dit.UnsequencedEquals(dit));
}
[TearDown]
public void Dispose()
{
dit = null;
dat = null;
dut = null;
}
}
[TestFixture]
public class MultiLevelUnorderedOfUnOrdered
{
private ICollection<int> dit, dat, dut;
private ICollection<ICollection<int>> Dit, Dat, Dut;
[SetUp]
public void Init()
{
dit = new HashSet<int>();
dat = new HashSet<int>();
dut = new HashSet<int>();
dit.Add(2); dit.Add(1);
dat.Add(1); dat.Add(2);
dut.Add(3);
Dit = new HashSet<ICollection<int>>();
Dat = new HashSet<ICollection<int>>();
Dut = new HashSet<ICollection<int>>();
}
[Test]
public void Check()
{
Assert.IsTrue(dit.UnsequencedEquals(dat));
Assert.IsFalse(dit.UnsequencedEquals(dut));
}
[Test]
public void Multi()
{
Dit.Add(dit); Dit.Add(dut); Dit.Add(dit);
Dat.Add(dut); Dat.Add(dit); Dat.Add(dat);
Assert.IsTrue(Dit.UnsequencedEquals(Dat));
Assert.IsFalse(Dit.UnsequencedEquals(Dut));
}
[TearDown]
public void Dispose()
{
dit = dat = dut = null;
Dit = Dat = Dut = null;
}
}
[TestFixture]
public class MultiLevelOrderedOfUnOrdered
{
private ICollection<int> dit, dat, dut;
private ISequenced<ICollection<int>> Dit, Dat, Dut;
[SetUp]
public void Init()
{
dit = new HashSet<int>();
dat = new HashSet<int>();
dut = new HashSet<int>();
dit.Add(2); dit.Add(1);
dat.Add(1); dat.Add(2);
dut.Add(3);
Dit = new LinkedList<ICollection<int>>();
Dat = new LinkedList<ICollection<int>>();
Dut = new LinkedList<ICollection<int>>();
}
[Test]
public void Check()
{
Assert.IsTrue(dit.UnsequencedEquals(dat));
Assert.IsFalse(dit.UnsequencedEquals(dut));
}
[Test]
public void Multi()
{
Dit.Add(dit); Dit.Add(dut); Dit.Add(dit);
Dat.Add(dut); Dat.Add(dit); Dat.Add(dat);
Dut.Add(dit); Dut.Add(dut); Dut.Add(dat);
Assert.IsFalse(Dit.SequencedEquals(Dat));
Assert.IsTrue(Dit.SequencedEquals(Dut));
}
[TearDown]
public void Dispose()
{
dit = dat = dut = null;
Dit = Dat = Dut = null;
}
}
[TestFixture]
public class MultiLevelUnOrderedOfOrdered
{
private ISequenced<int> dit, dat, dut, dot;
private ICollection<ISequenced<int>> Dit, Dat, Dut, Dot;
[SetUp]
public void Init()
{
dit = new LinkedList<int>();
dat = new LinkedList<int>();
dut = new LinkedList<int>();
dot = new LinkedList<int>();
dit.Add(2); dit.Add(1);
dat.Add(1); dat.Add(2);
dut.Add(3);
dot.Add(2); dot.Add(1);
Dit = new HashSet<ISequenced<int>>();
Dat = new HashSet<ISequenced<int>>();
Dut = new HashSet<ISequenced<int>>();
Dot = new HashSet<ISequenced<int>>();
}
[Test]
public void Check()
{
Assert.IsFalse(dit.SequencedEquals(dat));
Assert.IsTrue(dit.SequencedEquals(dot));
Assert.IsFalse(dit.SequencedEquals(dut));
}
[Test]
public void Multi()
{
Dit.Add(dit); Dit.Add(dut);//Dit.Add(dit);
Dat.Add(dut); Dat.Add(dit); Dat.Add(dat);
Dut.Add(dot); Dut.Add(dut);//Dut.Add(dit);
Dot.Add(dit); Dot.Add(dit); Dot.Add(dut);
Assert.IsTrue(Dit.UnsequencedEquals(Dit));
Assert.IsTrue(Dit.UnsequencedEquals(Dut));
Assert.IsFalse(Dit.UnsequencedEquals(Dat));
Assert.IsTrue(Dit.UnsequencedEquals(Dot));
}
[TearDown]
public void Dispose()
{
dit = dat = dut = dot = null;
Dit = Dat = Dut = Dot = null;
}
}
}
}
| |
// Copyright (c) Alexandre Mutel. All rights reserved.
// This file is licensed under the BSD-Clause 2 license.
// See the license.txt file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using Microsoft.DocAsCode.DataContracts.ManagedReference;
namespace Lunet.Api.DotNet.Extractor
{
public partial class JsonSerializer
{
private bool _isFirstKeyValue;
private readonly TextWriter _writer;
private static readonly Dictionary<Type, Action<JsonSerializer, object>> _serializers = new Dictionary<Type, Action<JsonSerializer, object>>();
private int _level;
private bool _prettyOutput;
private bool _newLine;
public JsonSerializer(TextWriter writer)
{
this._writer = writer ?? throw new ArgumentNullException(nameof(writer));
}
public bool PrettyOutput
{
get => _prettyOutput;
set => _prettyOutput = value;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Write(object value)
{
WriteJsonValue(value);
}
private void WriteIndent()
{
if (_prettyOutput && _newLine)
{
for (int i = 0; i < _level; i++)
{
_writer.Write('\t');
}
_newLine = false;
}
}
private void WriteOutput(char value)
{
WriteIndent();
_writer.Write(value);
}
private void WriteOutput(string value)
{
WriteIndent();
_writer.Write(value);
}
private void WriteLine()
{
if (_prettyOutput)
{
WriteOutput('\n');
_newLine = true;
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void StartObject()
{
WriteOutput('{');
WriteLine();
_level++;
_isFirstKeyValue = true;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void EndObject()
{
if (!_isFirstKeyValue)
{
WriteLine();
}
_level--;
WriteOutput('}');
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void WriteJsonKeyValue( object key, object value)
{
if (value is null) return;
WriteKey(key);
if (_prettyOutput)
{
WriteOutput(' ');
}
WriteJsonValue(value);
WriteLine();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void WriteJsonKeyValue(object key, string value)
{
if (value is null) return;
WriteKey(key);
WriteJsonString(value);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void WriteJsonKeyValue(object key, bool value)
{
WriteKey(key);
WriteJsonBoolean(value);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void WriteJsonKeyValue(object key, int value)
{
WriteKey(key);
WriteJsonInt32(value);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void WriteJsonKeyValue(object key, IEnumerable value)
{
if (value is null) return;
WriteKey(key);
WriteJsonArrayValue(value);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void WriteKey(object key)
{
if (!_isFirstKeyValue)
{
WriteOutput(',');
if (_prettyOutput)
{
WriteLine();
}
}
_isFirstKeyValue = false;
WriteJsonValue(key);
WriteOutput(":");
}
private void StartArray()
{
WriteOutput('[');
WriteLine();
_level++;
}
private void EndArray()
{
_level--;
WriteOutput(']');
}
private void WriteJsonArrayValue(IEnumerable values)
{
if (values == null)
{
WriteOutput("null");
return;
}
StartArray();
bool isFirst = true;
try
{
foreach (var item in values)
{
if (!isFirst)
{
WriteOutput(',');
WriteLine();
}
isFirst = false;
WriteJsonValue(item);
}
}
catch (Exception ex)
{
var supportedInterfaces = values.GetType().GetInterfaces();
throw new InvalidOperationException($"Error while trying to serialize {values.GetType()}. Reason: {ex.Message}. Supported interfaces: {string.Join("\n", supportedInterfaces.Select(x=> x.FullName))}", ex);
}
if (_prettyOutput && !isFirst)
{
WriteLine();
}
EndArray();
}
private void WriteJsonValue(object value)
{
if (value is null)
{
WriteOutput("null");
return;
}
if (_serializers.TryGetValue(value.GetType(), out var valueSerializer))
{
valueSerializer(this, value);
return;
}
if (value is bool b)
{
WriteJsonBoolean(b);
}
else if (value is int i32)
{
WriteJsonInt32(i32);
}
else if (value is string str)
{
WriteJsonString(str);
}
else if (value is IDictionary dictionary)
{
var it = dictionary.GetEnumerator();
StartObject();
while (it.MoveNext())
{
WriteJsonKeyValue(it.Key, it.Value);
}
EndObject();
}
else if (!(value is string) && value is IEnumerable it)
{
WriteJsonArrayValue(it);
}
else
{
var type = value.GetType();
if (value is Enum e)
{
WriteJsonString(e.ToString());
}
else
{
throw new InvalidOperationException($"The serializer for the type {value.GetType()} is out of date. You must re-run the serializer gen.");
}
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void WriteJsonInt32(int i32)
{
WriteOutput(i32.ToString(CultureInfo.InvariantCulture));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void WriteJsonBoolean(bool b)
{
WriteOutput(b ? "true" : "false");
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void WriteJsonString(string str)
{
var newStr = JsonStringEncode(str);
WriteOutput(newStr);
}
private static bool CharRequiresJsonEncoding(char c) => c < ' ' || c == '"' || c == '\\';
private static string JsonStringEncode(string value)
{
if (string.IsNullOrEmpty(value))
return "\"\"";
var builder = new StringBuilder(value.Length + 5);
builder.Append('"');
int startIndex = 0;
int count = 0;
for (int index = 0; index < value.Length; ++index)
{
char c = value[index];
if (CharRequiresJsonEncoding(c))
{
if (count > 0)
builder.Append(value, startIndex, count);
startIndex = index + 1;
count = 0;
switch (c)
{
case '\b':
builder.Append("\\b");
continue;
case '\t':
builder.Append("\\t");
continue;
case '\n':
builder.Append("\\n");
continue;
case '\f':
builder.Append("\\f");
continue;
case '\r':
builder.Append("\\r");
continue;
case '"':
builder.Append("\\\"");
continue;
case '\\':
builder.Append("\\\\");
continue;
default:
AppendCharAsUnicodeJavaScript(builder, c);
continue;
}
}
else
++count;
}
if (count > 0)
builder.Append(value, startIndex, count);
builder.Append('"');
return builder.ToString();
}
private static void AppendCharAsUnicodeJavaScript(StringBuilder builder, char c)
{
builder.Append("\\u");
builder.Append(((int)c).ToString("x4", (IFormatProvider)CultureInfo.InvariantCulture));
}
}
}
| |
using System;
using System.Runtime.InteropServices;
namespace BuzzIO
{
/// <summary>
/// Class that wraps USB API calls and structures
/// </summary>
public class Win32Usb
{
#region Structures
/// <summary>
/// An overlapped structure used for overlapped IO operations. The structure is
/// only used by the OS to keep state on pending operations. You don't need to fill anything in if you
/// unless you want a Windows event to fire when the operation is complete.
/// </summary>
[StructLayout(LayoutKind.Sequential, Pack = 1)]
protected struct Overlapped
{
public uint Internal;
public uint InternalHigh;
public uint Offset;
public uint OffsetHigh;
public IntPtr Event;
}
/// <summary>
/// Provides details about a single USB device
/// </summary>
[StructLayout(LayoutKind.Sequential, Pack = 1)]
protected struct DeviceInterfaceData
{
public int Size;
public Guid InterfaceClassGuid;
public int Flags;
public IntPtr Reserved;
}
/// <summary>
/// Provides the capabilities of a HID device
/// </summary>
[StructLayout(LayoutKind.Sequential, Pack = 1)]
protected struct HidCaps
{
public short Usage;
public short UsagePage;
public short InputReportByteLength;
public short OutputReportByteLength;
public short FeatureReportByteLength;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 17)]
public short[] Reserved;
public short NumberLinkCollectionNodes;
public short NumberInputButtonCaps;
public short NumberInputValueCaps;
public short NumberInputDataIndices;
public short NumberOutputButtonCaps;
public short NumberOutputValueCaps;
public short NumberOutputDataIndices;
public short NumberFeatureButtonCaps;
public short NumberFeatureValueCaps;
public short NumberFeatureDataIndices;
}
/// <summary>
/// Access to the path for a device
/// </summary>
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct DeviceInterfaceDetailData
{
public int Size;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
public string DevicePath;
}
/// <summary>
/// Used when registering a window to receive messages about devices added or removed from the system.
/// </summary>
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode, Pack = 1)]
public class DeviceBroadcastInterface
{
public int Size;
public int DeviceType;
public int Reserved;
public Guid ClassGuid;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
public string Name;
}
#endregion
#region Constants
/// <summary>Windows message sent when a device is inserted or removed</summary>
public const int WM_DEVICECHANGE = 0x0219;
/// <summary>WParam for above : A device was inserted</summary>
public const int DEVICE_ARRIVAL = 0x8000;
/// <summary>WParam for above : A device was removed</summary>
public const int DEVICE_REMOVECOMPLETE = 0x8004;
/// <summary>Used in SetupDiClassDevs to get devices present in the system</summary>
protected const int DIGCF_PRESENT = 0x02;
/// <summary>Used in SetupDiClassDevs to get device interface details</summary>
protected const int DIGCF_DEVICEINTERFACE = 0x10;
/// <summary>Used when registering for device insert/remove messages : specifies the type of device</summary>
protected const int DEVTYP_DEVICEINTERFACE = 0x05;
/// <summary>Used when registering for device insert/remove messages : we're giving the API call a window handle</summary>
protected const int DEVICE_NOTIFY_WINDOW_HANDLE = 0;
/// <summary>Purges Win32 transmit buffer by aborting the current transmission.</summary>
protected const uint PURGE_TXABORT = 0x01;
/// <summary>Purges Win32 receive buffer by aborting the current receive.</summary>
protected const uint PURGE_RXABORT = 0x02;
/// <summary>Purges Win32 transmit buffer by clearing it.</summary>
protected const uint PURGE_TXCLEAR = 0x04;
/// <summary>Purges Win32 receive buffer by clearing it.</summary>
protected const uint PURGE_RXCLEAR = 0x08;
/// <summary>CreateFile : Open file for read</summary>
protected const uint GENERIC_READ = 0x80000000;
/// <summary>CreateFile : Open file for write</summary>
protected const uint GENERIC_WRITE = 0x40000000;
/// <summary>CreateFile : Open handle for overlapped operations</summary>
protected const uint FILE_FLAG_OVERLAPPED = 0x40000000;
/// <summary>CreateFile : Resource to be "created" must exist</summary>
protected const uint OPEN_EXISTING = 3;
/// <summary>ReadFile/WriteFile : Overlapped operation is incomplete.</summary>
protected const uint ERROR_IO_PENDING = 997;
/// <summary>Infinite timeout</summary>
protected const uint INFINITE = 0xFFFFFFFF;
/// <summary>Simple representation of a null handle : a closed stream will get this handle. Note it is public for comparison by higher level classes.</summary>
public static IntPtr NullHandle = IntPtr.Zero;
/// <summary>Simple representation of the handle returned when CreateFile fails.</summary>
protected static IntPtr InvalidHandleValue = new IntPtr(-1);
#endregion
#region P/Invoke
/// <summary>
/// Gets the GUID that Windows uses to represent HID class devices
/// </summary>
/// <param name="gHid">An out parameter to take the Guid</param>
[DllImport("hid.dll", SetLastError = true)]
protected static extern void HidD_GetHidGuid(out Guid gHid);
/// <summary>
/// Allocates an InfoSet memory block within Windows that contains details of devices.
/// </summary>
/// <param name="gClass">Class guid (e.g. HID guid)</param>
/// <param name="strEnumerator">Not used</param>
/// <param name="hParent">Not used</param>
/// <param name="nFlags">Type of device details required (DIGCF_ constants)</param>
/// <returns>A reference to the InfoSet</returns>
[DllImport("setupapi.dll", SetLastError = true)]
protected static extern IntPtr SetupDiGetClassDevs(ref Guid gClass, [MarshalAs(UnmanagedType.LPStr)] string strEnumerator, IntPtr hParent, uint nFlags);
/// <summary>
/// Frees InfoSet allocated in call to above.
/// </summary>
/// <param name="lpInfoSet">Reference to InfoSet</param>
/// <returns>true if successful</returns>
[DllImport("setupapi.dll", SetLastError = true)]
protected static extern int SetupDiDestroyDeviceInfoList(IntPtr lpInfoSet);
/// <summary>
/// Gets the DeviceInterfaceData for a device from an InfoSet.
/// </summary>
/// <param name="lpDeviceInfoSet">InfoSet to access</param>
/// <param name="nDeviceInfoData">Not used</param>
/// <param name="gClass">Device class guid</param>
/// <param name="nIndex">Index into InfoSet for device</param>
/// <param name="oInterfaceData">DeviceInterfaceData to fill with data</param>
/// <returns>True if successful, false if not (e.g. when index is passed end of InfoSet)</returns>
[DllImport("setupapi.dll", SetLastError = true)]
protected static extern bool SetupDiEnumDeviceInterfaces(IntPtr lpDeviceInfoSet, uint nDeviceInfoData, ref Guid gClass, uint nIndex, ref DeviceInterfaceData oInterfaceData);
/// <summary>
/// SetupDiGetDeviceInterfaceDetail - two of these, overloaded because they are used together in slightly different
/// ways and the parameters have different meanings.
/// Gets the interface detail from a DeviceInterfaceData. This is pretty much the device path.
/// You call this twice, once to get the size of the struct you need to send (nDeviceInterfaceDetailDataSize=0)
/// and once again when you've allocated the required space.
/// </summary>
/// <param name="lpDeviceInfoSet">InfoSet to access</param>
/// <param name="oInterfaceData">DeviceInterfaceData to use</param>
/// <param name="lpDeviceInterfaceDetailData">DeviceInterfaceDetailData to fill with data</param>
/// <param name="nDeviceInterfaceDetailDataSize">The size of the above</param>
/// <param name="nRequiredSize">The required size of the above when above is set as zero</param>
/// <param name="lpDeviceInfoData">Not used</param>
/// <returns></returns>
[DllImport("setupapi.dll", SetLastError = true)]
protected static extern bool SetupDiGetDeviceInterfaceDetail(IntPtr lpDeviceInfoSet, ref DeviceInterfaceData oInterfaceData, IntPtr lpDeviceInterfaceDetailData, uint nDeviceInterfaceDetailDataSize, ref uint nRequiredSize, IntPtr lpDeviceInfoData);
[DllImport("setupapi.dll", SetLastError = true)]
protected static extern bool SetupDiGetDeviceInterfaceDetail(IntPtr lpDeviceInfoSet, ref DeviceInterfaceData oInterfaceData, ref DeviceInterfaceDetailData oDetailData, uint nDeviceInterfaceDetailDataSize, ref uint nRequiredSize, IntPtr lpDeviceInfoData);
/// <summary>
/// Registers a window for device insert/remove messages
/// </summary>
/// <param name="hwnd">Handle to the window that will receive the messages</param>
/// <param name="oInterface">DeviceBroadcastInterrface structure</param>
/// <param name="nFlags">set to DEVICE_NOTIFY_WINDOW_HANDLE</param>
/// <returns>A handle used when unregistering</returns>
[DllImport("user32.dll", SetLastError = true)]
protected static extern IntPtr RegisterDeviceNotification(IntPtr hwnd, DeviceBroadcastInterface oInterface, uint nFlags);
/// <summary>
/// Unregister from above.
/// </summary>
/// <param name="hHandle">Handle returned in call to RegisterDeviceNotification</param>
/// <returns>True if success</returns>
[DllImport("user32.dll", SetLastError = true)]
protected static extern bool UnregisterDeviceNotification(IntPtr hHandle);
/// <summary>
/// Gets details from an open device. Reserves a block of memory which must be freed.
/// </summary>
/// <param name="hFile">Device file handle</param>
/// <param name="lpData">Reference to the preparsed data block</param>
/// <returns></returns>
[DllImport("hid.dll", SetLastError = true)]
protected static extern bool HidD_GetPreparsedData(IntPtr hFile, out IntPtr lpData);
/// <summary>
/// Frees the memory block reserved above.
/// </summary>
/// <param name="pData">Reference to preparsed data returned in call to GetPreparsedData</param>
/// <returns></returns>
[DllImport("hid.dll", SetLastError = true)]
protected static extern bool HidD_FreePreparsedData(ref IntPtr pData);
/// <summary>
/// Gets a device's capabilities from the preparsed data.
/// </summary>
/// <param name="lpData">Preparsed data reference</param>
/// <param name="oCaps">HidCaps structure to receive the capabilities</param>
/// <returns>True if successful</returns>
[DllImport("hid.dll", SetLastError = true)]
protected static extern int HidP_GetCaps(IntPtr lpData, out HidCaps oCaps);
/// <summary>
/// Creates/opens a file, serial port, USB device... etc
/// </summary>
/// <param name="strName">Path to object to open</param>
/// <param name="nAccess">Access mode. e.g. Read, write</param>
/// <param name="nShareMode">Sharing mode</param>
/// <param name="lpSecurity">Security details (can be null)</param>
/// <param name="nCreationFlags">Specifies if the file is created or opened</param>
/// <param name="nAttributes">Any extra attributes? e.g. open overlapped</param>
/// <param name="lpTemplate">Not used</param>
/// <returns></returns>
[DllImport("kernel32.dll", SetLastError = true)]
protected static extern IntPtr CreateFile([MarshalAs(UnmanagedType.LPStr)] string strName, uint nAccess, uint nShareMode, IntPtr lpSecurity, uint nCreationFlags, uint nAttributes, IntPtr lpTemplate);
/// <summary>
/// Closes a window handle. File handles, event handles, mutex handles... etc
/// </summary>
/// <param name="hFile">Handle to close</param>
/// <returns>True if successful.</returns>
[DllImport("kernel32.dll", SetLastError = true)]
protected static extern int CloseHandle(IntPtr hFile);
[DllImport("hid.dll", SetLastError = true, CallingConvention = CallingConvention.StdCall)]
internal static extern bool HidD_GetProductString(
IntPtr hDevice,
IntPtr buffer,
uint bufferLength);
#endregion P/Invoke
#region Public methods
/// <summary>
/// Registers a window to receive windows messages when a device is inserted/removed. Need to call this
/// from a form when its handle has been created, not in the form constructor. Use form's OnHandleCreated override.
/// </summary>
/// <param name="hWnd">Handle to window that will receive messages</param>
/// <param name="gClass">Class of devices to get messages for</param>
/// <returns>A handle used when unregistering</returns>
public static IntPtr RegisterForUsbEvents(IntPtr hWnd, Guid gClass)
{
var oInterfaceIn = new DeviceBroadcastInterface {ClassGuid = gClass, DeviceType = DEVTYP_DEVICEINTERFACE, Reserved = 0};
oInterfaceIn.Size = Marshal.SizeOf(oInterfaceIn);
return RegisterDeviceNotification(hWnd, oInterfaceIn, DEVICE_NOTIFY_WINDOW_HANDLE);
}
/// <summary>
/// Unregisters notifications. Can be used in form dispose
/// </summary>
/// <param name="hHandle">Handle returned from RegisterForUSBEvents</param>
/// <returns>True if successful</returns>
public static bool UnregisterForUsbEvents(IntPtr hHandle)
{
return UnregisterDeviceNotification(hHandle);
}
/// <summary>
/// Helper to get the HID guid.
/// </summary>
public static Guid HIDGuid
{
get
{
Guid gHid;
HidD_GetHidGuid(out gHid);
return gHid;
}
}
#endregion
}
}
| |
//=============================================================================
// System : EWSoftware Design Time Attributes and Editors
// File : ComponentConfigurationEditorDlg.cs
// Author : Eric Woodruff ([email protected])
// Updated : 07/01/2008
// Note : Copyright 2007-2008, Eric Woodruff, All rights reserved
// Compiler: Microsoft Visual C#
//
// This file contains the form used to select and edit the third-party build
// component configurations.
//
// This code is published under the Microsoft Public License (Ms-PL). A copy
// of the license should be distributed with the code. It can also be found
// at the project website: http://SHFB.CodePlex.com. This notice, the
// author's name, and all copyright notices must remain intact in all
// applications, documentation, and source files.
//
// Version Date Who Comments
// ============================================================================
// 1.6.0.2 09/10/2007 EFW Created the code
//=============================================================================
using System;
using System.ComponentModel;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using System.Xml;
using SandcastleBuilder.Utils;
using SandcastleBuilder.Utils.BuildComponent;
namespace SandcastleBuilder.Utils.Design
{
/// <summary>
/// This is used to select and edit the third-party build component
/// configurations.
/// </summary>
/// <remarks>To be editable, the build component configuration file must
/// be present in the <b>.\Build Components</b> folder or a subfolder
/// beneath it. The build components folder is found under the common
/// application data folder.</remarks>
internal partial class ComponentConfigurationEditorDlg : Form
{
#region Private data members
// The current configurations
private ComponentConfigurationDictionary currentConfigs;
#endregion
//=====================================================================
// Methods, etc.
/// <summary>
/// Constructor
/// </summary>
/// <param name="configs">The current configurations</param>
internal ComponentConfigurationEditorDlg(
ComponentConfigurationDictionary configs)
{
int idx;
InitializeComponent();
currentConfigs = configs;
try
{
// Show all but the hidden components
foreach(string key in BuildComponentManager.BuildComponents.Keys)
if(!BuildComponentManager.BuildComponents[key].IsHidden)
lbAvailableComponents.Items.Add(key);
}
catch(Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.ToString());
MessageBox.Show("Unexpected error loading build components: " +
ex.Message, Constants.AppName,
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
if(lbAvailableComponents.Items.Count != 0)
lbAvailableComponents.SelectedIndex = 0;
else
{
MessageBox.Show("No valid build components found",
Constants.AppName, MessageBoxButtons.OK,
MessageBoxIcon.Information);
gbAvailableComponents.Enabled = gbProjectAddIns.Enabled = false;
}
foreach(string key in currentConfigs.Keys)
{
idx = lbProjectComponents.Items.Add(key);
lbProjectComponents.SetItemChecked(idx,
currentConfigs[key].Enabled);
}
if(lbProjectComponents.Items.Count != 0)
lbProjectComponents.SelectedIndex = 0;
else
btnConfigure.Enabled = btnDelete.Enabled = false;
}
/// <summary>
/// Close this form
/// </summary>
/// <param name="sender">The sender of the event</param>
/// <param name="e">The event arguments</param>
private void btnClose_Click(object sender, EventArgs e)
{
this.Close();
}
/// <summary>
/// Update the build component details when the selected index changes
/// </summary>
/// <param name="sender">The sender of the event</param>
/// <param name="e">The event arguments</param>
private void lbAvailableComponents_SelectedIndexChanged(object sender,
EventArgs e)
{
string key = (string)lbAvailableComponents.SelectedItem;
BuildComponentInfo info = BuildComponentManager.BuildComponents[key];
txtComponentCopyright.Text = info.Copyright;
txtComponentVersion.Text = String.Format(CultureInfo.CurrentCulture,
"Version {0}", info.Version);
txtComponentDescription.Text = info.Description;
}
/// <summary>
/// Update the enabled state of the build component based on its
/// checked state.
/// </summary>
/// <param name="sender">The sender of the event</param>
/// <param name="e">The event arguments</param>
private void lbProjectComponents_ItemCheck(object sender,
ItemCheckEventArgs e)
{
string key = (string)lbProjectComponents.Items[e.Index];
bool newState = (e.NewValue == CheckState.Checked);
if(currentConfigs[key].Enabled != newState)
currentConfigs[key].Enabled = newState;
}
/// <summary>
/// Add the selected build component to the project with a default
/// configuration.
/// </summary>
/// <param name="sender">The sender of the event</param>
/// <param name="e">The event arguments</param>
private void btnAddComponent_Click(object sender, EventArgs e)
{
string key = (string)lbAvailableComponents.SelectedItem;
int idx = lbProjectComponents.FindStringExact(key);
// Currently, no duplicates are allowed
if(idx != -1)
{
lbProjectComponents.SelectedIndex = idx;
return;
}
idx = lbProjectComponents.Items.Add(key);
if(idx != -1)
{
currentConfigs.Add(key, true,
BuildComponentManager.BuildComponents[key].DefaultConfiguration);
lbProjectComponents.SelectedIndex = idx;
lbProjectComponents.SetItemChecked(idx, true);
btnConfigure.Enabled = btnDelete.Enabled = true;
currentConfigs.OnDictionaryChanged(new ListChangedEventArgs(
ListChangedType.ItemAdded, -1));
}
}
/// <summary>
/// Edit the selected build component's project configuration
/// </summary>
/// <param name="sender">The sender of the event</param>
/// <param name="e">The event arguments</param>
private void btnConfigure_Click(object sender, EventArgs e)
{
BuildComponentConfiguration componentConfig;
string newConfig, currentConfig, assembly,
key = (string)lbProjectComponents.SelectedItem;
BuildComponentInfo info = BuildComponentManager.BuildComponents[key];
componentConfig = currentConfigs[key];
currentConfig = componentConfig.Configuration;
// If it doesn't have a configuration method, use the default
// configuration editor.
if(String.IsNullOrEmpty(info.ConfigureMethod))
{
using(ConfigurationEditorDlg dlg = new ConfigurationEditorDlg())
{
dlg.Configuration = currentConfig;
if(dlg.ShowDialog() == DialogResult.OK)
{
// Only store it if new or if it changed
newConfig = dlg.Configuration;
if(currentConfig != newConfig)
componentConfig.Configuration = newConfig;
}
}
return;
}
// Don't allow editing if set to "-"
if(info.ConfigureMethod == "-")
{
MessageBox.Show("The selected component contains no " +
"editable configuration information",
Constants.AppName, MessageBoxButtons.OK,
MessageBoxIcon.Information);
return;
}
try
{
// Change into the component's folder so that it has a
// better chance of finding all of its dependencies.
assembly = BuildComponentManager.ResolveComponentPath(
info.AssemblyPath);
Directory.SetCurrentDirectory(Path.GetDirectoryName(
Path.GetFullPath(assembly)));
// The exception is BuildAssemblerLibrary.dll which is in
// the Sandcastle installation folder. We'll have to resolve
// that one manually.
AppDomain.CurrentDomain.AssemblyResolve +=
new ResolveEventHandler(CurrentDomain_AssemblyResolve);
// Load the type and get a reference to the static
// configuration method.
Assembly asm = Assembly.LoadFrom(assembly);
Type component = asm.GetType(info.TypeName);
MethodInfo mi = null;
if(component != null)
mi = component.GetMethod(info.ConfigureMethod,
BindingFlags.Public | BindingFlags.Static);
if(component != null && mi != null)
{
// Invoke the method to let it configure the settings
newConfig = (string)mi.Invoke(null, new object[] {
currentConfig });
// Only store it if new or if it changed
if(currentConfig != newConfig)
componentConfig.Configuration = newConfig;
}
else
MessageBox.Show(String.Format(CultureInfo.InvariantCulture,
"Unable to locate the '{0}' method in component " +
"'{1}' in assembly {2}", info.ConfigureMethod,
info.TypeName, assembly), Constants.AppName,
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
catch(IOException ioEx)
{
System.Diagnostics.Debug.WriteLine(ioEx.ToString());
MessageBox.Show(String.Format(CultureInfo.InvariantCulture,
"A file access error occurred trying to configure the " +
"component '{0}'. Error: {1}", info.TypeName, ioEx.Message),
Constants.AppName, MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
catch(Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.ToString());
MessageBox.Show(String.Format(CultureInfo.InvariantCulture,
"An error occurred trying to configure the component " +
"'{0}'. Error: {1}", info.TypeName, ex.Message),
Constants.AppName, MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
finally
{
AppDomain.CurrentDomain.AssemblyResolve -=
new ResolveEventHandler(CurrentDomain_AssemblyResolve);
}
}
/// <summary>
/// This is handled to resolve dependent assemblies and load them
/// when necessary.
/// </summary>
/// <param name="sender">The sender of the event</param>
/// <param name="args">The event arguments</param>
/// <returns>The loaded assembly</returns>
private Assembly CurrentDomain_AssemblyResolve(object sender,
ResolveEventArgs args)
{
Assembly asm = null;
string[] nameInfo = args.Name.Split(new char[] { ',' });
string resolveName = nameInfo[0];
// See if it has already been loaded
foreach(Assembly a in AppDomain.CurrentDomain.GetAssemblies())
if(args.Name == a.FullName)
{
asm = a;
break;
}
// Is it a Sandcastle component?
if(asm == null)
{
string[] files = Directory.GetFiles(
BuildComponentManager.SandcastlePath, "*.dll",
SearchOption.AllDirectories);
foreach(string file in files)
if(resolveName == Path.GetFileNameWithoutExtension(file))
{
asm = Assembly.LoadFile(file);
break;
}
}
if(asm == null)
throw new FileLoadException("Unable to resolve reference to " +
args.Name);
return asm;
}
/// <summary>
/// Delete the selected build component from the project
/// </summary>
/// <param name="sender">The sender of the event</param>
/// <param name="e">The event arguments</param>
private void btnDelete_Click(object sender, EventArgs e)
{
string key = (string)lbProjectComponents.SelectedItem;
int idx = lbProjectComponents.SelectedIndex;
if(currentConfigs.ContainsKey(key))
{
currentConfigs.Remove(key);
currentConfigs.OnDictionaryChanged(new ListChangedEventArgs(
ListChangedType.ItemDeleted, -1));
lbProjectComponents.Items.RemoveAt(idx);
if(lbProjectComponents.Items.Count == 0)
btnConfigure.Enabled = btnDelete.Enabled = false;
else
if(idx < lbProjectComponents.Items.Count)
lbProjectComponents.SelectedIndex = idx;
else
lbProjectComponents.SelectedIndex = idx - 1;
}
}
/// <summary>
/// View help for this form
/// </summary>
/// <param name="sender">The sender of the event</param>
/// <param name="e">The event arguments</param>
private void btnHelp_Click(object sender, EventArgs e)
{
string path = Path.GetDirectoryName(
Assembly.GetExecutingAssembly().Location);
try
{
#if DEBUG
path += @"\..\..\..\Doc\Help\SandcastleBuilder.chm";
#else
path += @"\SandcastleBuilder.chm";
#endif
Form form = new Form();
form.CreateControl();
Help.ShowHelp(form, path, HelpNavigator.Topic,
"html/8dcbb69b-7a1a-4049-8e6b-2bf344efbbc9.htm");
}
catch(Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.ToString());
MessageBox.Show(String.Format(CultureInfo.CurrentCulture,
"Unable to open help file '{0}'. Reason: {1}",
path, ex.Message), Constants.AppName,
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
}
}
| |
// 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.Text;
using System.Diagnostics;
namespace System.IO
{
public class BinaryReader : IDisposable
{
private const int MaxCharBytesSize = 128;
private Stream _stream;
private byte[] _buffer;
private Decoder _decoder;
private byte[] _charBytes;
private char[] _singleChar;
private char[] _charBuffer;
private int _maxCharsSize; // From MaxCharBytesSize & Encoding
// Performance optimization for Read() w/ Unicode. Speeds us up by ~40%
private bool _2BytesPerChar;
private bool _isMemoryStream; // "do we sit on MemoryStream?" for Read/ReadInt32 perf
private bool _leaveOpen;
public BinaryReader(Stream input) : this(input, new UTF8Encoding(), false)
{
}
public BinaryReader(Stream input, Encoding encoding) : this(input, encoding, false)
{
}
public BinaryReader(Stream input, Encoding encoding, bool leaveOpen)
{
if (input == null)
{
throw new ArgumentNullException(nameof(input));
}
if (encoding == null)
{
throw new ArgumentNullException(nameof(encoding));
}
if (!input.CanRead)
{
throw new ArgumentException(SR.Argument_StreamNotReadable);
}
_stream = input;
_decoder = encoding.GetDecoder();
_maxCharsSize = encoding.GetMaxCharCount(MaxCharBytesSize);
int minBufferSize = encoding.GetMaxByteCount(1); // max bytes per one char
if (minBufferSize < 16)
{
minBufferSize = 16;
}
_buffer = new byte[minBufferSize];
// _charBuffer and _charBytes will be left null.
// For Encodings that always use 2 bytes per char (or more),
// special case them here to make Read() & Peek() faster.
_2BytesPerChar = encoding is UnicodeEncoding;
// check if BinaryReader is based on MemoryStream, and keep this for it's life
// we cannot use "as" operator, since derived classes are not allowed
_isMemoryStream = (_stream.GetType() == typeof(MemoryStream));
_leaveOpen = leaveOpen;
Debug.Assert(_decoder != null, "[BinaryReader.ctor]_decoder!=null");
}
public virtual Stream BaseStream
{
get
{
return _stream;
}
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
Stream copyOfStream = _stream;
_stream = null;
if (copyOfStream != null && !_leaveOpen)
{
copyOfStream.Dispose();
}
}
_stream = null;
_buffer = null;
_decoder = null;
_charBytes = null;
_singleChar = null;
_charBuffer = null;
}
public void Dispose()
{
Dispose(true);
}
public virtual int PeekChar()
{
if (_stream == null)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_FileClosed);
}
if (!_stream.CanSeek)
{
return -1;
}
long origPos = _stream.Position;
int ch = Read();
_stream.Position = origPos;
return ch;
}
public virtual int Read()
{
if (_stream == null)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_FileClosed);
}
return InternalReadOneChar();
}
public virtual bool ReadBoolean()
{
FillBuffer(1);
return (_buffer[0] != 0);
}
public virtual byte ReadByte()
{
// Inlined to avoid some method call overhead with FillBuffer.
if (_stream == null)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_FileClosed);
}
int b = _stream.ReadByte();
if (b == -1)
{
throw new EndOfStreamException(SR.IO_EOF_ReadBeyondEOF);
}
return (byte)b;
}
[CLSCompliant(false)]
public virtual sbyte ReadSByte()
{
FillBuffer(1);
return (sbyte)(_buffer[0]);
}
public virtual char ReadChar()
{
int value = Read();
if (value == -1)
{
throw new EndOfStreamException(SR.IO_EOF_ReadBeyondEOF);
}
return (char)value;
}
public virtual short ReadInt16()
{
FillBuffer(2);
return (short)(_buffer[0] | _buffer[1] << 8);
}
[CLSCompliant(false)]
public virtual ushort ReadUInt16()
{
FillBuffer(2);
return (ushort)(_buffer[0] | _buffer[1] << 8);
}
public virtual int ReadInt32()
{
if (_isMemoryStream)
{
if (_stream == null)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_FileClosed);
}
// read directly from MemoryStream buffer
MemoryStream mStream = _stream as MemoryStream;
Debug.Assert(mStream != null, "_stream as MemoryStream != null");
return mStream.InternalReadInt32();
}
else
{
FillBuffer(4);
return (int)(_buffer[0] | _buffer[1] << 8 | _buffer[2] << 16 | _buffer[3] << 24);
}
}
[CLSCompliant(false)]
public virtual uint ReadUInt32()
{
FillBuffer(4);
return (uint)(_buffer[0] | _buffer[1] << 8 | _buffer[2] << 16 | _buffer[3] << 24);
}
public virtual long ReadInt64()
{
FillBuffer(8);
uint lo = (uint)(_buffer[0] | _buffer[1] << 8 |
_buffer[2] << 16 | _buffer[3] << 24);
uint hi = (uint)(_buffer[4] | _buffer[5] << 8 |
_buffer[6] << 16 | _buffer[7] << 24);
return (long)((ulong)hi) << 32 | lo;
}
[CLSCompliant(false)]
public virtual ulong ReadUInt64()
{
FillBuffer(8);
uint lo = (uint)(_buffer[0] | _buffer[1] << 8 |
_buffer[2] << 16 | _buffer[3] << 24);
uint hi = (uint)(_buffer[4] | _buffer[5] << 8 |
_buffer[6] << 16 | _buffer[7] << 24);
return ((ulong)hi) << 32 | lo;
}
public virtual unsafe float ReadSingle()
{
FillBuffer(4);
uint tmpBuffer = (uint)(_buffer[0] | _buffer[1] << 8 | _buffer[2] << 16 | _buffer[3] << 24);
return *((float*)&tmpBuffer);
}
public virtual unsafe double ReadDouble()
{
FillBuffer(8);
uint lo = (uint)(_buffer[0] | _buffer[1] << 8 |
_buffer[2] << 16 | _buffer[3] << 24);
uint hi = (uint)(_buffer[4] | _buffer[5] << 8 |
_buffer[6] << 16 | _buffer[7] << 24);
ulong tmpBuffer = ((ulong)hi) << 32 | lo;
return *((double*)&tmpBuffer);
}
public virtual decimal ReadDecimal()
{
FillBuffer(16);
int[] ints = new int[4];
Buffer.BlockCopy(_buffer, 0, ints, 0, 16);
try
{
return new decimal(ints);
}
catch (ArgumentException e)
{
// ReadDecimal cannot leak out ArgumentException
throw new IOException(SR.Arg_DecBitCtor, e);
}
}
public virtual string ReadString()
{
if (_stream == null)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_FileClosed);
}
int currPos = 0;
int n;
int stringLength;
int readLength;
int charsRead;
// Length of the string in bytes, not chars
stringLength = Read7BitEncodedInt();
if (stringLength < 0)
{
throw new IOException(SR.Format(SR.IO_IO_InvalidStringLen_Len, stringLength));
}
if (stringLength == 0)
{
return string.Empty;
}
if (_charBytes == null)
{
_charBytes = new byte[MaxCharBytesSize];
}
if (_charBuffer == null)
{
_charBuffer = new char[_maxCharsSize];
}
StringBuilder sb = null;
do
{
readLength = ((stringLength - currPos) > MaxCharBytesSize) ? MaxCharBytesSize : (stringLength - currPos);
n = _stream.Read(_charBytes, 0, readLength);
if (n == 0)
{
throw new EndOfStreamException(SR.IO_EOF_ReadBeyondEOF);
}
charsRead = _decoder.GetChars(_charBytes, 0, n, _charBuffer, 0);
if (currPos == 0 && n == stringLength)
{
return new string(_charBuffer, 0, charsRead);
}
if (sb == null)
{
sb = StringBuilderCache.Acquire(stringLength); // Actual string length in chars may be smaller.
}
sb.Append(_charBuffer, 0, charsRead);
currPos += n;
} while (currPos < stringLength);
return StringBuilderCache.GetStringAndRelease(sb);
}
public virtual int Read(char[] buffer, int index, int count)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
}
if (index < 0)
{
throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (count < 0)
{
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (buffer.Length - index < count)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
if (_stream == null)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_FileClosed);
}
// SafeCritical: index and count have already been verified to be a valid range for the buffer
return InternalReadChars(buffer, index, count);
}
private int InternalReadChars(char[] buffer, int index, int count)
{
Debug.Assert(buffer != null);
Debug.Assert(index >= 0 && count >= 0);
Debug.Assert(_stream != null);
int numBytes = 0;
int charsRemaining = count;
if (_charBytes == null)
{
_charBytes = new byte[MaxCharBytesSize];
}
while (charsRemaining > 0)
{
int charsRead = 0;
// We really want to know what the minimum number of bytes per char
// is for our encoding. Otherwise for UnicodeEncoding we'd have to
// do ~1+log(n) reads to read n characters.
numBytes = charsRemaining;
if (_2BytesPerChar)
{
numBytes <<= 1;
}
if (numBytes > MaxCharBytesSize)
{
numBytes = MaxCharBytesSize;
}
int position = 0;
byte[] byteBuffer = null;
if (_isMemoryStream)
{
MemoryStream mStream = _stream as MemoryStream;
Debug.Assert(mStream != null, "_stream as MemoryStream != null");
position = mStream.InternalGetPosition();
numBytes = mStream.InternalEmulateRead(numBytes);
byteBuffer = mStream.InternalGetBuffer();
}
else
{
numBytes = _stream.Read(_charBytes, 0, numBytes);
byteBuffer = _charBytes;
}
if (numBytes == 0)
{
return (count - charsRemaining);
}
Debug.Assert(byteBuffer != null, "expected byteBuffer to be non-null");
unsafe
{
fixed (byte* pBytes = byteBuffer)
fixed (char* pChars = buffer)
{
charsRead = _decoder.GetChars(byteBuffer, position, numBytes, buffer, index, false);
}
}
charsRemaining -= charsRead;
index += charsRead;
}
// this should never fail
Debug.Assert(charsRemaining >= 0, "We read too many characters.");
// we may have read fewer than the number of characters requested if end of stream reached
// or if the encoding makes the char count too big for the buffer (e.g. fallback sequence)
return (count - charsRemaining);
}
private int InternalReadOneChar()
{
// I know having a separate InternalReadOneChar method seems a little
// redundant, but this makes a scenario like the security parser code
// 20% faster, in addition to the optimizations for UnicodeEncoding I
// put in InternalReadChars.
int charsRead = 0;
int numBytes = 0;
long posSav = posSav = 0;
if (_stream.CanSeek)
{
posSav = _stream.Position;
}
if (_charBytes == null)
{
_charBytes = new byte[MaxCharBytesSize]; //REVIEW: We need at most 2 bytes/char here?
}
if (_singleChar == null)
{
_singleChar = new char[1];
}
while (charsRead == 0)
{
// We really want to know what the minimum number of bytes per char
// is for our encoding. Otherwise for UnicodeEncoding we'd have to
// do ~1+log(n) reads to read n characters.
// Assume 1 byte can be 1 char unless _2BytesPerChar is true.
numBytes = _2BytesPerChar ? 2 : 1;
int r = _stream.ReadByte();
_charBytes[0] = (byte)r;
if (r == -1)
{
numBytes = 0;
}
if (numBytes == 2)
{
r = _stream.ReadByte();
_charBytes[1] = (byte)r;
if (r == -1)
{
numBytes = 1;
}
}
if (numBytes == 0)
{
// Console.WriteLine("Found no bytes. We're outta here.");
return -1;
}
Debug.Assert(numBytes == 1 || numBytes == 2, "BinaryReader::InternalReadOneChar assumes it's reading one or 2 bytes only.");
try
{
charsRead = _decoder.GetChars(_charBytes, 0, numBytes, _singleChar, 0);
}
catch
{
// Handle surrogate char
if (_stream.CanSeek)
{
_stream.Seek((posSav - _stream.Position), SeekOrigin.Current);
}
// else - we can't do much here
throw;
}
Debug.Assert(charsRead < 2, "InternalReadOneChar - assuming we only got 0 or 1 char, not 2!");
// Console.WriteLine("That became: " + charsRead + " characters.");
}
if (charsRead == 0)
{
return -1;
}
return _singleChar[0];
}
public virtual char[] ReadChars(int count)
{
if (count < 0)
{
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (_stream == null)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_FileClosed);
}
if (count == 0)
{
return Array.Empty<char>();
}
// SafeCritical: we own the chars buffer, and therefore can guarantee that the index and count are valid
char[] chars = new char[count];
int n = InternalReadChars(chars, 0, count);
if (n != count)
{
char[] copy = new char[n];
Buffer.BlockCopy(chars, 0, copy, 0, 2 * n); // sizeof(char)
chars = copy;
}
return chars;
}
public virtual int Read(byte[] buffer, int index, int count)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
}
if (index < 0)
{
throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (count < 0)
{
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (buffer.Length - index < count)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
if (_stream == null)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_FileClosed);
}
return _stream.Read(buffer, index, count);
}
public virtual byte[] ReadBytes(int count)
{
if (count < 0)
{
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (_stream == null)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_FileClosed);
}
if (count == 0)
{
return Array.Empty<byte>();
}
byte[] result = new byte[count];
int numRead = 0;
do
{
int n = _stream.Read(result, numRead, count);
if (n == 0)
{
break;
}
numRead += n;
count -= n;
} while (count > 0);
if (numRead != result.Length)
{
// Trim array. This should happen on EOF & possibly net streams.
byte[] copy = new byte[numRead];
Buffer.BlockCopy(result, 0, copy, 0, numRead);
result = copy;
}
return result;
}
protected virtual void FillBuffer(int numBytes)
{
if (_buffer != null && (numBytes < 0 || numBytes > _buffer.Length))
{
throw new ArgumentOutOfRangeException(nameof(numBytes), SR.ArgumentOutOfRange_BinaryReaderFillBuffer);
}
int bytesRead = 0;
int n = 0;
if (_stream == null)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_FileClosed);
}
// Need to find a good threshold for calling ReadByte() repeatedly
// vs. calling Read(byte[], int, int) for both buffered & unbuffered
// streams.
if (numBytes == 1)
{
n = _stream.ReadByte();
if (n == -1)
{
throw new EndOfStreamException(SR.IO_EOF_ReadBeyondEOF);
}
_buffer[0] = (byte)n;
return;
}
do
{
n = _stream.Read(_buffer, bytesRead, numBytes - bytesRead);
if (n == 0)
{
throw new EndOfStreamException(SR.IO_EOF_ReadBeyondEOF);
}
bytesRead += n;
} while (bytesRead < numBytes);
}
internal protected int Read7BitEncodedInt()
{
// Read out an Int32 7 bits at a time. The high bit
// of the byte when on means to continue reading more bytes.
int count = 0;
int shift = 0;
byte b;
do
{
// Check for a corrupted stream. Read a max of 5 bytes.
// In a future version, add a DataFormatException.
if (shift == 5 * 7) // 5 bytes max per Int32, shift += 7
{
throw new FormatException(SR.Format_Bad7BitInt32);
}
// ReadByte handles end of stream cases for us.
b = ReadByte();
count |= (b & 0x7F) << shift;
shift += 7;
} while ((b & 0x80) != 0);
return count;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.AcceptanceTestsAzureCompositeModelClient
{
using System.Linq;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// ArrayOperations operations.
/// </summary>
internal partial class ArrayOperations : Microsoft.Rest.IServiceOperations<AzureCompositeModel>, IArrayOperations
{
/// <summary>
/// Initializes a new instance of the ArrayOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal ArrayOperations(AzureCompositeModel client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the AzureCompositeModel
/// </summary>
public AzureCompositeModel Client { get; private set; }
/// <summary>
/// Get complex types with array property
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<ArrayWrapper>> GetValidWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
// 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("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "GetValid", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/array/valid").ToString();
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
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 ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse<ArrayWrapper>();
_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<ArrayWrapper>(_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>
/// Put complex types with array property
/// </summary>
/// <param name='array'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> PutValidWithHttpMessagesAsync(System.Collections.Generic.IList<string> array = default(System.Collections.Generic.IList<string>), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
ArrayWrapper complexBody = new ArrayWrapper();
if (array != null)
{
complexBody.Array = array;
}
// 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("complexBody", complexBody);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "PutValid", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/array/valid").ToString();
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
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(complexBody != null)
{
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(complexBody, 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 ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.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>
/// Get complex types with array property which is empty
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<ArrayWrapper>> GetEmptyWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
// 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("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "GetEmpty", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/array/empty").ToString();
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
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 ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse<ArrayWrapper>();
_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<ArrayWrapper>(_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>
/// Put complex types with array property which is empty
/// </summary>
/// <param name='array'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> PutEmptyWithHttpMessagesAsync(System.Collections.Generic.IList<string> array = default(System.Collections.Generic.IList<string>), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
ArrayWrapper complexBody = new ArrayWrapper();
if (array != null)
{
complexBody.Array = array;
}
// 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("complexBody", complexBody);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "PutEmpty", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/array/empty").ToString();
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
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(complexBody != null)
{
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(complexBody, 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 ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.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>
/// Get complex types with array property while server doesn't provide a
/// response payload
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<ArrayWrapper>> GetNotProvidedWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
// 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("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "GetNotProvided", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/array/notprovided").ToString();
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
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 ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse<ArrayWrapper>();
_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<ArrayWrapper>(_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) 2006 Charlie Poole, Rob Prouse
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using NUnit.TestUtilities.Collections;
using NUnit.TestUtilities.Comparers;
namespace NUnit.Framework.Assertions
{
/// <summary>
/// Test Library for the NUnit CollectionAssert class.
/// </summary>
[TestFixture()]
public class CollectionAssertTest
{
#region AllItemsAreInstancesOfType
[Test()]
public void ItemsOfType()
{
var collection = new SimpleObjectCollection("x", "y", "z");
CollectionAssert.AllItemsAreInstancesOfType(collection,typeof(string));
}
[Test]
public void ItemsOfTypeFailure()
{
var collection = new SimpleObjectCollection("x", "y", new object());
var expectedMessage =
" Expected: all items instance of <System.String>" + Environment.NewLine +
" But was: < \"x\", \"y\", <System.Object> >" + Environment.NewLine +
" First non-matching item at index [2]: <System.Object>" + Environment.NewLine;
var ex = Assert.Throws<AssertionException>(() => CollectionAssert.AllItemsAreInstancesOfType(collection, typeof(string)));
Assert.That(ex.Message, Is.EqualTo(expectedMessage));
}
#endregion
#region AllItemsAreNotNull
[Test()]
public void ItemsNotNull()
{
var collection = new SimpleObjectCollection("x", "y", "z");
CollectionAssert.AllItemsAreNotNull(collection);
}
[Test]
public void ItemsNotNullFailure()
{
var collection = new SimpleObjectCollection("x", null, "z");
var expectedMessage =
" Expected: all items not null" + Environment.NewLine +
" But was: < \"x\", null, \"z\" >" + Environment.NewLine +
" First non-matching item at index [1]: null" + Environment.NewLine;
var ex = Assert.Throws<AssertionException>(() => CollectionAssert.AllItemsAreNotNull(collection));
Assert.That(ex.Message, Is.EqualTo(expectedMessage));
}
#endregion
#region AllItemsAreUnique
[Test]
public void Unique_WithObjects()
{
CollectionAssert.AllItemsAreUnique(
new SimpleObjectCollection(new object(), new object(), new object()));
}
[Test]
public void Unique_WithStrings()
{
CollectionAssert.AllItemsAreUnique(new SimpleObjectCollection("x", "y", "z"));
}
[Test]
public void Unique_WithNull()
{
CollectionAssert.AllItemsAreUnique(new SimpleObjectCollection("x", "y", null, "z"));
}
[Test]
public void UniqueFailure()
{
var expectedMessage =
" Expected: all items unique" + Environment.NewLine +
" But was: < \"x\", \"y\", \"x\" >" + Environment.NewLine;
var ex = Assert.Throws<AssertionException>(() => CollectionAssert.AllItemsAreUnique(new SimpleObjectCollection("x", "y", "x")));
Assert.That(ex.Message, Is.EqualTo(expectedMessage));
}
[Test]
public void UniqueFailure_WithTwoNulls()
{
Assert.Throws<AssertionException>(
() => CollectionAssert.AllItemsAreUnique(new SimpleObjectCollection("x", null, "y", null, "z")));
}
[Test]
public void UniqueFailure_ElementTypeIsObject_NUnitEqualityIsUsed()
{
var collection = new List<object> { 42, null, 42f };
Assert.Throws<AssertionException>(() => CollectionAssert.AllItemsAreUnique(collection));
}
[Test]
public void UniqueFailure_ElementTypeIsInterface_NUnitEqualityIsUsed()
{
var collection = new List<IConvertible> { 42, null, 42f };
Assert.Throws<AssertionException>(() => CollectionAssert.AllItemsAreUnique(collection));
}
[Test]
public void UniqueFailure_ElementTypeIsStruct_ImplicitCastAndNewAlgorithmIsUsed()
{
var collection = new List<float> { 42, 42f };
Assert.Throws<AssertionException>(() => CollectionAssert.AllItemsAreUnique(collection));
}
[Test]
public void UniqueFailure_ElementTypeIsNotSealed_NUnitEqualityIsUsed()
{
var collection = new List<ValueType> { 42, 42f };
Assert.Throws<AssertionException>(() => CollectionAssert.AllItemsAreUnique(collection));
}
static readonly IEnumerable<int> RANGE = Enumerable.Range(0, 10000);
static readonly IEnumerable[] PerformanceData =
{
RANGE,
new List<int>(RANGE),
new List<double>(RANGE.Select(v => (double)v)),
new List<string>(RANGE.Select(v => v.ToString()))
};
[TestCaseSource(nameof(PerformanceData))]
public void PerformanceTests(IEnumerable values)
{
Warn.Unless(() => CollectionAssert.AllItemsAreUnique(values), HelperConstraints.HasMaxTime(100));
}
#endregion
#region AreEqual
[Test]
public void AreEqual()
{
var set1 = new SimpleEnumerable("x", "y", "z");
var set2 = new SimpleEnumerable("x", "y", "z");
CollectionAssert.AreEqual(set1,set2);
CollectionAssert.AreEqual(set1,set2,new TestComparer());
Assert.AreEqual(set1,set2);
}
[Test]
public void AreEqualFailCount()
{
var set1 = new SimpleObjectList("x", "y", "z");
var set2 = new SimpleObjectList("x", "y", "z", "a");
var expectedMessage =
" Expected is <NUnit.TestUtilities.Collections.SimpleObjectList> with 3 elements, actual is <NUnit.TestUtilities.Collections.SimpleObjectList> with 4 elements" + Environment.NewLine +
" Values differ at index [3]" + Environment.NewLine +
" Extra: < \"a\" >";
var ex = Assert.Throws<AssertionException>(() => CollectionAssert.AreEqual(set1, set2, new TestComparer()));
Assert.That(ex.Message, Is.EqualTo(expectedMessage));
}
[Test]
public void AreEqualFail()
{
var set1 = new SimpleObjectList("x", "y", "z");
var set2 = new SimpleObjectList("x", "y", "a");
var expectedMessage =
" Expected and actual are both <NUnit.TestUtilities.Collections.SimpleObjectList> with 3 elements" + Environment.NewLine +
" Values differ at index [2]" + Environment.NewLine +
" String lengths are both 1. Strings differ at index 0." + Environment.NewLine +
" Expected: \"z\"" + Environment.NewLine +
" But was: \"a\"" + Environment.NewLine +
" -----------^" + Environment.NewLine;
var ex = Assert.Throws<AssertionException>(() => CollectionAssert.AreEqual(set1,set2,new TestComparer()));
Assert.That(ex.Message, Is.EqualTo(expectedMessage));
}
[Test]
public void AreEqual_HandlesNull()
{
object[] set1 = new object[3];
object[] set2 = new object[3];
CollectionAssert.AreEqual(set1,set2);
CollectionAssert.AreEqual(set1,set2,new TestComparer());
}
[Test]
public void EnsureComparerIsUsed()
{
// Create two collections
int[] array1 = new int[2];
int[] array2 = new int[2];
array1[0] = 4;
array1[1] = 5;
array2[0] = 99;
array2[1] = -99;
CollectionAssert.AreEqual(array1, array2, new AlwaysEqualComparer());
}
[Test]
public void AreEqual_UsingIterator()
{
int[] array = new int[] { 1, 2, 3 };
CollectionAssert.AreEqual(array, CountToThree());
}
[Test]
public void AreEqualFails_ObjsUsingIEquatable()
{
IEnumerable set1 = new SimpleEnumerableWithIEquatable("x", "y", "z");
IEnumerable set2 = new SimpleEnumerableWithIEquatable("x", "z", "z");
CollectionAssert.AreNotEqual(set1, set2);
Assert.Throws<AssertionException>(() => CollectionAssert.AreEqual(set1, set2));
}
[Test]
public void IEnumerablesAreEqualWithCollectionsObjectsImplemetingIEquatable()
{
IEnumerable set1 = new SimpleEnumerable(new SimpleIEquatableObj());
IEnumerable set2 = new SimpleEnumerable(new SimpleIEquatableObj());
CollectionAssert.AreEqual(set1, set2);
}
[Test]
public void ArraysAreEqualWithCollectionsObjectsImplementingIEquatable()
{
SimpleIEquatableObj[] set1 = new SimpleIEquatableObj[] { new SimpleIEquatableObj() };
SimpleIEquatableObj[] set2 = new SimpleIEquatableObj[] { new SimpleIEquatableObj() };
CollectionAssert.AreEqual(set1, set2);
}
IEnumerable CountToThree()
{
yield return 1;
yield return 2;
yield return 3;
}
[Test]
public void AreEqual_UsingIterator_Fails()
{
int[] array = new int[] { 1, 3, 5 };
AssertionException ex = Assert.Throws<AssertionException>(
delegate { CollectionAssert.AreEqual(array, CountToThree()); } );
Assert.That(ex.Message, Does.Contain("Values differ at index [1]").And.
Contains("Expected: 3").And.
Contains("But was: 2"));
}
[Test]
public void AreEqual_UsingLinqQuery()
{
int[] array = new int[] { 1, 2, 3 };
CollectionAssert.AreEqual(array, array.Select((item) => item));
}
[Test]
public void AreEqual_UsingLinqQuery_Fails()
{
int[] array = new int[] { 1, 2, 3 };
AssertionException ex = Assert.Throws<AssertionException>(
delegate { CollectionAssert.AreEqual(array, array.Select((item) => item * 2)); } );
Assert.That(ex.Message, Does.Contain("Values differ at index [0]").And.
Contains("Expected: 1").And.
Contains("But was: 2"));
}
[Test]
public void AreEqual_IEquatableImplementationIsIgnored()
{
var x = new Constraints.EquatableWithEnumerableObject<int>(new[] { 1, 2, 3, 4, 5 }, 42);
var y = new Constraints.EnumerableObject<int>(new[] { 1, 2, 3, 4, 5 }, 15);
// They are not equal using Assert
Assert.AreNotEqual(x, y, "Assert 1");
Assert.AreNotEqual(y, x, "Assert 2");
// Using CollectionAssert they are equal
CollectionAssert.AreEqual(x, y, "CollectionAssert 1");
CollectionAssert.AreEqual(y, x, "CollectionAssert 2");
}
#endregion
#region AreEquivalent
[Test]
public void Equivalent()
{
ICollection set1 = new SimpleObjectCollection("x", "y", "z");
ICollection set2 = new SimpleObjectCollection("z", "y", "x");
CollectionAssert.AreEquivalent(set1,set2);
}
[Test]
public void EquivalentFailOne()
{
ICollection set1 = new SimpleObjectCollection("x", "y", "z");
ICollection set2 = new SimpleObjectCollection("x", "y", "x");
var expectedMessage =
" Expected: equivalent to < \"x\", \"y\", \"z\" >" + Environment.NewLine +
" But was: < \"x\", \"y\", \"x\" >" + Environment.NewLine +
" Missing (1): < \"z\" >" + Environment.NewLine +
" Extra (1): < \"x\" >" + Environment.NewLine;
var ex = Assert.Throws<AssertionException>(() => CollectionAssert.AreEquivalent(set1,set2));
Assert.That(ex.Message, Is.EqualTo(expectedMessage));
}
[Test]
public void EquivalentFailTwo()
{
ICollection set1 = new SimpleObjectCollection("x", "y", "x");
ICollection set2 = new SimpleObjectCollection("x", "y", "z");
var expectedMessage =
" Expected: equivalent to < \"x\", \"y\", \"x\" >" + Environment.NewLine +
" But was: < \"x\", \"y\", \"z\" >" + Environment.NewLine +
" Missing (1): < \"x\" >" + Environment.NewLine +
" Extra (1): < \"z\" >" + Environment.NewLine;
var ex = Assert.Throws<AssertionException>(() => CollectionAssert.AreEquivalent(set1,set2));
Assert.That(ex.Message, Is.EqualTo(expectedMessage));
}
[Test]
public void AreEquivalentHandlesNull()
{
ICollection set1 = new SimpleObjectCollection(null, "x", null, "z");
ICollection set2 = new SimpleObjectCollection("z", null, "x", null);
CollectionAssert.AreEquivalent(set1,set2);
}
#endregion
#region AreNotEqual
[Test]
public void AreNotEqual()
{
var set1 = new SimpleObjectCollection("x", "y", "z");
var set2 = new SimpleObjectCollection("x", "y", "x");
CollectionAssert.AreNotEqual(set1,set2);
CollectionAssert.AreNotEqual(set1,set2,new TestComparer());
CollectionAssert.AreNotEqual(set1,set2,"test");
CollectionAssert.AreNotEqual(set1,set2,new TestComparer(),"test");
CollectionAssert.AreNotEqual(set1,set2,"test {0}","1");
CollectionAssert.AreNotEqual(set1,set2,new TestComparer(),"test {0}","1");
}
[Test]
public void AreNotEqual_Fails()
{
var set1 = new SimpleObjectCollection("x", "y", "z");
var set2 = new SimpleObjectCollection("x", "y", "z");
var expectedMessage =
" Expected: not equal to < \"x\", \"y\", \"z\" >" + Environment.NewLine +
" But was: < \"x\", \"y\", \"z\" >" + Environment.NewLine;
var ex = Assert.Throws<AssertionException>(() => CollectionAssert.AreNotEqual(set1, set2));
Assert.That(ex.Message, Is.EqualTo(expectedMessage));
}
[Test]
public void AreNotEqual_HandlesNull()
{
object[] set1 = new object[3];
var set2 = new SimpleObjectCollection("x", "y", "z");
CollectionAssert.AreNotEqual(set1,set2);
CollectionAssert.AreNotEqual(set1,set2,new TestComparer());
}
[Test]
public void AreNotEqual_IEquatableImplementationIsIgnored()
{
var x = new Constraints.EquatableWithEnumerableObject<int>(new[] { 1, 2, 3, 4, 5 }, 42);
var y = new Constraints.EnumerableObject<int>(new[] { 5, 4, 3, 2, 1 }, 42);
// Equal using Assert
Assert.AreEqual(x, y, "Assert 1");
Assert.AreEqual(y, x, "Assert 2");
// Not equal using CollectionAssert
CollectionAssert.AreNotEqual(x, y, "CollectionAssert 1");
CollectionAssert.AreNotEqual(y, x, "CollectionAssert 2");
}
#endregion
#region AreNotEquivalent
[Test]
public void NotEquivalent()
{
var set1 = new SimpleObjectCollection("x", "y", "z");
var set2 = new SimpleObjectCollection("x", "y", "x");
CollectionAssert.AreNotEquivalent(set1,set2);
}
[Test]
public void NotEquivalent_Fails()
{
var set1 = new SimpleObjectCollection("x", "y", "z");
var set2 = new SimpleObjectCollection("x", "z", "y");
var expectedMessage =
" Expected: not equivalent to < \"x\", \"y\", \"z\" >" + Environment.NewLine +
" But was: < \"x\", \"z\", \"y\" >" + Environment.NewLine;
var ex = Assert.Throws<AssertionException>(() => CollectionAssert.AreNotEquivalent(set1,set2));
Assert.That(ex.Message, Is.EqualTo(expectedMessage));
}
[Test]
public void NotEquivalentHandlesNull()
{
var set1 = new SimpleObjectCollection("x", null, "z");
var set2 = new SimpleObjectCollection("x", null, "x");
CollectionAssert.AreNotEquivalent(set1,set2);
}
#endregion
#region Contains
[Test]
public void Contains_IList()
{
var list = new SimpleObjectList("x", "y", "z");
CollectionAssert.Contains(list, "x");
}
[Test]
public void Contains_ICollection()
{
var collection = new SimpleObjectCollection("x", "y", "z");
CollectionAssert.Contains(collection,"x");
}
[Test]
public void ContainsFails_ILIst()
{
var list = new SimpleObjectList("x", "y", "z");
var expectedMessage =
" Expected: some item equal to \"a\"" + Environment.NewLine +
" But was: < \"x\", \"y\", \"z\" >" + Environment.NewLine;
var ex = Assert.Throws<AssertionException>(() => CollectionAssert.Contains(list,"a"));
Assert.That(ex.Message, Is.EqualTo(expectedMessage));
}
[Test]
public void ContainsFails_ICollection()
{
var collection = new SimpleObjectCollection("x", "y", "z");
var expectedMessage =
" Expected: some item equal to \"a\"" + Environment.NewLine +
" But was: < \"x\", \"y\", \"z\" >" + Environment.NewLine;
var ex = Assert.Throws<AssertionException>(() => CollectionAssert.Contains(collection,"a"));
Assert.That(ex.Message, Is.EqualTo(expectedMessage));
}
[Test]
public void ContainsFails_EmptyIList()
{
var list = new SimpleObjectList();
var expectedMessage =
" Expected: some item equal to \"x\"" + Environment.NewLine +
" But was: <empty>" + Environment.NewLine;
var ex = Assert.Throws<AssertionException>(() => CollectionAssert.Contains(list,"x"));
Assert.That(ex.Message, Is.EqualTo(expectedMessage));
}
[Test]
public void ContainsFails_EmptyICollection()
{
var ca = new SimpleObjectCollection(new object[0]);
var expectedMessage =
" Expected: some item equal to \"x\"" + Environment.NewLine +
" But was: <empty>" + Environment.NewLine;
var ex = Assert.Throws<AssertionException>(() => CollectionAssert.Contains(ca,"x"));
Assert.That(ex.Message, Is.EqualTo(expectedMessage));
}
[Test]
public void ContainsNull_IList()
{
Object[] oa = new object[] { 1, 2, 3, null, 4, 5 };
CollectionAssert.Contains( oa, null );
}
[Test]
public void ContainsNull_ICollection()
{
var ca = new SimpleObjectCollection(new object[] { 1, 2, 3, null, 4, 5 });
CollectionAssert.Contains( ca, null );
}
#endregion
#region DoesNotContain
[Test]
public void DoesNotContain()
{
var list = new SimpleObjectList();
CollectionAssert.DoesNotContain(list,"a");
}
[Test]
public void DoesNotContain_Empty()
{
var list = new SimpleObjectList();
CollectionAssert.DoesNotContain(list,"x");
}
[Test]
public void DoesNotContain_Fails()
{
var list = new SimpleObjectList("x", "y", "z");
var expectedMessage =
" Expected: not some item equal to \"y\"" + Environment.NewLine +
" But was: < \"x\", \"y\", \"z\" >" + Environment.NewLine;
var ex = Assert.Throws<AssertionException>(() => CollectionAssert.DoesNotContain(list,"y"));
Assert.That(ex.Message, Is.EqualTo(expectedMessage));
}
#endregion
#region IsSubsetOf
[Test]
public void IsSubsetOf()
{
var set1 = new SimpleObjectList("x", "y", "z");
var set2 = new SimpleObjectList("y", "z");
CollectionAssert.IsSubsetOf(set2,set1);
Assert.That(set2, Is.SubsetOf(set1));
}
[Test]
public void IsSubsetOf_Fails()
{
var set1 = new SimpleObjectList("x", "y", "z");
var set2 = new SimpleObjectList("y", "z", "a");
var expectedMessage =
" Expected: subset of < \"y\", \"z\", \"a\" >" + Environment.NewLine +
" But was: < \"x\", \"y\", \"z\" >" + Environment.NewLine;
var ex = Assert.Throws<AssertionException>(() => CollectionAssert.IsSubsetOf(set1,set2));
Assert.That(ex.Message, Is.EqualTo(expectedMessage));
}
[Test]
public void IsSubsetOfHandlesNull()
{
var set1 = new SimpleObjectList("x", null, "z");
var set2 = new SimpleObjectList(null, "z");
CollectionAssert.IsSubsetOf(set2,set1);
Assert.That(set2, Is.SubsetOf(set1));
}
#endregion
#region IsNotSubsetOf
[Test]
public void IsNotSubsetOf()
{
var set1 = new SimpleObjectList("x", "y", "z");
var set2 = new SimpleObjectList("y", "z", "a");
CollectionAssert.IsNotSubsetOf(set1,set2);
Assert.That(set1, Is.Not.SubsetOf(set2));
}
[Test]
public void IsNotSubsetOf_Fails()
{
var set1 = new SimpleObjectList("x", "y", "z");
var set2 = new SimpleObjectList("y", "z");
var expectedMessage =
" Expected: not subset of < \"x\", \"y\", \"z\" >" + Environment.NewLine +
" But was: < \"y\", \"z\" >" + Environment.NewLine;
var ex = Assert.Throws<AssertionException>(() => CollectionAssert.IsNotSubsetOf(set2,set1));
Assert.That(ex.Message, Is.EqualTo(expectedMessage));
}
[Test]
public void IsNotSubsetOfHandlesNull()
{
var set1 = new SimpleObjectList("x", null, "z");
var set2 = new SimpleObjectList(null, "z", "a");
CollectionAssert.IsNotSubsetOf(set1,set2);
}
#endregion
#region IsOrdered
[Test]
public void IsOrdered()
{
var list = new SimpleObjectList("x", "y", "z");
CollectionAssert.IsOrdered(list);
}
[Test]
public void IsOrdered_Fails()
{
var list = new SimpleObjectList("x", "z", "y");
var expectedMessage =
" Expected: collection ordered" + Environment.NewLine +
" But was: < \"x\", \"z\", \"y\" >" + Environment.NewLine +
" Ordering breaks at index [2]: \"y\"" + Environment.NewLine;
var ex = Assert.Throws<AssertionException>(() => CollectionAssert.IsOrdered(list));
Assert.That(ex.Message, Is.EqualTo(expectedMessage));
}
[Test]
public void IsOrdered_Allows_adjacent_equal_values()
{
var list = new SimpleObjectList("x", "x", "z");
CollectionAssert.IsOrdered(list);
}
[Test]
public void IsOrdered_Handles_null()
{
var list = new SimpleObjectList(null, "x", "z");
Assert.That(list, Is.Ordered);
}
[Test]
public void IsOrdered_ContainedTypesMustBeCompatible()
{
var list = new SimpleObjectList(1, "x");
Assert.Throws<ArgumentException>(() => CollectionAssert.IsOrdered(list));
}
[Test]
public void IsOrdered_TypesMustImplementIComparable()
{
var list = new SimpleObjectList(new object(), new object());
Assert.Throws<ArgumentException>(() => CollectionAssert.IsOrdered(list));
}
[Test]
public void IsOrdered_Handles_custom_comparison()
{
var list = new SimpleObjectList(new object(), new object());
CollectionAssert.IsOrdered(list, new AlwaysEqualComparer());
}
[Test]
public void IsOrdered_Handles_custom_comparison2()
{
var list = new SimpleObjectList(2, 1);
CollectionAssert.IsOrdered(list, new TestComparer());
}
#endregion
#region Equals
[Test]
public void EqualsFailsWhenUsed()
{
var ex = Assert.Throws<InvalidOperationException>(() => CollectionAssert.Equals(string.Empty, string.Empty));
Assert.That(ex.Message, Does.StartWith("CollectionAssert.Equals should not be used for Assertions"));
}
[Test]
public void ReferenceEqualsFailsWhenUsed()
{
var ex = Assert.Throws<InvalidOperationException>(() => CollectionAssert.ReferenceEquals(string.Empty, string.Empty));
Assert.That(ex.Message, Does.StartWith("CollectionAssert.ReferenceEquals should not be used for Assertions"));
}
#endregion
#if NET45
#region ValueTuple
[Test]
public void ValueTupleAreEqual()
{
var set1 = new SimpleEnumerable(ValueTuple.Create(1,2,3), ValueTuple.Create(1, 2, 3), ValueTuple.Create(1, 2, 3));
var set2 = new SimpleEnumerable(ValueTuple.Create(1,2,3), ValueTuple.Create(1, 2, 3), ValueTuple.Create(1, 2, 3));
CollectionAssert.AreEqual(set1, set2);
CollectionAssert.AreEqual(set1, set2, new TestComparer());
Assert.AreEqual(set1, set2);
}
[Test]
public void ValueTupleAreEqualFail()
{
var set1 = new SimpleEnumerable(ValueTuple.Create(1, 2, 3), ValueTuple.Create(1, 2, 3), ValueTuple.Create(1, 2, 3));
var set2 = new SimpleEnumerable(ValueTuple.Create(1, 2, 3), ValueTuple.Create(1, 2, 3), ValueTuple.Create(1, 2, 4));
var expectedMessage =
" Expected and actual are both <NUnit.TestUtilities.Collections.SimpleEnumerable>" + Environment.NewLine +
" Values differ at index [2]" + Environment.NewLine +
" Expected: (1, 2, 3)" + Environment.NewLine +
" But was: (1, 2, 4)" + Environment.NewLine;
var ex = Assert.Throws<AssertionException>(() => CollectionAssert.AreEqual(set1, set2, new TestComparer()));
Assert.That(ex.Message, Is.EqualTo(expectedMessage));
}
#endregion
#endif
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Tests.TestObjects;
using Newtonsoft.Json.Utilities;
#if !NETFX_CORE
using NUnit.Framework;
#else
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute;
#endif
using Newtonsoft.Json.Schema;
using System.IO;
using Newtonsoft.Json.Linq;
using System.Text;
using Extensions = Newtonsoft.Json.Schema.Extensions;
#if NET20
using Newtonsoft.Json.Utilities.LinqBridge;
#else
using System.Linq;
#endif
namespace Newtonsoft.Json.Tests.Schema
{
[TestFixture]
public class JsonSchemaGeneratorTests : TestFixtureBase
{
[Test]
public void Generate_GenericDictionary()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
JsonSchema schema = generator.Generate(typeof(Dictionary<string, List<string>>));
string json = schema.ToString();
StringAssert.AreEqual(@"{
""type"": ""object"",
""additionalProperties"": {
""type"": [
""array"",
""null""
],
""items"": {
""type"": [
""string"",
""null""
]
}
}
}", json);
Dictionary<string, List<string>> value = new Dictionary<string, List<string>>
{
{ "HasValue", new List<string>() { "first", "second", null } },
{ "NoValue", null }
};
string valueJson = JsonConvert.SerializeObject(value, Formatting.Indented);
JObject o = JObject.Parse(valueJson);
Assert.IsTrue(o.IsValid(schema));
}
#if !(NETFX_CORE || PORTABLE || PORTABLE40)
[Test]
public void Generate_DefaultValueAttributeTestClass()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
JsonSchema schema = generator.Generate(typeof(DefaultValueAttributeTestClass));
string json = schema.ToString();
StringAssert.AreEqual(@"{
""description"": ""DefaultValueAttributeTestClass description!"",
""type"": ""object"",
""additionalProperties"": false,
""properties"": {
""TestField1"": {
""required"": true,
""type"": ""integer"",
""default"": 21
},
""TestProperty1"": {
""required"": true,
""type"": [
""string"",
""null""
],
""default"": ""TestProperty1Value""
}
}
}", json);
}
#endif
[Test]
public void Generate_Person()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
JsonSchema schema = generator.Generate(typeof(Person));
string json = schema.ToString();
StringAssert.AreEqual(@"{
""id"": ""Person"",
""title"": ""Title!"",
""description"": ""JsonObjectAttribute description!"",
""type"": ""object"",
""properties"": {
""Name"": {
""required"": true,
""type"": [
""string"",
""null""
]
},
""BirthDate"": {
""required"": true,
""type"": ""string""
},
""LastModified"": {
""required"": true,
""type"": ""string""
}
}
}", json);
}
[Test]
public void Generate_UserNullable()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
JsonSchema schema = generator.Generate(typeof(UserNullable));
string json = schema.ToString();
StringAssert.AreEqual(@"{
""type"": ""object"",
""properties"": {
""Id"": {
""required"": true,
""type"": ""string""
},
""FName"": {
""required"": true,
""type"": [
""string"",
""null""
]
},
""LName"": {
""required"": true,
""type"": [
""string"",
""null""
]
},
""RoleId"": {
""required"": true,
""type"": ""integer""
},
""NullableRoleId"": {
""required"": true,
""type"": [
""integer"",
""null""
]
},
""NullRoleId"": {
""required"": true,
""type"": [
""integer"",
""null""
]
},
""Active"": {
""required"": true,
""type"": [
""boolean"",
""null""
]
}
}
}", json);
}
[Test]
public void Generate_RequiredMembersClass()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
JsonSchema schema = generator.Generate(typeof(RequiredMembersClass));
Assert.AreEqual(JsonSchemaType.String, schema.Properties["FirstName"].Type);
Assert.AreEqual(JsonSchemaType.String | JsonSchemaType.Null, schema.Properties["MiddleName"].Type);
Assert.AreEqual(JsonSchemaType.String | JsonSchemaType.Null, schema.Properties["LastName"].Type);
Assert.AreEqual(JsonSchemaType.String, schema.Properties["BirthDate"].Type);
}
[Test]
public void Generate_Store()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
JsonSchema schema = generator.Generate(typeof(Store));
Assert.AreEqual(11, schema.Properties.Count);
JsonSchema productArraySchema = schema.Properties["product"];
JsonSchema productSchema = productArraySchema.Items[0];
Assert.AreEqual(4, productSchema.Properties.Count);
}
[Test]
public void MissingSchemaIdHandlingTest()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
JsonSchema schema = generator.Generate(typeof(Store));
Assert.AreEqual(null, schema.Id);
generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName;
schema = generator.Generate(typeof(Store));
Assert.AreEqual(typeof(Store).FullName, schema.Id);
generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseAssemblyQualifiedName;
schema = generator.Generate(typeof(Store));
Assert.AreEqual(typeof(Store).AssemblyQualifiedName, schema.Id);
}
[Test]
public void CircularReferenceError()
{
ExceptionAssert.Throws<Exception>(() =>
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
generator.Generate(typeof(CircularReferenceClass));
}, @"Unresolved circular reference for type 'Newtonsoft.Json.Tests.TestObjects.CircularReferenceClass'. Explicitly define an Id for the type using a JsonObject/JsonArray attribute or automatically generate a type Id using the UndefinedSchemaIdHandling property.");
}
[Test]
public void CircularReferenceWithTypeNameId()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName;
JsonSchema schema = generator.Generate(typeof(CircularReferenceClass), true);
Assert.AreEqual(JsonSchemaType.String, schema.Properties["Name"].Type);
Assert.AreEqual(typeof(CircularReferenceClass).FullName, schema.Id);
Assert.AreEqual(JsonSchemaType.Object | JsonSchemaType.Null, schema.Properties["Child"].Type);
Assert.AreEqual(schema, schema.Properties["Child"]);
}
[Test]
public void CircularReferenceWithExplicitId()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
JsonSchema schema = generator.Generate(typeof(CircularReferenceWithIdClass));
Assert.AreEqual(JsonSchemaType.String | JsonSchemaType.Null, schema.Properties["Name"].Type);
Assert.AreEqual("MyExplicitId", schema.Id);
Assert.AreEqual(JsonSchemaType.Object | JsonSchemaType.Null, schema.Properties["Child"].Type);
Assert.AreEqual(schema, schema.Properties["Child"]);
}
[Test]
public void GenerateSchemaForType()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName;
JsonSchema schema = generator.Generate(typeof(Type));
Assert.AreEqual(JsonSchemaType.String, schema.Type);
string json = JsonConvert.SerializeObject(typeof(Version), Formatting.Indented);
JValue v = new JValue(json);
Assert.IsTrue(v.IsValid(schema));
}
#if !(NETFX_CORE || PORTABLE || PORTABLE40)
[Test]
public void GenerateSchemaForISerializable()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName;
JsonSchema schema = generator.Generate(typeof(Exception));
Assert.AreEqual(JsonSchemaType.Object, schema.Type);
Assert.AreEqual(true, schema.AllowAdditionalProperties);
Assert.AreEqual(null, schema.Properties);
}
#endif
#if !(NETFX_CORE || PORTABLE || PORTABLE40)
[Test]
public void GenerateSchemaForDBNull()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName;
JsonSchema schema = generator.Generate(typeof(DBNull));
Assert.AreEqual(JsonSchemaType.Null, schema.Type);
}
public class CustomDirectoryInfoMapper : DefaultContractResolver
{
public CustomDirectoryInfoMapper()
: base(true)
{
}
protected override JsonContract CreateContract(Type objectType)
{
if (objectType == typeof(DirectoryInfo))
return base.CreateObjectContract(objectType);
return base.CreateContract(objectType);
}
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);
JsonPropertyCollection c = new JsonPropertyCollection(type);
c.AddRange(properties.Where(m => m.PropertyName != "Root"));
return c;
}
}
[Test]
public void GenerateSchemaForDirectoryInfo()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName;
generator.ContractResolver = new CustomDirectoryInfoMapper
{
#if !(NETFX_CORE || PORTABLE)
IgnoreSerializableAttribute = true
#endif
};
JsonSchema schema = generator.Generate(typeof(DirectoryInfo), true);
string json = schema.ToString();
StringAssert.AreEqual(@"{
""id"": ""System.IO.DirectoryInfo"",
""required"": true,
""type"": [
""object"",
""null""
],
""additionalProperties"": false,
""properties"": {
""Name"": {
""required"": true,
""type"": [
""string"",
""null""
]
},
""Parent"": {
""$ref"": ""System.IO.DirectoryInfo""
},
""Exists"": {
""required"": true,
""type"": ""boolean""
},
""FullName"": {
""required"": true,
""type"": [
""string"",
""null""
]
},
""Extension"": {
""required"": true,
""type"": [
""string"",
""null""
]
},
""CreationTime"": {
""required"": true,
""type"": ""string""
},
""CreationTimeUtc"": {
""required"": true,
""type"": ""string""
},
""LastAccessTime"": {
""required"": true,
""type"": ""string""
},
""LastAccessTimeUtc"": {
""required"": true,
""type"": ""string""
},
""LastWriteTime"": {
""required"": true,
""type"": ""string""
},
""LastWriteTimeUtc"": {
""required"": true,
""type"": ""string""
},
""Attributes"": {
""required"": true,
""type"": ""integer""
}
}
}", json);
DirectoryInfo temp = new DirectoryInfo(@"c:\temp");
JTokenWriter jsonWriter = new JTokenWriter();
JsonSerializer serializer = new JsonSerializer();
serializer.Converters.Add(new IsoDateTimeConverter());
serializer.ContractResolver = new CustomDirectoryInfoMapper
{
#if !(NETFX_CORE || PORTABLE)
IgnoreSerializableInterface = true
#endif
};
serializer.Serialize(jsonWriter, temp);
List<string> errors = new List<string>();
jsonWriter.Token.Validate(schema, (sender, args) => errors.Add(args.Message));
Assert.AreEqual(0, errors.Count);
}
#endif
[Test]
public void GenerateSchemaCamelCase()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName;
generator.ContractResolver = new CamelCasePropertyNamesContractResolver()
{
#if !(NETFX_CORE || PORTABLE || PORTABLE40)
IgnoreSerializableAttribute = true
#endif
};
JsonSchema schema = generator.Generate(typeof(Version), true);
string json = schema.ToString();
StringAssert.AreEqual(@"{
""id"": ""System.Version"",
""type"": [
""object"",
""null""
],
""additionalProperties"": false,
""properties"": {
""major"": {
""required"": true,
""type"": ""integer""
},
""minor"": {
""required"": true,
""type"": ""integer""
},
""build"": {
""required"": true,
""type"": ""integer""
},
""revision"": {
""required"": true,
""type"": ""integer""
},
""majorRevision"": {
""required"": true,
""type"": ""integer""
},
""minorRevision"": {
""required"": true,
""type"": ""integer""
}
}
}", json);
}
#if !(NETFX_CORE || PORTABLE || PORTABLE40)
[Test]
public void GenerateSchemaSerializable()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
generator.ContractResolver = new DefaultContractResolver
{
IgnoreSerializableAttribute = false
};
generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName;
JsonSchema schema = generator.Generate(typeof(Version), true);
string json = schema.ToString();
StringAssert.AreEqual(@"{
""id"": ""System.Version"",
""type"": [
""object"",
""null""
],
""additionalProperties"": false,
""properties"": {
""_Major"": {
""required"": true,
""type"": ""integer""
},
""_Minor"": {
""required"": true,
""type"": ""integer""
},
""_Build"": {
""required"": true,
""type"": ""integer""
},
""_Revision"": {
""required"": true,
""type"": ""integer""
}
}
}", json);
JTokenWriter jsonWriter = new JTokenWriter();
JsonSerializer serializer = new JsonSerializer();
serializer.ContractResolver = new DefaultContractResolver
{
IgnoreSerializableAttribute = false
};
serializer.Serialize(jsonWriter, new Version(1, 2, 3, 4));
List<string> errors = new List<string>();
jsonWriter.Token.Validate(schema, (sender, args) => errors.Add(args.Message));
Assert.AreEqual(0, errors.Count);
StringAssert.AreEqual(@"{
""_Major"": 1,
""_Minor"": 2,
""_Build"": 3,
""_Revision"": 4
}", jsonWriter.Token.ToString());
Version version = jsonWriter.Token.ToObject<Version>(serializer);
Assert.AreEqual(1, version.Major);
Assert.AreEqual(2, version.Minor);
Assert.AreEqual(3, version.Build);
Assert.AreEqual(4, version.Revision);
}
#endif
public enum SortTypeFlag
{
No = 0,
Asc = 1,
Desc = -1
}
public class X
{
public SortTypeFlag x;
}
[Test]
public void GenerateSchemaWithNegativeEnum()
{
JsonSchemaGenerator jsonSchemaGenerator = new JsonSchemaGenerator();
JsonSchema schema = jsonSchemaGenerator.Generate(typeof(X));
string json = schema.ToString();
StringAssert.AreEqual(@"{
""type"": ""object"",
""properties"": {
""x"": {
""required"": true,
""type"": ""integer"",
""enum"": [
0,
1,
-1
]
}
}
}", json);
}
[Test]
public void CircularCollectionReferences()
{
Type type = typeof(Workspace);
JsonSchemaGenerator jsonSchemaGenerator = new JsonSchemaGenerator();
jsonSchemaGenerator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName;
JsonSchema jsonSchema = jsonSchemaGenerator.Generate(type);
// should succeed
Assert.IsNotNull(jsonSchema);
}
[Test]
public void CircularReferenceWithMixedRequires()
{
JsonSchemaGenerator jsonSchemaGenerator = new JsonSchemaGenerator();
jsonSchemaGenerator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName;
JsonSchema jsonSchema = jsonSchemaGenerator.Generate(typeof(CircularReferenceClass));
string json = jsonSchema.ToString();
StringAssert.AreEqual(@"{
""id"": ""Newtonsoft.Json.Tests.TestObjects.CircularReferenceClass"",
""type"": [
""object"",
""null""
],
""properties"": {
""Name"": {
""required"": true,
""type"": ""string""
},
""Child"": {
""$ref"": ""Newtonsoft.Json.Tests.TestObjects.CircularReferenceClass""
}
}
}", json);
}
[Test]
public void JsonPropertyWithHandlingValues()
{
JsonSchemaGenerator jsonSchemaGenerator = new JsonSchemaGenerator();
jsonSchemaGenerator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName;
JsonSchema jsonSchema = jsonSchemaGenerator.Generate(typeof(JsonPropertyWithHandlingValues));
string json = jsonSchema.ToString();
StringAssert.AreEqual(@"{
""id"": ""Newtonsoft.Json.Tests.TestObjects.JsonPropertyWithHandlingValues"",
""required"": true,
""type"": [
""object"",
""null""
],
""properties"": {
""DefaultValueHandlingIgnoreProperty"": {
""type"": [
""string"",
""null""
],
""default"": ""Default!""
},
""DefaultValueHandlingIncludeProperty"": {
""required"": true,
""type"": [
""string"",
""null""
],
""default"": ""Default!""
},
""DefaultValueHandlingPopulateProperty"": {
""required"": true,
""type"": [
""string"",
""null""
],
""default"": ""Default!""
},
""DefaultValueHandlingIgnoreAndPopulateProperty"": {
""type"": [
""string"",
""null""
],
""default"": ""Default!""
},
""NullValueHandlingIgnoreProperty"": {
""type"": [
""string"",
""null""
]
},
""NullValueHandlingIncludeProperty"": {
""required"": true,
""type"": [
""string"",
""null""
]
},
""ReferenceLoopHandlingErrorProperty"": {
""$ref"": ""Newtonsoft.Json.Tests.TestObjects.JsonPropertyWithHandlingValues""
},
""ReferenceLoopHandlingIgnoreProperty"": {
""$ref"": ""Newtonsoft.Json.Tests.TestObjects.JsonPropertyWithHandlingValues""
},
""ReferenceLoopHandlingSerializeProperty"": {
""$ref"": ""Newtonsoft.Json.Tests.TestObjects.JsonPropertyWithHandlingValues""
}
}
}", json);
}
[Test]
public void GenerateForNullableInt32()
{
JsonSchemaGenerator jsonSchemaGenerator = new JsonSchemaGenerator();
JsonSchema jsonSchema = jsonSchemaGenerator.Generate(typeof(NullableInt32TestClass));
string json = jsonSchema.ToString();
StringAssert.AreEqual(@"{
""type"": ""object"",
""properties"": {
""Value"": {
""required"": true,
""type"": [
""integer"",
""null""
]
}
}
}", json);
}
[JsonConverter(typeof(StringEnumConverter))]
public enum SortTypeFlagAsString
{
No = 0,
Asc = 1,
Desc = -1
}
public class Y
{
public SortTypeFlagAsString y;
}
[Test]
[Ignore]
public void GenerateSchemaWithStringEnum()
{
JsonSchemaGenerator jsonSchemaGenerator = new JsonSchemaGenerator();
JsonSchema schema = jsonSchemaGenerator.Generate(typeof(Y));
string json = schema.ToString();
// NOTE: This fails because the enum is serialized as an integer and not a string.
// NOTE: There should exist a way to serialize the enum as lowercase strings.
Assert.AreEqual(@"{
""type"": ""object"",
""properties"": {
""y"": {
""required"": true,
""type"": ""string"",
""enum"": [
""no"",
""asc"",
""desc""
]
}
}
}", json);
}
}
public class NullableInt32TestClass
{
public int? Value { get; set; }
}
public class DMDSLBase
{
public String Comment;
}
public class Workspace : DMDSLBase
{
public ControlFlowItemCollection Jobs = new ControlFlowItemCollection();
}
public class ControlFlowItemBase : DMDSLBase
{
public String Name;
}
public class ControlFlowItem : ControlFlowItemBase //A Job
{
public TaskCollection Tasks = new TaskCollection();
public ContainerCollection Containers = new ContainerCollection();
}
public class ControlFlowItemCollection : List<ControlFlowItem>
{
}
public class Task : ControlFlowItemBase
{
public DataFlowTaskCollection DataFlowTasks = new DataFlowTaskCollection();
public BulkInsertTaskCollection BulkInsertTask = new BulkInsertTaskCollection();
}
public class TaskCollection : List<Task>
{
}
public class Container : ControlFlowItemBase
{
public ControlFlowItemCollection ContainerJobs = new ControlFlowItemCollection();
}
public class ContainerCollection : List<Container>
{
}
public class DataFlowTask_DSL : ControlFlowItemBase
{
}
public class DataFlowTaskCollection : List<DataFlowTask_DSL>
{
}
public class SequenceContainer_DSL : Container
{
}
public class BulkInsertTaskCollection : List<BulkInsertTask_DSL>
{
}
public class BulkInsertTask_DSL
{
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Reflection;
using Internal.Metadata.NativeFormat;
using System.Threading;
using Debug = System.Diagnostics.Debug;
using Internal.TypeSystem;
using Internal.NativeFormat;
namespace Internal.TypeSystem.NativeFormat
{
/// <summary>
/// Override of MetadataType that uses actual NativeFormat335 metadata.
/// </summary>
public sealed partial class NativeFormatType : MetadataType, NativeFormatMetadataUnit.IHandleObject
{
private static readonly LowLevelDictionary<string, TypeFlags> s_primitiveTypes = InitPrimitiveTypesDictionary();
private static LowLevelDictionary<string, TypeFlags> InitPrimitiveTypesDictionary()
{
LowLevelDictionary<string, TypeFlags> result = new LowLevelDictionary<string, TypeFlags>();
result.Add("Void", TypeFlags.Void);
result.Add("Boolean", TypeFlags.Boolean);
result.Add("Char", TypeFlags.Char);
result.Add("SByte", TypeFlags.SByte);
result.Add("Byte", TypeFlags.Byte);
result.Add("Int16", TypeFlags.Int16);
result.Add("UInt16", TypeFlags.UInt16);
result.Add("Int32", TypeFlags.Int32);
result.Add("UInt32", TypeFlags.UInt32);
result.Add("Int64", TypeFlags.Int64);
result.Add("UInt64", TypeFlags.UInt64);
result.Add("IntPtr", TypeFlags.IntPtr);
result.Add("UIntPtr", TypeFlags.UIntPtr);
result.Add("Single", TypeFlags.Single);
result.Add("Double", TypeFlags.Double);
return result;
}
private NativeFormatModule _module;
private NativeFormatMetadataUnit _metadataUnit;
private TypeDefinitionHandle _handle;
private TypeDefinition _typeDefinition;
// Cached values
private string _typeName;
private string _typeNamespace;
private TypeDesc[] _genericParameters;
private MetadataType _baseType;
private int _hashcode;
internal NativeFormatType(NativeFormatMetadataUnit metadataUnit, TypeDefinitionHandle handle)
{
_handle = handle;
_metadataUnit = metadataUnit;
_typeDefinition = metadataUnit.MetadataReader.GetTypeDefinition(handle);
_module = metadataUnit.GetModuleFromNamespaceDefinition(_typeDefinition.NamespaceDefinition);
_baseType = this; // Not yet initialized flag
#if DEBUG
// Initialize name eagerly in debug builds for convenience
this.ToString();
#endif
}
public override int GetHashCode()
{
if (_hashcode != 0)
{
return _hashcode;
}
int nameHash = TypeHashingAlgorithms.ComputeNameHashCode(this.GetFullName());
TypeDesc containingType = ContainingType;
if (containingType == null)
{
_hashcode = nameHash;
}
else
{
_hashcode = TypeHashingAlgorithms.ComputeNestedTypeHashCode(containingType.GetHashCode(), nameHash);
}
return _hashcode;
}
Handle NativeFormatMetadataUnit.IHandleObject.Handle
{
get
{
return _handle;
}
}
NativeFormatType NativeFormatMetadataUnit.IHandleObject.Container
{
get
{
return null;
}
}
// TODO: Use stable hashcode based on the type name?
// public override int GetHashCode()
// {
// }
public override TypeSystemContext Context
{
get
{
return _module.Context;
}
}
private void ComputeGenericParameters()
{
var genericParameterHandles = _typeDefinition.GenericParameters;
int count = genericParameterHandles.Count;
if (count > 0)
{
TypeDesc[] genericParameters = new TypeDesc[count];
int i = 0;
foreach (var genericParameterHandle in genericParameterHandles)
{
genericParameters[i++] = new NativeFormatGenericParameter(_metadataUnit, genericParameterHandle);
}
Interlocked.CompareExchange(ref _genericParameters, genericParameters, null);
}
else
{
_genericParameters = TypeDesc.EmptyTypes;
}
}
public override Instantiation Instantiation
{
get
{
if (_genericParameters == null)
ComputeGenericParameters();
return new Instantiation(_genericParameters);
}
}
public override ModuleDesc Module
{
get
{
return _module;
}
}
public NativeFormatModule NativeFormatModule
{
get
{
return _module;
}
}
public MetadataReader MetadataReader
{
get
{
return _metadataUnit.MetadataReader;
}
}
public NativeFormatMetadataUnit MetadataUnit
{
get
{
return _metadataUnit;
}
}
public TypeDefinitionHandle Handle
{
get
{
return _handle;
}
}
private MetadataType InitializeBaseType()
{
var baseTypeHandle = _typeDefinition.BaseType;
if (baseTypeHandle.IsNull(MetadataReader))
{
_baseType = null;
return null;
}
var type = _metadataUnit.GetType(baseTypeHandle) as MetadataType;
if (type == null)
{
throw new BadImageFormatException();
}
_baseType = type;
return type;
}
public override DefType BaseType
{
get
{
if (_baseType == this)
return InitializeBaseType();
return _baseType;
}
}
public override MetadataType MetadataBaseType
{
get
{
if (_baseType == this)
return InitializeBaseType();
return _baseType;
}
}
protected override TypeFlags ComputeTypeFlags(TypeFlags mask)
{
TypeFlags flags = 0;
if ((mask & TypeFlags.ContainsGenericVariablesComputed) != 0)
{
flags |= TypeFlags.ContainsGenericVariablesComputed;
// TODO: Do we really want to get the instantiation to figure out whether the type is generic?
if (this.HasInstantiation)
flags |= TypeFlags.ContainsGenericVariables;
}
if ((mask & TypeFlags.CategoryMask) != 0 && (flags & TypeFlags.CategoryMask) == 0)
{
TypeDesc baseType = this.BaseType;
if (baseType != null && baseType.IsWellKnownType(WellKnownType.ValueType) &&
!this.IsWellKnownType(WellKnownType.Enum))
{
TypeFlags categoryFlags;
if (!TryGetCategoryFlagsForPrimitiveType(out categoryFlags))
{
categoryFlags = TypeFlags.ValueType;
}
flags |= categoryFlags;
}
else
if (baseType != null && baseType.IsWellKnownType(WellKnownType.Enum))
{
flags |= TypeFlags.Enum;
}
else
{
if ((_typeDefinition.Flags & TypeAttributes.Interface) != 0)
flags |= TypeFlags.Interface;
else
flags |= TypeFlags.Class;
}
// All other cases are handled during TypeSystemContext intitialization
}
if ((mask & TypeFlags.HasGenericVarianceComputed) != 0 &&
(flags & TypeFlags.HasGenericVarianceComputed) == 0)
{
flags |= TypeFlags.HasGenericVarianceComputed;
foreach (GenericParameterDesc genericParam in Instantiation)
{
if (genericParam.Variance != GenericVariance.None)
{
flags |= TypeFlags.HasGenericVariance;
break;
}
}
}
return flags;
}
private bool TryGetCategoryFlagsForPrimitiveType(out TypeFlags categoryFlags)
{
categoryFlags = 0;
if (_module != _metadataUnit.Context.SystemModule)
{
// Primitive types reside in the system module
return false;
}
NamespaceDefinition namespaceDef = MetadataReader.GetNamespaceDefinition(_typeDefinition.NamespaceDefinition);
if (namespaceDef.ParentScopeOrNamespace.HandleType != HandleType.NamespaceDefinition)
{
// Primitive types are in the System namespace the parent of which is the root namespace
return false;
}
if (!namespaceDef.Name.StringEquals("System", MetadataReader))
{
// Namespace name must be 'System'
return false;
}
NamespaceDefinitionHandle parentNamespaceDefHandle =
namespaceDef.ParentScopeOrNamespace.ToNamespaceDefinitionHandle(MetadataReader);
NamespaceDefinition parentDef = MetadataReader.GetNamespaceDefinition(parentNamespaceDefHandle);
if (parentDef.ParentScopeOrNamespace.HandleType != HandleType.ScopeDefinition)
{
// The root parent namespace should have scope (assembly) handle as its parent
return false;
}
return s_primitiveTypes.TryGetValue(Name, out categoryFlags);
}
private string InitializeName()
{
var metadataReader = this.MetadataReader;
_typeName = metadataReader.GetString(_typeDefinition.Name);
return _typeName;
}
public override string Name
{
get
{
if (_typeName == null)
return InitializeName();
return _typeName;
}
}
private string InitializeNamespace()
{
if (ContainingType == null)
{
var metadataReader = this.MetadataReader;
_typeNamespace = metadataReader.GetNamespaceName(_typeDefinition.NamespaceDefinition);
return _typeNamespace;
}
else
{
_typeNamespace = "";
return _typeNamespace;
}
}
public override string Namespace
{
get
{
if (_typeNamespace == null)
return InitializeNamespace();
return _typeNamespace;
}
}
public override IEnumerable<MethodDesc> GetMethods()
{
foreach (var handle in _typeDefinition.Methods)
{
yield return (MethodDesc)_metadataUnit.GetMethod(handle, this);
}
}
public override MethodDesc GetMethod(string name, MethodSignature signature)
{
var metadataReader = this.MetadataReader;
foreach (var handle in _typeDefinition.Methods)
{
if (metadataReader.GetMethod(handle).Name.StringEquals(name, metadataReader))
{
MethodDesc method = (MethodDesc)_metadataUnit.GetMethod(handle, this);
if (signature == null || signature.Equals(method.Signature))
return method;
}
}
return null;
}
public override MethodDesc GetStaticConstructor()
{
var metadataReader = this.MetadataReader;
foreach (var handle in _typeDefinition.Methods)
{
var methodDefinition = metadataReader.GetMethod(handle);
if (methodDefinition.Flags.IsRuntimeSpecialName() &&
methodDefinition.Name.StringEquals(".cctor", metadataReader))
{
MethodDesc method = (MethodDesc)_metadataUnit.GetMethod(handle, this);
return method;
}
}
return null;
}
public override MethodDesc GetDefaultConstructor()
{
if (IsAbstract)
return null;
MetadataReader metadataReader = this.MetadataReader;
foreach (var handle in _typeDefinition.Methods)
{
var methodDefinition = metadataReader.GetMethod(handle);
MethodAttributes attributes = methodDefinition.Flags;
if (attributes.IsRuntimeSpecialName() && attributes.IsPublic() &&
methodDefinition.Name.StringEquals(".ctor", metadataReader))
{
MethodDesc method = (MethodDesc)_metadataUnit.GetMethod(handle, this);
if (method.Signature.Length != 0)
continue;
return method;
}
}
return null;
}
public override MethodDesc GetFinalizer()
{
// System.Object defines Finalize but doesn't use it, so we can determine that a type has a Finalizer
// by checking for a virtual method override that lands anywhere other than Object in the inheritance
// chain.
if (!HasBaseType)
return null;
TypeDesc objectType = Context.GetWellKnownType(WellKnownType.Object);
MethodDesc decl = objectType.GetMethod("Finalize", null);
if (decl != null)
{
MethodDesc impl = this.FindVirtualFunctionTargetMethodOnObjectType(decl);
if (impl == null)
{
// TODO: invalid input: the type doesn't derive from our System.Object
throw new TypeLoadException(this.GetFullName());
}
if (impl.OwningType != objectType)
{
return impl;
}
return null;
}
// TODO: Better exception type. Should be: "CoreLib doesn't have a required thing in it".
throw new NotImplementedException();
}
public override IEnumerable<FieldDesc> GetFields()
{
foreach (var handle in _typeDefinition.Fields)
{
yield return _metadataUnit.GetField(handle, this);
}
}
public override FieldDesc GetField(string name)
{
var metadataReader = this.MetadataReader;
foreach (var handle in _typeDefinition.Fields)
{
if (metadataReader.GetField(handle).Name.StringEquals(name, metadataReader))
{
return _metadataUnit.GetField(handle, this);
}
}
return null;
}
public override IEnumerable<MetadataType> GetNestedTypes()
{
foreach (var handle in _typeDefinition.NestedTypes)
{
yield return (MetadataType)_metadataUnit.GetType(handle);
}
}
public override MetadataType GetNestedType(string name)
{
var metadataReader = this.MetadataReader;
foreach (var handle in _typeDefinition.NestedTypes)
{
if (metadataReader.GetTypeDefinition(handle).Name.StringEquals(name, metadataReader))
return (MetadataType)_metadataUnit.GetType(handle);
}
return null;
}
public TypeAttributes Attributes
{
get
{
return _typeDefinition.Flags;
}
}
//
// ContainingType of nested type
//
public override DefType ContainingType
{
get
{
var handle = _typeDefinition.EnclosingType;
if (handle.IsNull(MetadataReader))
return null;
return (DefType)_metadataUnit.GetType(handle);
}
}
public override bool HasCustomAttribute(string attributeNamespace, string attributeName)
{
return MetadataReader.HasCustomAttribute(_typeDefinition.CustomAttributes,
attributeNamespace, attributeName);
}
public override string ToString()
{
return "[" + NativeFormatModule.GetName().Name + "]" + this.GetFullName();
}
public override ClassLayoutMetadata GetClassLayout()
{
ClassLayoutMetadata result;
result.PackingSize = checked((int)_typeDefinition.PackingSize);
result.Size = checked((int)_typeDefinition.Size);
// Skip reading field offsets if this is not explicit layout
if (IsExplicitLayout)
{
var fieldDefinitionHandles = _typeDefinition.Fields;
var numInstanceFields = 0;
foreach (var handle in fieldDefinitionHandles)
{
var fieldDefinition = MetadataReader.GetField(handle);
if ((fieldDefinition.Flags & FieldAttributes.Static) != 0)
continue;
numInstanceFields++;
}
result.Offsets = new FieldAndOffset[numInstanceFields];
int index = 0;
foreach (var handle in fieldDefinitionHandles)
{
var fieldDefinition = MetadataReader.GetField(handle);
if ((fieldDefinition.Flags & FieldAttributes.Static) != 0)
continue;
// Note: GetOffset() returns -1 when offset was not set in the metadata which maps nicely
// to FieldAndOffset.InvalidOffset.
Debug.Assert(FieldAndOffset.InvalidOffset == -1);
result.Offsets[index] =
new FieldAndOffset(_metadataUnit.GetField(handle, this), checked((int)fieldDefinition.Offset));
index++;
}
}
else
result.Offsets = null;
return result;
}
public override bool IsExplicitLayout
{
get
{
return (_typeDefinition.Flags & TypeAttributes.ExplicitLayout) != 0;
}
}
public override bool IsSequentialLayout
{
get
{
return (_typeDefinition.Flags & TypeAttributes.SequentialLayout) != 0;
}
}
public override bool IsBeforeFieldInit
{
get
{
return (_typeDefinition.Flags & TypeAttributes.BeforeFieldInit) != 0;
}
}
public override bool IsSealed
{
get
{
return (_typeDefinition.Flags & TypeAttributes.Sealed) != 0;
}
}
public override bool IsAbstract
{
get
{
return (_typeDefinition.Flags & TypeAttributes.Abstract) != 0;
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.FindSymbols.Finders;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Formatting.Rules;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Notification;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.ChangeSignature
{
internal abstract class AbstractChangeSignatureService : ILanguageService
{
protected SyntaxAnnotation changeSignatureFormattingAnnotation = new SyntaxAnnotation("ChangeSignatureFormatting");
/// <summary>
/// Determines the symbol on which we are invoking ReorderParameters
/// </summary>
public abstract ISymbol GetInvocationSymbol(Document document, int position, bool restrictToDeclarations, CancellationToken cancellationToken);
/// <summary>
/// Given a SyntaxNode for which we want to reorder parameters/arguments, find the
/// SyntaxNode of a kind where we know how to reorder parameters/arguments.
/// </summary>
public abstract SyntaxNode FindNodeToUpdate(Document document, SyntaxNode node);
public abstract Task<IEnumerable<ISymbol>> DetermineCascadedSymbolsFromDelegateInvoke(IMethodSymbol symbol, Document document, CancellationToken cancellationToken);
public abstract SyntaxNode ChangeSignature(
Document document,
ISymbol declarationSymbol,
SyntaxNode potentiallyUpdatedNode,
SyntaxNode originalNode,
SignatureChange signaturePermutation,
CancellationToken cancellationToken);
protected abstract IEnumerable<IFormattingRule> GetFormattingRules(Document document);
public async Task<IEnumerable<ChangeSignatureCodeAction>> GetChangeSignatureCodeActionAsync(Document document, TextSpan span, CancellationToken cancellationToken)
{
var context = await GetContextAsync(document, span.Start, restrictToDeclarations: true, cancellationToken: cancellationToken).ConfigureAwait(false);
return context.CanChangeSignature
? SpecializedCollections.SingletonEnumerable(new ChangeSignatureCodeAction(this, context))
: SpecializedCollections.EmptyEnumerable<ChangeSignatureCodeAction>();
}
internal ChangeSignatureResult ChangeSignature(Document document, int position, Action<string, NotificationSeverity> errorHandler, CancellationToken cancellationToken)
{
var context = GetContextAsync(document, position, restrictToDeclarations: false, cancellationToken: cancellationToken).WaitAndGetResult(cancellationToken);
if (context.CanChangeSignature)
{
return ChangeSignatureWithContext(context, cancellationToken);
}
else
{
switch (context.CannotChangeSignatureReason)
{
case CannotChangeSignatureReason.DefinedInMetadata:
errorHandler(FeaturesResources.TheMemberIsDefinedInMetadata, NotificationSeverity.Error);
break;
case CannotChangeSignatureReason.IncorrectKind:
errorHandler(FeaturesResources.YouCanOnlyChangeTheSignatureOfAConstructorIndexerMethodOrDelegate, NotificationSeverity.Error);
break;
case CannotChangeSignatureReason.InsufficientParameters:
errorHandler(FeaturesResources.ThisSignatureDoesNotContainParametersThatCanBeChanged, NotificationSeverity.Error);
break;
}
return new ChangeSignatureResult(succeeded: false);
}
}
private async Task<ChangeSignatureAnalyzedContext> GetContextAsync(Document document, int position, bool restrictToDeclarations, CancellationToken cancellationToken)
{
var symbol = GetInvocationSymbol(document, position, restrictToDeclarations, cancellationToken);
// Cross-lang symbols will show as metadata, so map it to source if possible.
symbol = await SymbolFinder.FindSourceDefinitionAsync(symbol, document.Project.Solution, cancellationToken).ConfigureAwait(false) ?? symbol;
if (symbol == null)
{
return new ChangeSignatureAnalyzedContext(CannotChangeSignatureReason.IncorrectKind);
}
if (symbol is IMethodSymbol)
{
var method = symbol as IMethodSymbol;
var containingType = method.ContainingType;
if (method.Name == WellKnownMemberNames.DelegateBeginInvokeName &&
containingType != null &&
containingType.IsDelegateType() &&
containingType.DelegateInvokeMethod != null)
{
symbol = containingType.DelegateInvokeMethod;
}
}
if (symbol is IEventSymbol)
{
symbol = (symbol as IEventSymbol).Type;
}
if (symbol is INamedTypeSymbol)
{
var typeSymbol = symbol as INamedTypeSymbol;
if (typeSymbol.IsDelegateType() && typeSymbol.DelegateInvokeMethod != null)
{
symbol = typeSymbol.DelegateInvokeMethod;
}
}
if (symbol.Locations.Any(loc => loc.IsInMetadata))
{
return new ChangeSignatureAnalyzedContext(CannotChangeSignatureReason.DefinedInMetadata);
}
if (!symbol.MatchesKind(SymbolKind.Method, SymbolKind.Property, SymbolKind.NamedType))
{
return new ChangeSignatureAnalyzedContext(CannotChangeSignatureReason.IncorrectKind);
}
var parameterConfiguration = ParameterConfiguration.Create(symbol.GetParameters().ToList(), symbol is IMethodSymbol && (symbol as IMethodSymbol).IsExtensionMethod);
if (!parameterConfiguration.IsChangeable())
{
return new ChangeSignatureAnalyzedContext(CannotChangeSignatureReason.InsufficientParameters);
}
return new ChangeSignatureAnalyzedContext(document.Project.Solution, symbol, parameterConfiguration);
}
private ChangeSignatureResult ChangeSignatureWithContext(ChangeSignatureAnalyzedContext context, CancellationToken cancellationToken)
{
var options = GetChangeSignatureOptions(context, CancellationToken.None);
if (options.IsCancelled)
{
return new ChangeSignatureResult(succeeded: false);
}
return ChangeSignatureWithContext(context, options, cancellationToken);
}
internal ChangeSignatureResult ChangeSignatureWithContext(ChangeSignatureAnalyzedContext context, ChangeSignatureOptionsResult options, CancellationToken cancellationToken)
{
Solution updatedSolution;
var succeeded = TryCreateUpdatedSolution(context, options, cancellationToken, out updatedSolution);
return new ChangeSignatureResult(succeeded, updatedSolution, context.Symbol.ToDisplayString(), context.Symbol.GetGlyph(), options.PreviewChanges);
}
internal ChangeSignatureOptionsResult GetChangeSignatureOptions(ChangeSignatureAnalyzedContext context, CancellationToken cancellationToken)
{
var notificationService = context.Solution.Workspace.Services.GetService<INotificationService>();
var changeSignatureOptionsService = context.Solution.Workspace.Services.GetService<IChangeSignatureOptionsService>();
var isExtensionMethod = context.Symbol is IMethodSymbol && (context.Symbol as IMethodSymbol).IsExtensionMethod;
return changeSignatureOptionsService.GetChangeSignatureOptions(context.Symbol, context.ParameterConfiguration, notificationService);
}
private static Task<IEnumerable<ReferencedSymbol>> FindChangeSignatureReferencesAsync(
ISymbol symbol,
Solution solution,
CancellationToken cancellationToken)
{
using (Logger.LogBlock(FunctionId.FindReference_ChangeSignature, cancellationToken))
{
IImmutableSet<Document> documents = null;
var engine = new FindReferencesSearchEngine(
solution,
documents,
ReferenceFinders.DefaultReferenceFinders.Add(DelegateInvokeMethodReferenceFinder.DelegateInvokeMethod),
FindReferencesProgress.Instance,
cancellationToken);
return engine.FindReferencesAsync(symbol);
}
}
private bool TryCreateUpdatedSolution(ChangeSignatureAnalyzedContext context, ChangeSignatureOptionsResult options, CancellationToken cancellationToken, out Solution updatedSolution)
{
updatedSolution = context.Solution;
var declaredSymbol = context.Symbol;
var nodesToUpdate = new Dictionary<DocumentId, List<SyntaxNode>>();
var definitionToUse = new Dictionary<SyntaxNode, ISymbol>();
bool hasLocationsInMetadata = false;
var symbols = FindChangeSignatureReferencesAsync(declaredSymbol, context.Solution, cancellationToken).WaitAndGetResult(cancellationToken);
foreach (var symbol in symbols)
{
if (symbol.Definition.Kind == SymbolKind.Method &&
((symbol.Definition as IMethodSymbol).MethodKind == MethodKind.PropertyGet || (symbol.Definition as IMethodSymbol).MethodKind == MethodKind.PropertySet))
{
continue;
}
if (symbol.Definition.Kind == SymbolKind.NamedType)
{
continue;
}
if (symbol.Definition.Locations.Any(loc => loc.IsInMetadata))
{
hasLocationsInMetadata = true;
continue;
}
var symbolWithSyntacticParameters = symbol.Definition;
var symbolWithSemanticParameters = symbol.Definition;
var includeDefinitionLocations = true;
if (symbol.Definition.Kind == SymbolKind.Field)
{
includeDefinitionLocations = false;
}
if (symbolWithSyntacticParameters.Kind == SymbolKind.Event)
{
var eventSymbol = symbolWithSyntacticParameters as IEventSymbol;
var type = eventSymbol.Type as INamedTypeSymbol;
if (type != null && type.DelegateInvokeMethod != null)
{
symbolWithSemanticParameters = type.DelegateInvokeMethod;
}
else
{
continue;
}
}
if (symbolWithSyntacticParameters.Kind == SymbolKind.Method)
{
var methodSymbol = symbolWithSyntacticParameters as IMethodSymbol;
if (methodSymbol.MethodKind == MethodKind.DelegateInvoke)
{
symbolWithSyntacticParameters = methodSymbol.ContainingType;
}
if (methodSymbol.Name == WellKnownMemberNames.DelegateBeginInvokeName &&
methodSymbol.ContainingType != null &&
methodSymbol.ContainingType.IsDelegateType())
{
includeDefinitionLocations = false;
}
}
if (includeDefinitionLocations)
{
foreach (var def in symbolWithSyntacticParameters.Locations)
{
DocumentId documentId;
SyntaxNode nodeToUpdate;
if (!TryGetNodeWithEditableSignatureOrAttributes(def, updatedSolution, out nodeToUpdate, out documentId))
{
continue;
}
if (!nodesToUpdate.ContainsKey(documentId))
{
nodesToUpdate.Add(documentId, new List<SyntaxNode>());
}
AddUpdatableNodeToDictionaries(nodesToUpdate, documentId, nodeToUpdate, definitionToUse, symbolWithSemanticParameters);
}
}
// TODO: Find references to containing type for Add methods & collection initializers (for example)
foreach (var location in symbol.Locations)
{
if (location.Location.IsInMetadata)
{
hasLocationsInMetadata = true;
continue;
}
DocumentId documentId2;
SyntaxNode nodeToUpdate2;
if (!TryGetNodeWithEditableSignatureOrAttributes(location.Location, updatedSolution, out nodeToUpdate2, out documentId2))
{
continue;
}
if (!nodesToUpdate.ContainsKey(documentId2))
{
nodesToUpdate.Add(documentId2, new List<SyntaxNode>());
}
AddUpdatableNodeToDictionaries(nodesToUpdate, documentId2, nodeToUpdate2, definitionToUse, symbolWithSemanticParameters);
}
}
if (hasLocationsInMetadata)
{
var notificationService = context.Solution.Workspace.Services.GetService<INotificationService>();
if (!notificationService.ConfirmMessageBox(FeaturesResources.ThisSymbolHasRelatedDefinitionsOrReferencesInMetadata, severity: NotificationSeverity.Warning))
{
return false;
}
}
foreach (var docId in nodesToUpdate.Keys)
{
var doc = updatedSolution.GetDocument(docId);
var updater = doc.Project.LanguageServices.GetService<AbstractChangeSignatureService>();
var root = doc.GetSyntaxRootAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None);
var nodes = nodesToUpdate[docId];
var newRoot = root.ReplaceNodes(nodes, (originalNode, potentiallyUpdatedNode) =>
{
return updater.ChangeSignature(doc, definitionToUse[originalNode], potentiallyUpdatedNode, originalNode, CreateCompensatingSignatureChange(definitionToUse[originalNode], options.UpdatedSignature), cancellationToken);
});
var annotatedNodes = newRoot.GetAnnotatedNodes<SyntaxNode>(syntaxAnnotation: changeSignatureFormattingAnnotation);
var formattedRoot = Formatter.Format(
newRoot,
changeSignatureFormattingAnnotation,
doc.Project.Solution.Workspace,
options: null,
rules: GetFormattingRules(doc),
cancellationToken: CancellationToken.None);
updatedSolution = updatedSolution.WithDocumentSyntaxRoot(docId, formattedRoot);
}
return true;
}
private void AddUpdatableNodeToDictionaries(Dictionary<DocumentId, List<SyntaxNode>> nodesToUpdate, DocumentId documentId, SyntaxNode nodeToUpdate, Dictionary<SyntaxNode, ISymbol> definitionToUse, ISymbol symbolWithSemanticParameters)
{
nodesToUpdate[documentId].Add(nodeToUpdate);
ISymbol sym;
if (definitionToUse.TryGetValue(nodeToUpdate, out sym) && sym != symbolWithSemanticParameters)
{
Debug.Assert(false, "Change Signature: Attempted to modify node twice with different semantic parameters.");
}
definitionToUse[nodeToUpdate] = symbolWithSemanticParameters;
}
private bool TryGetNodeWithEditableSignatureOrAttributes(Location location, Solution solution, out SyntaxNode nodeToUpdate, out DocumentId documentId)
{
var tree = location.SourceTree;
documentId = solution.GetDocumentId(tree);
var document = solution.GetDocument(documentId);
var root = tree.GetRoot();
SyntaxNode node = root.FindNode(location.SourceSpan, findInsideTrivia: true, getInnermostNodeForTie: true);
var updater = document.Project.LanguageServices.GetService<AbstractChangeSignatureService>();
nodeToUpdate = updater.FindNodeToUpdate(document, node);
return nodeToUpdate != null;
}
protected static List<IUnifiedArgumentSyntax> PermuteArguments(
Document document,
ISymbol declarationSymbol,
List<IUnifiedArgumentSyntax> arguments,
SignatureChange updatedSignature,
bool isReducedExtensionMethod = false)
{
// 1. Determine which parameters are permutable
var declarationParameters = declarationSymbol.GetParameters().ToList();
var declarationParametersToPermute = GetParametersToPermute(arguments, declarationParameters, isReducedExtensionMethod);
var argumentsToPermute = arguments.Take(declarationParametersToPermute.Count).ToList();
// 2. Create an argument to parameter map, and a parameter to index map for the sort.
var argumentToParameterMap = new Dictionary<IUnifiedArgumentSyntax, IParameterSymbol>();
var parameterToIndexMap = new Dictionary<IParameterSymbol, int>();
for (int i = 0; i < declarationParametersToPermute.Count; i++)
{
var decl = declarationParametersToPermute[i];
var arg = argumentsToPermute[i];
argumentToParameterMap[arg] = decl;
var originalIndex = declarationParameters.IndexOf(decl);
var updatedIndex = updatedSignature.GetUpdatedIndex(originalIndex);
// If there's no value, then we may be handling a method with more parameters than the original symbol (like BeginInvoke).
parameterToIndexMap[decl] = updatedIndex.HasValue ? updatedIndex.Value : -1;
}
// 3. Sort the arguments that need to be reordered
argumentsToPermute.Sort((a1, a2) => { return parameterToIndexMap[argumentToParameterMap[a1]].CompareTo(parameterToIndexMap[argumentToParameterMap[a2]]); });
// 4. Add names to arguments where necessary.
var newArguments = new List<IUnifiedArgumentSyntax>();
int expectedIndex = 0 + (isReducedExtensionMethod ? 1 : 0);
bool seenNamedArgument = false;
foreach (var argument in argumentsToPermute)
{
var param = argumentToParameterMap[argument];
var actualIndex = updatedSignature.GetUpdatedIndex(declarationParameters.IndexOf(param));
if (!actualIndex.HasValue)
{
continue;
}
if ((seenNamedArgument || actualIndex != expectedIndex) && !argument.IsNamed)
{
newArguments.Add(argument.WithName(param.Name).WithAdditionalAnnotations(Formatter.Annotation));
seenNamedArgument = true;
}
else
{
newArguments.Add(argument);
}
seenNamedArgument |= argument.IsNamed;
expectedIndex++;
}
// 5. Add the remaining arguments. These will already have names or be params arguments, but may have been removed.
bool removedParams = updatedSignature.OriginalConfiguration.ParamsParameter != null && updatedSignature.UpdatedConfiguration.ParamsParameter == null;
for (int i = declarationParametersToPermute.Count; i < arguments.Count; i++)
{
if (!arguments[i].IsNamed && removedParams && i >= updatedSignature.UpdatedConfiguration.ToListOfParameters().Count)
{
break;
}
if (!arguments[i].IsNamed || updatedSignature.UpdatedConfiguration.ToListOfParameters().Any(p => p.Name == arguments[i].GetName()))
{
newArguments.Add(arguments[i]);
}
}
return newArguments;
}
private static SignatureChange CreateCompensatingSignatureChange(ISymbol declarationSymbol, SignatureChange updatedSignature)
{
if (declarationSymbol.GetParameters().Count() > updatedSignature.OriginalConfiguration.ToListOfParameters().Count)
{
var origStuff = updatedSignature.OriginalConfiguration.ToListOfParameters();
var newStuff = updatedSignature.UpdatedConfiguration.ToListOfParameters();
var realStuff = declarationSymbol.GetParameters();
var bonusParameters = realStuff.Skip(origStuff.Count);
origStuff.AddRange(bonusParameters);
newStuff.AddRange(bonusParameters);
var newOrigParams = ParameterConfiguration.Create(origStuff, updatedSignature.OriginalConfiguration.ThisParameter != null);
var newUpdatedParams = ParameterConfiguration.Create(newStuff, updatedSignature.OriginalConfiguration.ThisParameter != null);
updatedSignature = new SignatureChange(newOrigParams, newUpdatedParams);
}
return updatedSignature;
}
private static List<IParameterSymbol> GetParametersToPermute(
List<IUnifiedArgumentSyntax> arguments,
List<IParameterSymbol> originalParameters,
bool isReducedExtensionMethod)
{
int position = -1 + (isReducedExtensionMethod ? 1 : 0);
var parametersToPermute = new List<IParameterSymbol>();
foreach (var argument in arguments)
{
if (argument.IsNamed)
{
var name = argument.GetName();
// TODO: file bug for var match = originalParameters.FirstOrDefault(p => p.Name == <ISymbol here>);
var match = originalParameters.FirstOrDefault(p => p.Name == name);
if (match == null || originalParameters.IndexOf(match) <= position)
{
break;
}
else
{
position = originalParameters.IndexOf(match);
parametersToPermute.Add(match);
}
}
else
{
position++;
if (position >= originalParameters.Count)
{
break;
}
parametersToPermute.Add(originalParameters[position]);
}
}
return parametersToPermute;
}
}
}
| |
//
// Copyright (c) 2004-2011 Jaroslaw Kowalski <[email protected]>
//
// 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.
//
#if !SILVERLIGHT
namespace NLog.UnitTests.LayoutRenderers
{
using System;
using Microsoft.Win32;
using Xunit;
public class RegistryTests : NLogTestBase, IDisposable
{
private const string TestKey = @"Software\NLogTest";
public RegistryTests()
{
var key = Registry.CurrentUser.CreateSubKey(TestKey);
key.SetValue("Foo", "FooValue");
key.SetValue(null, "UnnamedValue");
#if !NET3_5
//different keys because in 32bit the 64bits uses the 32
RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry32).CreateSubKey("Software\\NLogTest").SetValue("view32", "reg32");
RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry64).CreateSubKey("Software\\NLogTest").SetValue("view64", "reg64");
#endif
}
public void Dispose()
{
#if !NET3_5
//different keys because in 32bit the 64bits uses the 32
try
{
RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry32).DeleteSubKey("Software\\NLogTest");
}
catch (Exception)
{
}
try
{
RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry64).DeleteSubKey("Software\\NLogTest");
}
catch (Exception)
{
}
#endif
try
{
Registry.CurrentUser.DeleteSubKey(TestKey);
}
catch (Exception)
{
}
}
[Fact]
public void RegistryNamedValueTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${registry:key=HKCU\\Software\\NLogTest:value=Foo}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
LogManager.GetLogger("d").Debug("zzz");
AssertDebugLastMessage("debug", "FooValue");
}
#if !NET3_5
[Fact]
public void RegistryNamedValueTest_hive32()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${registry:key=HKCU\\Software\\NLogTest:value=view32:view=Registry32}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
LogManager.GetLogger("d").Debug("zzz");
AssertDebugLastMessage("debug", "reg32");
}
[Fact]
public void RegistryNamedValueTest_hive64()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${registry:key=HKCU\\Software\\NLogTest:value=view64:view=Registry64}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
LogManager.GetLogger("d").Debug("zzz");
AssertDebugLastMessage("debug", "reg64");
}
#endif
[Fact]
public void RegistryNamedValueTest_forward_slash()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${registry:key=HKCU/Software/NLogTest:value=Foo}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
LogManager.GetLogger("d").Debug("zzz");
AssertDebugLastMessage("debug", "FooValue");
}
[Fact]
public void RegistryUnnamedValueTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${registry:key=HKCU\\Software\\NLogTest}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
LogManager.GetLogger("d").Debug("zzz");
AssertDebugLastMessage("debug", "UnnamedValue");
}
[Fact]
public void RegistryUnnamedValueTest_forward_slash()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${registry:key=HKCU/Software/NLogTest}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
LogManager.GetLogger("d").Debug("zzz");
AssertDebugLastMessage("debug", "UnnamedValue");
}
[Fact]
public void RegistryKeyNotFoundTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${registry:key=HKCU\\Software\\NoSuchKey:defaultValue=xyz}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
LogManager.GetLogger("d").Debug("zzz");
AssertDebugLastMessage("debug", "xyz");
}
[Fact]
public void RegistryKeyNotFoundTest_forward_slash()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${registry:key=HKCU/Software/NoSuchKey:defaultValue=xyz}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
LogManager.GetLogger("d").Debug("zzz");
AssertDebugLastMessage("debug", "xyz");
}
[Fact]
public void RegistryValueNotFoundTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${registry:key=HKCU\\Software\\NLogTest:value=NoSuchValue:defaultValue=xyz}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
LogManager.GetLogger("d").Debug("zzz");
AssertDebugLastMessage("debug", "xyz");
}
[Fact]
public void RegistryDefaultValueTest()
{
//example: 0003: NLog.UnitTests
AssertLayoutRendererOutput("${registry:value=NOT_EXISTENT:key=HKLM/NOT_EXISTENT:defaultValue=logdefaultvalue}",
"logdefaultvalue");
}
[Fact]
public void RegistryDefaultValueTest_with_colon()
{
//example: 0003: NLog.UnitTests
AssertLayoutRendererOutput("${registry:value=NOT_EXISTENT:key=HKLM/NOT_EXISTENT:defaultValue=C\\:temp}",
"C:temp");
}
[Fact]
public void RegistryDefaultValueTest_with_slash()
{
//example: 0003: NLog.UnitTests
AssertLayoutRendererOutput("${registry:value=NOT_EXISTENT:key=HKLM/NOT_EXISTENT:defaultValue=C/temp}",
"C/temp");
}
[Fact]
public void RegistryDefaultValueTest_with_foward_slash()
{
//example: 0003: NLog.UnitTests
AssertLayoutRendererOutput("${registry:value=NOT_EXISTENT:key=HKLM/NOT_EXISTENT:defaultValue=C\\\\temp}",
"C\\temp");
}
[Fact]
public void RegistryDefaultValueTest_with_foward_slash2()
{
//example: 0003: NLog.UnitTests
AssertLayoutRendererOutput("${registry:value=NOT_EXISTENT:key=HKLM/NOT_EXISTENT:defaultValue=C\\temp:requireEscapingSlashesInDefaultValue=false}",
"C\\temp");
}
[Fact]
public void Registry_nosubky()
{
//example: 0003: NLog.UnitTests
AssertLayoutRendererOutput("${registry:key=HKEY_CURRENT_CONFIG}", "");
}
[Fact]
public void RegistryDefaultValueNull()
{
//example: 0003: NLog.UnitTests
AssertLayoutRendererOutput("${registry:value=NOT_EXISTENT:key=HKLM/NOT_EXISTENT}", "");
}
[Fact]
public void RegistryTestWrongKey_no_ex()
{
var throwExceptions = LogManager.ThrowExceptions;
try
{
LogManager.ThrowExceptions = false;
AssertLayoutRendererOutput("${registry:value=NOT_EXISTENT:key=garabageHKLM/NOT_EXISTENT:defaultValue=empty}", "");
}
finally
{
//restore
LogManager.ThrowExceptions = throwExceptions;
}
}
[Fact(Skip = "SimpleLayout.GetFormattedMessage catches exception. Will be fixed in the future")]
public void RegistryTestWrongKey_ex()
{
var throwExceptions = LogManager.ThrowExceptions;
try
{
LogManager.ThrowExceptions = true;
Assert.Throws<ArgumentException>(
() => { AssertLayoutRendererOutput("${registry:value=NOT_EXISTENT:key=garabageHKLM/NOT_EXISTENT:defaultValue=empty}", ""); });
}
finally
{
//restore
LogManager.ThrowExceptions = throwExceptions;
}
}
}
}
#endif
| |
// This file was generated by CSLA Object Generator - CslaGenFork v4.5
//
// Filename: CircTypeTagEditDyna
// ObjectType: CircTypeTagEditDyna
// CSLAType: DynamicEditableRoot
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
using DocStore.Business.Util;
using DocStore.Business.Security;
namespace DocStore.Business
{
/// <summary>
/// Textual tags for standard circulation types (dynamic root object).<br/>
/// This is a generated <see cref="CircTypeTagEditDyna"/> business object.
/// </summary>
/// <remarks>
/// This class is an item of <see cref="CircTypeTagEditDynaColl"/> collection.
/// </remarks>
[Serializable]
public partial class CircTypeTagEditDyna : BusinessBase<CircTypeTagEditDyna>
{
#region Static Fields
private static int _lastId;
#endregion
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="CircTypeID"/> property.
/// </summary>
[NotUndoable]
public static readonly PropertyInfo<int> CircTypeIDProperty = RegisterProperty<int>(p => p.CircTypeID, "Circ Type ID");
/// <summary>
/// Gets the Circ Type ID.
/// </summary>
/// <value>The Circ Type ID.</value>
public int CircTypeID
{
get { return GetProperty(CircTypeIDProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="CircTypeTag"/> property.
/// </summary>
public static readonly PropertyInfo<string> CircTypeTagProperty = RegisterProperty<string>(p => p.CircTypeTag, "Circ Type Tag");
/// <summary>
/// Gets or sets the Circ Type Tag.
/// </summary>
/// <value>The Circ Type Tag.</value>
public string CircTypeTag
{
get { return GetProperty(CircTypeTagProperty); }
set { SetProperty(CircTypeTagProperty, value); }
}
/// <summary>
/// Maintains metadata about <see cref="CreateDate"/> property.
/// </summary>
public static readonly PropertyInfo<SmartDate> CreateDateProperty = RegisterProperty<SmartDate>(p => p.CreateDate, "Create Date");
/// <summary>
/// Date of creation
/// </summary>
/// <value>The Create Date.</value>
public SmartDate CreateDate
{
get { return GetProperty(CreateDateProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="CreateUserID"/> property.
/// </summary>
public static readonly PropertyInfo<int> CreateUserIDProperty = RegisterProperty<int>(p => p.CreateUserID, "Create User ID");
/// <summary>
/// ID of the creating user
/// </summary>
/// <value>The Create User ID.</value>
public int CreateUserID
{
get { return GetProperty(CreateUserIDProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="ChangeDate"/> property.
/// </summary>
public static readonly PropertyInfo<SmartDate> ChangeDateProperty = RegisterProperty<SmartDate>(p => p.ChangeDate, "Change Date");
/// <summary>
/// Date of last change
/// </summary>
/// <value>The Change Date.</value>
public SmartDate ChangeDate
{
get { return GetProperty(ChangeDateProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="ChangeUserID"/> property.
/// </summary>
public static readonly PropertyInfo<int> ChangeUserIDProperty = RegisterProperty<int>(p => p.ChangeUserID, "Change User ID");
/// <summary>
/// ID of the last changing user
/// </summary>
/// <value>The Change User ID.</value>
public int ChangeUserID
{
get { return GetProperty(ChangeUserIDProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="RowVersion"/> property.
/// </summary>
[NotUndoable]
public static readonly PropertyInfo<byte[]> RowVersionProperty = RegisterProperty<byte[]>(p => p.RowVersion, "Row Version");
/// <summary>
/// Row version counter for concurrency control
/// </summary>
/// <value>The Row Version.</value>
public byte[] RowVersion
{
get { return GetProperty(RowVersionProperty); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="CircTypeTagEditDyna"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="CircTypeTagEditDyna"/> object.</returns>
internal static CircTypeTagEditDyna NewCircTypeTagEditDyna()
{
return DataPortal.Create<CircTypeTagEditDyna>();
}
/// <summary>
/// Factory method. Loads a <see cref="CircTypeTagEditDyna"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
/// <returns>A reference to the fetched <see cref="CircTypeTagEditDyna"/> object.</returns>
internal static CircTypeTagEditDyna GetCircTypeTagEditDyna(SafeDataReader dr)
{
CircTypeTagEditDyna obj = new CircTypeTagEditDyna();
obj.Fetch(dr);
obj.MarkOld();
// check all object rules and property rules
obj.BusinessRules.CheckRules();
return obj;
}
/// <summary>
/// Factory method. Deletes a <see cref="CircTypeTagEditDyna"/> object, based on given parameters.
/// </summary>
/// <param name="circTypeID">The CircTypeID of the CircTypeTagEditDyna to delete.</param>
internal static void DeleteCircTypeTagEditDyna(int circTypeID)
{
DataPortal.Delete<CircTypeTagEditDyna>(circTypeID);
}
/// <summary>
/// Factory method. Asynchronously creates a new <see cref="CircTypeTagEditDyna"/> object.
/// </summary>
/// <param name="callback">The completion callback method.</param>
internal static void NewCircTypeTagEditDyna(EventHandler<DataPortalResult<CircTypeTagEditDyna>> callback)
{
DataPortal.BeginCreate<CircTypeTagEditDyna>(callback);
}
/// <summary>
/// Factory method. Asynchronously deletes a <see cref="CircTypeTagEditDyna"/> object, based on given parameters.
/// </summary>
/// <param name="circTypeID">The CircTypeID of the CircTypeTagEditDyna to delete.</param>
/// <param name="callback">The completion callback method.</param>
internal static void DeleteCircTypeTagEditDyna(int circTypeID, EventHandler<DataPortalResult<CircTypeTagEditDyna>> callback)
{
DataPortal.BeginDelete<CircTypeTagEditDyna>(circTypeID, callback);
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="CircTypeTagEditDyna"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public CircTypeTagEditDyna()
{
// Use factory methods and do not use direct creation.
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="CircTypeTagEditDyna"/> object properties.
/// </summary>
[RunLocal]
protected override void DataPortal_Create()
{
LoadProperty(CircTypeIDProperty, System.Threading.Interlocked.Decrement(ref _lastId));
LoadProperty(CreateDateProperty, new SmartDate(DateTime.Now));
LoadProperty(CreateUserIDProperty, UserInformation.UserId);
LoadProperty(ChangeDateProperty, ReadProperty(CreateDateProperty));
LoadProperty(ChangeUserIDProperty, ReadProperty(CreateUserIDProperty));
var args = new DataPortalHookArgs();
OnCreate(args);
base.DataPortal_Create();
}
/// <summary>
/// Loads a <see cref="CircTypeTagEditDyna"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
// Value properties
LoadProperty(CircTypeIDProperty, dr.GetInt32("CircTypeID"));
LoadProperty(CircTypeTagProperty, dr.GetString("CircTypeTag"));
LoadProperty(CreateDateProperty, dr.GetSmartDate("CreateDate", true));
LoadProperty(CreateUserIDProperty, dr.GetInt32("CreateUserID"));
LoadProperty(ChangeDateProperty, dr.GetSmartDate("ChangeDate", true));
LoadProperty(ChangeUserIDProperty, dr.GetInt32("ChangeUserID"));
LoadProperty(RowVersionProperty, dr.GetValue("RowVersion") as byte[]);
var args = new DataPortalHookArgs(dr);
OnFetchRead(args);
}
/// <summary>
/// Inserts a new <see cref="CircTypeTagEditDyna"/> object in the database.
/// </summary>
protected override void DataPortal_Insert()
{
SimpleAuditTrail();
using (var ctx = TransactionManager<SqlConnection, SqlTransaction>.GetManager(Database.DocStoreConnection, false))
{
using (var cmd = new SqlCommand("AddCircTypeTagEditDyna", ctx.Connection))
{
cmd.Transaction = ctx.Transaction;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@CircTypeID", ReadProperty(CircTypeIDProperty)).Direction = ParameterDirection.Output;
cmd.Parameters.AddWithValue("@CircTypeTag", ReadProperty(CircTypeTagProperty)).DbType = DbType.String;
cmd.Parameters.AddWithValue("@CreateDate", ReadProperty(CreateDateProperty).DBValue).DbType = DbType.DateTime2;
cmd.Parameters.AddWithValue("@CreateUserID", ReadProperty(CreateUserIDProperty)).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@ChangeDate", ReadProperty(ChangeDateProperty).DBValue).DbType = DbType.DateTime2;
cmd.Parameters.AddWithValue("@ChangeUserID", ReadProperty(ChangeUserIDProperty)).DbType = DbType.Int32;
cmd.Parameters.Add("@NewRowVersion", SqlDbType.Timestamp).Direction = ParameterDirection.Output;
var args = new DataPortalHookArgs(cmd);
OnInsertPre(args);
cmd.ExecuteNonQuery();
OnInsertPost(args);
LoadProperty(CircTypeIDProperty, (int) cmd.Parameters["@CircTypeID"].Value);
LoadProperty(RowVersionProperty, (byte[]) cmd.Parameters["@NewRowVersion"].Value);
}
ctx.Commit();
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="CircTypeTagEditDyna"/> object.
/// </summary>
protected override void DataPortal_Update()
{
SimpleAuditTrail();
using (var ctx = TransactionManager<SqlConnection, SqlTransaction>.GetManager(Database.DocStoreConnection, false))
{
using (var cmd = new SqlCommand("UpdateCircTypeTagEditDyna", ctx.Connection))
{
cmd.Transaction = ctx.Transaction;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@CircTypeID", ReadProperty(CircTypeIDProperty)).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@CircTypeTag", ReadProperty(CircTypeTagProperty)).DbType = DbType.String;
cmd.Parameters.AddWithValue("@ChangeDate", ReadProperty(ChangeDateProperty).DBValue).DbType = DbType.DateTime2;
cmd.Parameters.AddWithValue("@ChangeUserID", ReadProperty(ChangeUserIDProperty)).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@RowVersion", ReadProperty(RowVersionProperty)).DbType = DbType.Binary;
cmd.Parameters.Add("@NewRowVersion", SqlDbType.Timestamp).Direction = ParameterDirection.Output;
var args = new DataPortalHookArgs(cmd);
OnUpdatePre(args);
cmd.ExecuteNonQuery();
OnUpdatePost(args);
LoadProperty(RowVersionProperty, (byte[]) cmd.Parameters["@NewRowVersion"].Value);
}
ctx.Commit();
}
}
private void SimpleAuditTrail()
{
LoadProperty(ChangeDateProperty, DateTime.Now);
LoadProperty(ChangeUserIDProperty, UserInformation.UserId);
if (IsNew)
{
LoadProperty(CreateDateProperty, ReadProperty(ChangeDateProperty));
LoadProperty(CreateUserIDProperty, ReadProperty(ChangeUserIDProperty));
}
}
/// <summary>
/// Self deletes the <see cref="CircTypeTagEditDyna"/> object.
/// </summary>
protected override void DataPortal_DeleteSelf()
{
DataPortal_Delete(CircTypeID);
}
/// <summary>
/// Deletes the <see cref="CircTypeTagEditDyna"/> object from database.
/// </summary>
/// <param name="circTypeID">The delete criteria.</param>
protected void DataPortal_Delete(int circTypeID)
{
// audit the object, just in case soft delete is used on this object
SimpleAuditTrail();
using (var ctx = TransactionManager<SqlConnection, SqlTransaction>.GetManager(Database.DocStoreConnection, false))
{
using (var cmd = new SqlCommand("DeleteCircTypeTagEditDyna", ctx.Connection))
{
cmd.Transaction = ctx.Transaction;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@CircTypeID", circTypeID).DbType = DbType.Int32;
var args = new DataPortalHookArgs(cmd, circTypeID);
OnDeletePre(args);
cmd.ExecuteNonQuery();
OnDeletePost(args);
}
ctx.Commit();
}
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Diagnostics;
using System.Linq;
using JetBrains.Annotations;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Logging;
using osu.Framework.Screens;
using osu.Game.Input;
using osu.Game.Online.API;
using osu.Game.Online.Rooms;
using osu.Game.Screens.OnlinePlay.Components;
using osu.Game.Screens.OnlinePlay.Match;
using osu.Game.Screens.OnlinePlay.Match.Components;
using osu.Game.Screens.Play;
using osu.Game.Screens.Play.HUD;
using osu.Game.Users;
using osuTK;
namespace osu.Game.Screens.OnlinePlay.Playlists
{
public class PlaylistsRoomSubScreen : RoomSubScreen
{
public override string Title { get; }
public override string ShortTitle => "playlist";
[Resolved]
private IAPIProvider api { get; set; }
private readonly IBindable<bool> isIdle = new BindableBool();
private MatchLeaderboard leaderboard;
private SelectionPollingComponent selectionPollingComponent;
public PlaylistsRoomSubScreen(Room room)
: base(room, false) // Editing is temporarily not allowed.
{
Title = room.RoomID.Value == null ? "New playlist" : room.Name.Value;
Activity.Value = new UserActivity.InLobby(room);
}
[BackgroundDependencyLoader(true)]
private void load([CanBeNull] IdleTracker idleTracker)
{
if (idleTracker != null)
isIdle.BindTo(idleTracker.IsIdle);
AddInternal(selectionPollingComponent = new SelectionPollingComponent(Room));
}
protected override void LoadComplete()
{
base.LoadComplete();
isIdle.BindValueChanged(_ => updatePollingRate(), true);
RoomId.BindValueChanged(id =>
{
if (id.NewValue != null)
{
// Set the first playlist item.
// This is scheduled since updating the room and playlist may happen in an arbitrary order (via Room.CopyFrom()).
Schedule(() => SelectedItem.Value = Room.Playlist.FirstOrDefault());
}
}, true);
}
protected override Drawable CreateMainContent() => new GridContainer
{
RelativeSizeAxes = Axes.Both,
Content = new[]
{
new Drawable[]
{
new Container
{
RelativeSizeAxes = Axes.Both,
Padding = new MarginPadding { Right = 5 },
Child = new GridContainer
{
RelativeSizeAxes = Axes.Both,
Content = new[]
{
new Drawable[] { new OverlinedPlaylistHeader(), },
new Drawable[]
{
new DrawableRoomPlaylistWithResults
{
RelativeSizeAxes = Axes.Both,
Items = { BindTarget = Room.Playlist },
SelectedItem = { BindTarget = SelectedItem },
RequestShowResults = item =>
{
Debug.Assert(RoomId.Value != null);
ParentScreen?.Push(new PlaylistsResultsScreen(null, RoomId.Value.Value, item, false));
}
}
},
},
RowDimensions = new[]
{
new Dimension(GridSizeMode.AutoSize),
new Dimension(),
}
}
},
null,
new GridContainer
{
RelativeSizeAxes = Axes.Both,
Content = new[]
{
new[]
{
UserModsSection = new FillFlowContainer
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Alpha = 0,
Margin = new MarginPadding { Bottom = 10 },
Children = new Drawable[]
{
new OverlinedHeader("Extra mods"),
new FillFlowContainer
{
AutoSizeAxes = Axes.Both,
Direction = FillDirection.Horizontal,
Spacing = new Vector2(10, 0),
Children = new Drawable[]
{
new UserModSelectButton
{
Anchor = Anchor.CentreLeft,
Origin = Anchor.CentreLeft,
Width = 90,
Text = "Select",
Action = ShowUserModSelect,
},
new ModDisplay
{
Anchor = Anchor.CentreLeft,
Origin = Anchor.CentreLeft,
Current = UserMods,
Scale = new Vector2(0.8f),
},
}
}
}
},
},
new Drawable[]
{
new OverlinedHeader("Leaderboard")
},
new Drawable[] { leaderboard = new MatchLeaderboard { RelativeSizeAxes = Axes.Both }, },
new Drawable[] { new OverlinedHeader("Chat"), },
new Drawable[] { new MatchChatDisplay(Room) { RelativeSizeAxes = Axes.Both } }
},
RowDimensions = new[]
{
new Dimension(GridSizeMode.AutoSize),
new Dimension(GridSizeMode.AutoSize),
new Dimension(),
new Dimension(GridSizeMode.AutoSize),
new Dimension(GridSizeMode.Relative, size: 0.4f, minSize: 120),
}
},
},
},
ColumnDimensions = new[]
{
new Dimension(GridSizeMode.Relative, size: 0.5f, maxSize: 400),
new Dimension(),
new Dimension(GridSizeMode.Relative, size: 0.5f, maxSize: 600),
}
};
protected override Drawable CreateFooter() => new PlaylistsRoomFooter
{
OnStart = StartPlay
};
protected override RoomSettingsOverlay CreateRoomSettingsOverlay(Room room) => new PlaylistsRoomSettingsOverlay(room)
{
EditPlaylist = () =>
{
if (this.IsCurrentScreen())
this.Push(new PlaylistsSongSelect(Room));
},
};
private void updatePollingRate()
{
selectionPollingComponent.TimeBetweenPolls.Value = isIdle.Value ? 30000 : 5000;
Logger.Log($"Polling adjusted (selection: {selectionPollingComponent.TimeBetweenPolls.Value})");
}
protected override Screen CreateGameplayScreen() => new PlayerLoader(() => new PlaylistsPlayer(Room, SelectedItem.Value)
{
Exited = () => leaderboard.RefreshScores()
});
}
}
| |
// 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.
//
// The Reflection stack has grown a large legacy of apis that thunk others.
// Apis that do little more than wrap another api will be kept here to
// keep the main files less cluttered.
//
using System.IO;
using System.Text;
using System.Diagnostics;
using System.Globalization;
using System.Reflection.Runtime.General;
using Internal.LowLevelLinq;
namespace System.Reflection.Runtime.Assemblies
{
internal partial class RuntimeAssembly
{
public sealed override Type[] GetExportedTypes() => ExportedTypes.ToArray();
public sealed override Module[] GetLoadedModules(bool getResourceModules) => Modules.ToArray();
public sealed override Module[] GetModules(bool getResourceModules) => Modules.ToArray();
public sealed override Type[] GetTypes() => DefinedTypes.ToArray();
// "copiedName" only affects whether CodeBase is set to the assembly location before or after the shadow-copy.
// That concept is meaningless on .NET Native.
public sealed override AssemblyName GetName(bool copiedName) => GetName();
public sealed override Stream GetManifestResourceStream(Type type, string name)
{
StringBuilder sb = new StringBuilder();
if (type == null)
{
if (name == null)
throw new ArgumentNullException(nameof(type));
}
else
{
string nameSpace = type.Namespace;
if (nameSpace != null)
{
sb.Append(nameSpace);
if (name != null)
{
sb.Append(Type.Delimiter);
}
}
}
if (name != null)
{
sb.Append(name);
}
return GetManifestResourceStream(sb.ToString());
}
public sealed override string Location => string.Empty;
public sealed override string CodeBase { get { throw new PlatformNotSupportedException(); } }
public sealed override Assembly GetSatelliteAssembly(CultureInfo culture) { throw new PlatformNotSupportedException(); }
public sealed override Assembly GetSatelliteAssembly(CultureInfo culture, Version version) { throw new PlatformNotSupportedException(); }
public sealed override string ImageRuntimeVersion { get { throw new PlatformNotSupportedException(); } }
public sealed override AssemblyName[] GetReferencedAssemblies() { throw new PlatformNotSupportedException(); }
public sealed override Module GetModule(string name) { throw new PlatformNotSupportedException(); }
}
}
namespace System.Reflection.Runtime.MethodInfos
{
internal abstract partial class RuntimeConstructorInfo
{
public sealed override MethodImplAttributes GetMethodImplementationFlags() => MethodImplementationFlags;
// Partial trust doesn't exist in Aot so these legacy apis are meaningless. Will report everything as SecurityCritical by fiat.
public sealed override bool IsSecurityCritical => true;
public sealed override bool IsSecuritySafeCritical => false;
public sealed override bool IsSecurityTransparent => false;
}
}
namespace System.Reflection.Runtime.EventInfos
{
internal abstract partial class RuntimeEventInfo
{
public sealed override MethodInfo GetAddMethod(bool nonPublic) => AddMethod.FilterAccessor(nonPublic);
public sealed override MethodInfo GetRemoveMethod(bool nonPublic) => RemoveMethod.FilterAccessor(nonPublic);
public sealed override MethodInfo GetRaiseMethod(bool nonPublic) => RaiseMethod?.FilterAccessor(nonPublic);
}
}
namespace System.Reflection.Runtime.MethodInfos
{
internal abstract partial class RuntimeMethodInfo
{
public sealed override MethodImplAttributes GetMethodImplementationFlags() => MethodImplementationFlags;
public sealed override ICustomAttributeProvider ReturnTypeCustomAttributes => ReturnParameter;
// Partial trust doesn't exist in Aot so these legacy apis are meaningless. Will report everything as SecurityCritical by fiat.
public sealed override bool IsSecurityCritical => true;
public sealed override bool IsSecuritySafeCritical => false;
public sealed override bool IsSecurityTransparent => false;
}
}
namespace System.Reflection.Runtime.PropertyInfos
{
internal abstract partial class RuntimePropertyInfo
{
public sealed override MethodInfo GetGetMethod(bool nonPublic) => Getter?.FilterAccessor(nonPublic);
public sealed override MethodInfo GetSetMethod(bool nonPublic) => Setter?.FilterAccessor(nonPublic);
public sealed override MethodInfo[] GetAccessors(bool nonPublic)
{
MethodInfo getter = GetGetMethod(nonPublic);
MethodInfo setter = GetSetMethod(nonPublic);
int count = 0;
if (getter != null)
count++;
if (setter != null)
count++;
MethodInfo[] accessors = new MethodInfo[count];
int index = 0;
if (getter != null)
accessors[index++] = getter;
if (setter != null)
accessors[index++] = setter;
return accessors;
}
}
}
namespace System.Reflection.Runtime.TypeInfos
{
internal abstract partial class RuntimeTypeInfo
{
public sealed override Type[] GetGenericArguments()
{
if (IsConstructedGenericType)
return GenericTypeArguments;
if (IsGenericTypeDefinition)
return GenericTypeParameters;
return Array.Empty<Type>();
}
public sealed override bool IsGenericType => IsConstructedGenericType || IsGenericTypeDefinition;
public sealed override Type[] GetInterfaces() => ImplementedInterfaces.ToArray();
public sealed override string GetEnumName(object value) => Enum.GetName(this, value);
public sealed override string[] GetEnumNames() => Enum.GetNames(this);
public sealed override Type GetEnumUnderlyingType() => Enum.GetUnderlyingType(this);
public sealed override Array GetEnumValues() => Enum.GetValues(this);
public sealed override bool IsEnumDefined(object value) => Enum.IsDefined(this, value);
// Partial trust doesn't exist in Aot so these legacy apis are meaningless. Will report everything as SecurityCritical by fiat.
public sealed override bool IsSecurityCritical => true;
public sealed override bool IsSecuritySafeCritical => false;
public sealed override bool IsSecurityTransparent => false;
public sealed override Type GetInterface(string name, bool ignoreCase)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
string simpleName;
string ns;
SplitTypeName(name, out simpleName, out ns);
Type match = null;
foreach (Type ifc in ImplementedInterfaces)
{
string ifcSimpleName = ifc.Name;
bool simpleNameMatches = ignoreCase
? (0 == CultureInfo.InvariantCulture.CompareInfo.Compare(simpleName, ifcSimpleName, CompareOptions.IgnoreCase)) // @todo: This could be expressed simpler but the necessary parts of String api not yet ported.
: simpleName.Equals(ifcSimpleName);
if (!simpleNameMatches)
continue;
// This check exists for desktop compat:
// (1) caller can optionally omit namespace part of name in pattern- we'll still match.
// (2) ignoreCase:true does not apply to the namespace portion.
if (ns != null && !ns.Equals(ifc.Namespace))
continue;
if (match != null)
throw new AmbiguousMatchException(SR.Arg_AmbiguousMatchException);
match = ifc;
}
return match;
}
private static void SplitTypeName(string fullname, out string name, out string ns)
{
Debug.Assert(fullname != null);
// Get namespace
int nsDelimiter = fullname.LastIndexOf(".", StringComparison.Ordinal);
if (nsDelimiter != -1)
{
ns = fullname.Substring(0, nsDelimiter);
int nameLength = fullname.Length - ns.Length - 1;
name = fullname.Substring(nsDelimiter + 1, nameLength);
Debug.Assert(fullname.Equals(ns + "." + name));
}
else
{
ns = null;
name = fullname;
}
}
}
}
| |
#region Copyright & License
//
// Copyright 2001-2005 The Apache Software Foundation
//
// 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;
namespace log4net.Appender
{
/// <summary>
/// A strongly-typed collection of <see cref="IAppender"/> objects.
/// </summary>
/// <author>Nicko Cadell</author>
public class AppenderCollection : ICollection, IList, IEnumerable, ICloneable
{
#region Interfaces
/// <summary>
/// Supports type-safe iteration over a <see cref="AppenderCollection"/>.
/// </summary>
/// <exclude/>
public interface IAppenderCollectionEnumerator
{
/// <summary>
/// Gets the current element in the collection.
/// </summary>
IAppender Current { get; }
/// <summary>
/// Advances the enumerator to the next element in the collection.
/// </summary>
/// <returns>
/// <c>true</c> if the enumerator was successfully advanced to the next element;
/// <c>false</c> if the enumerator has passed the end of the collection.
/// </returns>
/// <exception cref="InvalidOperationException">
/// The collection was modified after the enumerator was created.
/// </exception>
bool MoveNext();
/// <summary>
/// Sets the enumerator to its initial position, before the first element in the collection.
/// </summary>
void Reset();
}
#endregion
private const int DEFAULT_CAPACITY = 16;
#region Implementation (data)
private IAppender[] m_array;
private int m_count = 0;
private int m_version = 0;
#endregion
#region Static Wrappers
/// <summary>
/// Creates a read-only wrapper for a <c>AppenderCollection</c> instance.
/// </summary>
/// <param name="list">list to create a readonly wrapper arround</param>
/// <returns>
/// An <c>AppenderCollection</c> wrapper that is read-only.
/// </returns>
public static AppenderCollection ReadOnly(AppenderCollection list)
{
if(list==null) throw new ArgumentNullException("list");
return new ReadOnlyAppenderCollection(list);
}
#endregion
#region Static Fields
/// <summary>
/// An empty readonly static AppenderCollection
/// </summary>
public static readonly AppenderCollection EmptyCollection = ReadOnly(new AppenderCollection(0));
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <c>AppenderCollection</c> class
/// that is empty and has the default initial capacity.
/// </summary>
public AppenderCollection()
{
m_array = new IAppender[DEFAULT_CAPACITY];
}
/// <summary>
/// Initializes a new instance of the <c>AppenderCollection</c> class
/// that has the specified initial capacity.
/// </summary>
/// <param name="capacity">
/// The number of elements that the new <c>AppenderCollection</c> is initially capable of storing.
/// </param>
public AppenderCollection(int capacity)
{
m_array = new IAppender[capacity];
}
/// <summary>
/// Initializes a new instance of the <c>AppenderCollection</c> class
/// that contains elements copied from the specified <c>AppenderCollection</c>.
/// </summary>
/// <param name="c">The <c>AppenderCollection</c> whose elements are copied to the new collection.</param>
public AppenderCollection(AppenderCollection c)
{
m_array = new IAppender[c.Count];
AddRange(c);
}
/// <summary>
/// Initializes a new instance of the <c>AppenderCollection</c> class
/// that contains elements copied from the specified <see cref="IAppender"/> array.
/// </summary>
/// <param name="a">The <see cref="IAppender"/> array whose elements are copied to the new list.</param>
public AppenderCollection(IAppender[] a)
{
m_array = new IAppender[a.Length];
AddRange(a);
}
/// <summary>
/// Initializes a new instance of the <c>AppenderCollection</c> class
/// that contains elements copied from the specified <see cref="IAppender"/> collection.
/// </summary>
/// <param name="col">The <see cref="IAppender"/> collection whose elements are copied to the new list.</param>
public AppenderCollection(ICollection col)
{
m_array = new IAppender[col.Count];
AddRange(col);
}
/// <summary>
/// Type visible only to our subclasses
/// Used to access protected constructor
/// </summary>
/// <exclude/>
internal protected enum Tag
{
/// <summary>
/// A value
/// </summary>
Default
}
/// <summary>
/// Allow subclasses to avoid our default constructors
/// </summary>
/// <param name="tag"></param>
/// <exclude/>
internal protected AppenderCollection(Tag tag)
{
m_array = null;
}
#endregion
#region Operations (type-safe ICollection)
/// <summary>
/// Gets the number of elements actually contained in the <c>AppenderCollection</c>.
/// </summary>
public virtual int Count
{
get { return m_count; }
}
/// <summary>
/// Copies the entire <c>AppenderCollection</c> to a one-dimensional
/// <see cref="IAppender"/> array.
/// </summary>
/// <param name="array">The one-dimensional <see cref="IAppender"/> array to copy to.</param>
public virtual void CopyTo(IAppender[] array)
{
this.CopyTo(array, 0);
}
/// <summary>
/// Copies the entire <c>AppenderCollection</c> to a one-dimensional
/// <see cref="IAppender"/> array, starting at the specified index of the target array.
/// </summary>
/// <param name="array">The one-dimensional <see cref="IAppender"/> array to copy to.</param>
/// <param name="start">The zero-based index in <paramref name="array"/> at which copying begins.</param>
public virtual void CopyTo(IAppender[] array, int start)
{
if (m_count > array.GetUpperBound(0) + 1 - start)
{
throw new System.ArgumentException("Destination array was not long enough.");
}
Array.Copy(m_array, 0, array, start, m_count);
}
/// <summary>
/// Gets a value indicating whether access to the collection is synchronized (thread-safe).
/// </summary>
/// <returns>true if access to the ICollection is synchronized (thread-safe); otherwise, false.</returns>
public virtual bool IsSynchronized
{
get { return m_array.IsSynchronized; }
}
/// <summary>
/// Gets an object that can be used to synchronize access to the collection.
/// </summary>
public virtual object SyncRoot
{
get { return m_array.SyncRoot; }
}
#endregion
#region Operations (type-safe IList)
/// <summary>
/// Gets or sets the <see cref="IAppender"/> at the specified index.
/// </summary>
/// <param name="index">The zero-based index of the element to get or set.</param>
/// <exception cref="ArgumentOutOfRangeException">
/// <para><paramref name="index"/> is less than zero</para>
/// <para>-or-</para>
/// <para><paramref name="index"/> is equal to or greater than <see cref="AppenderCollection.Count"/>.</para>
/// </exception>
public virtual IAppender this[int index]
{
get
{
ValidateIndex(index); // throws
return m_array[index];
}
set
{
ValidateIndex(index); // throws
++m_version;
m_array[index] = value;
}
}
/// <summary>
/// Adds a <see cref="IAppender"/> to the end of the <c>AppenderCollection</c>.
/// </summary>
/// <param name="item">The <see cref="IAppender"/> to be added to the end of the <c>AppenderCollection</c>.</param>
/// <returns>The index at which the value has been added.</returns>
public virtual int Add(IAppender item)
{
if (m_count == m_array.Length)
{
EnsureCapacity(m_count + 1);
}
m_array[m_count] = item;
m_version++;
return m_count++;
}
/// <summary>
/// Removes all elements from the <c>AppenderCollection</c>.
/// </summary>
public virtual void Clear()
{
++m_version;
m_array = new IAppender[DEFAULT_CAPACITY];
m_count = 0;
}
/// <summary>
/// Creates a shallow copy of the <see cref="AppenderCollection"/>.
/// </summary>
/// <returns>A new <see cref="AppenderCollection"/> with a shallow copy of the collection data.</returns>
public virtual object Clone()
{
AppenderCollection newCol = new AppenderCollection(m_count);
Array.Copy(m_array, 0, newCol.m_array, 0, m_count);
newCol.m_count = m_count;
newCol.m_version = m_version;
return newCol;
}
/// <summary>
/// Determines whether a given <see cref="IAppender"/> is in the <c>AppenderCollection</c>.
/// </summary>
/// <param name="item">The <see cref="IAppender"/> to check for.</param>
/// <returns><c>true</c> if <paramref name="item"/> is found in the <c>AppenderCollection</c>; otherwise, <c>false</c>.</returns>
public virtual bool Contains(IAppender item)
{
for (int i=0; i != m_count; ++i)
{
if (m_array[i].Equals(item))
{
return true;
}
}
return false;
}
/// <summary>
/// Returns the zero-based index of the first occurrence of a <see cref="IAppender"/>
/// in the <c>AppenderCollection</c>.
/// </summary>
/// <param name="item">The <see cref="IAppender"/> to locate in the <c>AppenderCollection</c>.</param>
/// <returns>
/// The zero-based index of the first occurrence of <paramref name="item"/>
/// in the entire <c>AppenderCollection</c>, if found; otherwise, -1.
/// </returns>
public virtual int IndexOf(IAppender item)
{
for (int i=0; i != m_count; ++i)
{
if (m_array[i].Equals(item))
{
return i;
}
}
return -1;
}
/// <summary>
/// Inserts an element into the <c>AppenderCollection</c> at the specified index.
/// </summary>
/// <param name="index">The zero-based index at which <paramref name="item"/> should be inserted.</param>
/// <param name="item">The <see cref="IAppender"/> to insert.</param>
/// <exception cref="ArgumentOutOfRangeException">
/// <para><paramref name="index"/> is less than zero</para>
/// <para>-or-</para>
/// <para><paramref name="index"/> is equal to or greater than <see cref="AppenderCollection.Count"/>.</para>
/// </exception>
public virtual void Insert(int index, IAppender item)
{
ValidateIndex(index, true); // throws
if (m_count == m_array.Length)
{
EnsureCapacity(m_count + 1);
}
if (index < m_count)
{
Array.Copy(m_array, index, m_array, index + 1, m_count - index);
}
m_array[index] = item;
m_count++;
m_version++;
}
/// <summary>
/// Removes the first occurrence of a specific <see cref="IAppender"/> from the <c>AppenderCollection</c>.
/// </summary>
/// <param name="item">The <see cref="IAppender"/> to remove from the <c>AppenderCollection</c>.</param>
/// <exception cref="ArgumentException">
/// The specified <see cref="IAppender"/> was not found in the <c>AppenderCollection</c>.
/// </exception>
public virtual void Remove(IAppender item)
{
int i = IndexOf(item);
if (i < 0)
{
throw new System.ArgumentException("Cannot remove the specified item because it was not found in the specified Collection.");
}
++m_version;
RemoveAt(i);
}
/// <summary>
/// Removes the element at the specified index of the <c>AppenderCollection</c>.
/// </summary>
/// <param name="index">The zero-based index of the element to remove.</param>
/// <exception cref="ArgumentOutOfRangeException">
/// <para><paramref name="index"/> is less than zero</para>
/// <para>-or-</para>
/// <para><paramref name="index"/> is equal to or greater than <see cref="AppenderCollection.Count"/>.</para>
/// </exception>
public virtual void RemoveAt(int index)
{
ValidateIndex(index); // throws
m_count--;
if (index < m_count)
{
Array.Copy(m_array, index + 1, m_array, index, m_count - index);
}
// We can't set the deleted entry equal to null, because it might be a value type.
// Instead, we'll create an empty single-element array of the right type and copy it
// over the entry we want to erase.
IAppender[] temp = new IAppender[1];
Array.Copy(temp, 0, m_array, m_count, 1);
m_version++;
}
/// <summary>
/// Gets a value indicating whether the collection has a fixed size.
/// </summary>
/// <value>true if the collection has a fixed size; otherwise, false. The default is false</value>
public virtual bool IsFixedSize
{
get { return false; }
}
/// <summary>
/// Gets a value indicating whether the IList is read-only.
/// </summary>
/// <value>true if the collection is read-only; otherwise, false. The default is false</value>
public virtual bool IsReadOnly
{
get { return false; }
}
#endregion
#region Operations (type-safe IEnumerable)
/// <summary>
/// Returns an enumerator that can iterate through the <c>AppenderCollection</c>.
/// </summary>
/// <returns>An <see cref="Enumerator"/> for the entire <c>AppenderCollection</c>.</returns>
public virtual IAppenderCollectionEnumerator GetEnumerator()
{
return new Enumerator(this);
}
#endregion
#region Public helpers (just to mimic some nice features of ArrayList)
/// <summary>
/// Gets or sets the number of elements the <c>AppenderCollection</c> can contain.
/// </summary>
public virtual int Capacity
{
get
{
return m_array.Length;
}
set
{
if (value < m_count)
{
value = m_count;
}
if (value != m_array.Length)
{
if (value > 0)
{
IAppender[] temp = new IAppender[value];
Array.Copy(m_array, 0, temp, 0, m_count);
m_array = temp;
}
else
{
m_array = new IAppender[DEFAULT_CAPACITY];
}
}
}
}
/// <summary>
/// Adds the elements of another <c>AppenderCollection</c> to the current <c>AppenderCollection</c>.
/// </summary>
/// <param name="x">The <c>AppenderCollection</c> whose elements should be added to the end of the current <c>AppenderCollection</c>.</param>
/// <returns>The new <see cref="AppenderCollection.Count"/> of the <c>AppenderCollection</c>.</returns>
public virtual int AddRange(AppenderCollection x)
{
if (m_count + x.Count >= m_array.Length)
{
EnsureCapacity(m_count + x.Count);
}
Array.Copy(x.m_array, 0, m_array, m_count, x.Count);
m_count += x.Count;
m_version++;
return m_count;
}
/// <summary>
/// Adds the elements of a <see cref="IAppender"/> array to the current <c>AppenderCollection</c>.
/// </summary>
/// <param name="x">The <see cref="IAppender"/> array whose elements should be added to the end of the <c>AppenderCollection</c>.</param>
/// <returns>The new <see cref="AppenderCollection.Count"/> of the <c>AppenderCollection</c>.</returns>
public virtual int AddRange(IAppender[] x)
{
if (m_count + x.Length >= m_array.Length)
{
EnsureCapacity(m_count + x.Length);
}
Array.Copy(x, 0, m_array, m_count, x.Length);
m_count += x.Length;
m_version++;
return m_count;
}
/// <summary>
/// Adds the elements of a <see cref="IAppender"/> collection to the current <c>AppenderCollection</c>.
/// </summary>
/// <param name="col">The <see cref="IAppender"/> collection whose elements should be added to the end of the <c>AppenderCollection</c>.</param>
/// <returns>The new <see cref="AppenderCollection.Count"/> of the <c>AppenderCollection</c>.</returns>
public virtual int AddRange(ICollection col)
{
if (m_count + col.Count >= m_array.Length)
{
EnsureCapacity(m_count + col.Count);
}
foreach(object item in col)
{
Add((IAppender)item);
}
return m_count;
}
/// <summary>
/// Sets the capacity to the actual number of elements.
/// </summary>
public virtual void TrimToSize()
{
this.Capacity = m_count;
}
/// <summary>
/// Return the collection elements as an array
/// </summary>
/// <returns>the array</returns>
public virtual IAppender[] ToArray()
{
IAppender[] resultArray = new IAppender[m_count];
if (m_count > 0)
{
Array.Copy(m_array, 0, resultArray, 0, m_count);
}
return resultArray;
}
#endregion
#region Implementation (helpers)
/// <exception cref="ArgumentOutOfRangeException">
/// <para><paramref name="index"/> is less than zero</para>
/// <para>-or-</para>
/// <para><paramref name="index"/> is equal to or greater than <see cref="AppenderCollection.Count"/>.</para>
/// </exception>
private void ValidateIndex(int i)
{
ValidateIndex(i, false);
}
/// <exception cref="ArgumentOutOfRangeException">
/// <para><paramref name="index"/> is less than zero</para>
/// <para>-or-</para>
/// <para><paramref name="index"/> is equal to or greater than <see cref="AppenderCollection.Count"/>.</para>
/// </exception>
private void ValidateIndex(int i, bool allowEqualEnd)
{
int max = (allowEqualEnd) ? (m_count) : (m_count-1);
if (i < 0 || i > max)
{
throw log4net.Util.SystemInfo.CreateArgumentOutOfRangeException("i", (object)i, "Index was out of range. Must be non-negative and less than the size of the collection. [" + (object)i + "] Specified argument was out of the range of valid values.");
}
}
private void EnsureCapacity(int min)
{
int newCapacity = ((m_array.Length == 0) ? DEFAULT_CAPACITY : m_array.Length * 2);
if (newCapacity < min)
{
newCapacity = min;
}
this.Capacity = newCapacity;
}
#endregion
#region Implementation (ICollection)
void ICollection.CopyTo(Array array, int start)
{
if (m_count > 0)
{
Array.Copy(m_array, 0, array, start, m_count);
}
}
#endregion
#region Implementation (IList)
object IList.this[int i]
{
get { return (object)this[i]; }
set { this[i] = (IAppender)value; }
}
int IList.Add(object x)
{
return this.Add((IAppender)x);
}
bool IList.Contains(object x)
{
return this.Contains((IAppender)x);
}
int IList.IndexOf(object x)
{
return this.IndexOf((IAppender)x);
}
void IList.Insert(int pos, object x)
{
this.Insert(pos, (IAppender)x);
}
void IList.Remove(object x)
{
this.Remove((IAppender)x);
}
void IList.RemoveAt(int pos)
{
this.RemoveAt(pos);
}
#endregion
#region Implementation (IEnumerable)
IEnumerator IEnumerable.GetEnumerator()
{
return (IEnumerator)(this.GetEnumerator());
}
#endregion
#region Nested enumerator class
/// <summary>
/// Supports simple iteration over a <see cref="AppenderCollection"/>.
/// </summary>
/// <exclude/>
private sealed class Enumerator : IEnumerator, IAppenderCollectionEnumerator
{
#region Implementation (data)
private readonly AppenderCollection m_collection;
private int m_index;
private int m_version;
#endregion
#region Construction
/// <summary>
/// Initializes a new instance of the <c>Enumerator</c> class.
/// </summary>
/// <param name="tc"></param>
internal Enumerator(AppenderCollection tc)
{
m_collection = tc;
m_index = -1;
m_version = tc.m_version;
}
#endregion
#region Operations (type-safe IEnumerator)
/// <summary>
/// Gets the current element in the collection.
/// </summary>
public IAppender Current
{
get { return m_collection[m_index]; }
}
/// <summary>
/// Advances the enumerator to the next element in the collection.
/// </summary>
/// <returns>
/// <c>true</c> if the enumerator was successfully advanced to the next element;
/// <c>false</c> if the enumerator has passed the end of the collection.
/// </returns>
/// <exception cref="InvalidOperationException">
/// The collection was modified after the enumerator was created.
/// </exception>
public bool MoveNext()
{
if (m_version != m_collection.m_version)
{
throw new System.InvalidOperationException("Collection was modified; enumeration operation may not execute.");
}
++m_index;
return (m_index < m_collection.Count);
}
/// <summary>
/// Sets the enumerator to its initial position, before the first element in the collection.
/// </summary>
public void Reset()
{
m_index = -1;
}
#endregion
#region Implementation (IEnumerator)
object IEnumerator.Current
{
get { return this.Current; }
}
#endregion
}
#endregion
#region Nested Read Only Wrapper class
/// <exclude/>
private sealed class ReadOnlyAppenderCollection : AppenderCollection, ICollection
{
#region Implementation (data)
private readonly AppenderCollection m_collection;
#endregion
#region Construction
internal ReadOnlyAppenderCollection(AppenderCollection list) : base(Tag.Default)
{
m_collection = list;
}
#endregion
#region Type-safe ICollection
public override void CopyTo(IAppender[] array)
{
m_collection.CopyTo(array);
}
public override void CopyTo(IAppender[] array, int start)
{
m_collection.CopyTo(array,start);
}
void ICollection.CopyTo(Array array, int start)
{
((ICollection)m_collection).CopyTo(array, start);
}
public override int Count
{
get { return m_collection.Count; }
}
public override bool IsSynchronized
{
get { return m_collection.IsSynchronized; }
}
public override object SyncRoot
{
get { return this.m_collection.SyncRoot; }
}
#endregion
#region Type-safe IList
public override IAppender this[int i]
{
get { return m_collection[i]; }
set { throw new NotSupportedException("This is a Read Only Collection and can not be modified"); }
}
public override int Add(IAppender x)
{
throw new NotSupportedException("This is a Read Only Collection and can not be modified");
}
public override void Clear()
{
throw new NotSupportedException("This is a Read Only Collection and can not be modified");
}
public override bool Contains(IAppender x)
{
return m_collection.Contains(x);
}
public override int IndexOf(IAppender x)
{
return m_collection.IndexOf(x);
}
public override void Insert(int pos, IAppender x)
{
throw new NotSupportedException("This is a Read Only Collection and can not be modified");
}
public override void Remove(IAppender x)
{
throw new NotSupportedException("This is a Read Only Collection and can not be modified");
}
public override void RemoveAt(int pos)
{
throw new NotSupportedException("This is a Read Only Collection and can not be modified");
}
public override bool IsFixedSize
{
get { return true; }
}
public override bool IsReadOnly
{
get { return true; }
}
#endregion
#region Type-safe IEnumerable
public override IAppenderCollectionEnumerator GetEnumerator()
{
return m_collection.GetEnumerator();
}
#endregion
#region Public Helpers
// (just to mimic some nice features of ArrayList)
public override int Capacity
{
get { return m_collection.Capacity; }
set { throw new NotSupportedException("This is a Read Only Collection and can not be modified"); }
}
public override int AddRange(AppenderCollection x)
{
throw new NotSupportedException("This is a Read Only Collection and can not be modified");
}
public override int AddRange(IAppender[] x)
{
throw new NotSupportedException("This is a Read Only Collection and can not be modified");
}
#endregion
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Globalization;
using System.Runtime.InteropServices;
using Xunit;
namespace System.Numerics.Tests
{
public class Vector2Tests
{
[Fact]
public void Vector2MarshalSizeTest()
{
Assert.Equal(8, Marshal.SizeOf<Vector2>());
Assert.Equal(8, Marshal.SizeOf<Vector2>(new Vector2()));
}
[Fact]
public void Vector2CopyToTest()
{
Vector2 v1 = new Vector2(2.0f, 3.0f);
float[] a = new float[3];
float[] b = new float[2];
Assert.Throws<ArgumentNullException>(() => v1.CopyTo(null, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => v1.CopyTo(a, -1));
Assert.Throws<ArgumentOutOfRangeException>(() => v1.CopyTo(a, a.Length));
Assert.Throws<ArgumentException>(() => v1.CopyTo(a, 2));
v1.CopyTo(a, 1);
v1.CopyTo(b);
Assert.Equal(0.0, a[0]);
Assert.Equal(2.0, a[1]);
Assert.Equal(3.0, a[2]);
Assert.Equal(2.0, b[0]);
Assert.Equal(3.0, b[1]);
}
[Fact]
public void Vector2GetHashCodeTest()
{
Vector2 v1 = new Vector2(2.0f, 3.0f);
Vector2 v3 = new Vector2(2.0f, 3.0f);
Vector2 v5 = new Vector2(3.0f, 2.0f);
Assert.True(v1.GetHashCode() == v1.GetHashCode());
Assert.False(v1.GetHashCode() == v5.GetHashCode());
Assert.True(v1.GetHashCode() == v3.GetHashCode());
Vector2 v4 = new Vector2(0.0f, 0.0f);
Vector2 v6 = new Vector2(1.0f, 0.0f);
Vector2 v7 = new Vector2(0.0f, 1.0f);
Vector2 v8 = new Vector2(1.0f, 1.0f);
Assert.False(v4.GetHashCode() == v6.GetHashCode());
Assert.False(v4.GetHashCode() == v7.GetHashCode());
Assert.False(v4.GetHashCode() == v8.GetHashCode());
Assert.False(v7.GetHashCode() == v6.GetHashCode());
Assert.False(v8.GetHashCode() == v6.GetHashCode());
Assert.False(v8.GetHashCode() == v7.GetHashCode());
}
[Fact]
public void Vector2ToStringTest()
{
string separator = CultureInfo.CurrentCulture.NumberFormat.NumberGroupSeparator;
CultureInfo enUsCultureInfo = new CultureInfo("en-US");
Vector2 v1 = new Vector2(2.0f, 3.0f);
string v1str = v1.ToString();
string expectedv1 = string.Format(CultureInfo.CurrentCulture
, "<{1:G}{0} {2:G}>"
, new object[] { separator, 2, 3 });
Assert.Equal(expectedv1, v1str);
string v1strformatted = v1.ToString("c", CultureInfo.CurrentCulture);
string expectedv1formatted = string.Format(CultureInfo.CurrentCulture
, "<{1:c}{0} {2:c}>"
, new object[] { separator, 2, 3 });
Assert.Equal(expectedv1formatted, v1strformatted);
string v2strformatted = v1.ToString("c", enUsCultureInfo);
string expectedv2formatted = string.Format(enUsCultureInfo
, "<{1:c}{0} {2:c}>"
, new object[] { enUsCultureInfo.NumberFormat.NumberGroupSeparator, 2, 3 });
Assert.Equal(expectedv2formatted, v2strformatted);
string v3strformatted = v1.ToString("c");
string expectedv3formatted = string.Format(CultureInfo.CurrentCulture
, "<{1:c}{0} {2:c}>"
, new object[] { separator, 2, 3 });
Assert.Equal(expectedv3formatted, v3strformatted);
}
// A test for Distance (Vector2f, Vector2f)
[Fact]
public void Vector2DistanceTest()
{
Vector2 a = new Vector2(1.0f, 2.0f);
Vector2 b = new Vector2(3.0f, 4.0f);
float expected = (float)System.Math.Sqrt(8);
float actual;
actual = Vector2.Distance(a, b);
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Distance did not return the expected value.");
}
// A test for Distance (Vector2f, Vector2f)
// Distance from the same point
[Fact]
public void Vector2DistanceTest2()
{
Vector2 a = new Vector2(1.051f, 2.05f);
Vector2 b = new Vector2(1.051f, 2.05f);
float actual = Vector2.Distance(a, b);
Assert.Equal(0.0f, actual);
}
// A test for DistanceSquared (Vector2f, Vector2f)
[Fact]
public void Vector2DistanceSquaredTest()
{
Vector2 a = new Vector2(1.0f, 2.0f);
Vector2 b = new Vector2(3.0f, 4.0f);
float expected = 8.0f;
float actual;
actual = Vector2.DistanceSquared(a, b);
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.DistanceSquared did not return the expected value.");
}
// A test for Dot (Vector2f, Vector2f)
[Fact]
public void Vector2DotTest()
{
Vector2 a = new Vector2(1.0f, 2.0f);
Vector2 b = new Vector2(3.0f, 4.0f);
float expected = 11.0f;
float actual;
actual = Vector2.Dot(a, b);
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Dot did not return the expected value.");
}
// A test for Dot (Vector2f, Vector2f)
// Dot test for perpendicular vector
[Fact]
public void Vector2DotTest1()
{
Vector2 a = new Vector2(1.55f, 1.55f);
Vector2 b = new Vector2(-1.55f, 1.55f);
float expected = 0.0f;
float actual = Vector2.Dot(a, b);
Assert.Equal(expected, actual);
}
// A test for Dot (Vector2f, Vector2f)
// Dot test with specail float values
[Fact]
public void Vector2DotTest2()
{
Vector2 a = new Vector2(float.MinValue, float.MinValue);
Vector2 b = new Vector2(float.MaxValue, float.MaxValue);
float actual = Vector2.Dot(a, b);
Assert.True(float.IsNegativeInfinity(actual), "Vector2f.Dot did not return the expected value.");
}
// A test for Length ()
[Fact]
public void Vector2LengthTest()
{
Vector2 a = new Vector2(2.0f, 4.0f);
Vector2 target = a;
float expected = (float)System.Math.Sqrt(20);
float actual;
actual = target.Length();
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Length did not return the expected value.");
}
// A test for Length ()
// Length test where length is zero
[Fact]
public void Vector2LengthTest1()
{
Vector2 target = new Vector2();
target.X = 0.0f;
target.Y = 0.0f;
float expected = 0.0f;
float actual;
actual = target.Length();
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Length did not return the expected value.");
}
// A test for LengthSquared ()
[Fact]
public void Vector2LengthSquaredTest()
{
Vector2 a = new Vector2(2.0f, 4.0f);
Vector2 target = a;
float expected = 20.0f;
float actual;
actual = target.LengthSquared();
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.LengthSquared did not return the expected value.");
}
// A test for LengthSquared ()
// LengthSquared test where the result is zero
[Fact]
public void Vector2LengthSquaredTest1()
{
Vector2 a = new Vector2(0.0f, 0.0f);
float expected = 0.0f;
float actual = a.LengthSquared();
Assert.Equal(expected, actual);
}
// A test for Min (Vector2f, Vector2f)
[Fact]
public void Vector2MinTest()
{
Vector2 a = new Vector2(-1.0f, 4.0f);
Vector2 b = new Vector2(2.0f, 1.0f);
Vector2 expected = new Vector2(-1.0f, 1.0f);
Vector2 actual;
actual = Vector2.Min(a, b);
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Min did not return the expected value.");
}
[Fact]
public void Vector2MinMaxCodeCoverageTest()
{
Vector2 min = new Vector2(0, 0);
Vector2 max = new Vector2(1, 1);
Vector2 actual;
// Min.
actual = Vector2.Min(min, max);
Assert.Equal(actual, min);
actual = Vector2.Min(max, min);
Assert.Equal(actual, min);
// Max.
actual = Vector2.Max(min, max);
Assert.Equal(actual, max);
actual = Vector2.Max(max, min);
Assert.Equal(actual, max);
}
// A test for Max (Vector2f, Vector2f)
[Fact]
public void Vector2MaxTest()
{
Vector2 a = new Vector2(-1.0f, 4.0f);
Vector2 b = new Vector2(2.0f, 1.0f);
Vector2 expected = new Vector2(2.0f, 4.0f);
Vector2 actual;
actual = Vector2.Max(a, b);
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Max did not return the expected value.");
}
// A test for Clamp (Vector2f, Vector2f, Vector2f)
[Fact]
public void Vector2ClampTest()
{
Vector2 a = new Vector2(0.5f, 0.3f);
Vector2 min = new Vector2(0.0f, 0.1f);
Vector2 max = new Vector2(1.0f, 1.1f);
// Normal case.
// Case N1: specified value is in the range.
Vector2 expected = new Vector2(0.5f, 0.3f);
Vector2 actual = Vector2.Clamp(a, min, max);
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Clamp did not return the expected value.");
// Normal case.
// Case N2: specified value is bigger than max value.
a = new Vector2(2.0f, 3.0f);
expected = max;
actual = Vector2.Clamp(a, min, max);
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Clamp did not return the expected value.");
// Case N3: specified value is smaller than max value.
a = new Vector2(-1.0f, -2.0f);
expected = min;
actual = Vector2.Clamp(a, min, max);
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Clamp did not return the expected value.");
// Case N4: combination case.
a = new Vector2(-2.0f, 4.0f);
expected = new Vector2(min.X, max.Y);
actual = Vector2.Clamp(a, min, max);
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Clamp did not return the expected value.");
// User specified min value is bigger than max value.
max = new Vector2(0.0f, 0.1f);
min = new Vector2(1.0f, 1.1f);
// Case W1: specified value is in the range.
a = new Vector2(0.5f, 0.3f);
expected = min;
actual = Vector2.Clamp(a, min, max);
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Clamp did not return the expected value.");
// Normal case.
// Case W2: specified value is bigger than max and min value.
a = new Vector2(2.0f, 3.0f);
expected = min;
actual = Vector2.Clamp(a, min, max);
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Clamp did not return the expected value.");
// Case W3: specified value is smaller than min and max value.
a = new Vector2(-1.0f, -2.0f);
expected = min;
actual = Vector2.Clamp(a, min, max);
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Clamp did not return the expected value.");
}
// A test for Lerp (Vector2f, Vector2f, float)
[Fact]
public void Vector2LerpTest()
{
Vector2 a = new Vector2(1.0f, 2.0f);
Vector2 b = new Vector2(3.0f, 4.0f);
float t = 0.5f;
Vector2 expected = new Vector2(2.0f, 3.0f);
Vector2 actual;
actual = Vector2.Lerp(a, b, t);
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Lerp did not return the expected value.");
}
// A test for Lerp (Vector2f, Vector2f, float)
// Lerp test with factor zero
[Fact]
public void Vector2LerpTest1()
{
Vector2 a = new Vector2(0.0f, 0.0f);
Vector2 b = new Vector2(3.18f, 4.25f);
float t = 0.0f;
Vector2 expected = Vector2.Zero;
Vector2 actual = Vector2.Lerp(a, b, t);
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Lerp did not return the expected value.");
}
// A test for Lerp (Vector2f, Vector2f, float)
// Lerp test with factor one
[Fact]
public void Vector2LerpTest2()
{
Vector2 a = new Vector2(0.0f, 0.0f);
Vector2 b = new Vector2(3.18f, 4.25f);
float t = 1.0f;
Vector2 expected = new Vector2(3.18f, 4.25f);
Vector2 actual = Vector2.Lerp(a, b, t);
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Lerp did not return the expected value.");
}
// A test for Lerp (Vector2f, Vector2f, float)
// Lerp test with factor > 1
[Fact]
public void Vector2LerpTest3()
{
Vector2 a = new Vector2(0.0f, 0.0f);
Vector2 b = new Vector2(3.18f, 4.25f);
float t = 2.0f;
Vector2 expected = b * 2.0f;
Vector2 actual = Vector2.Lerp(a, b, t);
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Lerp did not return the expected value.");
}
// A test for Lerp (Vector2f, Vector2f, float)
// Lerp test with factor < 0
[Fact]
public void Vector2LerpTest4()
{
Vector2 a = new Vector2(0.0f, 0.0f);
Vector2 b = new Vector2(3.18f, 4.25f);
float t = -2.0f;
Vector2 expected = -(b * 2.0f);
Vector2 actual = Vector2.Lerp(a, b, t);
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Lerp did not return the expected value.");
}
// A test for Lerp (Vector2f, Vector2f, float)
// Lerp test with special float value
[Fact]
public void Vector2LerpTest5()
{
Vector2 a = new Vector2(45.67f, 90.0f);
Vector2 b = new Vector2(float.PositiveInfinity, float.NegativeInfinity);
float t = 0.408f;
Vector2 actual = Vector2.Lerp(a, b, t);
Assert.True(float.IsPositiveInfinity(actual.X), "Vector2f.Lerp did not return the expected value.");
Assert.True(float.IsNegativeInfinity(actual.Y), "Vector2f.Lerp did not return the expected value.");
}
// A test for Lerp (Vector2f, Vector2f, float)
// Lerp test from the same point
[Fact]
public void Vector2LerpTest6()
{
Vector2 a = new Vector2(1.0f, 2.0f);
Vector2 b = new Vector2(1.0f, 2.0f);
float t = 0.5f;
Vector2 expected = new Vector2(1.0f, 2.0f);
Vector2 actual = Vector2.Lerp(a, b, t);
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Lerp did not return the expected value.");
}
// A test for Transform(Vector2f, Matrix4x4)
[Fact]
public void Vector2TransformTest()
{
Vector2 v = new Vector2(1.0f, 2.0f);
Matrix4x4 m =
Matrix4x4.CreateRotationX(MathHelper.ToRadians(30.0f)) *
Matrix4x4.CreateRotationY(MathHelper.ToRadians(30.0f)) *
Matrix4x4.CreateRotationZ(MathHelper.ToRadians(30.0f));
m.M41 = 10.0f;
m.M42 = 20.0f;
m.M43 = 30.0f;
Vector2 expected = new Vector2(10.316987f, 22.183012f);
Vector2 actual;
actual = Vector2.Transform(v, m);
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Transform did not return the expected value.");
}
// A test for Transform(Vector2f, Matrix3x2)
[Fact]
public void Vector2Transform3x2Test()
{
Vector2 v = new Vector2(1.0f, 2.0f);
Matrix3x2 m = Matrix3x2.CreateRotation(MathHelper.ToRadians(30.0f));
m.M31 = 10.0f;
m.M32 = 20.0f;
Vector2 expected = new Vector2(9.866025f, 22.23205f);
Vector2 actual;
actual = Vector2.Transform(v, m);
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Transform did not return the expected value.");
}
// A test for TransformNormal (Vector2f, Matrix4x4)
[Fact]
public void Vector2TransformNormalTest()
{
Vector2 v = new Vector2(1.0f, 2.0f);
Matrix4x4 m =
Matrix4x4.CreateRotationX(MathHelper.ToRadians(30.0f)) *
Matrix4x4.CreateRotationY(MathHelper.ToRadians(30.0f)) *
Matrix4x4.CreateRotationZ(MathHelper.ToRadians(30.0f));
m.M41 = 10.0f;
m.M42 = 20.0f;
m.M43 = 30.0f;
Vector2 expected = new Vector2(0.3169873f, 2.18301272f);
Vector2 actual;
actual = Vector2.TransformNormal(v, m);
Assert.Equal(expected, actual);
}
// A test for TransformNormal (Vector2f, Matrix3x2)
[Fact]
public void Vector2TransformNormal3x2Test()
{
Vector2 v = new Vector2(1.0f, 2.0f);
Matrix3x2 m = Matrix3x2.CreateRotation(MathHelper.ToRadians(30.0f));
m.M31 = 10.0f;
m.M32 = 20.0f;
Vector2 expected = new Vector2(-0.133974612f, 2.232051f);
Vector2 actual;
actual = Vector2.TransformNormal(v, m);
Assert.Equal(expected, actual);
}
// A test for Transform (Vector2f, Quaternion)
[Fact]
public void Vector2TransformByQuaternionTest()
{
Vector2 v = new Vector2(1.0f, 2.0f);
Matrix4x4 m =
Matrix4x4.CreateRotationX(MathHelper.ToRadians(30.0f)) *
Matrix4x4.CreateRotationY(MathHelper.ToRadians(30.0f)) *
Matrix4x4.CreateRotationZ(MathHelper.ToRadians(30.0f));
Quaternion q = Quaternion.CreateFromRotationMatrix(m);
Vector2 expected = Vector2.Transform(v, m);
Vector2 actual = Vector2.Transform(v, q);
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Transform did not return the expected value.");
}
// A test for Transform (Vector2f, Quaternion)
// Transform Vector2f with zero quaternion
[Fact]
public void Vector2TransformByQuaternionTest1()
{
Vector2 v = new Vector2(1.0f, 2.0f);
Quaternion q = new Quaternion();
Vector2 expected = v;
Vector2 actual = Vector2.Transform(v, q);
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Transform did not return the expected value.");
}
// A test for Transform (Vector2f, Quaternion)
// Transform Vector2f with identity quaternion
[Fact]
public void Vector2TransformByQuaternionTest2()
{
Vector2 v = new Vector2(1.0f, 2.0f);
Quaternion q = Quaternion.Identity;
Vector2 expected = v;
Vector2 actual = Vector2.Transform(v, q);
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Transform did not return the expected value.");
}
// A test for Normalize (Vector2f)
[Fact]
public void Vector2NormalizeTest()
{
Vector2 a = new Vector2(2.0f, 3.0f);
Vector2 expected = new Vector2(0.554700196225229122018341733457f, 0.8320502943378436830275126001855f);
Vector2 actual;
actual = Vector2.Normalize(a);
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Normalize did not return the expected value.");
}
// A test for Normalize (Vector2f)
// Normalize zero length vector
[Fact]
public void Vector2NormalizeTest1()
{
Vector2 a = new Vector2(); // no parameter, default to 0.0f
Vector2 actual = Vector2.Normalize(a);
Assert.True(float.IsNaN(actual.X) && float.IsNaN(actual.Y), "Vector2f.Normalize did not return the expected value.");
}
// A test for Normalize (Vector2f)
// Normalize infinite length vector
[Fact]
public void Vector2NormalizeTest2()
{
Vector2 a = new Vector2(float.MaxValue, float.MaxValue);
Vector2 actual = Vector2.Normalize(a);
Vector2 expected = new Vector2(0, 0);
Assert.Equal(expected, actual);
}
// A test for operator - (Vector2f)
[Fact]
public void Vector2UnaryNegationTest()
{
Vector2 a = new Vector2(1.0f, 2.0f);
Vector2 expected = new Vector2(-1.0f, -2.0f);
Vector2 actual;
actual = -a;
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.operator - did not return the expected value.");
}
// A test for operator - (Vector2f)
// Negate test with special float value
[Fact]
public void Vector2UnaryNegationTest1()
{
Vector2 a = new Vector2(float.PositiveInfinity, float.NegativeInfinity);
Vector2 actual = -a;
Assert.True(float.IsNegativeInfinity(actual.X), "Vector2f.operator - did not return the expected value.");
Assert.True(float.IsPositiveInfinity(actual.Y), "Vector2f.operator - did not return the expected value.");
}
// A test for operator - (Vector2f)
// Negate test with special float value
[Fact]
public void Vector2UnaryNegationTest2()
{
Vector2 a = new Vector2(float.NaN, 0.0f);
Vector2 actual = -a;
Assert.True(float.IsNaN(actual.X), "Vector2f.operator - did not return the expected value.");
Assert.True(float.Equals(0.0f, actual.Y), "Vector2f.operator - did not return the expected value.");
}
// A test for operator - (Vector2f, Vector2f)
[Fact]
public void Vector2SubtractionTest()
{
Vector2 a = new Vector2(1.0f, 3.0f);
Vector2 b = new Vector2(2.0f, 1.5f);
Vector2 expected = new Vector2(-1.0f, 1.5f);
Vector2 actual;
actual = a - b;
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.operator - did not return the expected value.");
}
// A test for operator * (Vector2f, float)
[Fact]
public void Vector2MultiplyOperatorTest()
{
Vector2 a = new Vector2(2.0f, 3.0f);
const float factor = 2.0f;
Vector2 expected = new Vector2(4.0f, 6.0f);
Vector2 actual;
actual = a * factor;
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.operator * did not return the expected value.");
}
// A test for operator * (float, Vector2f)
[Fact]
public void Vector2MultiplyOperatorTest2()
{
Vector2 a = new Vector2(2.0f, 3.0f);
const float factor = 2.0f;
Vector2 expected = new Vector2(4.0f, 6.0f);
Vector2 actual;
actual = factor * a;
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.operator * did not return the expected value.");
}
// A test for operator * (Vector2f, Vector2f)
[Fact]
public void Vector2MultiplyOperatorTest3()
{
Vector2 a = new Vector2(2.0f, 3.0f);
Vector2 b = new Vector2(4.0f, 5.0f);
Vector2 expected = new Vector2(8.0f, 15.0f);
Vector2 actual;
actual = a * b;
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.operator * did not return the expected value.");
}
// A test for operator / (Vector2f, float)
[Fact]
public void Vector2DivisionTest()
{
Vector2 a = new Vector2(2.0f, 3.0f);
float div = 2.0f;
Vector2 expected = new Vector2(1.0f, 1.5f);
Vector2 actual;
actual = a / div;
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.operator / did not return the expected value.");
}
// A test for operator / (Vector2f, Vector2f)
[Fact]
public void Vector2DivisionTest1()
{
Vector2 a = new Vector2(2.0f, 3.0f);
Vector2 b = new Vector2(4.0f, 5.0f);
Vector2 expected = new Vector2(2.0f / 4.0f, 3.0f / 5.0f);
Vector2 actual;
actual = a / b;
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.operator / did not return the expected value.");
}
// A test for operator / (Vector2f, float)
// Divide by zero
[Fact]
public void Vector2DivisionTest2()
{
Vector2 a = new Vector2(-2.0f, 3.0f);
float div = 0.0f;
Vector2 actual = a / div;
Assert.True(float.IsNegativeInfinity(actual.X), "Vector2f.operator / did not return the expected value.");
Assert.True(float.IsPositiveInfinity(actual.Y), "Vector2f.operator / did not return the expected value.");
}
// A test for operator / (Vector2f, Vector2f)
// Divide by zero
[Fact]
public void Vector2DivisionTest3()
{
Vector2 a = new Vector2(0.047f, -3.0f);
Vector2 b = new Vector2();
Vector2 actual = a / b;
Assert.True(float.IsInfinity(actual.X), "Vector2f.operator / did not return the expected value.");
Assert.True(float.IsInfinity(actual.Y), "Vector2f.operator / did not return the expected value.");
}
// A test for operator + (Vector2f, Vector2f)
[Fact]
public void Vector2AdditionTest()
{
Vector2 a = new Vector2(1.0f, 2.0f);
Vector2 b = new Vector2(3.0f, 4.0f);
Vector2 expected = new Vector2(4.0f, 6.0f);
Vector2 actual;
actual = a + b;
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.operator + did not return the expected value.");
}
// A test for Vector2f (float, float)
[Fact]
public void Vector2ConstructorTest()
{
float x = 1.0f;
float y = 2.0f;
Vector2 target = new Vector2(x, y);
Assert.True(MathHelper.Equal(target.X, x) && MathHelper.Equal(target.Y, y), "Vector2f(x,y) constructor did not return the expected value.");
}
// A test for Vector2f ()
// Constructor with no parameter
[Fact]
public void Vector2ConstructorTest2()
{
Vector2 target = new Vector2();
Assert.Equal(target.X, 0.0f);
Assert.Equal(target.Y, 0.0f);
}
// A test for Vector2f (float, float)
// Constructor with special floating values
[Fact]
public void Vector2ConstructorTest3()
{
Vector2 target = new Vector2(float.NaN, float.MaxValue);
Assert.Equal(target.X, float.NaN);
Assert.Equal(target.Y, float.MaxValue);
}
// A test for Vector2f (float)
[Fact]
public void Vector2ConstructorTest4()
{
float value = 1.0f;
Vector2 target = new Vector2(value);
Vector2 expected = new Vector2(value, value);
Assert.Equal(expected, target);
value = 2.0f;
target = new Vector2(value);
expected = new Vector2(value, value);
Assert.Equal(expected, target);
}
// A test for Add (Vector2f, Vector2f)
[Fact]
public void Vector2AddTest()
{
Vector2 a = new Vector2(1.0f, 2.0f);
Vector2 b = new Vector2(5.0f, 6.0f);
Vector2 expected = new Vector2(6.0f, 8.0f);
Vector2 actual;
actual = Vector2.Add(a, b);
Assert.Equal(expected, actual);
}
// A test for Divide (Vector2f, float)
[Fact]
public void Vector2DivideTest()
{
Vector2 a = new Vector2(1.0f, 2.0f);
float div = 2.0f;
Vector2 expected = new Vector2(0.5f, 1.0f);
Vector2 actual;
actual = Vector2.Divide(a, div);
Assert.Equal(expected, actual);
}
// A test for Divide (Vector2f, Vector2f)
[Fact]
public void Vector2DivideTest1()
{
Vector2 a = new Vector2(1.0f, 6.0f);
Vector2 b = new Vector2(5.0f, 2.0f);
Vector2 expected = new Vector2(1.0f / 5.0f, 6.0f / 2.0f);
Vector2 actual;
actual = Vector2.Divide(a, b);
Assert.Equal(expected, actual);
}
// A test for Equals (object)
[Fact]
public void Vector2EqualsTest()
{
Vector2 a = new Vector2(1.0f, 2.0f);
Vector2 b = new Vector2(1.0f, 2.0f);
// case 1: compare between same values
object obj = b;
bool expected = true;
bool actual = a.Equals(obj);
Assert.Equal(expected, actual);
// case 2: compare between different values
b.X = 10.0f;
obj = b;
expected = false;
actual = a.Equals(obj);
Assert.Equal(expected, actual);
// case 3: compare between different types.
obj = new Quaternion();
expected = false;
actual = a.Equals(obj);
Assert.Equal(expected, actual);
// case 3: compare against null.
obj = null;
expected = false;
actual = a.Equals(obj);
Assert.Equal(expected, actual);
}
// A test for Multiply (Vector2f, float)
[Fact]
public void Vector2MultiplyTest()
{
Vector2 a = new Vector2(1.0f, 2.0f);
const float factor = 2.0f;
Vector2 expected = new Vector2(2.0f, 4.0f);
Vector2 actual = Vector2.Multiply(a, factor);
Assert.Equal(expected, actual);
}
// A test for Multiply (float, Vector2f)
[Fact]
public void Vector2MultiplyTest2()
{
Vector2 a = new Vector2(1.0f, 2.0f);
const float factor = 2.0f;
Vector2 expected = new Vector2(2.0f, 4.0f);
Vector2 actual = Vector2.Multiply(factor, a);
Assert.Equal(expected, actual);
}
// A test for Multiply (Vector2f, Vector2f)
[Fact]
public void Vector2MultiplyTest3()
{
Vector2 a = new Vector2(1.0f, 2.0f);
Vector2 b = new Vector2(5.0f, 6.0f);
Vector2 expected = new Vector2(5.0f, 12.0f);
Vector2 actual;
actual = Vector2.Multiply(a, b);
Assert.Equal(expected, actual);
}
// A test for Negate (Vector2f)
[Fact]
public void Vector2NegateTest()
{
Vector2 a = new Vector2(1.0f, 2.0f);
Vector2 expected = new Vector2(-1.0f, -2.0f);
Vector2 actual;
actual = Vector2.Negate(a);
Assert.Equal(expected, actual);
}
// A test for operator != (Vector2f, Vector2f)
[Fact]
public void Vector2InequalityTest()
{
Vector2 a = new Vector2(1.0f, 2.0f);
Vector2 b = new Vector2(1.0f, 2.0f);
// case 1: compare between same values
bool expected = false;
bool actual = a != b;
Assert.Equal(expected, actual);
// case 2: compare between different values
b.X = 10.0f;
expected = true;
actual = a != b;
Assert.Equal(expected, actual);
}
// A test for operator == (Vector2f, Vector2f)
[Fact]
public void Vector2EqualityTest()
{
Vector2 a = new Vector2(1.0f, 2.0f);
Vector2 b = new Vector2(1.0f, 2.0f);
// case 1: compare between same values
bool expected = true;
bool actual = a == b;
Assert.Equal(expected, actual);
// case 2: compare between different values
b.X = 10.0f;
expected = false;
actual = a == b;
Assert.Equal(expected, actual);
}
// A test for Subtract (Vector2f, Vector2f)
[Fact]
public void Vector2SubtractTest()
{
Vector2 a = new Vector2(1.0f, 6.0f);
Vector2 b = new Vector2(5.0f, 2.0f);
Vector2 expected = new Vector2(-4.0f, 4.0f);
Vector2 actual;
actual = Vector2.Subtract(a, b);
Assert.Equal(expected, actual);
}
// A test for UnitX
[Fact]
public void Vector2UnitXTest()
{
Vector2 val = new Vector2(1.0f, 0.0f);
Assert.Equal(val, Vector2.UnitX);
}
// A test for UnitY
[Fact]
public void Vector2UnitYTest()
{
Vector2 val = new Vector2(0.0f, 1.0f);
Assert.Equal(val, Vector2.UnitY);
}
// A test for One
[Fact]
public void Vector2OneTest()
{
Vector2 val = new Vector2(1.0f, 1.0f);
Assert.Equal(val, Vector2.One);
}
// A test for Zero
[Fact]
public void Vector2ZeroTest()
{
Vector2 val = new Vector2(0.0f, 0.0f);
Assert.Equal(val, Vector2.Zero);
}
// A test for Equals (Vector2f)
[Fact]
public void Vector2EqualsTest1()
{
Vector2 a = new Vector2(1.0f, 2.0f);
Vector2 b = new Vector2(1.0f, 2.0f);
// case 1: compare between same values
bool expected = true;
bool actual = a.Equals(b);
Assert.Equal(expected, actual);
// case 2: compare between different values
b.X = 10.0f;
expected = false;
actual = a.Equals(b);
Assert.Equal(expected, actual);
}
// A test for Vector2f comparison involving NaN values
[Fact]
public void Vector2EqualsNanTest()
{
Vector2 a = new Vector2(float.NaN, 0);
Vector2 b = new Vector2(0, float.NaN);
Assert.False(a == Vector2.Zero);
Assert.False(b == Vector2.Zero);
Assert.True(a != Vector2.Zero);
Assert.True(b != Vector2.Zero);
Assert.False(a.Equals(Vector2.Zero));
Assert.False(b.Equals(Vector2.Zero));
// Counterintuitive result - IEEE rules for NaN comparison are weird!
Assert.False(a.Equals(a));
Assert.False(b.Equals(b));
}
// A test for Reflect (Vector2f, Vector2f)
[Fact]
[ActiveIssue(1011)]
public void Vector2ReflectTest()
{
Vector2 a = Vector2.Normalize(new Vector2(1.0f, 1.0f));
// Reflect on XZ plane.
Vector2 n = new Vector2(0.0f, 1.0f);
Vector2 expected = new Vector2(a.X, -a.Y);
Vector2 actual = Vector2.Reflect(a, n);
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Reflect did not return the expected value.");
// Reflect on XY plane.
n = new Vector2(0.0f, 0.0f);
expected = new Vector2(a.X, a.Y);
actual = Vector2.Reflect(a, n);
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Reflect did not return the expected value.");
// Reflect on YZ plane.
n = new Vector2(1.0f, 0.0f);
expected = new Vector2(-a.X, a.Y);
actual = Vector2.Reflect(a, n);
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Reflect did not return the expected value.");
}
// A test for Reflect (Vector2f, Vector2f)
// Reflection when normal and source are the same
[Fact]
[ActiveIssue(1011)]
public void Vector2ReflectTest1()
{
Vector2 n = new Vector2(0.45f, 1.28f);
n = Vector2.Normalize(n);
Vector2 a = n;
Vector2 expected = -n;
Vector2 actual = Vector2.Reflect(a, n);
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Reflect did not return the expected value.");
}
// A test for Reflect (Vector2f, Vector2f)
// Reflection when normal and source are negation
[Fact]
public void Vector2ReflectTest2()
{
Vector2 n = new Vector2(0.45f, 1.28f);
n = Vector2.Normalize(n);
Vector2 a = -n;
Vector2 expected = n;
Vector2 actual = Vector2.Reflect(a, n);
Assert.True(MathHelper.Equal(expected, actual), "Vector2f.Reflect did not return the expected value.");
}
[Fact]
public void Vector2AbsTest()
{
Vector2 v1 = new Vector2(-2.5f, 2.0f);
Vector2 v3 = Vector2.Abs(new Vector2(0.0f, Single.NegativeInfinity));
Vector2 v = Vector2.Abs(v1);
Assert.Equal(2.5f, v.X);
Assert.Equal(2.0f, v.Y);
Assert.Equal(0.0f, v3.X);
Assert.Equal(Single.PositiveInfinity, v3.Y);
}
[Fact]
public void Vector2SqrtTest()
{
Vector2 v1 = new Vector2(-2.5f, 2.0f);
Vector2 v2 = new Vector2(5.5f, 4.5f);
Assert.Equal(2, (int)Vector2.SquareRoot(v2).X);
Assert.Equal(2, (int)Vector2.SquareRoot(v2).Y);
Assert.Equal(Single.NaN, Vector2.SquareRoot(v1).X);
}
// A test to make sure these types are blittable directly into GPU buffer memory layouts
[Fact]
public unsafe void Vector2SizeofTest()
{
Assert.Equal(8, sizeof(Vector2));
Assert.Equal(16, sizeof(Vector2_2x));
Assert.Equal(12, sizeof(Vector2PlusFloat));
Assert.Equal(24, sizeof(Vector2PlusFloat_2x));
}
[StructLayout(LayoutKind.Sequential)]
struct Vector2_2x
{
private Vector2 _a;
private Vector2 _b;
}
[StructLayout(LayoutKind.Sequential)]
struct Vector2PlusFloat
{
private Vector2 _v;
private float _f;
}
[StructLayout(LayoutKind.Sequential)]
struct Vector2PlusFloat_2x
{
private Vector2PlusFloat _a;
private Vector2PlusFloat _b;
}
[Fact]
public void SetFieldsTest()
{
Vector2 v3 = new Vector2(4f, 5f);
v3.X = 1.0f;
v3.Y = 2.0f;
Assert.Equal(1.0f, v3.X);
Assert.Equal(2.0f, v3.Y);
Vector2 v4 = v3;
v4.Y = 0.5f;
Assert.Equal(1.0f, v4.X);
Assert.Equal(0.5f, v4.Y);
Assert.Equal(2.0f, v3.Y);
}
[Fact]
public void EmbeddedVectorSetFields()
{
EmbeddedVectorObject evo = new EmbeddedVectorObject();
evo.FieldVector.X = 5.0f;
evo.FieldVector.Y = 5.0f;
Assert.Equal(5.0f, evo.FieldVector.X);
Assert.Equal(5.0f, evo.FieldVector.Y);
}
private class EmbeddedVectorObject
{
public Vector2 FieldVector;
}
}
}
| |
//---------------------------------------------------------------------------
//
// <copyright file=?DisplayAttributeHighlightLayer.cs? company=?Microsoft?>
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
//
// Description: Highlight rendering for IME compositions.
//
// History:
// 07/01/2004 : benwest - Created
//
//---------------------------------------------------------------------------
using System;
using System.Diagnostics;
using System.Collections;
using System.Windows.Media;
namespace System.Windows.Documents
{
#if UNUSED_IME_HIGHLIGHT_LAYER
// Highlight rendering for IME compositions.
internal class DisplayAttributeHighlightLayer : HighlightLayer
{
//------------------------------------------------------
//
// Constructors
//
//------------------------------------------------------
#region Constructors
// Constructor.
internal DisplayAttributeHighlightLayer()
{
// No point in delay allocating _attributeRanges -- we don't
// create a DisplayAttributeHighlightLayer unless we have
// at least one highlight to add.
_attributeRanges = new ArrayList(1);
}
#endregion Constructors
//------------------------------------------------------
//
// Internal Methods
//
//------------------------------------------------------
#region Internal Methods
// Returns the value of a property stored on scoping highlight, if any.
//
// If no property value is set, returns DependencyProperty.UnsetValue.
internal override object GetHighlightValue(StaticTextPointer textPosition, LogicalDirection direction)
{
AttributeRange attributeRange;
object value;
value = DependencyProperty.UnsetValue;
attributeRange = GetRangeAtPosition(textPosition, direction);
if (attributeRange != null)
{
value = attributeRange.TextDecorations;
}
return value;
}
// Returns true iff the indicated content has scoping highlights.
internal override bool IsContentHighlighted(StaticTextPointer textPosition, LogicalDirection direction)
{
return (GetRangeAtPosition(textPosition, direction) != null);
}
// Returns the position of the next highlight start or end in an
// indicated direction, or null if there is no such position.
internal override StaticTextPointer GetNextChangePosition(StaticTextPointer textPosition, LogicalDirection direction)
{
StaticTextPointer transitionPosition;
AttributeRange attributeRange;
int i;
transitionPosition = StaticTextPointer.Null;
// Use a simple iterative search since we don't ever have
// more than a handful of attributes in a composition.
if (direction == LogicalDirection.Forward)
{
for (i = 0; i < _attributeRanges.Count; i++)
{
attributeRange = (AttributeRange)_attributeRanges[i];
if (attributeRange.Start.CompareTo(attributeRange.End) != 0)
{
if (textPosition.CompareTo(attributeRange.Start) < 0)
{
transitionPosition = attributeRange.Start.CreateStaticPointer();
break;
}
else if (textPosition.CompareTo(attributeRange.End) < 0)
{
transitionPosition = attributeRange.End.CreateStaticPointer();
break;
}
}
}
}
else
{
for (i = _attributeRanges.Count - 1; i >= 0; i--)
{
attributeRange = (AttributeRange)_attributeRanges[i];
if (attributeRange.Start.CompareTo(attributeRange.End) != 0)
{
if (textPosition.CompareTo(attributeRange.End) > 0)
{
transitionPosition = attributeRange.End.CreateStaticPointer();
break;
}
else if (textPosition.CompareTo(attributeRange.Start) > 0)
{
transitionPosition = attributeRange.Start.CreateStaticPointer();
break;
}
}
}
}
return transitionPosition;
}
#endregion Internal Methods
//------------------------------------------------------
//
// Internal Properties
//
//------------------------------------------------------
#region Internal Properties
/// <summary>
/// Type identifying this layer for Highlights.GetHighlightValue calls.
/// </summary>
internal override Type OwnerType
{
get
{
return typeof(FrameworkTextComposition);
}
}
#endregion Internal Properties
//------------------------------------------------------
//
// Internal Events
//
//------------------------------------------------------
#region Internal Events
// Event raised when a highlight range is inserted, removed, moved, or
// has a local property value change.
//
// This event is never fired by this class, so no implementation
// is needed. (We rely on Highlights to automatically raise a
// change event when the layer is added.)
internal override event HighlightChangedEventHandler Changed
{
add
{
}
remove
{
}
}
#endregion Internal Events
//------------------------------------------------------
//
// Internal Methods
//
//------------------------------------------------------
#region Internal Methods
// Adds a range to this collection. Additions are expected to be in
// order, and non-overlapping.
internal void Add(ITextPointer start, ITextPointer end, TextDecorationCollection textDecorations)
{
// We expect all ranges to be added in order....
Debug.Assert(_attributeRanges.Count == 0 || ((AttributeRange)_attributeRanges[_attributeRanges.Count - 1]).End.CompareTo(start) <= 0);
_attributeRanges.Add(new AttributeRange(start, end, textDecorations));
}
#endregion Internal Methods
// Returns the AttributeRange covering specified content, or null
// if no such range exists.
private AttributeRange GetRangeAtPosition(StaticTextPointer textPosition, LogicalDirection direction)
{
int i;
AttributeRange attributeRange;
AttributeRange attributeRangeAtPosition;
// Use a simple iterative search since we don't ever have
// more than a handful of attributes in a composition.
attributeRangeAtPosition = null;
if (direction == LogicalDirection.Forward)
{
for (i = 0; i < _attributeRanges.Count; i++)
{
attributeRange = (AttributeRange)_attributeRanges[i];
if (attributeRange.Start.CompareTo(attributeRange.End) != 0)
{
if (textPosition.CompareTo(attributeRange.Start) < 0)
{
break;
}
else if (textPosition.CompareTo(attributeRange.End) < 0)
{
attributeRangeAtPosition = attributeRange;
break;
}
}
}
}
else
{
for (i = _attributeRanges.Count - 1; i >= 0; i--)
{
attributeRange = (AttributeRange)_attributeRanges[i];
if (attributeRange.Start.CompareTo(attributeRange.End) != 0)
{
if (textPosition.CompareTo(attributeRange.End) > 0)
{
break;
}
else if (textPosition.CompareTo(attributeRange.Start) > 0)
{
attributeRangeAtPosition = attributeRange;
break;
}
}
}
}
return attributeRangeAtPosition;
}
//------------------------------------------------------
//
// Private Types
//
//------------------------------------------------------
#region Private Types
// A run of a text with associated TextDecorations.
// Because we rely on TextServices for the start/end bounds,
// over time a range may collapse to empty. In this case
// it should be hidden from callers.
private class AttributeRange
{
internal AttributeRange(ITextPointer start, ITextPointer end, TextDecorationCollection textDecorations)
{
// AttributeRange should not be crossed later.
Debug.Assert((start.LogicalDirection != LogicalDirection.Forward) || (end.LogicalDirection != LogicalDirection.Backward));
_start = start;
_end = end;
_textDecorations = textDecorations;
}
internal ITextPointer Start
{
get
{
return _start;
}
}
internal ITextPointer End
{
get
{
return _end;
}
}
internal TextDecorationCollection TextDecorations
{
get
{
return _textDecorations;
}
}
// Start position of the run.
private readonly ITextPointer _start;
// End position of the run.
private readonly ITextPointer _end;
// TextDecorations used to highlight the run.
private readonly TextDecorationCollection _textDecorations;
}
#endregion Private Types
//------------------------------------------------------
//
// Private Fields
//
//------------------------------------------------------
#region Private Fields
// Array of AttributeRange highlights.
private readonly ArrayList _attributeRanges;
#endregion Private Fields
}
#endif
}
| |
// Copyright Naked Objects Group Ltd, 45 Station Road, Henley on Thames, UK, RG9 1AT
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using NakedFramework;
using NakedObjects;
namespace AdventureWorksModel {
public class WorkOrder {
#region Injected Servives
public IDomainObjectContainer Container { set; protected get; }
public ProductRepository ProductRepository { set; protected get; }
#endregion
#region Life Cycle Methods
public virtual void Persisting() {
ModifiedDate = DateTime.Now;
}
public virtual void Updating() {
ModifiedDate = DateTime.Now;
}
#endregion
#region Title
public override string ToString() {
var t = Container.NewTitleBuilder();
t.Append(Product).Append(":",StartDate, "d MMM yyyy", null);
return t.ToString();
}
#endregion
#region ID
[NakedObjectsIgnore]
public virtual int WorkOrderID { get; set; }
#endregion
#region StockedQty
[MemberOrder(22)]
[Disabled]
public virtual int StockedQty { get; set; }
#endregion
#region ScrappedQty
[MemberOrder(24)]
public virtual short ScrappedQty { get; set; }
#endregion
#region EndDate
[Hidden(WhenTo.UntilPersisted)] //Mandatory - for testing only
[MemberOrder(32)]
[Mask("d")]
public virtual DateTime? EndDate { get; set; }
#endregion
#region ModifiedDate
[MemberOrder(99)]
[Disabled]
[ConcurrencyCheck]
[Hidden(WhenTo.OncePersisted)] // for testing
public virtual DateTime ModifiedDate { get; set; }
#endregion
#region ScrapReason
[NakedObjectsIgnore]
public virtual short? ScrapReasonID { get; set; }
[Optionally]
[MemberOrder(26)]
public virtual ScrapReason ScrapReason { get; set; }
#endregion
#region OrderQty
[MemberOrder(20)]
public virtual int OrderQty { get; set; }
public virtual string ValidateOrderQty(int qty) {
var rb = new ReasonBuilder();
if (qty <= 0) {
rb.Append("Order Quantity must be > 0");
}
return rb.Reason;
}
#endregion
#region StartDate
[MemberOrder(30)]
[Mask("d")]
public virtual DateTime StartDate { get; set; }
public virtual DateTime DefaultStartDate() {
return DateTime.Now;
}
#endregion
#region DueDate
[MemberOrder(34)]
[Mask("d")]
public virtual DateTime DueDate { get; set; }
public virtual DateTime DefaultDueDate() {
return DateTime.Now.AddMonths(1);
}
[Edit]
public void EditDates(DateTime startDate, DateTime dueDate)
{
StartDate = startDate;
DueDate = dueDate;
}
public string ValidateEditDates(DateTime startDate, DateTime dueDate) =>
dueDate < startDate ? "Due date is before start date" : null;
#endregion
#region Product
[NakedObjectsIgnore]
public virtual int ProductID { get; set; }
[MemberOrder(10), FindMenu]
public virtual Product Product { get; set; }
[PageSize(20)]
public IQueryable<Product> AutoCompleteProduct([MinLength(2)] string name) {
return ProductRepository.FindProductByName(name);
}
#endregion
#region WorkOrderRoutings
[Disabled]
[Hidden(WhenTo.UntilPersisted)]
[Eagerly(Do.Rendering)]
[TableView(true, "OperationSequence", "ScheduledStartDate", "ScheduledEndDate", "Location", "PlannedCost")]
public virtual ICollection<WorkOrderRouting> WorkOrderRoutings { get; set; } = new List<WorkOrderRouting>();
#region AddNewRouting (Action)
[Hidden(WhenTo.UntilPersisted)]
[MemberOrder(1)]
public WorkOrderRouting AddNewRouting(Location loc) {
var wor = Container.NewTransientInstance<WorkOrderRouting>();
wor.WorkOrder = this;
wor.Location = loc;
short highestSequence = 0;
short increment = 1;
if (WorkOrderRoutings.Count > 0) {
highestSequence = WorkOrderRoutings.Max(n => n.OperationSequence);
}
highestSequence += increment;
wor.OperationSequence = highestSequence;
return wor;
}
#endregion
#endregion
public string Validate(DateTime startDate, DateTime dueDate) {
return startDate > dueDate ? "StartDate must be before DueDate" : null;
}
// for testing
[Hidden(WhenTo.Always)]
[NotMapped]
public virtual string AnAlwaysHiddenReadOnlyProperty {
get { return ""; }
}
public void ChangeScrappedQuantity(short newQty)
{
this.ScrappedQty = newQty;
}
}
}
| |
#region --- License ---
/* Copyright (c) 2006, 2007 Stefanos Apostolopoulos
* See license.txt for license info
*/
#endregion
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml.XPath;
namespace Bind.Structures
{
/// <summary>
/// Represents an opengl function.
/// The return value, function name, function parameters and opengl version can be retrieved or set.
/// </summary>
class Delegate : IComparable<Delegate>
{
//internal static DelegateCollection Delegates;
bool? cls_compliance_overriden;
protected static Regex endings = new Regex(@"((((d|f|fi)|u?[isb])_?v?)|v)", RegexOptions.Compiled | RegexOptions.RightToLeft);
protected static Regex endingsNotToTrim = new Regex("(ib|[tdrey]s|[eE]n[vd]|bled|Flag|Tess|Status|Pixels|Instanced|Indexed|Varyings|Boolean|IDs)", RegexOptions.Compiled | RegexOptions.RightToLeft);
// Add a trailing v to functions matching this regex. Used to differntiate between overloads taking both
// a 'type' and a 'ref type' (such overloads are not CLS Compliant).
// The default Regex matches no functions. Create a new Regex in Bind.Generator classes to override the default behavior.
internal static Regex endingsAddV = new Regex("^0", RegexOptions.Compiled);
#region --- Constructors ---
public Delegate()
{
Parameters = new ParameterCollection();
}
public Delegate(Delegate d)
{
Category = d.Category;
Name = d.Name;
Parameters = new ParameterCollection(d.Parameters);
ReturnType = new Type(d.ReturnType);
Version = d.Version;
//this.Version = !String.IsNullOrEmpty(d.Version) ? new string(d.Version.ToCharArray()) : "";
Deprecated = d.Deprecated;
DeprecatedVersion = d.DeprecatedVersion;
}
#endregion
#region --- Properties ---
#region public bool CLSCompliant
/// <summary>
/// Gets the CLSCompliant property. True if the delegate is not CLSCompliant.
/// </summary>
public virtual bool CLSCompliant
{
get
{
if (cls_compliance_overriden != null)
return (bool)cls_compliance_overriden;
if (Unsafe)
return false;
if (!ReturnType.CLSCompliant)
return false;
foreach (Parameter p in Parameters)
{
if (!p.CLSCompliant)
return false;
}
return true;
}
set
{
cls_compliance_overriden = value;
}
}
#endregion
#region public string Category
private string _category;
public string Category
{
get { return _category; }
set { _category = value; }
}
#endregion
#region public bool NeedsWrapper
/// <summary>
/// Gets a value that indicates whether this function needs to be wrapped with a Marshaling function.
/// This flag is set if a function contains an Array parameter, or returns
/// an Array or string.
/// </summary>
public bool NeedsWrapper
{
get
{
// TODO: Add special cases for (Get)ShaderSource.
if (ReturnType.WrapperType != WrapperTypes.None)
return true;
foreach (Parameter p in Parameters)
{
if (p.WrapperType != WrapperTypes.None)
return true;
}
return false;
}
}
#endregion
#region public virtual bool Unsafe
/// <summary>
/// True if the delegate must be declared as 'unsafe'.
/// </summary>
public virtual bool Unsafe
{
//get { return @unsafe; }
//set { @unsafe = value; }
get
{
//if ((Settings.Compatibility & Settings.Legacy.NoPublicUnsafeFunctions) != Settings.Legacy.None)
// return false;
if (ReturnType.Pointer != 0)
return true;
foreach (Parameter p in Parameters)
{
if (p.Pointer != 0)
{
return true;
}
}
return false;
}
}
#endregion
#region public Parameter ReturnType
Type _return_type = new Type();
/// <summary>
/// Gets or sets the return value of the opengl function.
/// </summary>
public Type ReturnType
{
get { return _return_type; }
set
{
_return_type = value;
}
}
#endregion
#region public virtual string Name
string _name;
/// <summary>
/// Gets or sets the name of the opengl function.
/// </summary>
public virtual string Name
{
get { return _name; }
set
{
if (!String.IsNullOrEmpty(value))
{
_name = value.Trim();
}
}
}
#endregion
#region public ParameterCollection Parameters
ParameterCollection _parameters;
public ParameterCollection Parameters
{
get { return _parameters; }
set { _parameters = value; }
}
#endregion
#region public string Version
string _version;
/// <summary>
/// Defines the opengl version that introduced this function.
/// </summary>
public string Version
{
get { return _version; }
set { _version = value; }
}
#endregion
#region public bool Extension
string _extension;
public string Extension
{
get
{
if (!String.IsNullOrEmpty(Name))
{
_extension = Utilities.GetGL2Extension(Name);
return String.IsNullOrEmpty(_extension) ? "Core" : _extension;
}
else
{
return null;
}
}
}
#endregion
public bool Deprecated { get; set; }
public string DeprecatedVersion { get; set; }
#endregion
/// <summary>
/// Returns a string that represents an invocation of this delegate.
/// </summary>
public string CallString()
{
StringBuilder sb = new StringBuilder();
sb.Append(Settings.DelegatesClass);
sb.Append(Settings.NamespaceSeparator);
sb.Append(Settings.FunctionPrefix);
sb.Append(Name);
sb.Append(Parameters.CallString());
return sb.ToString();
}
/// <summary>
/// Returns a string representing the full non-delegate declaration without decorations.
/// (ie "(unsafe) void glXxxYyy(int a, float b, IntPtr c)"
/// </summary>
public string DeclarationString()
{
StringBuilder sb = new StringBuilder();
sb.Append(Unsafe ? "unsafe " : "");
sb.Append(ReturnType);
sb.Append(" ");
sb.Append(Name);
sb.Append(Parameters.ToString(true));
return sb.ToString();
}
/// <summary>
/// Returns a string representing the full delegate declaration without decorations.
/// (ie "(unsafe) void delegate glXxxYyy(int a, float b, IntPtr c)"
/// </summary>
override public string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append(Unsafe ? "unsafe " : "");
sb.Append("delegate ");
sb.Append(ReturnType);
sb.Append(" ");
sb.Append(Name);
sb.Append(Parameters.ToString(true));
return sb.ToString();
}
public Delegate GetCLSCompliantDelegate()
{
Delegate f = new Delegate(this);
for (int i = 0; i < f.Parameters.Count; i++)
{
f.Parameters[i].CurrentType = f.Parameters[i].GetCLSCompliantType();
}
f.ReturnType.CurrentType = f.ReturnType.GetCLSCompliantType();
return f;
}
#region IComparable<Delegate> Members
public int CompareTo(Delegate other)
{
return Name.CompareTo(other.Name);
}
#endregion
}
#region class DelegateCollection : SortedDictionary<string, Delegate>
class DelegateCollection : SortedDictionary<string, Delegate>
{
public void Add(Delegate d)
{
if (!ContainsKey(d.Name))
{
Add(d.Name, d);
}
else
{
Trace.WriteLine(String.Format(
"Spec error: function {0} redefined, ignoring second definition.",
d.Name));
}
}
}
#endregion
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
namespace NPOI.SS.Formula
{
using System;
using System.Text;
using NPOI.SS.Formula.PTG;
/**
* @author Josh Micich
*/
public class FormulaShifter
{
public enum ShiftMode
{
Row,
Sheet
}
/**
* Extern sheet index of sheet where moving is occurring
*/
private int _externSheetIndex;
private int _firstMovedIndex;
private int _lastMovedIndex;
private int _amountToMove;
private int _srcSheetIndex;
private int _dstSheetIndex;
private ShiftMode _mode;
private FormulaShifter(int externSheetIndex, int firstMovedIndex, int lastMovedIndex, int amountToMove)
{
if (amountToMove == 0)
{
throw new ArgumentException("amountToMove must not be zero");
}
if (firstMovedIndex > lastMovedIndex)
{
throw new ArgumentException("firstMovedIndex, lastMovedIndex out of order");
}
_externSheetIndex = externSheetIndex;
_firstMovedIndex = firstMovedIndex;
_lastMovedIndex = lastMovedIndex;
_amountToMove = amountToMove;
_mode = ShiftMode.Row;
_srcSheetIndex = _dstSheetIndex = -1;
}
/**
* Create an instance for shifting sheets.
*
* For example, this will be called on {@link org.apache.poi.hssf.usermodel.HSSFWorkbook#setSheetOrder(String, int)}
*/
private FormulaShifter(int srcSheetIndex, int dstSheetIndex)
{
_externSheetIndex = _firstMovedIndex = _lastMovedIndex = _amountToMove = -1;
_srcSheetIndex = srcSheetIndex;
_dstSheetIndex = dstSheetIndex;
_mode = ShiftMode.Sheet;
}
public static FormulaShifter CreateForRowShift(int externSheetIndex, int firstMovedRowIndex, int lastMovedRowIndex, int numberOfRowsToMove)
{
return new FormulaShifter(externSheetIndex, firstMovedRowIndex, lastMovedRowIndex, numberOfRowsToMove);
}
public static FormulaShifter CreateForSheetShift(int srcSheetIndex, int dstSheetIndex)
{
return new FormulaShifter(srcSheetIndex, dstSheetIndex);
}
public override String ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append(GetType().Name);
sb.Append(" [");
sb.Append(_firstMovedIndex);
sb.Append(_lastMovedIndex);
sb.Append(_amountToMove);
return sb.ToString();
}
/**
* @param ptgs - if necessary, will get modified by this method
* @param currentExternSheetIx - the extern sheet index of the sheet that contains the formula being adjusted
* @return <c>true</c> if a change was made to the formula tokens
*/
public bool AdjustFormula(Ptg[] ptgs, int currentExternSheetIx)
{
bool refsWereChanged = false;
for (int i = 0; i < ptgs.Length; i++)
{
Ptg newPtg = AdjustPtg(ptgs[i], currentExternSheetIx);
if (newPtg != null)
{
refsWereChanged = true;
ptgs[i] = newPtg;
}
}
return refsWereChanged;
}
private Ptg AdjustPtg(Ptg ptg, int currentExternSheetIx)
{
//return AdjustPtgDueToRowMove(ptg, currentExternSheetIx);
switch (_mode)
{
case ShiftMode.Row:
return AdjustPtgDueToRowMove(ptg, currentExternSheetIx);
case ShiftMode.Sheet:
return AdjustPtgDueToShiftMove(ptg);
default:
throw new InvalidOperationException("Unsupported shift mode: " + _mode);
}
}
/**
* @return <c>true</c> if this Ptg needed to be changed
*/
private Ptg AdjustPtgDueToRowMove(Ptg ptg, int currentExternSheetIx)
{
if (ptg is RefPtg)
{
if (currentExternSheetIx != _externSheetIndex)
{
// local refs on other sheets are unaffected
return null;
}
RefPtg rptg = (RefPtg)ptg;
return RowMoveRefPtg(rptg);
}
if (ptg is Ref3DPtg)
{
Ref3DPtg rptg = (Ref3DPtg)ptg;
if (_externSheetIndex != rptg.ExternSheetIndex)
{
// only move 3D refs that refer to the sheet with cells being moved
// (currentExternSheetIx is irrelevant)
return null;
}
return RowMoveRefPtg(rptg);
}
if (ptg is Area2DPtgBase)
{
if (currentExternSheetIx != _externSheetIndex)
{
// local refs on other sheets are unaffected
return ptg;
}
return RowMoveAreaPtg((Area2DPtgBase)ptg);
}
if (ptg is Area3DPtg)
{
Area3DPtg aptg = (Area3DPtg)ptg;
if (_externSheetIndex != aptg.ExternSheetIndex)
{
// only move 3D refs that refer to the sheet with cells being moved
// (currentExternSheetIx is irrelevant)
return null;
}
return RowMoveAreaPtg(aptg);
}
return null;
}
private Ptg AdjustPtgDueToShiftMove(Ptg ptg)
{
Ptg updatedPtg = null;
if (ptg is Ref3DPtg)
{
Ref3DPtg ref1 = (Ref3DPtg)ptg;
if (ref1.ExternSheetIndex == _srcSheetIndex)
{
ref1.ExternSheetIndex = (_dstSheetIndex);
updatedPtg = ref1;
}
else if (ref1.ExternSheetIndex == _dstSheetIndex)
{
ref1.ExternSheetIndex = (_srcSheetIndex);
updatedPtg = ref1;
}
}
return updatedPtg;
}
private Ptg RowMoveRefPtg(RefPtgBase rptg)
{
int refRow = rptg.Row;
if (_firstMovedIndex <= refRow && refRow <= _lastMovedIndex)
{
// Rows being moved completely enclose the ref.
// - move the area ref along with the rows regardless of destination
rptg.Row = (refRow + _amountToMove);
return rptg;
}
// else rules for adjusting area may also depend on the destination of the moved rows
int destFirstRowIndex = _firstMovedIndex + _amountToMove;
int destLastRowIndex = _lastMovedIndex + _amountToMove;
// ref is outside source rows
// check for clashes with destination
if (destLastRowIndex < refRow || refRow < destFirstRowIndex)
{
// destination rows are completely outside ref
return null;
}
if (destFirstRowIndex <= refRow && refRow <= destLastRowIndex)
{
// destination rows enclose the area (possibly exactly)
return CreateDeletedRef(rptg);
}
throw new InvalidOperationException("Situation not covered: (" + _firstMovedIndex + ", " +
_lastMovedIndex + ", " + _amountToMove + ", " + refRow + ", " + refRow + ")");
}
private Ptg RowMoveAreaPtg(AreaPtgBase aptg)
{
int aFirstRow = aptg.FirstRow;
int aLastRow = aptg.LastRow;
if (_firstMovedIndex <= aFirstRow && aLastRow <= _lastMovedIndex)
{
// Rows being moved completely enclose the area ref.
// - move the area ref along with the rows regardless of destination
aptg.FirstRow = (aFirstRow + _amountToMove);
aptg.LastRow = (aLastRow + _amountToMove);
return aptg;
}
// else rules for adjusting area may also depend on the destination of the moved rows
int destFirstRowIndex = _firstMovedIndex + _amountToMove;
int destLastRowIndex = _lastMovedIndex + _amountToMove;
if (aFirstRow < _firstMovedIndex && _lastMovedIndex < aLastRow)
{
// Rows moved were originally *completely* within the area ref
// If the destination of the rows overlaps either the top
// or bottom of the area ref there will be a change
if (destFirstRowIndex < aFirstRow && aFirstRow <= destLastRowIndex)
{
// truncate the top of the area by the moved rows
aptg.FirstRow = (destLastRowIndex + 1);
return aptg;
}
else if (destFirstRowIndex <= aLastRow && aLastRow < destLastRowIndex)
{
// truncate the bottom of the area by the moved rows
aptg.LastRow = (destFirstRowIndex - 1);
return aptg;
}
// else - rows have moved completely outside the area ref,
// or still remain completely within the area ref
return null; // - no change to the area
}
if (_firstMovedIndex <= aFirstRow && aFirstRow <= _lastMovedIndex)
{
// Rows moved include the first row of the area ref, but not the last row
// btw: (aLastRow > _lastMovedIndex)
if (_amountToMove < 0)
{
// simple case - expand area by shifting top upward
aptg.FirstRow = (aFirstRow + _amountToMove);
return aptg;
}
if (destFirstRowIndex > aLastRow)
{
// in this case, excel ignores the row move
return null;
}
int newFirstRowIx = aFirstRow + _amountToMove;
if (destLastRowIndex < aLastRow)
{
// end of area is preserved (will remain exact same row)
// the top area row is moved simply
aptg.FirstRow = (newFirstRowIx);
return aptg;
}
// else - bottom area row has been replaced - both area top and bottom may move now
int areaRemainingTopRowIx = _lastMovedIndex + 1;
if (destFirstRowIndex > areaRemainingTopRowIx)
{
// old top row of area has moved deep within the area, and exposed a new top row
newFirstRowIx = areaRemainingTopRowIx;
}
aptg.FirstRow = (newFirstRowIx);
aptg.LastRow = (Math.Max(aLastRow, destLastRowIndex));
return aptg;
}
if (_firstMovedIndex <= aLastRow && aLastRow <= _lastMovedIndex)
{
// Rows moved include the last row of the area ref, but not the first
// btw: (aFirstRow < _firstMovedIndex)
if (_amountToMove > 0)
{
// simple case - expand area by shifting bottom downward
aptg.LastRow = (aLastRow + _amountToMove);
return aptg;
}
if (destLastRowIndex < aFirstRow)
{
// in this case, excel ignores the row move
return null;
}
int newLastRowIx = aLastRow + _amountToMove;
if (destFirstRowIndex > aFirstRow)
{
// top of area is preserved (will remain exact same row)
// the bottom area row is moved simply
aptg.LastRow = (newLastRowIx);
return aptg;
}
// else - top area row has been replaced - both area top and bottom may move now
int areaRemainingBottomRowIx = _firstMovedIndex - 1;
if (destLastRowIndex < areaRemainingBottomRowIx)
{
// old bottom row of area has moved up deep within the area, and exposed a new bottom row
newLastRowIx = areaRemainingBottomRowIx;
}
aptg.FirstRow = (Math.Min(aFirstRow, destFirstRowIndex));
aptg.LastRow = (newLastRowIx);
return aptg;
}
// else source rows include none of the rows of the area ref
// check for clashes with destination
if (destLastRowIndex < aFirstRow || aLastRow < destFirstRowIndex)
{
// destination rows are completely outside area ref
return null;
}
if (destFirstRowIndex <= aFirstRow && aLastRow <= destLastRowIndex)
{
// destination rows enclose the area (possibly exactly)
return CreateDeletedRef(aptg);
}
if (aFirstRow <= destFirstRowIndex && destLastRowIndex <= aLastRow)
{
// destination rows are within area ref (possibly exact on top or bottom, but not both)
return null; // - no change to area
}
if (destFirstRowIndex < aFirstRow && aFirstRow <= destLastRowIndex)
{
// dest rows overlap top of area
// - truncate the top
aptg.FirstRow = (destLastRowIndex + 1);
return aptg;
}
if (destFirstRowIndex < aLastRow && aLastRow <= destLastRowIndex)
{
// dest rows overlap bottom of area
// - truncate the bottom
aptg.LastRow = (destFirstRowIndex - 1);
return aptg;
}
throw new InvalidOperationException("Situation not covered: (" + _firstMovedIndex + ", " +
_lastMovedIndex + ", " + _amountToMove + ", " + aFirstRow + ", " + aLastRow + ")");
}
private static Ptg CreateDeletedRef(Ptg ptg)
{
if (ptg is RefPtg)
{
return new RefErrorPtg();
}
if (ptg is Ref3DPtg)
{
Ref3DPtg rptg = (Ref3DPtg)ptg;
return new DeletedRef3DPtg(rptg.ExternSheetIndex);
}
if (ptg is AreaPtg)
{
return new AreaErrPtg();
}
if (ptg is Area3DPtg)
{
Area3DPtg area3DPtg = (Area3DPtg)ptg;
return new DeletedArea3DPtg(area3DPtg.ExternSheetIndex);
}
throw new ArgumentException("Unexpected ref ptg class (" + ptg.GetType().Name + ")");
}
}
}
| |
using System;
using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace QText {
internal class FolderOpenDialog : IDisposable {
/// <summary>
/// Gets/sets folder in which dialog will be open.
/// </summary>
public string InitialFolder { get; set; }
/// <summary>
/// Gets/sets directory in which dialog will be open if there is no recent directory available.
/// </summary>
public string DefaultFolder { get; set; }
/// <summary>
/// Gets selected folder.
/// </summary>
public string Folder { get; private set; }
internal DialogResult ShowDialog(IWin32Window owner) {
if (Environment.OSVersion.Version.Major >= 6) {
return ShowVistaDialog(owner);
} else {
return ShowLegacyDialog(owner);
}
}
private DialogResult ShowVistaDialog(IWin32Window owner) {
var frm = (NativeMethods.IFileDialog)(new NativeMethods.FileOpenDialogRCW());
frm.GetOptions(out var options);
options |= NativeMethods.FOS_PICKFOLDERS | NativeMethods.FOS_FORCEFILESYSTEM | NativeMethods.FOS_NOVALIDATE | NativeMethods.FOS_NOTESTFILECREATE | NativeMethods.FOS_DONTADDTORECENT;
frm.SetOptions(options);
if (InitialFolder != null) {
var riid = new Guid("43826D1E-E718-42EE-BC55-A1E261C37BFE"); //IShellItem
if (NativeMethods.SHCreateItemFromParsingName(InitialFolder, IntPtr.Zero, ref riid, out var directoryShellItem) == NativeMethods.S_OK) {
frm.SetFolder(directoryShellItem);
}
}
if (DefaultFolder != null) {
var riid = new Guid("43826D1E-E718-42EE-BC55-A1E261C37BFE"); //IShellItem
if (NativeMethods.SHCreateItemFromParsingName(DefaultFolder, IntPtr.Zero, ref riid, out var directoryShellItem) == NativeMethods.S_OK) {
frm.SetDefaultFolder(directoryShellItem);
}
}
if (frm.Show(owner.Handle) == NativeMethods.S_OK) {
if (frm.GetResult(out var shellItem) == NativeMethods.S_OK) {
if (shellItem.GetDisplayName(NativeMethods.SIGDN_FILESYSPATH, out var pszString) == NativeMethods.S_OK) {
if (pszString != IntPtr.Zero) {
try {
Folder = Marshal.PtrToStringAuto(pszString);
return DialogResult.OK;
} finally {
Marshal.FreeCoTaskMem(pszString);
}
}
}
}
}
return DialogResult.Cancel;
}
private DialogResult ShowLegacyDialog(IWin32Window owner) {
using (var frm = new SaveFileDialog()) {
frm.CheckFileExists = false;
frm.CheckPathExists = true;
frm.CreatePrompt = false;
frm.Filter = "|" + Guid.Empty.ToString();
frm.FileName = "any";
if (InitialFolder != null) { frm.InitialDirectory = InitialFolder; }
frm.OverwritePrompt = false;
frm.Title = "Select Folder";
frm.ValidateNames = false;
if (frm.ShowDialog(owner) == DialogResult.OK) {
Folder = Path.GetDirectoryName(frm.FileName);
return DialogResult.OK;
} else {
return DialogResult.Cancel;
}
}
}
public void Dispose() { } //just to have possibility of Using statement.
}
internal static class NativeMethods {
#region Constants
public const uint FOS_PICKFOLDERS = 0x00000020;
public const uint FOS_FORCEFILESYSTEM = 0x00000040;
public const uint FOS_NOVALIDATE = 0x00000100;
public const uint FOS_NOTESTFILECREATE = 0x00010000;
public const uint FOS_DONTADDTORECENT = 0x02000000;
public const uint S_OK = 0x0000;
public const uint SIGDN_FILESYSPATH = 0x80058000;
#endregion
#region COM
[ComImport, ClassInterface(ClassInterfaceType.None), TypeLibType(TypeLibTypeFlags.FCanCreate), Guid("DC1C5A9C-E88A-4DDE-A5A1-60F82A20AEF7")]
internal class FileOpenDialogRCW { }
[ComImport(), Guid("42F85136-DB7E-439C-85F1-E4075D135FC8"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
internal interface IFileDialog {
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
[PreserveSig()]
uint Show([In, Optional] IntPtr hwndOwner); //IModalWindow
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint SetFileTypes([In] uint cFileTypes, [In, MarshalAs(UnmanagedType.LPArray)] IntPtr rgFilterSpec);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint SetFileTypeIndex([In] uint iFileType);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint GetFileTypeIndex(out uint piFileType);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint Advise([In, MarshalAs(UnmanagedType.Interface)] IntPtr pfde, out uint pdwCookie);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint Unadvise([In] uint dwCookie);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint SetOptions([In] uint fos);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint GetOptions(out uint fos);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void SetDefaultFolder([In, MarshalAs(UnmanagedType.Interface)] IShellItem psi);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint SetFolder([In, MarshalAs(UnmanagedType.Interface)] IShellItem psi);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint GetFolder([MarshalAs(UnmanagedType.Interface)] out IShellItem ppsi);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint GetCurrentSelection([MarshalAs(UnmanagedType.Interface)] out IShellItem ppsi);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint SetFileName([In, MarshalAs(UnmanagedType.LPWStr)] string pszName);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint GetFileName([MarshalAs(UnmanagedType.LPWStr)] out string pszName);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint SetTitle([In, MarshalAs(UnmanagedType.LPWStr)] string pszTitle);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint SetOkButtonLabel([In, MarshalAs(UnmanagedType.LPWStr)] string pszText);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint SetFileNameLabel([In, MarshalAs(UnmanagedType.LPWStr)] string pszLabel);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint GetResult([MarshalAs(UnmanagedType.Interface)] out IShellItem ppsi);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint AddPlace([In, MarshalAs(UnmanagedType.Interface)] IShellItem psi, uint fdap);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint SetDefaultExtension([In, MarshalAs(UnmanagedType.LPWStr)] string pszDefaultExtension);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint Close([MarshalAs(UnmanagedType.Error)] uint hr);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint SetClientGuid([In] ref Guid guid);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint ClearClientData();
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint SetFilter([MarshalAs(UnmanagedType.Interface)] IntPtr pFilter);
}
[ComImport, Guid("43826D1E-E718-42EE-BC55-A1E261C37BFE"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
internal interface IShellItem {
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint BindToHandler([In] IntPtr pbc, [In] ref Guid rbhid, [In] ref Guid riid, [Out, MarshalAs(UnmanagedType.Interface)] out IntPtr ppvOut);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint GetParent([MarshalAs(UnmanagedType.Interface)] out IShellItem ppsi);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint GetDisplayName([In] uint sigdnName, out IntPtr ppszName);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint GetAttributes([In] uint sfgaoMask, out uint psfgaoAttribs);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint Compare([In, MarshalAs(UnmanagedType.Interface)] IShellItem psi, [In] uint hint, out int piOrder);
}
#endregion
[DllImport("shell32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
internal static extern int SHCreateItemFromParsingName([MarshalAs(UnmanagedType.LPWStr)] string pszPath, IntPtr pbc, ref Guid riid, [MarshalAs(UnmanagedType.Interface)] out IShellItem ppv);
}
}
| |
// Copyright 2016 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using Google.Cloud.ClientTesting;
using Google.Rpc;
using Google.Type;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Xunit;
namespace Google.Cloud.Vision.V1.Snippets
{
[SnippetOutputCollector]
[Collection(nameof(VisionFixture))]
public class ImageAnnotatorClientSnippets
{
private readonly VisionFixture _fixture;
public ImageAnnotatorClientSnippets(VisionFixture fixture) =>
_fixture = fixture;
[Fact]
public void Annotate()
{
Image image = LoadResourceImage("SchmidtBrinPage.jpg");
// Snippet: Annotate
ImageAnnotatorClient client = ImageAnnotatorClient.Create();
AnnotateImageRequest request = new AnnotateImageRequest
{
Image = image,
Features =
{
new Feature { Type = Feature.Types.Type.FaceDetection },
// By default, no limits are put on the number of results per annotation.
// Use the MaxResults property to specify a limit.
new Feature { Type = Feature.Types.Type.LandmarkDetection, MaxResults = 5 },
}
};
AnnotateImageResponse response = client.Annotate(request);
Console.WriteLine("Faces:");
foreach (FaceAnnotation face in response.FaceAnnotations)
{
string poly = string.Join(" - ", face.BoundingPoly.Vertices.Select(v => $"({v.X}, {v.Y})"));
Console.WriteLine($" Confidence: {(int)(face.DetectionConfidence * 100)}%; BoundingPoly: {poly}");
}
Console.WriteLine("Landmarks:");
foreach (EntityAnnotation landmark in response.LandmarkAnnotations)
{
Console.WriteLine($"Score: {(int)(landmark.Score * 100)}%; Description: {landmark.Description}");
}
if (response.Error != null)
{
Console.WriteLine($"Error detected: {response.Error}");
}
// End snippet
Assert.Equal(3, response.FaceAnnotations.Count);
Assert.Equal(0, response.LandmarkAnnotations.Count);
}
// See-also: Annotate(*, *)
// Member: AnnotateAsync(*, CallSettings)
// Member: AnnotateAsync(*, CancellationToken)
// See [Annotate](ref) for a synchronous example.
// End see-also
[Fact]
public void BatchAnnotateImages()
{
Image image1 = LoadResourceImage("SchmidtBrinPage.jpg");
Image image2 = LoadResourceImage("Chrome.png");
// Sample: BatchAnnotateImages
// Additional: BatchAnnotateImages(IEnumerable<AnnotateImageRequest>,*)
ImageAnnotatorClient client = ImageAnnotatorClient.Create();
// Perform face recognition on one image, and logo recognition on another.
AnnotateImageRequest request1 = new AnnotateImageRequest
{
Image = image1,
Features = { new Feature { Type = Feature.Types.Type.FaceDetection } }
};
AnnotateImageRequest request2 = new AnnotateImageRequest
{
Image = image2,
Features = { new Feature { Type = Feature.Types.Type.LogoDetection } }
};
BatchAnnotateImagesResponse response = client.BatchAnnotateImages(new[] { request1, request2 });
Console.WriteLine("Faces in image 1:");
foreach (FaceAnnotation face in response.Responses[0].FaceAnnotations)
{
string poly = string.Join(" - ", face.BoundingPoly.Vertices.Select(v => $"({v.X}, {v.Y})"));
Console.WriteLine($" Confidence: {(int)(face.DetectionConfidence * 100)}%; BoundingPoly: {poly}");
}
Console.WriteLine("Logos in image 2:");
foreach (EntityAnnotation logo in response.Responses[1].LogoAnnotations)
{
Console.WriteLine($"Description: {logo.Description}");
}
foreach (Status error in response.Responses.Select(r => r.Error))
{
Console.WriteLine($"Error detected: error");
}
// End sample
Assert.Equal(3, response.Responses[0].FaceAnnotations.Count);
Assert.Equal(1, response.Responses[1].LogoAnnotations.Count);
}
[Fact]
public void DetectFaces()
{
Image image = LoadResourceImage("SchmidtBrinPage.jpg");
// Snippet: DetectFaces
ImageAnnotatorClient client = ImageAnnotatorClient.Create();
IReadOnlyList<FaceAnnotation> result = client.DetectFaces(image);
foreach (FaceAnnotation face in result)
{
string poly = string.Join(" - ", face.BoundingPoly.Vertices.Select(v => $"({v.X}, {v.Y})"));
Console.WriteLine($"Confidence: {(int)(face.DetectionConfidence * 100)}%; BoundingPoly: {poly}");
}
// End snippet
Assert.Equal(3, result.Count);
var rectangles = result.Select(x => Rectangle.FromBoundingPoly(x.BoundingPoly)).ToList();
Assert.True(rectangles.All(x => x != null));
}
// See-also: DetectFaces(*, *, *, *)
// Member: DetectFacesAsync(*, *, *, *)
// See [DetectFaces](ref) for a synchronous example.
// End see-also
[Fact]
public void DetectLandmarks()
{
Image image = LoadResourceImage("SydneyOperaHouse.jpg");
// Snippet: DetectLandmarks
ImageAnnotatorClient client = ImageAnnotatorClient.Create();
IReadOnlyList<EntityAnnotation> result = client.DetectLandmarks(image);
foreach (EntityAnnotation landmark in result)
{
Console.WriteLine($"Score: {(int)(landmark.Score * 100)}%; Description: {landmark.Description}");
}
// End snippet
Assert.InRange(result.Count, 1, 10);
var descriptions = result.Select(r => r.Description).ToList();
Assert.Contains("Sydney Opera House", descriptions);
}
// See-also: DetectLandmarks(*, *, *, *)
// Member: DetectLandmarksAsync(*, *, *, *)
// See [DetectLandmarks](ref) for a synchronous example.
// End see-also
[Fact]
public void DetectImageProperties()
{
Image image = LoadResourceImage("SchmidtBrinPage.jpg");
// Snippet: DetectImageProperties
ImageAnnotatorClient client = ImageAnnotatorClient.Create();
ImageProperties properties = client.DetectImageProperties(image);
ColorInfo dominantColor = properties.DominantColors.Colors.OrderByDescending(c => c.PixelFraction).First();
Console.WriteLine($"Dominant color in image: {dominantColor}");
// End snippet
Assert.Equal(0.18, dominantColor.PixelFraction, 2);
Assert.Equal(new Color { Red = 16, Green = 13, Blue = 8 }, dominantColor.Color);
}
// See-also: DetectImageProperties(*, *, *)
// Member: DetectImagePropertiesAsync(*, *, *)
// See [DetectImageProperties](ref) for a synchronous example.
// End see-also
[Fact]
public void DetectLabels()
{
Image image = LoadResourceImage("Gladiolos.jpg");
// Snippet: DetectLabels
ImageAnnotatorClient client = ImageAnnotatorClient.Create();
IReadOnlyList<EntityAnnotation> labels = client.DetectLabels(image);
foreach (EntityAnnotation label in labels)
{
Console.WriteLine($"Score: {(int)(label.Score * 100)}%; Description: {label.Description}");
}
// End snippet
// Not exhaustive, but let's check certain basic labels.
var descriptions = labels.Select(l => l.Description).ToList();
Assert.Contains("flower", descriptions, StringComparer.OrdinalIgnoreCase);
Assert.Contains("petal", descriptions, StringComparer.OrdinalIgnoreCase);
Assert.Contains("vase", descriptions, StringComparer.OrdinalIgnoreCase);
}
// See-also: DetectLabels(*, *, *, *)
// Member: DetectLabelsAsync(*, *, *, *)
// See [DetectLabels](ref) for a synchronous example.
// End see-also
[Fact]
public void DetectText()
{
Image image = LoadResourceImage("Ellesborough.png");
// Snippet: DetectText
ImageAnnotatorClient client = ImageAnnotatorClient.Create();
IReadOnlyList<EntityAnnotation> textAnnotations = client.DetectText(image);
foreach (EntityAnnotation text in textAnnotations)
{
Console.WriteLine($"Description: {text.Description}");
}
// End snippet
var descriptions = textAnnotations.Select(t => t.Description).ToList();
Assert.Contains("Ellesborough", descriptions);
}
// See-also: DetectText(*, *, *, *)
// Member: DetectTextAsync(*, *, *, *)
// See [DetectText](ref) for a synchronous example.
// End see-also
[Fact]
public void DetectSafeSearch()
{
Image image = LoadResourceImage("SchmidtBrinPage.jpg");
// Snippet: DetectSafeSearch
ImageAnnotatorClient client = ImageAnnotatorClient.Create();
SafeSearchAnnotation annotation = client.DetectSafeSearch(image);
// Each category is classified as Very Unlikely, Unlikely, Possible, Likely or Very Likely.
Console.WriteLine($"Adult? {annotation.Adult}");
Console.WriteLine($"Spoof? {annotation.Spoof}");
Console.WriteLine($"Violence? {annotation.Violence}");
Console.WriteLine($"Medical? {annotation.Medical}");
// End snippet
Assert.InRange(annotation.Adult, Likelihood.VeryUnlikely, Likelihood.Unlikely);
Assert.InRange(annotation.Spoof, Likelihood.VeryUnlikely, Likelihood.Unlikely);
Assert.InRange(annotation.Violence, Likelihood.VeryUnlikely, Likelihood.Unlikely);
Assert.InRange(annotation.Medical, Likelihood.VeryUnlikely, Likelihood.Unlikely);
}
// See-also: DetectSafeSearch(*, *, *)
// Member: DetectSafeSearchAsync(*, *, *)
// See [DetectSafeSearch](ref) for a synchronous example.
// End see-also
[Fact]
public void DetectLogos()
{
Image image = LoadResourceImage("Chrome.png");
// Snippet: DetectLogos
ImageAnnotatorClient client = ImageAnnotatorClient.Create();
IReadOnlyList<EntityAnnotation> logos = client.DetectLogos(image);
foreach (EntityAnnotation logo in logos)
{
Console.WriteLine($"Description: {logo.Description}");
}
// End snippet
Assert.Equal(1, logos.Count);
Assert.Contains("chrome", logos[0].Description, StringComparison.OrdinalIgnoreCase);
}
// See-also: DetectLogos(*, *, *, *)
// Member: DetectLogosAsync(*, *, *, *)
// See [DetectLogos](ref) for a synchronous example.
// End see-also
[Fact]
public void DetectCropHints()
{
Image image = LoadResourceImage("Gladiolos.jpg");
// Snippet: DetectCropHints
ImageAnnotatorClient client = ImageAnnotatorClient.Create();
CropHintsAnnotation cropHints = client.DetectCropHints(image);
foreach (CropHint hint in cropHints.CropHints)
{
Console.WriteLine("Crop hint:");
string poly = string.Join(" - ", hint.BoundingPoly.Vertices.Select(v => $"({v.X}, {v.Y})"));
Console.WriteLine($" Poly: {poly}");
Console.WriteLine($" Confidence: {hint.Confidence}");
Console.WriteLine($" Importance fraction: {hint.ImportanceFraction}");
}
// End snippet
Assert.Equal(1, cropHints.CropHints.Count);
}
// See-also: DetectCropHints(*, *, *)
// Member: DetectCropHintsAsync(*, *, *)
// See [DetectCropHints](ref) for a synchronous example.
// End see-also
[Fact]
public void DetectDocumentText()
{
Image image = LoadResourceImage("DocumentText.png");
// Snippet: DetectDocumentText
ImageAnnotatorClient client = ImageAnnotatorClient.Create();
TextAnnotation text = client.DetectDocumentText(image);
Console.WriteLine($"Text: {text.Text}");
foreach (var page in text.Pages)
{
foreach (var block in page.Blocks)
{
string box = string.Join(" - ", block.BoundingBox.Vertices.Select(v => $"({v.X}, {v.Y})"));
Console.WriteLine($"Block {block.BlockType} at {box}");
foreach (var paragraph in block.Paragraphs)
{
box = string.Join(" - ", paragraph.BoundingBox.Vertices.Select(v => $"({v.X}, {v.Y})"));
Console.WriteLine($" Paragraph at {box}");
foreach (var word in paragraph.Words)
{
Console.WriteLine($" Word: {string.Join("", word.Symbols.Select(s => s.Text))}");
}
}
}
}
// End snippet
var lines = text.Pages[0].Blocks
.Select(b => b.Paragraphs[0].Words.Select(w => string.Join("", w.Symbols.Select(s => s.Text))))
.ToList();
Assert.Equal(new[] { "Sample", "text", "line", "1", }, lines[0]);
Assert.Equal(new[] { "Text", "near", "the", "middle", }, lines[1]);
Assert.Equal(new[] { "Text", "near", "bottom", "right", }, lines[2]);
}
// See-also: DetectDocumentText(*, *, *)
// Member: DetectDocumentTextAsync(*, *, *)
// See [DetectDocumentText](ref) for a synchronous example.
// End see-also
[Fact]
public void DetectWebInformation()
{
Image image = LoadResourceImage("SchmidtBrinPage.jpg");
// Snippet: DetectWebInformation
ImageAnnotatorClient client = ImageAnnotatorClient.Create();
WebDetection webDetection = client.DetectWebInformation(image);
foreach (WebDetection.Types.WebImage webImage in webDetection.FullMatchingImages)
{
Console.WriteLine($"Full image: {webImage.Url} ({webImage.Score})");
}
foreach (WebDetection.Types.WebImage webImage in webDetection.PartialMatchingImages)
{
Console.WriteLine($"Partial image: {webImage.Url} ({webImage.Score})");
}
foreach (WebDetection.Types.WebPage webPage in webDetection.PagesWithMatchingImages)
{
Console.WriteLine($"Page with matching image: {webPage.Url} ({webPage.Score})");
}
foreach (WebDetection.Types.WebEntity entity in webDetection.WebEntities)
{
Console.WriteLine($"Web entity: {entity.EntityId} / {entity.Description} ({entity.Score})");
}
// End snippet
}
// See-also: DetectWebInformation(*, *, *)
// Member: DetectWebInformationAsync(*, *, *)
// See [DetectWebInformation](ref) for a synchronous example.
// End see-also
[Fact(Skip = "Flaky; see https://github.com/googleapis/google-cloud-dotnet/issues/3174")]
public void DetectLocalizedObjects()
{
Image image = Image.FromUri("https://cloud.google.com/vision/docs/images/bicycle_example.png");
// Snippet: DetectLocalizedObjects
ImageAnnotatorClient client = ImageAnnotatorClient.Create();
IReadOnlyList<LocalizedObjectAnnotation> annotations = client.DetectLocalizedObjects(image);
foreach (LocalizedObjectAnnotation annotation in annotations)
{
string poly = string.Join(" - ", annotation.BoundingPoly.NormalizedVertices.Select(v => $"({v.X}, {v.Y})"));
Console.WriteLine(
$"Name: {annotation.Name}; ID: {annotation.Mid}; Score: {annotation.Score}; Bounding poly: {poly}");
}
// End snippet
// We don't want to be too strict about what we get back here, but these should be okay.
Assert.Contains(annotations, a => a.Name == "Bicycle");
Assert.Contains(annotations, a => a.Name == "Picture frame");
}
// See-also: DetectLocalizedObjects(*, *, *, *)
// Member: DetectLocalizedObjectsAsync(*, *, *, *)
// See [DetectLocalizedObjects](ref) for a synchronous example.
// End see-also
[Fact]
public void ErrorHandling_SingleImage()
{
// Sample: ErrorHandling_SingleImage
// We create a request which passes simple validation, but isn't a valid image.
Image image = Image.FromBytes(new byte[10]);
ImageAnnotatorClient client = ImageAnnotatorClient.Create();
try
{
IReadOnlyList<EntityAnnotation> logos = client.DetectLogos(image);
// Normally use logos here...
}
catch (AnnotateImageException e)
{
AnnotateImageResponse response = e.Response;
Console.WriteLine(response.Error);
}
// End sample
}
[Fact]
public void DetectSimilarProducts()
{
Image image = LoadResourceImage("shoes_1.jpg");
string projectId = _fixture.ProjectId;
string locationId = "us-west1";
string productSetId = $"{projectId}_product_search_test";
// Sample: ProductSearch
// Additional: DetectSimilarProducts(*, *, *)
ProductSetName productSetName = new ProductSetName(projectId, locationId, productSetId);
ImageAnnotatorClient client = ImageAnnotatorClient.Create();
ProductSearchParams searchParams = new ProductSearchParams
{
ProductCategories = { "apparel" },
ProductSetAsProductSetName = productSetName,
};
ProductSearchResults results = client.DetectSimilarProducts(image, searchParams);
foreach (var result in results.Results)
{
Console.WriteLine($"{result.Product.DisplayName}: {result.Score}");
}
// End sample
}
// See-also: DetectSimilarProducts(*, *, *)
// Member: DetectSimilarProductsAsync(*, *, *)
// See [DetectSimilarProducts](ref) for a synchronous example.
// End see-also
[Fact]
public void DetectSimilarProducts_WithFilter()
{
Image image = LoadResourceImage("shoes_1.jpg");
string projectId = _fixture.ProjectId;
string locationId = "us-west1";
string productSetId = $"{projectId}_product_search_test";
// Sample: ProductSearchWithFilter
ProductSetName productSetName = new ProductSetName(projectId, locationId, productSetId);
ImageAnnotatorClient client = ImageAnnotatorClient.Create();
ProductSearchParams searchParams = new ProductSearchParams
{
ProductCategories = { "apparel" },
ProductSetAsProductSetName = productSetName,
Filter = "style=womens"
};
ProductSearchResults results = client.DetectSimilarProducts(image, searchParams);
foreach (var result in results.Results)
{
Console.WriteLine($"{result.Product.DisplayName}: {result.Score}");
}
// End sample
}
private static Image LoadResourceImage(string name)
{
var type = typeof(ImageAnnotatorClientSnippets);
using (var stream = type.GetTypeInfo().Assembly.GetManifestResourceStream($"{type.Namespace}.{name}"))
{
return Image.FromStream(stream);
}
}
}
}
| |
namespace GenerateDto
{
using System;
using System.Collections.Generic;
using System.Linq;
public static class CodeBuilder
{
private static readonly Dictionary<string, string> MethodNameMap = new()
{
{ "getAllArtworkStatuses", "ArtworkStatuses" },
{ "getAllArtworkTypes", "ArtworkTypes" },
{ "getAllAwards", "Awards" },
{ "getAllCompanies", "Companies" },
{ "getAllContentRatings", "ContentRatings" },
{ "getAllCountries", "Countries" },
{ "getAllGenders", "Genders" },
{ "getAllGenres", "Genres" },
{ "getAllLanguages", "Languages" },
{ "getAllLists", "Lists" },
{ "getAllMovie", "Movies" },
{ "getAllMovieStatuses", "MovieStatuses" },
{ "getAllPeopleTypes", "PeopleTypes" },
{ "getAllSeasons", "Seasons" },
{ "getAllSeries", "AllSeries" },
{ "getAllSeriesStatuses", "SeriesStatuses" },
{ "getAllSourceTypes", "SourceTypes" },
{ "getArtworkBase", "Artwork" },
{ "getArtworkExtended", "ArtworkExtended" },
{ "getArtworkTranslation", "ArtworkTranslation" },
{ "getAward", "Award" },
{ "getAwardCategory", "AwardCategory" },
{ "getAwardCategoryExtended", "AwardCategoryExtended" },
{ "getAwardExtended", "AwardExtended" },
{ "getCharacterBase", "Character" },
{ "getCompany", "Company" },
{ "getCompanyTypes", "CompanyTypes" },
{ "getEntityTypes", "EntityTypes" },
{ "getEpisodeBase", "Episode" },
{ "getEpisodeExtended", "EpisodeExtended" },
{ "getEpisodeTranslation", "EpisodeTranslation" },
{ "getGenreBase", "Genre" },
{ "getList", "List" },
{ "getListExtended", "ListExtended" },
{ "getListTranslation", "ListTranslation" },
{ "getMovieBase", "Movie" },
{ "getMovieExtended", "MovieExtended" },
{ "getMovieTranslation", "MovieTranslation" },
{ "getPeopleBase", "People" },
{ "getPeopleExtended", "PeopleExtended" },
{ "getPeopleTranslation", "PeopleTranslation" },
{ "getSearchResults", "Search" },
{ "getSeasonBase", "Season" },
{ "getSeasonExtended", "SeasonExtended" },
{ "getSeasonTranslation", "SeasonTranslation" },
{ "getSeasonTypes", "SeasonTypes" },
{ "getSeriesBase", "Series" },
{ "getSeriesExtended", "SeriesExtended" },
{ "getSeriesEpisodes", "SeriesEpisodes" },
{ "getSeriesSeasonEpisodesTranslated", "SeriesSeasonEpisodesTranslated" },
{ "getSeriesTranslation", "SeriesTranslation" },
{ "updates", "Updates" },
{ "getAllInspirationTypes", "InspirationTypes" },
};
private static readonly List<PropertyOverrideModel> PropertyOverrides = new()
{
new()
{
MatchClassName = "ArtworkExtendedRecordDto",
MatchFieldName = "peopleId",
OverrideType = "int?",
},
new()
{
MatchClassName = "ArtworkExtendedRecordDto",
MatchFieldName = "seasonId",
OverrideType = "int?",
},
new()
{
MatchClassName = "ArtworkExtendedRecordDto",
MatchFieldName = "episodeId",
OverrideType = "int?",
},
new()
{
MatchClassName = "ArtworkExtendedRecordDto",
MatchFieldName = "seriesPeopleId",
OverrideType = "int?",
},
new()
{
MatchClassName = "ArtworkExtendedRecordDto",
MatchFieldName = "networkId",
OverrideType = "int?",
},
new()
{
MatchClassName = "ArtworkExtendedRecordDto",
MatchFieldName = "movieId",
OverrideType = "int?",
},
new()
{
MatchClassName = "MovieBaseRecordDto",
MatchFieldName = "score",
OverrideType = "double?",
},
new()
{
MatchClassName = "CharacterDto",
MatchFieldName = "episodeId",
OverrideType = "int?",
},
new()
{
MatchClassName = "CharacterDto",
MatchFieldName = "movieId",
OverrideType = "int?",
},
new()
{
MatchClassName = "CompanyTypeDto",
MatchFieldName = "id",
OverrideFieldName = "companyTypeId",
OverridePropertyName = "CompanyTypeId",
OverridePropertyAttributes = new List<string>
{
"[JsonProperty(\"companyTypeId\")]",
},
},
new()
{
MatchClassName = "CompanyTypeDto",
MatchFieldName = "name",
OverrideFieldName = "companyTypeName",
OverridePropertyName = "CompanyTypeName",
OverridePropertyAttributes = new List<string>
{
"[JsonProperty(\"companyTypeName\")]",
},
},
new()
{
MatchClassName = "SeasonTypeDto",
MatchFieldName = "type",
OverrideType = "string",
},
new()
{
MatchClassName = "CompaniesDto",
MatchFieldName = "specialEffects",
OverrideFieldName = "special_effects",
OverrideType = "CompanyDto[]",
OverridePropertyAttributes = new List<string>
{
"[JsonProperty(\"special_effects\")]",
},
},
new()
{
MatchClassName = "CompaniesDto",
MatchFieldName = "studio",
OverrideType = "CompanyDto[]",
},
new()
{
MatchClassName = "CompaniesDto",
MatchFieldName = "network",
OverrideType = "CompanyDto[]",
},
new()
{
MatchClassName = "CompaniesDto",
MatchFieldName = "production",
OverrideType = "CompanyDto[]",
},
new()
{
MatchClassName = "CompaniesDto",
MatchFieldName = "distributor",
OverrideType = "CompanyDto[]",
},
new()
{
MatchClassName = "EpisodeBaseRecordDto",
MatchFieldName = "imageType",
OverrideType = "int?",
},
new()
{
MatchClassName = "EpisodeBaseRecordDto",
MatchFieldName = "runtime",
OverrideType = "int?",
},
new()
{
MatchClassName = "EpisodeExtendedRecordDto",
MatchFieldName = "airsAfterSeason",
OverrideType = "int?",
},
new()
{
MatchClassName = "EpisodeExtendedRecordDto",
MatchFieldName = "airsBeforeSeason",
OverrideType = "int?",
},
new()
{
MatchClassName = "EpisodeExtendedRecordDto",
MatchFieldName = "airsBeforeEpisode",
OverrideType = "int?",
},
new()
{
MatchClassName = "EpisodeExtendedRecordDto",
MatchFieldName = "imageType",
OverrideType = "int?",
},
new()
{
MatchClassName = "EpisodeExtendedRecordDto",
MatchFieldName = "runtime",
OverrideType = "int?",
},
new()
{
MatchClassName = "EntityDto",
MatchFieldName = "seriesId",
OverrideType = "int?",
},
new()
{
MatchClassName = "MovieBaseRecordDto",
MatchFieldName = "runtime",
OverrideType = "int?",
},
new()
{
MatchClassName = "MovieExtendedRecordDto",
MatchFieldName = "score",
OverrideType = "double?",
},
new()
{
MatchClassName = "CharacterDto",
MatchFieldName = "seriesId",
OverrideType = "int?",
},
new()
{
MatchClassName = "MovieExtendedRecordDto",
MatchFieldName = "productionCountries",
OverrideFieldName = "production_countries",
OverridePropertyAttributes = new List<string>
{
"[JsonProperty(\"production_countries\")]",
},
},
new()
{
MatchClassName = "MovieExtendedRecordDto",
MatchFieldName = "spokenLanguages",
OverrideFieldName = "spoken_languages",
OverridePropertyAttributes = new List<string>
{
"[JsonProperty(\"spoken_languages\")]",
},
},
new()
{
MatchClassName = "MovieExtendedRecordDto",
MatchFieldName = "firstRelease",
OverrideFieldName = "first_release",
OverridePropertyAttributes = new List<string>
{
"[JsonProperty(\"first_release\")]",
},
},
new()
{
MatchClassName = "SearchResultDto",
MatchFieldName = "extendedTitle",
OverrideFieldName = "extended_title",
OverridePropertyAttributes = new List<string>
{
"[JsonProperty(\"extended_title\")]",
},
},
new()
{
MatchClassName = "SearchResultDto",
MatchFieldName = "imageUrl",
OverrideFieldName = "image_url",
OverridePropertyAttributes = new List<string>
{
"[JsonProperty(\"image_url\")]",
},
},
new()
{
MatchClassName = "SearchResultDto",
MatchFieldName = "primaryLanguage",
OverrideFieldName = "primary_language",
OverridePropertyAttributes = new List<string>
{
"[JsonProperty(\"primary_language\")]",
},
},
new()
{
MatchClassName = "SearchResultDto",
MatchFieldName = "translations",
OverrideType = "Dictionary<string, string>",
},
new()
{
MatchClassName = "SearchResultDto",
MatchFieldName = "overviews",
OverrideType = "Dictionary<string, string>",
},
new()
{
MatchClassName = "SearchResultDto",
MatchFieldName = "remoteIds",
OverrideFieldName = "remote_ids",
OverridePropertyAttributes = new List<string>
{
"[JsonProperty(\"remote_ids\")]",
},
},
new()
{
MatchClassName = "SearchResultDto",
MatchFieldName = "nameTranslated",
OverrideFieldName = "name_translated",
OverridePropertyAttributes = new List<string>
{
"[JsonProperty(\"name_translated\")]",
},
},
new()
{
MatchClassName = "SeasonBaseRecordDto",
MatchFieldName = "imageType",
OverrideType = "int?",
},
new()
{
MatchClassName = "SeasonExtendedRecordDto",
MatchFieldName = "type",
OverrideType = "SeasonTypeDto",
},
new()
{
MatchClassName = "SeasonExtendedRecordDto",
MatchFieldName = "imageType",
OverrideType = "int?",
},
new()
{
MatchClassName = "StatusDto",
MatchFieldName = "id",
OverrideType = "long?",
},
new()
{
MatchClassName = "ArtworkExtendedRecordDto",
MatchFieldName = "seriesId",
OverrideType = "int?",
},
new()
{
MatchClassName = "SeriesBaseRecordDto",
MatchFieldName = "averageRuntime",
OverrideType = "int?",
},
};
private static readonly Dictionary<string, List<PropertyModel>> ExtraProperties = new()
{
{
"ArtworkExtendedRecordDto", new List<PropertyModel>
{
new()
{
FieldName = "status",
PropertyName = "Status",
PropertyType = "object",
PropertyAttributes = new List<string>
{
"[JsonIgnore]",
},
},
}
},
{
"CharacterDto", new List<PropertyModel>
{
new()
{
FieldName = "peopleType",
PropertyName = "PeopleType",
PropertyType = "string",
PropertyAttributes = new List<string>
{
"[JsonProperty(\"peopleType\")]",
},
},
new()
{
FieldName = "tagOptions",
PropertyName = "TagOptions",
PropertyType = "TagOptionDto[]",
PropertyAttributes = new List<string>
{
"[JsonProperty(\"tagOptions\")]",
},
},
}
},
{
"CompanyDto", new List<PropertyModel>
{
new()
{
FieldName = "companyType",
PropertyName = "CompanyType",
PropertyType = "CompanyTypeDto",
PropertyAttributes = new List<string>
{
"[JsonProperty(\"companyType\")]",
},
},
new()
{
FieldName = "tagOptions",
PropertyName = "TagOptions",
PropertyType = "TagOptionDto[]",
PropertyAttributes = new List<string>
{
"[JsonProperty(\"tagOptions\")]",
},
},
}
},
{
"EpisodeBaseRecordDto", new List<PropertyModel>
{
new()
{
FieldName = "overview",
PropertyName = "Overview",
PropertyType = "string",
PropertyAttributes = new List<string>
{
"[JsonProperty(\"overview\")]",
},
},
}
},
{
"EpisodeExtendedRecordDto", new List<PropertyModel>
{
new()
{
FieldName = "overview",
PropertyName = "Overview",
PropertyType = "string",
PropertyAttributes = new List<string>
{
"[JsonProperty(\"overview\")]",
},
},
new()
{
FieldName = "nominations",
PropertyName = "Nominations",
PropertyType = "string",
PropertyAttributes = new List<string>
{
"[JsonProperty(\"nominations\")]",
},
},
new()
{
FieldName = "networks",
PropertyName = "Networks",
PropertyType = "string",
PropertyAttributes = new List<string>
{
"[JsonProperty(\"networks\")]",
},
},
new()
{
FieldName = "studios",
PropertyName = "Studios",
PropertyType = "StudioBaseRecordDto[]",
PropertyAttributes = new List<string>
{
"[JsonProperty(\"studios\")]",
},
},
}
},
{
"MovieExtendedRecordDto", new List<PropertyModel>
{
new()
{
FieldName = "runtime",
PropertyName = "Runtime",
PropertyType = "int",
PropertyAttributes = new List<string>
{
"[JsonProperty(\"runtime\")]",
},
},
new()
{
FieldName = "lastUpdated",
PropertyName = "LastUpdated",
PropertyType = "string",
PropertyAttributes = new List<string>
{
"[JsonProperty(\"lastUpdated\")]",
},
},
}
},
{
"PeopleExtendedRecordDto", new List<PropertyModel>
{
new()
{
FieldName = "nameTranslations",
PropertyName = "NameTranslations",
PropertyType = "string[]",
PropertyAttributes = new List<string>
{
"[JsonProperty(\"nameTranslations\")]",
},
},
new()
{
FieldName = "overviewTranslations",
PropertyName = "OverviewTranslations",
PropertyType = "string[]",
PropertyAttributes = new List<string>
{
"[JsonProperty(\"overviewTranslations\")]",
},
},
new()
{
FieldName = "translations",
PropertyName = "Translations",
PropertyType = "object",
PropertyAttributes = new List<string>
{
"[JsonIgnore]",
},
},
}
},
{
"SearchResultDto", new List<PropertyModel>
{
new()
{
FieldName = "studios",
PropertyName = "Studios",
PropertyType = "string[]",
PropertyAttributes = new List<string>
{
"[JsonProperty(\"studios\")]",
},
},
new()
{
FieldName = "first_air_time",
PropertyName = "FirstAirTime",
PropertyType = "string",
PropertyAttributes = new List<string>
{
"[JsonProperty(\"first_air_time\")]",
},
},
new()
{
FieldName = "extended_title",
PropertyName = "ExtendedTitle",
PropertyType = "string",
PropertyAttributes = new List<string>
{
"[JsonProperty(\"extended_title\")]",
},
},
}
},
{
"SeriesExtendedRecordDto", new List<PropertyModel>
{
new()
{
FieldName = "lastUpdated",
PropertyName = "LastUpdated",
PropertyType = "string",
PropertyAttributes = new List<string>
{
"[JsonProperty(\"lastUpdated\")]",
},
},
new()
{
FieldName = "averageRuntime",
PropertyName = "AverageRuntime",
PropertyType = "int?",
PropertyAttributes = new List<string>
{
"[JsonProperty(\"averageRuntime\")]",
},
},
new()
{
FieldName = "airsTimeUTC",
PropertyName = "AirsTimeUTC",
PropertyType = "string",
PropertyAttributes = new List<string>
{
"[JsonProperty(\"airsTimeUTC\")]",
},
},
new()
{
FieldName = "episodes",
PropertyName = "Episodes",
PropertyType = "EpisodeBaseRecordDto[]",
PropertyAttributes = new List<string>
{
"[JsonProperty(\"episodes\")]",
},
},
}
},
{
"ListBaseRecordDto", new List<PropertyModel>
{
new()
{
FieldName = "image",
PropertyName = "Image",
PropertyType = "string",
PropertyAttributes = new List<string>
{
"[JsonProperty(\"image\")]",
},
},
new()
{
FieldName = "imageIsFallback",
PropertyName = "ImageIsFallback",
PropertyType = "bool",
PropertyAttributes = new List<string>
{
"[JsonProperty(\"imageIsFallback\")]",
},
},
}
},
};
private static readonly Dictionary<string, string> MethodReturnTypeOverrides = new()
{
{ "getSeriesEpisodes", "GetSeriesEpisodesResponseData" },
{ "getSeriesSeasonEpisodesTranslated", "SeriesExtendedRecordDto" },
{ "getListTranslation", "TranslationDto[]" },
{ "getSeasonTypes", "SeasonTypeDto[]" },
};
public static NamespaceModel GetNamespace(SwaggerConfig swaggerConfig)
{
var tvdbClient = new ClassModel
{
ClassName = "TvDbClient",
Partial = true,
};
var ns = new NamespaceModel
{
NamespaceName = "TvDbSharper",
TopLevelComments = new List<string>
{
"// ReSharper disable HeapView.BoxingAllocation",
"// ReSharper disable MemberCanBePrivate.Global",
"// ReSharper disable UnusedMember.Global",
"// ReSharper disable RedundantStringInterpolation",
},
Usings = new List<string>
{
"System.Threading",
"System.Threading.Tasks",
"Newtonsoft.Json",
"System.Collections.Generic",
},
Classes = new List<ClassModel>
{
tvdbClient,
},
};
// Generate client methods
foreach ((string path, var rest) in swaggerConfig.Paths)
{
if (path == "/login")
{
continue;
}
var requestInfo = rest.Single().Value;
string url = path.TrimStart('/');
var pathParameters = (requestInfo.Parameters ?? Array.Empty<ParameterInfo>()).Where(x => x.In == "path").ToList();
var methodArgumentsMap = pathParameters.ToDictionary(x => x.Name, x => new MethodArgument
{
Type = GetParameterType(x),
Name = KebabToPascal(x.Name),
});
foreach ((string key, var methodArgument) in methodArgumentsMap)
{
url = url.Replace(key, methodArgument.Name);
}
var returnType = GetMethodReturnType(requestInfo);
string methodName = MethodNameMap[requestInfo.OperationId];
// With CT
tvdbClient.Methods.Add(new MethodModel
{
MethodName = methodName,
Arguments = methodArgumentsMap.Values
.Concat(new[] { new MethodArgument { Type = "CancellationToken", Name = "cancellationToken" } }).ToList(),
ReturnType = $"Task<TvDbApiResponse<{returnType}>>",
Body = $"return this.Get<{returnType}>($\"{url}\", null, cancellationToken);",
});
// Without CT
tvdbClient.Methods.Add(new MethodModel
{
MethodName = methodName,
Arguments = methodArgumentsMap.Values.ToList(),
ReturnType = $"Task<TvDbApiResponse<{returnType}>>",
Body =
$"return this.{methodName}({string.Join(", ", methodArgumentsMap.Values.Select(x => x.Name).Concat(new[] { "CancellationToken.None" }))});",
});
var queryParameters = (requestInfo.Parameters ?? Array.Empty<ParameterInfo>()).Where(x => x.In == "query").ToList();
if (queryParameters.Any())
{
string optionalParamsClassName = methodName + "OptionalParams";
var optionalParamsClass = new ClassModel
{
ClassName = optionalParamsClassName,
Properties = queryParameters.Select(x => new PropertyModel
{
PropertyName = CamelCase(x.Name),
PropertyType = GetQueryParameterType(x),
PropertyAttributes = new List<string>
{
$"[QueryParameter(\"{x.Name}\")]",
},
}).ToList(),
};
ns.Classes.Add(optionalParamsClass);
// With optional parameters and CT
tvdbClient.Methods.Add(new MethodModel
{
MethodName = methodName,
Arguments = methodArgumentsMap.Values
.Concat(new[]
{
new MethodArgument { Type = optionalParamsClassName, Name = "optionalParameters" },
new MethodArgument { Type = "CancellationToken", Name = "cancellationToken" },
}).ToList(),
ReturnType = $"Task<TvDbApiResponse<{returnType}>>",
Body = $"return this.Get<{returnType}>($\"{url}\", optionalParameters, cancellationToken);",
});
// With optional parameters and without CT
tvdbClient.Methods.Add(new MethodModel
{
MethodName = methodName,
Arguments = methodArgumentsMap.Values.Concat(new[]
{
new MethodArgument { Type = optionalParamsClassName, Name = "optionalParameters" },
}).ToList(),
ReturnType = $"Task<TvDbApiResponse<{returnType}>>",
Body =
$"return this.{methodName}({string.Join(", ", methodArgumentsMap.Values.Select(x => x.Name).Concat(new[] { "optionalParameters", "CancellationToken.None" }))});",
});
}
}
// Generate Dto classes
foreach ((string modelName, var model) in swaggerConfig.Components.Schemas)
{
var classModel = new ClassModel
{
ClassName = modelName + "Dto",
Properties = new List<PropertyModel>(),
};
if (model.Properties != null)
{
foreach ((string fieldName, var propertyType) in model.Properties)
{
string propertyName = GetPropertyName(fieldName);
classModel.Properties.Add(new PropertyModel
{
FieldName = fieldName,
PropertyName = propertyName,
PropertyType = GetComplexType(fieldName, propertyType),
PropertyAttributes = new List<string>
{
$"[JsonProperty(\"{fieldName}\")]",
},
});
}
}
ns.Classes.Add(classModel);
}
foreach ((string _, var methodMap) in swaggerConfig.Paths)
{
foreach ((string method, var requestInfo) in methodMap)
{
if (method != "get")
{
continue;
}
var classModel = new ClassModel
{
ClassName = char.ToUpper(requestInfo.OperationId[0]) + requestInfo.OperationId.Remove(0, 1) + "Response",
Properties = new List<PropertyModel>(),
};
var properties = requestInfo.Responses["200"].Content["application/json"].Schema.Properties;
foreach ((string fieldName, var propertyType) in properties)
{
string propertyName = GetPropertyName(fieldName);
if (propertyType.Type == "object")
{
// Create a new class for the data property.
string dataClassName = classModel.ClassName + "Data";
var dataClassProperties = propertyType.Properties;
var dataClass = CreateDataClass(dataClassName, dataClassProperties);
ns.Classes.Add(dataClass);
classModel.Properties.Add(new PropertyModel
{
FieldName = fieldName,
PropertyName = propertyName,
PropertyType = dataClass.ClassName,
PropertyAttributes = new List<string>
{
$"[JsonProperty(\"{fieldName}\")]",
},
});
}
else
{
classModel.Properties.Add(new PropertyModel
{
FieldName = fieldName,
PropertyName = propertyName,
PropertyType = GetComplexType(fieldName, propertyType),
PropertyAttributes = new List<string>
{
$"[JsonProperty(\"{fieldName}\")]",
},
});
}
}
// Ignore this for now. If the abstraction that replaces it fails then used it.
// ns.Classes.Add(classModel);
}
}
ApplyDtoPropertyOverrides(ns);
return ns;
}
private static string GetQueryParameterType(ParameterInfo parameterInfo)
{
string type = GetParameterType(parameterInfo);
return type switch
{
"int" => "int?",
_ => type,
};
}
private static string GetParameterType(ParameterInfo parameterInfo)
{
return parameterInfo.Schema.Type switch
{
"integer" => "int",
"number" => "int",
_ => parameterInfo.Schema.Type,
};
}
private static string GetMethodReturnType(RequestInfo requestInfo)
{
if (MethodReturnTypeOverrides.ContainsKey(requestInfo.OperationId))
{
return MethodReturnTypeOverrides[requestInfo.OperationId];
}
var returnData = requestInfo.Responses["200"].Content["application/json"].Schema.Properties["data"];
string returnType = "unknown";
if (returnData.Reference != null)
{
returnType = returnData.Reference.Split('/')[^1] + "Dto";
}
else if (returnData.Type == "array")
{
returnType = returnData.Items.Reference.Split('/')[^1] + "Dto[]";
}
return returnType;
}
private static string CamelCase(string name)
{
char[] array = name.ToCharArray();
array[0] = char.ToUpper(array[0]);
return new string(array);
}
private static string KebabToPascal(string name)
{
var parts = name.Split('-').Select((x, i) =>
{
if (i == 0)
{
return x;
}
return x[0].ToString().ToUpper() + x[1..];
});
return string.Join("", parts);
}
private static ClassModel CreateDataClass(string className, Dictionary<string, TypeModel> dataClassProperties)
{
var classModel = new ClassModel
{
ClassName = className,
Properties = new List<PropertyModel>(),
};
foreach ((string fieldName, var propertyType) in dataClassProperties)
{
string propertyName = GetPropertyName(fieldName);
classModel.Properties.Add(new PropertyModel
{
FieldName = fieldName,
PropertyName = propertyName,
PropertyType = GetComplexType(fieldName, propertyType),
PropertyAttributes = new List<string>
{
$"[JsonProperty(\"{fieldName}\")]",
},
});
}
return classModel;
}
private static string GetPropertyName(string fieldName)
{
string name = char.ToUpper(fieldName[0]) + fieldName.Remove(0, 1);
var parts = name.Split('_');
if (parts.Length == 1)
{
return name;
}
name = parts[0];
foreach (string part in parts.Skip(1))
{
name += char.ToUpper(part[0]) + part.Remove(0, 1);
}
return name;
}
private static string GetComplexType(string fieldName, TypeModel typeModel)
{
if (typeModel.Reference != null)
{
return GetReferenceName(typeModel.Reference);
}
if (typeModel.Format != null)
{
return GetFormat(typeModel.Format);
}
if (typeModel.Type != null)
{
return GetType(fieldName, typeModel);
}
if (typeModel.Items != null)
{
return GetComplexType(fieldName, typeModel.Items) + "[]";
}
// this is bullshit
if (fieldName == "name")
{
return "string";
}
throw new ApplicationException("Cannot find type information.");
}
private static string GetReferenceName(string reference)
{
return reference.Split('/')[^1] + "Dto";
}
private static string GetFormat(string format)
{
return format switch
{
"int64" => "long",
"double" => "double",
_ => throw new ApplicationException($"Unknown format `{format}`."),
};
}
private static string GetType(string fieldName, TypeModel typeModel)
{
return typeModel.Type switch
{
"string" => "string",
"number" => fieldName == "id" ? "long" : "int",
"integer" => fieldName == "id" ? "long" : "int",
"boolean" => "bool",
"array" => GetComplexType(fieldName, typeModel.Items) + "[]",
_ => throw new ApplicationException($"Unknown type `{typeModel.Type}`."),
};
}
private static void ApplyDtoPropertyOverrides(NamespaceModel namespaceModel)
{
foreach (var classModel in namespaceModel.Classes)
{
if (ExtraProperties.ContainsKey(classModel.ClassName))
{
classModel.Properties.AddRange(ExtraProperties[classModel.ClassName]);
}
foreach (var modelProperty in classModel.Properties)
{
foreach (var overrideModel in PropertyOverrides)
{
if (classModel.ClassName == overrideModel.MatchClassName && modelProperty.FieldName == overrideModel.MatchFieldName)
{
if (overrideModel.OverrideType != null)
{
modelProperty.PropertyType = overrideModel.OverrideType;
}
if (overrideModel.OverridePropertyName != null)
{
modelProperty.PropertyName = overrideModel.OverridePropertyName;
}
if (overrideModel.OverrideFieldName != null)
{
modelProperty.FieldName = overrideModel.OverrideFieldName;
}
if (overrideModel.OverridePropertyAttributes.Any())
{
modelProperty.PropertyAttributes = overrideModel.OverridePropertyAttributes;
}
}
}
}
}
}
}
public class NamespaceModel
{
public List<string> TopLevelComments { get; set; } = new();
public string NamespaceName { get; set; }
public List<string> Usings { get; set; } = new();
public List<ClassModel> Classes { get; set; } = new();
}
public class ClassModel
{
public string ClassName { get; set; }
public bool Partial { get; set; }
public List<PropertyModel> Properties { get; set; } = new();
public List<MethodModel> Methods { get; set; } = new();
public bool IsEmpty => !this.Properties.Any() && !this.Methods.Any();
}
public class PropertyModel
{
public string FieldName { get; set; }
public string PropertyName { get; set; }
public string PropertyType { get; set; }
public List<string> PropertyAttributes { get; set; } = new();
}
public class MethodModel
{
public List<MethodArgument> Arguments { get; set; } = new();
public string ReturnType { get; set; }
public string MethodName { get; set; }
public string Body { get; set; }
}
public class MethodArgument
{
public string Type { get; set; }
public string Name { get; set; }
}
public class PropertyOverrideModel
{
public string MatchClassName { get; set; }
public string MatchFieldName { get; set; }
public string OverrideType { get; set; }
public string OverridePropertyName { get; set; }
public string OverrideFieldName { get; set; }
public List<string> OverridePropertyAttributes { get; set; } = new();
}
}
| |
/*
* Copyright (C) Sony Computer Entertainment America LLC.
* All Rights Reserved.
*/
using Sce.Atf.Adaptation;
using Sce.Atf.Applications;
using Sce.Atf.Dom;
using Sce.Sled.Shared.Resources;
using Sce.Sled.SyntaxEditor;
namespace Sce.Sled.Shared.Dom
{
/// <summary>
/// Complex Type of a breakpoint
/// </summary>
public class SledProjectFilesBreakpointType : DomNodeAdapter, IItemView
{
/// <summary>
/// Gets the parent as a SledProjectFilesFileType
/// </summary>
public SledProjectFilesFileType File
{
get { return DomNode.Parent.As<SledProjectFilesFileType>(); }
}
/// <summary>
/// Gets or sets the line attribute
/// </summary>
public int Line
{
get
{
if (Breakpoint != null)
SetAttribute(SledSchema.SledProjectFilesBreakpointType.lineAttribute, Breakpoint.LineNumber);
return GetAttribute<int>(SledSchema.SledProjectFilesBreakpointType.lineAttribute);
}
set { SetAttribute(SledSchema.SledProjectFilesBreakpointType.lineAttribute, value); }
}
/// <summary>
/// Gets or sets the enabled attribute
/// </summary>
public bool Enabled
{
get
{
if (Breakpoint == null)
return GetAttribute<bool>(SledSchema.SledProjectFilesBreakpointType.enabledAttribute);
return Breakpoint.Enabled;
}
set
{
if (Breakpoint != null)
Breakpoint.Enabled = value;
SetAttribute(SledSchema.SledProjectFilesBreakpointType.enabledAttribute, value);
}
}
/// <summary>
/// Gets or sets the condition attribute
/// </summary>
public string Condition
{
get { return GetAttribute<string>(SledSchema.SledProjectFilesBreakpointType.conditionAttribute); }
set { SetAttribute(SledSchema.SledProjectFilesBreakpointType.conditionAttribute, value); }
}
/// <summary>
/// Gets or sets the condition enabled attribute
/// </summary>
public bool ConditionEnabled
{
get { return GetAttribute<bool>(SledSchema.SledProjectFilesBreakpointType.conditionenabledAttribute); }
set
{
if (Breakpoint != null)
Breakpoint.Marker = value;
SetAttribute(SledSchema.SledProjectFilesBreakpointType.conditionenabledAttribute, value);
}
}
/// <summary>
/// Gets or sets the result the condition is expecting
/// </summary>
public bool ConditionResult
{
get { return GetAttribute<bool>(SledSchema.SledProjectFilesBreakpointType.conditionresultAttribute); }
set { SetAttribute(SledSchema.SledProjectFilesBreakpointType.conditionresultAttribute, value); }
}
/// <summary>
/// Gets or sets whether to use the current function's environment or _G
/// </summary>
public bool UseFunctionEnvironment
{
get { return GetAttribute<bool>(SledSchema.SledProjectFilesBreakpointType.usefunctionenvironmentAttribute); }
set { SetAttribute(SledSchema.SledProjectFilesBreakpointType.usefunctionenvironmentAttribute, value); }
}
/// <summary>
/// Gets or sets the actual IBreakpoint this breakpoint references
/// </summary>
public IBreakpoint Breakpoint { get; set; }
/// <summary>
/// Gets the raw line number from the line attribute
/// </summary>
public int RawLine
{
get { return GetAttribute<int>(SledSchema.SledProjectFilesBreakpointType.lineAttribute); }
}
/// <summary>
/// Gets or sets the line text
/// </summary>
/// <remarks>Value is string.Empty if the document isn't open</remarks>
public string LineText { get; set; }
private void Setup(IBreakpoint bp)
{
if (bp != null)
{
Line = bp.LineNumber;
Enabled = bp.Enabled;
LineText = bp.LineText;
Breakpoint = bp;
}
// Assume true for now
ConditionResult = true;
}
/// <summary>
/// Adjust some properties based on the live IBreakpoint object
/// </summary>
public void Refresh()
{
// Update from live IBreakpoint
if (Breakpoint == null)
return;
Line = Breakpoint.LineNumber;
Enabled = Breakpoint.Enabled;
LineText = Breakpoint.LineText;
}
#region IItemView Interface
/// <summary>
/// Fills in or modifies the given display info for the item</summary>
/// <param name="item">Item</param>
/// <param name="info">Display info to update</param>
public void GetInfo(object item, ItemInfo info)
{
info.Label = Enabled.ToString();
info.Properties =
new[]
{
File.Name,
Line.ToString(),
Condition,
ConditionEnabled.ToString(),
ConditionResult.ToString(),
(UseFunctionEnvironment ? "Environment" : "Global")
};
info.ImageIndex = info.GetImageIndex(Atf.Resources.DataImage);
info.IsLeaf = true;
}
#endregion
/// <summary>
/// Create a SLED style breakpoint from a SyntaxEditorControl style breakpoint
/// </summary>
/// <param name="ibp">SyntaxEditorControl style breakpoint</param>
/// <returns>SLED breakpoint</returns>
public static SledProjectFilesBreakpointType Create(IBreakpoint ibp)
{
var node = new DomNode(SledSchema.SledProjectFilesBreakpointType.Type);
var bp = node.As<SledProjectFilesBreakpointType>();
bp.Setup(ibp);
return bp;
}
/// <summary>
/// Column names
/// </summary>
public static readonly string[] TheColumnNames =
{
Localization.SledSharedEnabled,
Localization.SledSharedFile,
Localization.SledSharedLine,
Localization.SledSharedCondition,
Localization.SledSharedConditionEnabled,
Localization.SledSharedResult,
"Environment"
};
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using Xunit;
namespace System.Linq.Expressions.Tests
{
public static class LambdaSubtractTests
{
#region Test methods
[Fact]
public static void LambdaSubtractDecimalTest()
{
decimal[] values = new decimal[] { decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifySubtractDecimal(values[i], values[j]);
}
}
}
[Fact]
public static void LambdaSubtractDoubleTest()
{
double[] values = new double[] { 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifySubtractDouble(values[i], values[j]);
}
}
}
[Fact]
public static void LambdaSubtractFloatTest()
{
float[] values = new float[] { 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifySubtractFloat(values[i], values[j]);
}
}
}
[Fact]
public static void LambdaSubtractIntTest()
{
int[] values = new int[] { 0, 1, -1, int.MinValue, int.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifySubtractInt(values[i], values[j]);
}
}
}
[Fact]
public static void LambdaSubtractLongTest()
{
long[] values = new long[] { 0, 1, -1, long.MinValue, long.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifySubtractLong(values[i], values[j]);
}
}
}
[Fact]
public static void LambdaSubtractShortTest()
{
short[] values = new short[] { 0, 1, -1, short.MinValue, short.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifySubtractShort(values[i], values[j]);
}
}
}
[Fact]
public static void LambdaSubtractUIntTest()
{
uint[] values = new uint[] { 0, 1, uint.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifySubtractUInt(values[i], values[j]);
}
}
}
[Fact]
public static void LambdaSubtractULongTest()
{
ulong[] values = new ulong[] { 0, 1, ulong.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifySubtractULong(values[i], values[j]);
}
}
}
[Fact]
public static void LambdaSubtractUShortTest()
{
ushort[] values = new ushort[] { 0, 1, ushort.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifySubtractUShort(values[i], values[j]);
}
}
}
#endregion
#region Test verifiers
#region Verify decimal
private static void VerifySubtractDecimal(decimal a, decimal b)
{
ParameterExpression p0 = Expression.Parameter(typeof(decimal), "p0");
ParameterExpression p1 = Expression.Parameter(typeof(decimal), "p1");
// verify with parameters supplied
Expression<Func<decimal>> e1 =
Expression.Lambda<Func<decimal>>(
Expression.Invoke(
Expression.Lambda<Func<decimal, decimal, decimal>>(
Expression.Subtract(p0, p1),
new ParameterExpression[] { p0, p1 }),
new Expression[]
{
Expression.Constant(a, typeof(decimal)),
Expression.Constant(b, typeof(decimal))
}),
Enumerable.Empty<ParameterExpression>());
Func<decimal> f1 = e1.Compile();
decimal f1Result = default(decimal);
Exception f1Ex = null;
try
{
f1Result = f1();
}
catch (Exception ex)
{
f1Ex = ex;
}
// verify with values passed to make parameters
Expression<Func<decimal, decimal, Func<decimal>>> e2 =
Expression.Lambda<Func<decimal, decimal, Func<decimal>>>(
Expression.Lambda<Func<decimal>>(
Expression.Subtract(p0, p1),
Enumerable.Empty<ParameterExpression>()),
new ParameterExpression[] { p0, p1 });
Func<decimal, decimal, Func<decimal>> f2 = e2.Compile();
decimal f2Result = default(decimal);
Exception f2Ex = null;
try
{
f2Result = f2(a, b)();
}
catch (Exception ex)
{
f2Ex = ex;
}
// verify with values directly passed
Expression<Func<Func<decimal, decimal, decimal>>> e3 =
Expression.Lambda<Func<Func<decimal, decimal, decimal>>>(
Expression.Invoke(
Expression.Lambda<Func<Func<decimal, decimal, decimal>>>(
Expression.Lambda<Func<decimal, decimal, decimal>>(
Expression.Subtract(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>()),
Enumerable.Empty<Expression>()),
Enumerable.Empty<ParameterExpression>());
Func<decimal, decimal, decimal> f3 = e3.Compile()();
decimal f3Result = default(decimal);
Exception f3Ex = null;
try
{
f3Result = f3(a, b);
}
catch (Exception ex)
{
f3Ex = ex;
}
// verify as a function generator
Expression<Func<Func<decimal, decimal, decimal>>> e4 =
Expression.Lambda<Func<Func<decimal, decimal, decimal>>>(
Expression.Lambda<Func<decimal, decimal, decimal>>(
Expression.Subtract(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>());
Func<Func<decimal, decimal, decimal>> f4 = e4.Compile();
decimal f4Result = default(decimal);
Exception f4Ex = null;
try
{
f4Result = f4()(a, b);
}
catch (Exception ex)
{
f4Ex = ex;
}
// verify with currying
Expression<Func<decimal, Func<decimal, decimal>>> e5 =
Expression.Lambda<Func<decimal, Func<decimal, decimal>>>(
Expression.Lambda<Func<decimal, decimal>>(
Expression.Subtract(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 });
Func<decimal, Func<decimal, decimal>> f5 = e5.Compile();
decimal f5Result = default(decimal);
Exception f5Ex = null;
try
{
f5Result = f5(a)(b);
}
catch (Exception ex)
{
f5Ex = ex;
}
// verify with one parameter
Expression<Func<Func<decimal, decimal>>> e6 =
Expression.Lambda<Func<Func<decimal, decimal>>>(
Expression.Invoke(
Expression.Lambda<Func<decimal, Func<decimal, decimal>>>(
Expression.Lambda<Func<decimal, decimal>>(
Expression.Subtract(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 }),
new Expression[] { Expression.Constant(a, typeof(decimal)) }),
Enumerable.Empty<ParameterExpression>());
Func<decimal, decimal> f6 = e6.Compile()();
decimal f6Result = default(decimal);
Exception f6Ex = null;
try
{
f6Result = f6(b);
}
catch (Exception ex)
{
f6Ex = ex;
}
// verify with regular IL
decimal csResult = default(decimal);
Exception csEx = null;
try
{
csResult = (decimal)(a - b);
}
catch (Exception ex)
{
csEx = ex;
}
// either all should have failed the same way or they should all produce the same result
if (f1Ex != null || f2Ex != null || f3Ex != null || f4Ex != null || f5Ex != null || f6Ex != null || csEx != null)
{
Assert.NotNull(f1Ex);
Assert.NotNull(f2Ex);
Assert.NotNull(f3Ex);
Assert.NotNull(f4Ex);
Assert.NotNull(f5Ex);
Assert.NotNull(f6Ex);
Assert.NotNull(csEx);
Assert.Equal(csEx.GetType(), f1Ex.GetType());
Assert.Equal(csEx.GetType(), f2Ex.GetType());
Assert.Equal(csEx.GetType(), f3Ex.GetType());
Assert.Equal(csEx.GetType(), f4Ex.GetType());
Assert.Equal(csEx.GetType(), f5Ex.GetType());
Assert.Equal(csEx.GetType(), f6Ex.GetType());
}
else
{
Assert.Equal(csResult, f1Result);
Assert.Equal(csResult, f2Result);
Assert.Equal(csResult, f3Result);
Assert.Equal(csResult, f4Result);
Assert.Equal(csResult, f5Result);
Assert.Equal(csResult, f6Result);
}
}
#endregion
#region Verify double
private static void VerifySubtractDouble(double a, double b)
{
ParameterExpression p0 = Expression.Parameter(typeof(double), "p0");
ParameterExpression p1 = Expression.Parameter(typeof(double), "p1");
// verify with parameters supplied
Expression<Func<double>> e1 =
Expression.Lambda<Func<double>>(
Expression.Invoke(
Expression.Lambda<Func<double, double, double>>(
Expression.Subtract(p0, p1),
new ParameterExpression[] { p0, p1 }),
new Expression[]
{
Expression.Constant(a, typeof(double)),
Expression.Constant(b, typeof(double))
}),
Enumerable.Empty<ParameterExpression>());
Func<double> f1 = e1.Compile();
double f1Result = default(double);
Exception f1Ex = null;
try
{
f1Result = f1();
}
catch (Exception ex)
{
f1Ex = ex;
}
// verify with values passed to make parameters
Expression<Func<double, double, Func<double>>> e2 =
Expression.Lambda<Func<double, double, Func<double>>>(
Expression.Lambda<Func<double>>(
Expression.Subtract(p0, p1),
Enumerable.Empty<ParameterExpression>()),
new ParameterExpression[] { p0, p1 });
Func<double, double, Func<double>> f2 = e2.Compile();
double f2Result = default(double);
Exception f2Ex = null;
try
{
f2Result = f2(a, b)();
}
catch (Exception ex)
{
f2Ex = ex;
}
// verify with values directly passed
Expression<Func<Func<double, double, double>>> e3 =
Expression.Lambda<Func<Func<double, double, double>>>(
Expression.Invoke(
Expression.Lambda<Func<Func<double, double, double>>>(
Expression.Lambda<Func<double, double, double>>(
Expression.Subtract(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>()),
Enumerable.Empty<Expression>()),
Enumerable.Empty<ParameterExpression>());
Func<double, double, double> f3 = e3.Compile()();
double f3Result = default(double);
Exception f3Ex = null;
try
{
f3Result = f3(a, b);
}
catch (Exception ex)
{
f3Ex = ex;
}
// verify as a function generator
Expression<Func<Func<double, double, double>>> e4 =
Expression.Lambda<Func<Func<double, double, double>>>(
Expression.Lambda<Func<double, double, double>>(
Expression.Subtract(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>());
Func<Func<double, double, double>> f4 = e4.Compile();
double f4Result = default(double);
Exception f4Ex = null;
try
{
f4Result = f4()(a, b);
}
catch (Exception ex)
{
f4Ex = ex;
}
// verify with currying
Expression<Func<double, Func<double, double>>> e5 =
Expression.Lambda<Func<double, Func<double, double>>>(
Expression.Lambda<Func<double, double>>(
Expression.Subtract(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 });
Func<double, Func<double, double>> f5 = e5.Compile();
double f5Result = default(double);
Exception f5Ex = null;
try
{
f5Result = f5(a)(b);
}
catch (Exception ex)
{
f5Ex = ex;
}
// verify with one parameter
Expression<Func<Func<double, double>>> e6 =
Expression.Lambda<Func<Func<double, double>>>(
Expression.Invoke(
Expression.Lambda<Func<double, Func<double, double>>>(
Expression.Lambda<Func<double, double>>(
Expression.Subtract(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 }),
new Expression[] { Expression.Constant(a, typeof(double)) }),
Enumerable.Empty<ParameterExpression>());
Func<double, double> f6 = e6.Compile()();
double f6Result = default(double);
Exception f6Ex = null;
try
{
f6Result = f6(b);
}
catch (Exception ex)
{
f6Ex = ex;
}
// verify with regular IL
double csResult = default(double);
Exception csEx = null;
try
{
csResult = (double)(a - b);
}
catch (Exception ex)
{
csEx = ex;
}
// either all should have failed the same way or they should all produce the same result
if (f1Ex != null || f2Ex != null || f3Ex != null || f4Ex != null || f5Ex != null || f6Ex != null || csEx != null)
{
Assert.NotNull(f1Ex);
Assert.NotNull(f2Ex);
Assert.NotNull(f3Ex);
Assert.NotNull(f4Ex);
Assert.NotNull(f5Ex);
Assert.NotNull(f6Ex);
Assert.NotNull(csEx);
Assert.Equal(csEx.GetType(), f1Ex.GetType());
Assert.Equal(csEx.GetType(), f2Ex.GetType());
Assert.Equal(csEx.GetType(), f3Ex.GetType());
Assert.Equal(csEx.GetType(), f4Ex.GetType());
Assert.Equal(csEx.GetType(), f5Ex.GetType());
Assert.Equal(csEx.GetType(), f6Ex.GetType());
}
else
{
Assert.Equal(csResult, f1Result);
Assert.Equal(csResult, f2Result);
Assert.Equal(csResult, f3Result);
Assert.Equal(csResult, f4Result);
Assert.Equal(csResult, f5Result);
Assert.Equal(csResult, f6Result);
}
}
#endregion
#region Verify float
private static void VerifySubtractFloat(float a, float b)
{
ParameterExpression p0 = Expression.Parameter(typeof(float), "p0");
ParameterExpression p1 = Expression.Parameter(typeof(float), "p1");
// verify with parameters supplied
Expression<Func<float>> e1 =
Expression.Lambda<Func<float>>(
Expression.Invoke(
Expression.Lambda<Func<float, float, float>>(
Expression.Subtract(p0, p1),
new ParameterExpression[] { p0, p1 }),
new Expression[]
{
Expression.Constant(a, typeof(float)),
Expression.Constant(b, typeof(float))
}),
Enumerable.Empty<ParameterExpression>());
Func<float> f1 = e1.Compile();
float f1Result = default(float);
Exception f1Ex = null;
try
{
f1Result = f1();
}
catch (Exception ex)
{
f1Ex = ex;
}
// verify with values passed to make parameters
Expression<Func<float, float, Func<float>>> e2 =
Expression.Lambda<Func<float, float, Func<float>>>(
Expression.Lambda<Func<float>>(
Expression.Subtract(p0, p1),
Enumerable.Empty<ParameterExpression>()),
new ParameterExpression[] { p0, p1 });
Func<float, float, Func<float>> f2 = e2.Compile();
float f2Result = default(float);
Exception f2Ex = null;
try
{
f2Result = f2(a, b)();
}
catch (Exception ex)
{
f2Ex = ex;
}
// verify with values directly passed
Expression<Func<Func<float, float, float>>> e3 =
Expression.Lambda<Func<Func<float, float, float>>>(
Expression.Invoke(
Expression.Lambda<Func<Func<float, float, float>>>(
Expression.Lambda<Func<float, float, float>>(
Expression.Subtract(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>()),
Enumerable.Empty<Expression>()),
Enumerable.Empty<ParameterExpression>());
Func<float, float, float> f3 = e3.Compile()();
float f3Result = default(float);
Exception f3Ex = null;
try
{
f3Result = f3(a, b);
}
catch (Exception ex)
{
f3Ex = ex;
}
// verify as a function generator
Expression<Func<Func<float, float, float>>> e4 =
Expression.Lambda<Func<Func<float, float, float>>>(
Expression.Lambda<Func<float, float, float>>(
Expression.Subtract(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>());
Func<Func<float, float, float>> f4 = e4.Compile();
float f4Result = default(float);
Exception f4Ex = null;
try
{
f4Result = f4()(a, b);
}
catch (Exception ex)
{
f4Ex = ex;
}
// verify with currying
Expression<Func<float, Func<float, float>>> e5 =
Expression.Lambda<Func<float, Func<float, float>>>(
Expression.Lambda<Func<float, float>>(
Expression.Subtract(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 });
Func<float, Func<float, float>> f5 = e5.Compile();
float f5Result = default(float);
Exception f5Ex = null;
try
{
f5Result = f5(a)(b);
}
catch (Exception ex)
{
f5Ex = ex;
}
// verify with one parameter
Expression<Func<Func<float, float>>> e6 =
Expression.Lambda<Func<Func<float, float>>>(
Expression.Invoke(
Expression.Lambda<Func<float, Func<float, float>>>(
Expression.Lambda<Func<float, float>>(
Expression.Subtract(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 }),
new Expression[] { Expression.Constant(a, typeof(float)) }),
Enumerable.Empty<ParameterExpression>());
Func<float, float> f6 = e6.Compile()();
float f6Result = default(float);
Exception f6Ex = null;
try
{
f6Result = f6(b);
}
catch (Exception ex)
{
f6Ex = ex;
}
// verify with regular IL
float csResult = default(float);
Exception csEx = null;
try
{
csResult = (float)(a - b);
}
catch (Exception ex)
{
csEx = ex;
}
// either all should have failed the same way or they should all produce the same result
if (f1Ex != null || f2Ex != null || f3Ex != null || f4Ex != null || f5Ex != null || f6Ex != null || csEx != null)
{
Assert.NotNull(f1Ex);
Assert.NotNull(f2Ex);
Assert.NotNull(f3Ex);
Assert.NotNull(f4Ex);
Assert.NotNull(f5Ex);
Assert.NotNull(f6Ex);
Assert.NotNull(csEx);
Assert.Equal(csEx.GetType(), f1Ex.GetType());
Assert.Equal(csEx.GetType(), f2Ex.GetType());
Assert.Equal(csEx.GetType(), f3Ex.GetType());
Assert.Equal(csEx.GetType(), f4Ex.GetType());
Assert.Equal(csEx.GetType(), f5Ex.GetType());
Assert.Equal(csEx.GetType(), f6Ex.GetType());
}
else
{
Assert.Equal(csResult, f1Result);
Assert.Equal(csResult, f2Result);
Assert.Equal(csResult, f3Result);
Assert.Equal(csResult, f4Result);
Assert.Equal(csResult, f5Result);
Assert.Equal(csResult, f6Result);
}
}
#endregion
#region Verify int
private static void VerifySubtractInt(int a, int b)
{
ParameterExpression p0 = Expression.Parameter(typeof(int), "p0");
ParameterExpression p1 = Expression.Parameter(typeof(int), "p1");
// verify with parameters supplied
Expression<Func<int>> e1 =
Expression.Lambda<Func<int>>(
Expression.Invoke(
Expression.Lambda<Func<int, int, int>>(
Expression.Subtract(p0, p1),
new ParameterExpression[] { p0, p1 }),
new Expression[]
{
Expression.Constant(a, typeof(int)),
Expression.Constant(b, typeof(int))
}),
Enumerable.Empty<ParameterExpression>());
Func<int> f1 = e1.Compile();
int f1Result = default(int);
Exception f1Ex = null;
try
{
f1Result = f1();
}
catch (Exception ex)
{
f1Ex = ex;
}
// verify with values passed to make parameters
Expression<Func<int, int, Func<int>>> e2 =
Expression.Lambda<Func<int, int, Func<int>>>(
Expression.Lambda<Func<int>>(
Expression.Subtract(p0, p1),
Enumerable.Empty<ParameterExpression>()),
new ParameterExpression[] { p0, p1 });
Func<int, int, Func<int>> f2 = e2.Compile();
int f2Result = default(int);
Exception f2Ex = null;
try
{
f2Result = f2(a, b)();
}
catch (Exception ex)
{
f2Ex = ex;
}
// verify with values directly passed
Expression<Func<Func<int, int, int>>> e3 =
Expression.Lambda<Func<Func<int, int, int>>>(
Expression.Invoke(
Expression.Lambda<Func<Func<int, int, int>>>(
Expression.Lambda<Func<int, int, int>>(
Expression.Subtract(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>()),
Enumerable.Empty<Expression>()),
Enumerable.Empty<ParameterExpression>());
Func<int, int, int> f3 = e3.Compile()();
int f3Result = default(int);
Exception f3Ex = null;
try
{
f3Result = f3(a, b);
}
catch (Exception ex)
{
f3Ex = ex;
}
// verify as a function generator
Expression<Func<Func<int, int, int>>> e4 =
Expression.Lambda<Func<Func<int, int, int>>>(
Expression.Lambda<Func<int, int, int>>(
Expression.Subtract(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>());
Func<Func<int, int, int>> f4 = e4.Compile();
int f4Result = default(int);
Exception f4Ex = null;
try
{
f4Result = f4()(a, b);
}
catch (Exception ex)
{
f4Ex = ex;
}
// verify with currying
Expression<Func<int, Func<int, int>>> e5 =
Expression.Lambda<Func<int, Func<int, int>>>(
Expression.Lambda<Func<int, int>>(
Expression.Subtract(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 });
Func<int, Func<int, int>> f5 = e5.Compile();
int f5Result = default(int);
Exception f5Ex = null;
try
{
f5Result = f5(a)(b);
}
catch (Exception ex)
{
f5Ex = ex;
}
// verify with one parameter
Expression<Func<Func<int, int>>> e6 =
Expression.Lambda<Func<Func<int, int>>>(
Expression.Invoke(
Expression.Lambda<Func<int, Func<int, int>>>(
Expression.Lambda<Func<int, int>>(
Expression.Subtract(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 }),
new Expression[] { Expression.Constant(a, typeof(int)) }),
Enumerable.Empty<ParameterExpression>());
Func<int, int> f6 = e6.Compile()();
int f6Result = default(int);
Exception f6Ex = null;
try
{
f6Result = f6(b);
}
catch (Exception ex)
{
f6Ex = ex;
}
// verify with regular IL
int csResult = default(int);
Exception csEx = null;
try
{
csResult = (int)(a - b);
}
catch (Exception ex)
{
csEx = ex;
}
// either all should have failed the same way or they should all produce the same result
if (f1Ex != null || f2Ex != null || f3Ex != null || f4Ex != null || f5Ex != null || f6Ex != null || csEx != null)
{
Assert.NotNull(f1Ex);
Assert.NotNull(f2Ex);
Assert.NotNull(f3Ex);
Assert.NotNull(f4Ex);
Assert.NotNull(f5Ex);
Assert.NotNull(f6Ex);
Assert.NotNull(csEx);
Assert.Equal(csEx.GetType(), f1Ex.GetType());
Assert.Equal(csEx.GetType(), f2Ex.GetType());
Assert.Equal(csEx.GetType(), f3Ex.GetType());
Assert.Equal(csEx.GetType(), f4Ex.GetType());
Assert.Equal(csEx.GetType(), f5Ex.GetType());
Assert.Equal(csEx.GetType(), f6Ex.GetType());
}
else
{
Assert.Equal(csResult, f1Result);
Assert.Equal(csResult, f2Result);
Assert.Equal(csResult, f3Result);
Assert.Equal(csResult, f4Result);
Assert.Equal(csResult, f5Result);
Assert.Equal(csResult, f6Result);
}
}
#endregion
#region Verify long
private static void VerifySubtractLong(long a, long b)
{
ParameterExpression p0 = Expression.Parameter(typeof(long), "p0");
ParameterExpression p1 = Expression.Parameter(typeof(long), "p1");
// verify with parameters supplied
Expression<Func<long>> e1 =
Expression.Lambda<Func<long>>(
Expression.Invoke(
Expression.Lambda<Func<long, long, long>>(
Expression.Subtract(p0, p1),
new ParameterExpression[] { p0, p1 }),
new Expression[]
{
Expression.Constant(a, typeof(long)),
Expression.Constant(b, typeof(long))
}),
Enumerable.Empty<ParameterExpression>());
Func<long> f1 = e1.Compile();
long f1Result = default(long);
Exception f1Ex = null;
try
{
f1Result = f1();
}
catch (Exception ex)
{
f1Ex = ex;
}
// verify with values passed to make parameters
Expression<Func<long, long, Func<long>>> e2 =
Expression.Lambda<Func<long, long, Func<long>>>(
Expression.Lambda<Func<long>>(
Expression.Subtract(p0, p1),
Enumerable.Empty<ParameterExpression>()),
new ParameterExpression[] { p0, p1 });
Func<long, long, Func<long>> f2 = e2.Compile();
long f2Result = default(long);
Exception f2Ex = null;
try
{
f2Result = f2(a, b)();
}
catch (Exception ex)
{
f2Ex = ex;
}
// verify with values directly passed
Expression<Func<Func<long, long, long>>> e3 =
Expression.Lambda<Func<Func<long, long, long>>>(
Expression.Invoke(
Expression.Lambda<Func<Func<long, long, long>>>(
Expression.Lambda<Func<long, long, long>>(
Expression.Subtract(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>()),
Enumerable.Empty<Expression>()),
Enumerable.Empty<ParameterExpression>());
Func<long, long, long> f3 = e3.Compile()();
long f3Result = default(long);
Exception f3Ex = null;
try
{
f3Result = f3(a, b);
}
catch (Exception ex)
{
f3Ex = ex;
}
// verify as a function generator
Expression<Func<Func<long, long, long>>> e4 =
Expression.Lambda<Func<Func<long, long, long>>>(
Expression.Lambda<Func<long, long, long>>(
Expression.Subtract(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>());
Func<Func<long, long, long>> f4 = e4.Compile();
long f4Result = default(long);
Exception f4Ex = null;
try
{
f4Result = f4()(a, b);
}
catch (Exception ex)
{
f4Ex = ex;
}
// verify with currying
Expression<Func<long, Func<long, long>>> e5 =
Expression.Lambda<Func<long, Func<long, long>>>(
Expression.Lambda<Func<long, long>>(
Expression.Subtract(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 });
Func<long, Func<long, long>> f5 = e5.Compile();
long f5Result = default(long);
Exception f5Ex = null;
try
{
f5Result = f5(a)(b);
}
catch (Exception ex)
{
f5Ex = ex;
}
// verify with one parameter
Expression<Func<Func<long, long>>> e6 =
Expression.Lambda<Func<Func<long, long>>>(
Expression.Invoke(
Expression.Lambda<Func<long, Func<long, long>>>(
Expression.Lambda<Func<long, long>>(
Expression.Subtract(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 }),
new Expression[] { Expression.Constant(a, typeof(long)) }),
Enumerable.Empty<ParameterExpression>());
Func<long, long> f6 = e6.Compile()();
long f6Result = default(long);
Exception f6Ex = null;
try
{
f6Result = f6(b);
}
catch (Exception ex)
{
f6Ex = ex;
}
// verify with regular IL
long csResult = default(long);
Exception csEx = null;
try
{
csResult = (long)(a - b);
}
catch (Exception ex)
{
csEx = ex;
}
// either all should have failed the same way or they should all produce the same result
if (f1Ex != null || f2Ex != null || f3Ex != null || f4Ex != null || f5Ex != null || f6Ex != null || csEx != null)
{
Assert.NotNull(f1Ex);
Assert.NotNull(f2Ex);
Assert.NotNull(f3Ex);
Assert.NotNull(f4Ex);
Assert.NotNull(f5Ex);
Assert.NotNull(f6Ex);
Assert.NotNull(csEx);
Assert.Equal(csEx.GetType(), f1Ex.GetType());
Assert.Equal(csEx.GetType(), f2Ex.GetType());
Assert.Equal(csEx.GetType(), f3Ex.GetType());
Assert.Equal(csEx.GetType(), f4Ex.GetType());
Assert.Equal(csEx.GetType(), f5Ex.GetType());
Assert.Equal(csEx.GetType(), f6Ex.GetType());
}
else
{
Assert.Equal(csResult, f1Result);
Assert.Equal(csResult, f2Result);
Assert.Equal(csResult, f3Result);
Assert.Equal(csResult, f4Result);
Assert.Equal(csResult, f5Result);
Assert.Equal(csResult, f6Result);
}
}
#endregion
#region Verify short
private static void VerifySubtractShort(short a, short b)
{
ParameterExpression p0 = Expression.Parameter(typeof(short), "p0");
ParameterExpression p1 = Expression.Parameter(typeof(short), "p1");
// verify with parameters supplied
Expression<Func<short>> e1 =
Expression.Lambda<Func<short>>(
Expression.Invoke(
Expression.Lambda<Func<short, short, short>>(
Expression.Subtract(p0, p1),
new ParameterExpression[] { p0, p1 }),
new Expression[]
{
Expression.Constant(a, typeof(short)),
Expression.Constant(b, typeof(short))
}),
Enumerable.Empty<ParameterExpression>());
Func<short> f1 = e1.Compile();
short f1Result = default(short);
Exception f1Ex = null;
try
{
f1Result = f1();
}
catch (Exception ex)
{
f1Ex = ex;
}
// verify with values passed to make parameters
Expression<Func<short, short, Func<short>>> e2 =
Expression.Lambda<Func<short, short, Func<short>>>(
Expression.Lambda<Func<short>>(
Expression.Subtract(p0, p1),
Enumerable.Empty<ParameterExpression>()),
new ParameterExpression[] { p0, p1 });
Func<short, short, Func<short>> f2 = e2.Compile();
short f2Result = default(short);
Exception f2Ex = null;
try
{
f2Result = f2(a, b)();
}
catch (Exception ex)
{
f2Ex = ex;
}
// verify with values directly passed
Expression<Func<Func<short, short, short>>> e3 =
Expression.Lambda<Func<Func<short, short, short>>>(
Expression.Invoke(
Expression.Lambda<Func<Func<short, short, short>>>(
Expression.Lambda<Func<short, short, short>>(
Expression.Subtract(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>()),
Enumerable.Empty<Expression>()),
Enumerable.Empty<ParameterExpression>());
Func<short, short, short> f3 = e3.Compile()();
short f3Result = default(short);
Exception f3Ex = null;
try
{
f3Result = f3(a, b);
}
catch (Exception ex)
{
f3Ex = ex;
}
// verify as a function generator
Expression<Func<Func<short, short, short>>> e4 =
Expression.Lambda<Func<Func<short, short, short>>>(
Expression.Lambda<Func<short, short, short>>(
Expression.Subtract(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>());
Func<Func<short, short, short>> f4 = e4.Compile();
short f4Result = default(short);
Exception f4Ex = null;
try
{
f4Result = f4()(a, b);
}
catch (Exception ex)
{
f4Ex = ex;
}
// verify with currying
Expression<Func<short, Func<short, short>>> e5 =
Expression.Lambda<Func<short, Func<short, short>>>(
Expression.Lambda<Func<short, short>>(
Expression.Subtract(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 });
Func<short, Func<short, short>> f5 = e5.Compile();
short f5Result = default(short);
Exception f5Ex = null;
try
{
f5Result = f5(a)(b);
}
catch (Exception ex)
{
f5Ex = ex;
}
// verify with one parameter
Expression<Func<Func<short, short>>> e6 =
Expression.Lambda<Func<Func<short, short>>>(
Expression.Invoke(
Expression.Lambda<Func<short, Func<short, short>>>(
Expression.Lambda<Func<short, short>>(
Expression.Subtract(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 }),
new Expression[] { Expression.Constant(a, typeof(short)) }),
Enumerable.Empty<ParameterExpression>());
Func<short, short> f6 = e6.Compile()();
short f6Result = default(short);
Exception f6Ex = null;
try
{
f6Result = f6(b);
}
catch (Exception ex)
{
f6Ex = ex;
}
// verify with regular IL
short csResult = default(short);
Exception csEx = null;
try
{
csResult = (short)(a - b);
}
catch (Exception ex)
{
csEx = ex;
}
// either all should have failed the same way or they should all produce the same result
if (f1Ex != null || f2Ex != null || f3Ex != null || f4Ex != null || f5Ex != null || f6Ex != null || csEx != null)
{
Assert.NotNull(f1Ex);
Assert.NotNull(f2Ex);
Assert.NotNull(f3Ex);
Assert.NotNull(f4Ex);
Assert.NotNull(f5Ex);
Assert.NotNull(f6Ex);
Assert.NotNull(csEx);
Assert.Equal(csEx.GetType(), f1Ex.GetType());
Assert.Equal(csEx.GetType(), f2Ex.GetType());
Assert.Equal(csEx.GetType(), f3Ex.GetType());
Assert.Equal(csEx.GetType(), f4Ex.GetType());
Assert.Equal(csEx.GetType(), f5Ex.GetType());
Assert.Equal(csEx.GetType(), f6Ex.GetType());
}
else
{
Assert.Equal(csResult, f1Result);
Assert.Equal(csResult, f2Result);
Assert.Equal(csResult, f3Result);
Assert.Equal(csResult, f4Result);
Assert.Equal(csResult, f5Result);
Assert.Equal(csResult, f6Result);
}
}
#endregion
#region Verify uint
private static void VerifySubtractUInt(uint a, uint b)
{
ParameterExpression p0 = Expression.Parameter(typeof(uint), "p0");
ParameterExpression p1 = Expression.Parameter(typeof(uint), "p1");
// verify with parameters supplied
Expression<Func<uint>> e1 =
Expression.Lambda<Func<uint>>(
Expression.Invoke(
Expression.Lambda<Func<uint, uint, uint>>(
Expression.Subtract(p0, p1),
new ParameterExpression[] { p0, p1 }),
new Expression[]
{
Expression.Constant(a, typeof(uint)),
Expression.Constant(b, typeof(uint))
}),
Enumerable.Empty<ParameterExpression>());
Func<uint> f1 = e1.Compile();
uint f1Result = default(uint);
Exception f1Ex = null;
try
{
f1Result = f1();
}
catch (Exception ex)
{
f1Ex = ex;
}
// verify with values passed to make parameters
Expression<Func<uint, uint, Func<uint>>> e2 =
Expression.Lambda<Func<uint, uint, Func<uint>>>(
Expression.Lambda<Func<uint>>(
Expression.Subtract(p0, p1),
Enumerable.Empty<ParameterExpression>()),
new ParameterExpression[] { p0, p1 });
Func<uint, uint, Func<uint>> f2 = e2.Compile();
uint f2Result = default(uint);
Exception f2Ex = null;
try
{
f2Result = f2(a, b)();
}
catch (Exception ex)
{
f2Ex = ex;
}
// verify with values directly passed
Expression<Func<Func<uint, uint, uint>>> e3 =
Expression.Lambda<Func<Func<uint, uint, uint>>>(
Expression.Invoke(
Expression.Lambda<Func<Func<uint, uint, uint>>>(
Expression.Lambda<Func<uint, uint, uint>>(
Expression.Subtract(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>()),
Enumerable.Empty<Expression>()),
Enumerable.Empty<ParameterExpression>());
Func<uint, uint, uint> f3 = e3.Compile()();
uint f3Result = default(uint);
Exception f3Ex = null;
try
{
f3Result = f3(a, b);
}
catch (Exception ex)
{
f3Ex = ex;
}
// verify as a function generator
Expression<Func<Func<uint, uint, uint>>> e4 =
Expression.Lambda<Func<Func<uint, uint, uint>>>(
Expression.Lambda<Func<uint, uint, uint>>(
Expression.Subtract(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>());
Func<Func<uint, uint, uint>> f4 = e4.Compile();
uint f4Result = default(uint);
Exception f4Ex = null;
try
{
f4Result = f4()(a, b);
}
catch (Exception ex)
{
f4Ex = ex;
}
// verify with currying
Expression<Func<uint, Func<uint, uint>>> e5 =
Expression.Lambda<Func<uint, Func<uint, uint>>>(
Expression.Lambda<Func<uint, uint>>(
Expression.Subtract(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 });
Func<uint, Func<uint, uint>> f5 = e5.Compile();
uint f5Result = default(uint);
Exception f5Ex = null;
try
{
f5Result = f5(a)(b);
}
catch (Exception ex)
{
f5Ex = ex;
}
// verify with one parameter
Expression<Func<Func<uint, uint>>> e6 =
Expression.Lambda<Func<Func<uint, uint>>>(
Expression.Invoke(
Expression.Lambda<Func<uint, Func<uint, uint>>>(
Expression.Lambda<Func<uint, uint>>(
Expression.Subtract(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 }),
new Expression[] { Expression.Constant(a, typeof(uint)) }),
Enumerable.Empty<ParameterExpression>());
Func<uint, uint> f6 = e6.Compile()();
uint f6Result = default(uint);
Exception f6Ex = null;
try
{
f6Result = f6(b);
}
catch (Exception ex)
{
f6Ex = ex;
}
// verify with regular IL
uint csResult = default(uint);
Exception csEx = null;
try
{
csResult = (uint)(a - b);
}
catch (Exception ex)
{
csEx = ex;
}
// either all should have failed the same way or they should all produce the same result
if (f1Ex != null || f2Ex != null || f3Ex != null || f4Ex != null || f5Ex != null || f6Ex != null || csEx != null)
{
Assert.NotNull(f1Ex);
Assert.NotNull(f2Ex);
Assert.NotNull(f3Ex);
Assert.NotNull(f4Ex);
Assert.NotNull(f5Ex);
Assert.NotNull(f6Ex);
Assert.NotNull(csEx);
Assert.Equal(csEx.GetType(), f1Ex.GetType());
Assert.Equal(csEx.GetType(), f2Ex.GetType());
Assert.Equal(csEx.GetType(), f3Ex.GetType());
Assert.Equal(csEx.GetType(), f4Ex.GetType());
Assert.Equal(csEx.GetType(), f5Ex.GetType());
Assert.Equal(csEx.GetType(), f6Ex.GetType());
}
else
{
Assert.Equal(csResult, f1Result);
Assert.Equal(csResult, f2Result);
Assert.Equal(csResult, f3Result);
Assert.Equal(csResult, f4Result);
Assert.Equal(csResult, f5Result);
Assert.Equal(csResult, f6Result);
}
}
#endregion
#region Verify ulong
private static void VerifySubtractULong(ulong a, ulong b)
{
ParameterExpression p0 = Expression.Parameter(typeof(ulong), "p0");
ParameterExpression p1 = Expression.Parameter(typeof(ulong), "p1");
// verify with parameters supplied
Expression<Func<ulong>> e1 =
Expression.Lambda<Func<ulong>>(
Expression.Invoke(
Expression.Lambda<Func<ulong, ulong, ulong>>(
Expression.Subtract(p0, p1),
new ParameterExpression[] { p0, p1 }),
new Expression[]
{
Expression.Constant(a, typeof(ulong)),
Expression.Constant(b, typeof(ulong))
}),
Enumerable.Empty<ParameterExpression>());
Func<ulong> f1 = e1.Compile();
ulong f1Result = default(ulong);
Exception f1Ex = null;
try
{
f1Result = f1();
}
catch (Exception ex)
{
f1Ex = ex;
}
// verify with values passed to make parameters
Expression<Func<ulong, ulong, Func<ulong>>> e2 =
Expression.Lambda<Func<ulong, ulong, Func<ulong>>>(
Expression.Lambda<Func<ulong>>(
Expression.Subtract(p0, p1),
Enumerable.Empty<ParameterExpression>()),
new ParameterExpression[] { p0, p1 });
Func<ulong, ulong, Func<ulong>> f2 = e2.Compile();
ulong f2Result = default(ulong);
Exception f2Ex = null;
try
{
f2Result = f2(a, b)();
}
catch (Exception ex)
{
f2Ex = ex;
}
// verify with values directly passed
Expression<Func<Func<ulong, ulong, ulong>>> e3 =
Expression.Lambda<Func<Func<ulong, ulong, ulong>>>(
Expression.Invoke(
Expression.Lambda<Func<Func<ulong, ulong, ulong>>>(
Expression.Lambda<Func<ulong, ulong, ulong>>(
Expression.Subtract(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>()),
Enumerable.Empty<Expression>()),
Enumerable.Empty<ParameterExpression>());
Func<ulong, ulong, ulong> f3 = e3.Compile()();
ulong f3Result = default(ulong);
Exception f3Ex = null;
try
{
f3Result = f3(a, b);
}
catch (Exception ex)
{
f3Ex = ex;
}
// verify as a function generator
Expression<Func<Func<ulong, ulong, ulong>>> e4 =
Expression.Lambda<Func<Func<ulong, ulong, ulong>>>(
Expression.Lambda<Func<ulong, ulong, ulong>>(
Expression.Subtract(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>());
Func<Func<ulong, ulong, ulong>> f4 = e4.Compile();
ulong f4Result = default(ulong);
Exception f4Ex = null;
try
{
f4Result = f4()(a, b);
}
catch (Exception ex)
{
f4Ex = ex;
}
// verify with currying
Expression<Func<ulong, Func<ulong, ulong>>> e5 =
Expression.Lambda<Func<ulong, Func<ulong, ulong>>>(
Expression.Lambda<Func<ulong, ulong>>(
Expression.Subtract(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 });
Func<ulong, Func<ulong, ulong>> f5 = e5.Compile();
ulong f5Result = default(ulong);
Exception f5Ex = null;
try
{
f5Result = f5(a)(b);
}
catch (Exception ex)
{
f5Ex = ex;
}
// verify with one parameter
Expression<Func<Func<ulong, ulong>>> e6 =
Expression.Lambda<Func<Func<ulong, ulong>>>(
Expression.Invoke(
Expression.Lambda<Func<ulong, Func<ulong, ulong>>>(
Expression.Lambda<Func<ulong, ulong>>(
Expression.Subtract(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 }),
new Expression[] { Expression.Constant(a, typeof(ulong)) }),
Enumerable.Empty<ParameterExpression>());
Func<ulong, ulong> f6 = e6.Compile()();
ulong f6Result = default(ulong);
Exception f6Ex = null;
try
{
f6Result = f6(b);
}
catch (Exception ex)
{
f6Ex = ex;
}
// verify with regular IL
ulong csResult = default(ulong);
Exception csEx = null;
try
{
csResult = (ulong)(a - b);
}
catch (Exception ex)
{
csEx = ex;
}
// either all should have failed the same way or they should all produce the same result
if (f1Ex != null || f2Ex != null || f3Ex != null || f4Ex != null || f5Ex != null || f6Ex != null || csEx != null)
{
Assert.NotNull(f1Ex);
Assert.NotNull(f2Ex);
Assert.NotNull(f3Ex);
Assert.NotNull(f4Ex);
Assert.NotNull(f5Ex);
Assert.NotNull(f6Ex);
Assert.NotNull(csEx);
Assert.Equal(csEx.GetType(), f1Ex.GetType());
Assert.Equal(csEx.GetType(), f2Ex.GetType());
Assert.Equal(csEx.GetType(), f3Ex.GetType());
Assert.Equal(csEx.GetType(), f4Ex.GetType());
Assert.Equal(csEx.GetType(), f5Ex.GetType());
Assert.Equal(csEx.GetType(), f6Ex.GetType());
}
else
{
Assert.Equal(csResult, f1Result);
Assert.Equal(csResult, f2Result);
Assert.Equal(csResult, f3Result);
Assert.Equal(csResult, f4Result);
Assert.Equal(csResult, f5Result);
Assert.Equal(csResult, f6Result);
}
}
#endregion
#region Verify ushort
private static void VerifySubtractUShort(ushort a, ushort b)
{
ParameterExpression p0 = Expression.Parameter(typeof(ushort), "p0");
ParameterExpression p1 = Expression.Parameter(typeof(ushort), "p1");
// verify with parameters supplied
Expression<Func<ushort>> e1 =
Expression.Lambda<Func<ushort>>(
Expression.Invoke(
Expression.Lambda<Func<ushort, ushort, ushort>>(
Expression.Subtract(p0, p1),
new ParameterExpression[] { p0, p1 }),
new Expression[]
{
Expression.Constant(a, typeof(ushort)),
Expression.Constant(b, typeof(ushort))
}),
Enumerable.Empty<ParameterExpression>());
Func<ushort> f1 = e1.Compile();
ushort f1Result = default(ushort);
Exception f1Ex = null;
try
{
f1Result = f1();
}
catch (Exception ex)
{
f1Ex = ex;
}
// verify with values passed to make parameters
Expression<Func<ushort, ushort, Func<ushort>>> e2 =
Expression.Lambda<Func<ushort, ushort, Func<ushort>>>(
Expression.Lambda<Func<ushort>>(
Expression.Subtract(p0, p1),
Enumerable.Empty<ParameterExpression>()),
new ParameterExpression[] { p0, p1 });
Func<ushort, ushort, Func<ushort>> f2 = e2.Compile();
ushort f2Result = default(ushort);
Exception f2Ex = null;
try
{
f2Result = f2(a, b)();
}
catch (Exception ex)
{
f2Ex = ex;
}
// verify with values directly passed
Expression<Func<Func<ushort, ushort, ushort>>> e3 =
Expression.Lambda<Func<Func<ushort, ushort, ushort>>>(
Expression.Invoke(
Expression.Lambda<Func<Func<ushort, ushort, ushort>>>(
Expression.Lambda<Func<ushort, ushort, ushort>>(
Expression.Subtract(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>()),
Enumerable.Empty<Expression>()),
Enumerable.Empty<ParameterExpression>());
Func<ushort, ushort, ushort> f3 = e3.Compile()();
ushort f3Result = default(ushort);
Exception f3Ex = null;
try
{
f3Result = f3(a, b);
}
catch (Exception ex)
{
f3Ex = ex;
}
// verify as a function generator
Expression<Func<Func<ushort, ushort, ushort>>> e4 =
Expression.Lambda<Func<Func<ushort, ushort, ushort>>>(
Expression.Lambda<Func<ushort, ushort, ushort>>(
Expression.Subtract(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>());
Func<Func<ushort, ushort, ushort>> f4 = e4.Compile();
ushort f4Result = default(ushort);
Exception f4Ex = null;
try
{
f4Result = f4()(a, b);
}
catch (Exception ex)
{
f4Ex = ex;
}
// verify with currying
Expression<Func<ushort, Func<ushort, ushort>>> e5 =
Expression.Lambda<Func<ushort, Func<ushort, ushort>>>(
Expression.Lambda<Func<ushort, ushort>>(
Expression.Subtract(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 });
Func<ushort, Func<ushort, ushort>> f5 = e5.Compile();
ushort f5Result = default(ushort);
Exception f5Ex = null;
try
{
f5Result = f5(a)(b);
}
catch (Exception ex)
{
f5Ex = ex;
}
// verify with one parameter
Expression<Func<Func<ushort, ushort>>> e6 =
Expression.Lambda<Func<Func<ushort, ushort>>>(
Expression.Invoke(
Expression.Lambda<Func<ushort, Func<ushort, ushort>>>(
Expression.Lambda<Func<ushort, ushort>>(
Expression.Subtract(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 }),
new Expression[] { Expression.Constant(a, typeof(ushort)) }),
Enumerable.Empty<ParameterExpression>());
Func<ushort, ushort> f6 = e6.Compile()();
ushort f6Result = default(ushort);
Exception f6Ex = null;
try
{
f6Result = f6(b);
}
catch (Exception ex)
{
f6Ex = ex;
}
// verify with regular IL
ushort csResult = default(ushort);
Exception csEx = null;
try
{
csResult = (ushort)(a - b);
}
catch (Exception ex)
{
csEx = ex;
}
// either all should have failed the same way or they should all produce the same result
if (f1Ex != null || f2Ex != null || f3Ex != null || f4Ex != null || f5Ex != null || f6Ex != null || csEx != null)
{
Assert.NotNull(f1Ex);
Assert.NotNull(f2Ex);
Assert.NotNull(f3Ex);
Assert.NotNull(f4Ex);
Assert.NotNull(f5Ex);
Assert.NotNull(f6Ex);
Assert.NotNull(csEx);
Assert.Equal(csEx.GetType(), f1Ex.GetType());
Assert.Equal(csEx.GetType(), f2Ex.GetType());
Assert.Equal(csEx.GetType(), f3Ex.GetType());
Assert.Equal(csEx.GetType(), f4Ex.GetType());
Assert.Equal(csEx.GetType(), f5Ex.GetType());
Assert.Equal(csEx.GetType(), f6Ex.GetType());
}
else
{
Assert.Equal(csResult, f1Result);
Assert.Equal(csResult, f2Result);
Assert.Equal(csResult, f3Result);
Assert.Equal(csResult, f4Result);
Assert.Equal(csResult, f5Result);
Assert.Equal(csResult, f6Result);
}
}
#endregion
#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.Threading.Tasks;
using System.Threading;
using Xunit;
using System.Collections.Generic;
using System.Diagnostics;
namespace TaskCoverage
{
public class Coverage
{
// Regression test: Validates that tasks can wait on int.MaxValue without assertion.
[Fact]
[OuterLoop]
public static void TaskWait_MaxInt32()
{
Task t = Task.Delay(10000);
Debug.WriteLine("Wait with int.Maxvalue");
Task.WaitAll(new Task[] { t }, int.MaxValue);
}
//EH
[Fact]
[OuterLoop]
public static void TaskContinuation()
{
int taskCount = Environment.ProcessorCount;
int maxDOP = Int32.MaxValue;
int maxNumberExecutionsPerTask = 1;
int data = 0;
Task[] allTasks = new Task[taskCount + 1];
CancellationTokenSource[] cts = new CancellationTokenSource[taskCount + 1];
for (int i = 0; i <= taskCount; i++)
{
cts[i] = new CancellationTokenSource();
}
CancellationTokenSource cts2 = new CancellationTokenSource();
ConcurrentExclusiveSchedulerPair scheduler = new ConcurrentExclusiveSchedulerPair(TaskScheduler.Default, maxDOP, maxNumberExecutionsPerTask);
for (int i = 0; i <= taskCount; i++)
{
int j = i;
allTasks[i] = new Task(() =>
{
new TaskFactory(TaskScheduler.Current).StartNew(() => { }).
ContinueWith((task, o) =>
{
int d = (int)o;
Interlocked.Add(ref data, d);
}, j).
ContinueWith((task, o) =>
{
int d = (int)o;
Interlocked.Add(ref data, d);
cts[d].Cancel();
if (d <= taskCount)
{
throw new OperationCanceledException(cts[d].Token);
}
return "Done";
}, j, cts[j].Token).
ContinueWith((task, o) =>
{
int d = (int)o;
Interlocked.Add(ref data, d);
}, j, CancellationToken.None, TaskContinuationOptions.OnlyOnCanceled, TaskScheduler.Default).Wait(Int32.MaxValue - 1, cts2.Token);
});
allTasks[i].Start(scheduler.ConcurrentScheduler);
}
Task.WaitAll(allTasks, int.MaxValue - 1, CancellationToken.None);
Debug.WriteLine("Tasks ended: result {0}", data);
Task completion = scheduler.Completion;
scheduler.Complete();
completion.Wait();
int expectedResult = 3 * taskCount * (taskCount + 1) / 2;
Assert.Equal(expectedResult, data);
Assert.NotEqual(TaskScheduler.Default.Id, scheduler.ConcurrentScheduler.Id);
Assert.NotEqual(TaskScheduler.Default.Id, scheduler.ExclusiveScheduler.Id);
}
/// <summary>
/// Test various Task.WhenAll and Wait overloads - EH
/// </summary>
[Fact]
public static void TaskWaitWithCTS()
{
ManualResetEvent mre = new ManualResetEvent(false);
ManualResetEvent mreCont = new ManualResetEvent(false);
CancellationTokenSource cts = new CancellationTokenSource();
int? taskId1 = 0; int? taskId2 = 0;
int? taskId12 = 0; int? taskId22 = 0;
Task t1 = Task.Factory.StartNew(() => { mre.WaitOne(); taskId1 = Task.CurrentId; });
Task t2 = Task.Factory.StartNew(() => { mre.WaitOne(); taskId2 = Task.CurrentId; cts.Cancel(); });
List<Task<int?>> whenAllTaskResult = new List<Task<int?>>();
List<Task> whenAllTask = new List<Task>();
whenAllTask.Add(t1); whenAllTask.Add(t2);
Task<int> contTask = Task.WhenAll(whenAllTask).ContinueWith<int>(
(task) =>
{
// when task1 ends, the token will be cancelled
// move the continuation task in cancellation state
if (cts.IsCancellationRequested) { throw new OperationCanceledException(cts.Token); }
return 0;
}, cts.Token);
contTask.ContinueWith((task) => { mreCont.Set(); });
whenAllTaskResult.Add(Task<int?>.Factory.StartNew((o) => { mre.WaitOne((int)o); return Task.CurrentId; }, 10));
whenAllTaskResult.Add(Task<int?>.Factory.StartNew((o) => { mre.WaitOne((int)o); return Task.CurrentId; }, 10));
t1.Wait(5, cts.Token);
Task.WhenAll(whenAllTaskResult).ContinueWith((task) => { taskId12 = task.Result[0]; taskId22 = task.Result[1]; mre.Set(); });
// Task 2 calls CancellationTokenSource.Cancel. Thus, expect and not fail for System.OperationCanceledException being thrown.
try
{
t2.Wait(cts.Token);
}
catch (System.OperationCanceledException) { } // expected, do nothing
Assert.NotEqual<int?>(taskId1, taskId2);
Assert.NotEqual<int?>(taskId12, taskId22);
Debug.WriteLine("Waiting on continuation task that should move into the cancelled state.");
mreCont.WaitOne();
Assert.True(contTask.Status == TaskStatus.Canceled, "Task status is not correct");
}
/// <summary>
/// test WaitAny and when Any overloads
/// </summary>
[Fact]
public static void TaskWaitAny_WhenAny()
{
ManualResetEvent mre = new ManualResetEvent(false);
ManualResetEvent mre2 = new ManualResetEvent(false);
CancellationTokenSource cts = new CancellationTokenSource();
Task t1 = Task.Factory.StartNew(() => { mre.WaitOne(); });
Task t2 = Task.Factory.StartNew(() => { mre.WaitOne(); });
Task<int?> t11 = Task.Factory.StartNew(() => { mre2.WaitOne(); return Task.CurrentId; });
Task<int?> t21 = Task.Factory.StartNew(() => { mre2.WaitOne(); return Task.CurrentId; });
//waitAny with token and timeout
Task[] waitAny = new Task[] { t1, t2 };
int timeout = Task.WaitAny(waitAny, 1, cts.Token);
//task whenany
Task.Factory.StartNew(() => { Task.Delay(20); mre.Set(); });
List<Task> whenAnyTask = new List<Task>(); whenAnyTask.Add(t1); whenAnyTask.Add(t2);
List<Task<int?>> whenAnyTaskResult = new List<Task<int?>>(); whenAnyTaskResult.Add(t11); whenAnyTaskResult.Add(t21);
//task<tresult> whenany
int? taskId = 0; //this will be set to the first task<int?> ID that ends
Task waitOnIt = Task.WhenAny(whenAnyTaskResult).ContinueWith((task) => { taskId = task.Result.Result; });
Task.WhenAny(whenAnyTask).ContinueWith((task) => { mre2.Set(); });
Debug.WriteLine("Wait on the scenario to finish");
waitOnIt.Wait();
Assert.Equal<int>(-1, timeout);
Assert.Equal<int>(t11.Id, t11.Result.Value);
Assert.Equal<int>(t21.Id, t21.Result.Value);
bool whenAnyVerification = taskId == t11.Id || taskId == t21.Id;
Assert.True(whenAnyVerification, string.Format("The id for whenAny is not correct expected to be {0} or {1} and it is {2}", t11.Id, t21.Id, taskId));
}
[Fact]
public static void CancellationTokenRegitration()
{
ManualResetEvent mre = new ManualResetEvent(false);
ManualResetEvent mre2 = new ManualResetEvent(false);
CancellationTokenSource cts = new CancellationTokenSource();
cts.Token.Register((o) => { mre.Set(); }, 1, true);
cts.CancelAfter(5);
Debug.WriteLine("Wait on the scenario to finish");
mre.WaitOne();
}
/// <summary>
/// verify that the taskawaiter.UnsafeOnCompleted is invoked
/// </summary>
[Fact]
public static void TaskAwaiter()
{
ManualResetEvent mre = new ManualResetEvent(false);
ManualResetEvent mre2 = new ManualResetEvent(false);
ManualResetEvent mre3 = new ManualResetEvent(false);
Task t1 = Task.Factory.StartNew(() => { mre.WaitOne(); });
Task<int> t11 = Task.Factory.StartNew(() => { mre.WaitOne(); return 1; });
t1.GetAwaiter().UnsafeOnCompleted(() => { mre2.Set(); });
t11.GetAwaiter().UnsafeOnCompleted(() => { mre3.Set(); });
mre.Set();
Debug.WriteLine("Wait on the scenario to finish");
mre2.WaitOne(); mre3.WaitOne();
}
/// <summary>
/// verify that the taskawaiter.UnsafeOnCompleted is invoked
/// </summary>
[Fact]
public static void TaskConfigurableAwaiter()
{
ManualResetEvent mre = new ManualResetEvent(false);
ManualResetEvent mre2 = new ManualResetEvent(false);
ManualResetEvent mre3 = new ManualResetEvent(false);
Task t1 = Task.Factory.StartNew(() => { mre.WaitOne(); });
Task<int> t11 = Task.Factory.StartNew(() => { mre.WaitOne(); return 1; });
t1.ConfigureAwait(false).GetAwaiter().UnsafeOnCompleted(() => { mre2.Set(); });
t11.ConfigureAwait(false).GetAwaiter().UnsafeOnCompleted(() => { mre3.Set(); });
mre.Set();
Debug.WriteLine("Wait on the scenario to finish");
mre2.WaitOne(); mre3.WaitOne();
}
/// <summary>
/// FromAsync testing: Not supported in .NET Native
/// </summary>
[Fact]
public static void FromAsync()
{
Task emptyTask = new Task(() => { });
ManualResetEvent mre1 = new ManualResetEvent(false);
ManualResetEvent mre2 = new ManualResetEvent(false);
Task.Factory.FromAsync(emptyTask, (iar) => { mre1.Set(); }, TaskCreationOptions.None, TaskScheduler.Current);
Task<int>.Factory.FromAsync(emptyTask, (iar) => { mre2.Set(); return 1; }, TaskCreationOptions.None, TaskScheduler.Current);
emptyTask.Start();
Debug.WriteLine("Wait on the scenario to finish");
mre1.WaitOne();
mre2.WaitOne();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic; //StackTrace
using System.Diagnostics;
namespace OLEDB.Test.ModuleCore
{
////////////////////////////////////////////////////////////////
// CTestCases
//
////////////////////////////////////////////////////////////////
public class CTestCase : CTestBase//, ITestCases
{
public delegate int dlgtTestVariation();
//Data
private CVariation _curvariation;
//Constructor
public CTestCase()
: this(null)
{
//Delegate
}
public CTestCase(string desc)
: this(null, desc)
{
//Delegate
}
public CTestCase(CTestModule parent, string desc)
: base(desc)
{
Parent = parent;
}
public virtual void DOTEST()
{
if (this.Attribute != null)
{
Console.WriteLine("TestCase:{0} - {1}", this.Attribute.Name, this.Attribute.Desc);
}
}
public override tagVARIATION_STATUS Execute()
{
List<object> children = Children;
if (children != null && children.Count > 0)
{
// this is not a leaf node, just invoke all the children's execute
foreach (object child in children)
{
CTestCase childTc = child as CTestCase;
if (childTc != null) //nested test case class will be child of a test case
{
childTc.Init();
childTc.Execute();
continue;
}
CVariation var = child as CVariation;
if (var != null && CModInfo.IsVariationSelected(var.Desc))
{
const string indent = "\t";
try
{
CurVariation = var;
tagVARIATION_STATUS ret = var.Execute();
if (tagVARIATION_STATUS.eVariationStatusPassed == ret)
{
TestModule.PassCount++;
}
else if (tagVARIATION_STATUS.eVariationStatusFailed == ret)
{
System.Console.WriteLine(indent + var.Desc);
System.Console.WriteLine(indent + " FAILED");
TestModule.FailCount++;
}
else
{
TestModule.SkipCount++;
}
}
catch (CTestSkippedException)
{
TestModule.SkipCount++;
}
catch (Exception e)
{
System.Console.WriteLine(indent + var.Desc);
System.Console.WriteLine("unexpected exception happened:{0}", e.Message);
System.Console.WriteLine(e.StackTrace);
System.Console.WriteLine(indent + " FAILED");
TestModule.FailCount++;
}
}
}
}
return tagVARIATION_STATUS.eVariationStatusPassed;
}
public void RunVariation(dlgtTestVariation testmethod, Variation curVar)
{
if (!CModInfo.IsVariationSelected(curVar.Desc))
return;
const string indent = "\t";
try
{
CurVariation.Attribute = curVar;
int ret = testmethod();
if (TEST_PASS == ret)
{
TestModule.PassCount++;
}
else if (TEST_FAIL == ret)
{
System.Console.WriteLine(indent + curVar.Desc);
System.Console.WriteLine(indent + " FAILED");
TestModule.FailCount++;
}
else
{
System.Console.WriteLine(indent + curVar.Desc);
System.Console.WriteLine(indent + " SKIPPED");
TestModule.SkipCount++;
}
}
catch (CTestSkippedException tse)
{
System.Console.WriteLine(indent + curVar.Desc);
System.Console.WriteLine(indent + " SKIPPED" + ", Msg:" + tse.Message);
TestModule.SkipCount++;
}
catch (Exception e)
{
System.Console.WriteLine(indent + curVar.Desc);
System.Console.WriteLine("unexpected exception happened:{0}", e.Message);
System.Console.WriteLine(e.StackTrace);
System.Console.WriteLine(indent + " FAILED");
TestModule.FailCount++;
}
}
//Accessor
public CTestModule TestModule
{
get
{
if (Parent is CTestModule)
return (CTestModule)Parent;
else return ((CTestCase)Parent).TestModule;
}
set { Parent = value; }
}
//Accessors
protected override CAttrBase CreateAttribute()
{
return new TestCase();
}
public new virtual TestCase Attribute
{
get { return (TestCase)base.Attribute; }
set { base.Attribute = value; }
}
//Helpers
public void AddVariation(CVariation variation)
{
//Delegate
this.AddChild(variation);
}
public CVariation CurVariation
{
//Return the current variation:
//Note: We do this so that within the variation the user can have access to all the
//attributes of that particular method. Unlike the TestModule/TestCase which are objects
//and have properties to reference, the variations are function and don't. Each variation
//could also have multiple attributes (repeats), so we can't simply use the StackFrame
//to determine this info...
get { return _curvariation; }
set { _curvariation = value; }
}
public int GetVariationCount()
{
return Children.Count;
}
public virtual int ExecuteVariation(int index, object param)
{
//Execute the Variation
return (int)_curvariation.Execute();
}
public virtual tagVARIATION_STATUS ExecuteVariation(int index)
{
//Track the testcase were in
CTestModule testmodule = this.TestModule;
if (testmodule != null)
testmodule.CurTestCase = this;
//Track which variation were executing
_curvariation = (CVariation)Children[index];
int result = TEST_FAIL;
if (_curvariation.Skipped || !_curvariation.Implemented)
{
//Skipped
result = TEST_SKIPPED;
}
else
{
//Execute
result = ExecuteVariation(index, _curvariation.Param);
}
//Before exiting make sure we reset our CurVariation to null, to prevent
//incorrect uses of CurVariation within the TestCase, but not actually a running
//variation. This will only be valid within a function with a //[Variation] attribute...
_curvariation = null;
return (tagVARIATION_STATUS)result;
}
public int GetVariationID(int index)
{
CVariation variation = (CVariation)Children[index];
return variation.id;
}
public string GetVariationDesc(int index)
{
CVariation variation = (CVariation)Children[index];
return variation.GetDescription();
}
protected override void DetermineChildren()
{
AddChildren();
DetermineVariations();
}
public virtual void DetermineVariations()
{
//Default - no sort
bool bSort = false;
//Normally the reflection Type.GetMethods() api returns the methods in order
//of how they appear in the code. But it will change that order depending
//upon if there are virtual functions, which are returned first before other
//non-virtual functions. Then there are also inherited classes where the
//derived classes methods are returned before the inherited class. So we have
//added the support of specifying an id=x, as an attribute so you can have
//then sorted and displayed however your see fit.
if (bSort)
Children.Sort(/*Default sort is based upon IComparable of each item*/);
}
}
}
| |
namespace FluentLinqToSql.ActiveRecord {
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Reflection;
//From MvcContrib http://mvccontrib.org
internal class NameValueDeserializer {
private IConvertible GetConvertible(string sValue) {
return new DefaultConvertible(sValue);
}
public void Deserialize(NameValueCollection collection, string prefix, Type targetType, object instance) {
if (collection == null || collection.Count == 0) return;
if (prefix == string.Empty) prefix = null;
if (targetType == null) throw new ArgumentNullException("targetType");
if (targetType.IsArray) {
// Type elementType = targetType.GetElementType();
// ArrayList arrayInstance = DeserializeArrayList(collection, prefix, elementType);
// return arrayInstance.ToArray(elementType);
throw new NotSupportedException();
}
if (IsGenericList(targetType)) {
/*IList genericListInstance = CreateGenericListInstance(targetType);
DeserializeGenericList(collection, prefix, targetType, ref genericListInstance);
return genericListInstance;*/
throw new NotSupportedException();
}
Deserialize(collection, prefix, targetType, ref instance);
}
/// <summary>
/// Deserializes the specified request collection.
/// </summary>
/// <param name="collection">The collection.</param>
/// <param name="prefix">The prefix.</param>
/// <param name="targetType">Type of the target.</param>
/// <returns>The deserialized object</returns>
public object Deserialize(NameValueCollection collection, string prefix, Type targetType) {
if (collection == null || collection.Count == 0) return null;
if (prefix == string.Empty) throw new ArgumentException("prefix must not be empty", prefix);
if (targetType == null) throw new ArgumentNullException("targetType");
if (targetType.IsArray) {
Type elementType = targetType.GetElementType();
ArrayList arrayInstance = DeserializeArrayList(collection, prefix, elementType);
return arrayInstance.ToArray(elementType);
}
if (IsGenericList(targetType)) {
IList genericListInstance = CreateGenericListInstance(targetType);
DeserializeGenericList(collection, prefix, targetType, ref genericListInstance);
return genericListInstance;
}
object instance = null;
Deserialize(collection, prefix, targetType, ref instance);
return instance ?? CreateInstance(targetType);
}
protected virtual void Deserialize(NameValueCollection collection, string prefix, Type targetType, ref object instance) {
if (CheckPrefixInRequest(collection, prefix)) {
if (instance == null) {
instance = CreateInstance(targetType);
}
PropertyInfo[] properties = GetProperties(targetType);
foreach (var property in properties) {
string name = prefix != null ? string.Concat(prefix, ".", property.Name) : property.Name;
Type propertyType = property.PropertyType;
if (IsSimpleProperty(propertyType)) {
string sValue = collection.Get(name);
if (sValue != null) {
SetValue(instance, property, GetConvertible(sValue));
}
}
else if (propertyType.IsArray) {
Type elementType = propertyType.GetElementType();
ArrayList arrayInstance = DeserializeArrayList(collection, name, elementType);
SetValue(instance, property, arrayInstance.ToArray(elementType));
}
else if (IsGenericList(propertyType)) {
IList genericListProperty = GetGenericListProperty(instance, property);
if (genericListProperty == null) continue;
DeserializeGenericList(collection, name, propertyType, ref genericListProperty);
}
else {
object complexProperty = GetComplexProperty(instance, property);
if (complexProperty == null) continue;
Deserialize(collection, name, propertyType, ref complexProperty);
}
}
}
}
protected virtual void DeserializeGenericList(NameValueCollection collection, string prefix, Type targetType,
ref IList instance) {
Type elementType = targetType.GetGenericArguments()[0];
ArrayList arrayInstance = DeserializeArrayList(collection, prefix, elementType);
foreach (var inst in arrayInstance) {
instance.Add(inst);
}
}
protected virtual IList GetGenericListProperty(object instance, PropertyInfo property) {
// If property is already initialized (via object's constructor) use that
// Otherwise attempt to new it
var genericListProperty = property.GetValue(instance, null) as IList;
if (genericListProperty == null) {
genericListProperty = CreateGenericListInstance(property.PropertyType);
if (!SetValue(instance, property, genericListProperty)) {
return null;
}
}
return genericListProperty;
}
protected virtual IList CreateGenericListInstance(Type targetType) {
Type elementType = targetType.GetGenericArguments()[0];
Type desiredListType = targetType.IsInterface
? typeof(List<>).MakeGenericType(elementType)
: targetType;
return CreateInstance(desiredListType) as IList;
}
protected virtual bool IsGenericList(Type instanceType) {
if (!instanceType.IsGenericType) {
return false;
}
if (typeof(IList).IsAssignableFrom(instanceType)) {
return true;
}
Type[] genericArgs = instanceType.GetGenericArguments();
Type listType = typeof(IList<>).MakeGenericType(genericArgs[0]);
return listType.IsAssignableFrom(instanceType);
}
protected virtual ArrayList DeserializeArrayList(NameValueCollection collection, string prefix, Type elementType) {
ArrayList arrayInstance;
if (IsSimpleProperty(elementType)) {
string[] sValueArray = collection.GetValues(prefix);
if (sValueArray != null) {
arrayInstance = new ArrayList(sValueArray.Length);
foreach (var item in sValueArray) {
var inst = GetConvertible(item).ToType(elementType, CultureInfo.CurrentCulture);
if (inst != null) {
arrayInstance.Add(inst);
}
}
return arrayInstance;
}
}
string[] arrayPrefixes = GetArrayPrefixes(collection, prefix);
arrayInstance = new ArrayList(arrayPrefixes.Length);
foreach (var arrayPrefix in arrayPrefixes) {
object inst = null;
if (IsSimpleProperty(elementType)) {
string sValue = collection.Get(arrayPrefix);
if (sValue != null) {
inst = GetConvertible(sValue).ToType(elementType, CultureInfo.CurrentCulture);
}
}
else {
inst = Deserialize(collection, arrayPrefix, elementType);
}
if (inst != null) {
arrayInstance.Add(inst);
}
}
return arrayInstance;
}
protected virtual bool CheckPrefixInRequest(NameValueCollection collection, string prefix) {
return prefix != null
? collection.AllKeys.Any(key => key != null && key.StartsWith(prefix, true, CultureInfo.InvariantCulture))
: true;
}
protected virtual string[] GetArrayPrefixes(NameValueCollection collection, string prefix) {
var arrayPrefixes = new List<string>();
prefix = string.Concat(prefix, "[").ToLower();
int prefixLength = prefix.Length;
string[] names = collection.AllKeys;
foreach (var name in names) {
if (name.IndexOf(prefix, StringComparison.InvariantCultureIgnoreCase) == 0) {
int bracketIndex = name.IndexOf(']', prefixLength);
if (bracketIndex > prefixLength) {
string arrayPrefix = name.Substring(0, bracketIndex + 1).ToLower();
if (!arrayPrefixes.Contains(arrayPrefix)) {
arrayPrefixes.Add(arrayPrefix);
}
}
}
}
return arrayPrefixes.ToArray();
}
private static readonly Dictionary<Type, PropertyInfo[]> _cachedProperties = new Dictionary<Type, PropertyInfo[]>();
private static readonly object _syncRoot = new object();
protected static PropertyInfo[] GetProperties(Type targetType) {
PropertyInfo[] properties;
if (!_cachedProperties.TryGetValue(targetType, out properties)) {
lock (_syncRoot) {
if (!_cachedProperties.TryGetValue(targetType, out properties)) {
properties = targetType.GetProperties();
_cachedProperties.Add(targetType, properties);
}
}
}
return properties;
}
protected virtual bool SetValue(object instance, PropertyInfo property, object value) {
if (property.CanWrite) {
property.SetValue(instance, value, null);
return true;
}
return false;
}
protected virtual bool SetValue(object instance, PropertyInfo property, IConvertible oValue) {
try {
object convertedValue = oValue.ToType(property.PropertyType, CultureInfo.CurrentCulture);
return SetValue(instance, property, convertedValue);
}
catch {
return false;
}
}
protected virtual object CreateInstance(Type targetType) {
return Activator.CreateInstance(targetType);
}
protected virtual object GetComplexProperty(object instance, PropertyInfo property) {
// If property is already initialized (via object's constructor) use that
// Otherwise attempt to new it
object complexProperty = property.GetValue(instance, null);
if (complexProperty == null) {
complexProperty = CreateInstance(property.PropertyType);
if (!SetValue(instance, property, complexProperty)) {
return null;
}
}
return complexProperty;
}
protected virtual bool IsSimpleProperty(Type propertyType) {
if (propertyType.IsArray) {
return false;
}
bool isSimple = propertyType.IsPrimitive ||
propertyType.IsEnum ||
propertyType == typeof(String) ||
propertyType == typeof(Guid) ||
propertyType == typeof(DateTime) ||
propertyType == typeof(Decimal);
if (isSimple) {
return true;
}
TypeConverter tconverter = TypeDescriptor.GetConverter(propertyType);
return tconverter.CanConvertFrom(typeof(String));
}
}
internal class DefaultConvertible : IConvertible {
private static readonly Type[] ConvertTypes = new[] {
typeof(bool),
typeof(char), // 1
typeof(sbyte),
typeof(byte), // 3
typeof(short),
typeof(ushort), // 5
typeof(int),
typeof(uint), // 7
typeof(long),
typeof(ulong), // 9
typeof(float),
typeof(double), // 11
typeof(decimal),
typeof(DateTime), // 13
typeof(string),
typeof(Enum), // 15
typeof(Guid)
};
private readonly string _value;
public DefaultConvertible(string value) {
_value = value;
}
public TypeCode GetTypeCode() {
return _value.GetTypeCode();
}
public bool ToBoolean(IFormatProvider provider) {
string value = _value;
if (value != null && value.Contains(",")) {
value = value.Remove(value.IndexOf(','));
}
bool oValue;
if (bool.TryParse(value, out oValue)) {
return oValue;
}
return new bool();
}
public char ToChar(IFormatProvider provider) {
if (_value == null) {
return new char();
}
return _value[0];
}
public sbyte ToSByte(IFormatProvider provider) {
sbyte oValue;
if (sbyte.TryParse(_value, NumberStyles.Any, provider, out oValue)) {
return oValue;
}
return new sbyte();
}
public byte ToByte(IFormatProvider provider) {
byte oValue;
if (byte.TryParse(_value, NumberStyles.Any, provider, out oValue)) {
return oValue;
}
return new byte();
}
public short ToInt16(IFormatProvider provider) {
short oValue;
if (short.TryParse(_value, NumberStyles.Any, provider, out oValue)) {
return oValue;
}
return new short();
}
public ushort ToUInt16(IFormatProvider provider) {
ushort oValue;
if (ushort.TryParse(_value, NumberStyles.Any, provider, out oValue)) {
return oValue;
}
return new ushort();
}
public int ToInt32(IFormatProvider provider) {
int oValue;
if (int.TryParse(_value, NumberStyles.Any, provider, out oValue)) {
return oValue;
}
return new int();
}
public uint ToUInt32(IFormatProvider provider) {
uint oValue;
if (uint.TryParse(_value, NumberStyles.Any, provider, out oValue)) {
return oValue;
}
return new uint();
}
public long ToInt64(IFormatProvider provider) {
long oValue;
if (long.TryParse(_value, NumberStyles.Any, provider, out oValue)) {
return oValue;
}
return new long();
}
public ulong ToUInt64(IFormatProvider provider) {
ulong oValue;
if (ulong.TryParse(_value, NumberStyles.Any, provider, out oValue)) {
return oValue;
}
return new ulong();
}
public float ToSingle(IFormatProvider provider) {
float oValue;
if (float.TryParse(_value, NumberStyles.Any, provider, out oValue)) {
return oValue;
}
return new float();
}
public double ToDouble(IFormatProvider provider) {
double oValue;
if (double.TryParse(_value, NumberStyles.Any, provider, out oValue)) {
return oValue;
}
return new double();
}
public decimal ToDecimal(IFormatProvider provider) {
decimal oValue;
if (decimal.TryParse(_value, NumberStyles.Any, provider, out oValue)) {
return oValue;
}
return new decimal();
}
public DateTime ToDateTime(IFormatProvider provider) {
DateTime oValue;
if (DateTime.TryParse(_value, provider, DateTimeStyles.None, out oValue)) {
return oValue;
}
return new DateTime();
}
public string ToString(IFormatProvider provider) {
return _value;
}
public object ToEnum(Type conversionType) {
if (conversionType == null || !conversionType.IsEnum) {
return null;
}
if (_value == null) {
return Enum.ToObject(conversionType, 0);
}
try {
return Enum.Parse(conversionType, _value, true);
}
catch (ArgumentException) {
return Enum.ToObject(conversionType, 0);
}
}
public Guid ToGuid() {
if (_value == null) {
return Guid.Empty;
}
try {
return new Guid(_value);
}
catch (FormatException) {}
catch (OverflowException) {}
return Guid.Empty;
}
public object WithTypeConverter(Type conversionType) {
if (_value == null) return null;
TypeConverter typeConverter = TypeDescriptor.GetConverter(conversionType);
if (typeConverter == null || !typeConverter.CanConvertFrom(ConvertTypes[14])) {
return null;
}
return typeConverter.ConvertFromString(_value);
}
public virtual object ToType(Type conversionType, IFormatProvider provider) {
if (conversionType == ConvertTypes[0]) {
return ToBoolean(provider);
}
if (conversionType == ConvertTypes[1]) {
return ToChar(provider);
}
if (conversionType == ConvertTypes[2]) {
return ToSByte(provider);
}
if (conversionType == ConvertTypes[3]) {
return ToByte(provider);
}
if (conversionType == ConvertTypes[4]) {
return ToInt16(provider);
}
if (conversionType == ConvertTypes[5]) {
return ToUInt16(provider);
}
if (conversionType == ConvertTypes[6]) {
return ToInt32(provider);
}
if (conversionType == ConvertTypes[7]) {
return ToUInt32(provider);
}
if (conversionType == ConvertTypes[8]) {
return ToInt64(provider);
}
if (conversionType == ConvertTypes[9]) {
return ToUInt64(provider);
}
if (conversionType == ConvertTypes[10]) {
return ToSingle(provider);
}
if (conversionType == ConvertTypes[11]) {
return ToDouble(provider);
}
if (conversionType == ConvertTypes[12]) {
return ToDecimal(provider);
}
if (conversionType == ConvertTypes[13]) {
return ToDateTime(provider);
}
if (conversionType == ConvertTypes[14]) {
return ToString(provider);
}
if (ConvertTypes[15].IsAssignableFrom(conversionType)) {
return ToEnum(conversionType);
}
if (conversionType == ConvertTypes[16]) {
return ToGuid();
}
return WithTypeConverter(conversionType);
}
}
}
| |
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>
/// Event Attendees Data Set
/// </summary>
[GeneratedCode("EduHub Data", "0.9")]
public sealed partial class TETNDataSet : EduHubDataSet<TETN>
{
/// <inheritdoc />
public override string Name { get { return "TETN"; } }
/// <inheritdoc />
public override bool SupportsEntityLastModified { get { return true; } }
internal TETNDataSet(EduHubContext Context)
: base(Context)
{
Index_TETELINK_ATTENDEE_TYPE = new Lazy<Dictionary<Tuple<int?, string>, IReadOnlyList<TETN>>>(() => this.ToGroupedDictionary(i => Tuple.Create(i.TETELINK, i.ATTENDEE_TYPE)));
Index_TETNKEY = new Lazy<Dictionary<int, IReadOnlyList<TETN>>>(() => this.ToGroupedDictionary(i => i.TETNKEY));
Index_TID = new Lazy<Dictionary<int, TETN>>(() => this.ToDictionary(i => i.TID));
}
/// <summary>
/// Matches CSV file headers to actions, used to deserialize <see cref="TETN" />
/// </summary>
/// <param name="Headers">The CSV column headers</param>
/// <returns>An array of actions which deserialize <see cref="TETN" /> fields for each CSV column header</returns>
internal override Action<TETN, string>[] BuildMapper(IReadOnlyList<string> Headers)
{
var mapper = new Action<TETN, 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 "TETNKEY":
mapper[i] = (e, v) => e.TETNKEY = int.Parse(v);
break;
case "TETELINK":
mapper[i] = (e, v) => e.TETELINK = v == null ? (int?)null : int.Parse(v);
break;
case "ATTENDEE":
mapper[i] = (e, v) => e.ATTENDEE = v;
break;
case "ATTENDEE_TYPE":
mapper[i] = (e, v) => e.ATTENDEE_TYPE = v;
break;
case "ATTENDEE_DETAIL":
mapper[i] = (e, v) => e.ATTENDEE_DETAIL = 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="TETN" /> delta entities
/// </summary>
/// <param name="Entities">Iterator for base <see cref="TETN" /> entities</param>
/// <param name="DeltaEntities">List of delta <see cref="TETN" /> entities</param>
/// <returns>A merged <see cref="IEnumerable{TETN}"/> of entities</returns>
internal override IEnumerable<TETN> ApplyDeltaEntities(IEnumerable<TETN> Entities, List<TETN> 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.TETNKEY;
bool yieldEntity = false;
while (entityIterator.MoveNext())
{
var entity = entityIterator.Current;
bool overwritten = Index_TID.Remove(entity.TID);
if (entity.TETNKEY.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<Dictionary<Tuple<int?, string>, IReadOnlyList<TETN>>> Index_TETELINK_ATTENDEE_TYPE;
private Lazy<Dictionary<int, IReadOnlyList<TETN>>> Index_TETNKEY;
private Lazy<Dictionary<int, TETN>> Index_TID;
#endregion
#region Index Methods
/// <summary>
/// Find TETN by TETELINK and ATTENDEE_TYPE fields
/// </summary>
/// <param name="TETELINK">TETELINK value used to find TETN</param>
/// <param name="ATTENDEE_TYPE">ATTENDEE_TYPE value used to find TETN</param>
/// <returns>List of related TETN entities</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<TETN> FindByTETELINK_ATTENDEE_TYPE(int? TETELINK, string ATTENDEE_TYPE)
{
return Index_TETELINK_ATTENDEE_TYPE.Value[Tuple.Create(TETELINK, ATTENDEE_TYPE)];
}
/// <summary>
/// Attempt to find TETN by TETELINK and ATTENDEE_TYPE fields
/// </summary>
/// <param name="TETELINK">TETELINK value used to find TETN</param>
/// <param name="ATTENDEE_TYPE">ATTENDEE_TYPE value used to find TETN</param>
/// <param name="Value">List of related TETN entities</param>
/// <returns>True if the list of related TETN entities is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByTETELINK_ATTENDEE_TYPE(int? TETELINK, string ATTENDEE_TYPE, out IReadOnlyList<TETN> Value)
{
return Index_TETELINK_ATTENDEE_TYPE.Value.TryGetValue(Tuple.Create(TETELINK, ATTENDEE_TYPE), out Value);
}
/// <summary>
/// Attempt to find TETN by TETELINK and ATTENDEE_TYPE fields
/// </summary>
/// <param name="TETELINK">TETELINK value used to find TETN</param>
/// <param name="ATTENDEE_TYPE">ATTENDEE_TYPE value used to find TETN</param>
/// <returns>List of related TETN entities, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<TETN> TryFindByTETELINK_ATTENDEE_TYPE(int? TETELINK, string ATTENDEE_TYPE)
{
IReadOnlyList<TETN> value;
if (Index_TETELINK_ATTENDEE_TYPE.Value.TryGetValue(Tuple.Create(TETELINK, ATTENDEE_TYPE), out value))
{
return value;
}
else
{
return null;
}
}
/// <summary>
/// Find TETN by TETNKEY field
/// </summary>
/// <param name="TETNKEY">TETNKEY value used to find TETN</param>
/// <returns>List of related TETN entities</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<TETN> FindByTETNKEY(int TETNKEY)
{
return Index_TETNKEY.Value[TETNKEY];
}
/// <summary>
/// Attempt to find TETN by TETNKEY field
/// </summary>
/// <param name="TETNKEY">TETNKEY value used to find TETN</param>
/// <param name="Value">List of related TETN entities</param>
/// <returns>True if the list of related TETN entities is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByTETNKEY(int TETNKEY, out IReadOnlyList<TETN> Value)
{
return Index_TETNKEY.Value.TryGetValue(TETNKEY, out Value);
}
/// <summary>
/// Attempt to find TETN by TETNKEY field
/// </summary>
/// <param name="TETNKEY">TETNKEY value used to find TETN</param>
/// <returns>List of related TETN entities, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<TETN> TryFindByTETNKEY(int TETNKEY)
{
IReadOnlyList<TETN> value;
if (Index_TETNKEY.Value.TryGetValue(TETNKEY, out value))
{
return value;
}
else
{
return null;
}
}
/// <summary>
/// Find TETN by TID field
/// </summary>
/// <param name="TID">TID value used to find TETN</param>
/// <returns>Related TETN entity</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public TETN FindByTID(int TID)
{
return Index_TID.Value[TID];
}
/// <summary>
/// Attempt to find TETN by TID field
/// </summary>
/// <param name="TID">TID value used to find TETN</param>
/// <param name="Value">Related TETN entity</param>
/// <returns>True if the related TETN entity is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByTID(int TID, out TETN Value)
{
return Index_TID.Value.TryGetValue(TID, out Value);
}
/// <summary>
/// Attempt to find TETN by TID field
/// </summary>
/// <param name="TID">TID value used to find TETN</param>
/// <returns>Related TETN entity, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public TETN TryFindByTID(int TID)
{
TETN 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 TETN 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].[TETN]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[TETN](
[TID] int IDENTITY NOT NULL,
[TETNKEY] int NOT NULL,
[TETELINK] int NULL,
[ATTENDEE] varchar(10) NULL,
[ATTENDEE_TYPE] varchar(8) NULL,
[ATTENDEE_DETAIL] varchar(30) NULL,
[LW_DATE] datetime NULL,
[LW_TIME] smallint NULL,
[LW_USER] varchar(128) NULL,
CONSTRAINT [TETN_Index_TID] PRIMARY KEY NONCLUSTERED (
[TID] ASC
)
);
CREATE NONCLUSTERED INDEX [TETN_Index_TETELINK_ATTENDEE_TYPE] ON [dbo].[TETN]
(
[TETELINK] ASC,
[ATTENDEE_TYPE] ASC
);
CREATE CLUSTERED INDEX [TETN_Index_TETNKEY] ON [dbo].[TETN]
(
[TETNKEY] 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].[TETN]') AND name = N'TETN_Index_TETELINK_ATTENDEE_TYPE')
ALTER INDEX [TETN_Index_TETELINK_ATTENDEE_TYPE] ON [dbo].[TETN] DISABLE;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[TETN]') AND name = N'TETN_Index_TID')
ALTER INDEX [TETN_Index_TID] ON [dbo].[TETN] 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].[TETN]') AND name = N'TETN_Index_TETELINK_ATTENDEE_TYPE')
ALTER INDEX [TETN_Index_TETELINK_ATTENDEE_TYPE] ON [dbo].[TETN] REBUILD PARTITION = ALL;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[TETN]') AND name = N'TETN_Index_TID')
ALTER INDEX [TETN_Index_TID] ON [dbo].[TETN] REBUILD PARTITION = ALL;
");
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which deletes the <see cref="TETN"/> 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="TETN"/> entities to be deleted</param>
public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<TETN> 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].[TETN] 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 TETN data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the TETN data set</returns>
public override EduHubDataSetDataReader<TETN> GetDataSetDataReader()
{
return new TETNDataReader(Load());
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the TETN data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the TETN data set</returns>
public override EduHubDataSetDataReader<TETN> GetDataSetDataReader(List<TETN> Entities)
{
return new TETNDataReader(new EduHubDataSetLoadedReader<TETN>(this, Entities));
}
// Modest implementation to primarily support SqlBulkCopy
private class TETNDataReader : EduHubDataSetDataReader<TETN>
{
public TETNDataReader(IEduHubDataSetReader<TETN> Reader)
: base (Reader)
{
}
public override int FieldCount { get { return 9; } }
public override object GetValue(int i)
{
switch (i)
{
case 0: // TID
return Current.TID;
case 1: // TETNKEY
return Current.TETNKEY;
case 2: // TETELINK
return Current.TETELINK;
case 3: // ATTENDEE
return Current.ATTENDEE;
case 4: // ATTENDEE_TYPE
return Current.ATTENDEE_TYPE;
case 5: // ATTENDEE_DETAIL
return Current.ATTENDEE_DETAIL;
case 6: // LW_DATE
return Current.LW_DATE;
case 7: // LW_TIME
return Current.LW_TIME;
case 8: // LW_USER
return Current.LW_USER;
default:
throw new ArgumentOutOfRangeException(nameof(i));
}
}
public override bool IsDBNull(int i)
{
switch (i)
{
case 2: // TETELINK
return Current.TETELINK == null;
case 3: // ATTENDEE
return Current.ATTENDEE == null;
case 4: // ATTENDEE_TYPE
return Current.ATTENDEE_TYPE == null;
case 5: // ATTENDEE_DETAIL
return Current.ATTENDEE_DETAIL == null;
case 6: // LW_DATE
return Current.LW_DATE == null;
case 7: // LW_TIME
return Current.LW_TIME == null;
case 8: // 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: // TETNKEY
return "TETNKEY";
case 2: // TETELINK
return "TETELINK";
case 3: // ATTENDEE
return "ATTENDEE";
case 4: // ATTENDEE_TYPE
return "ATTENDEE_TYPE";
case 5: // ATTENDEE_DETAIL
return "ATTENDEE_DETAIL";
case 6: // LW_DATE
return "LW_DATE";
case 7: // LW_TIME
return "LW_TIME";
case 8: // LW_USER
return "LW_USER";
default:
throw new ArgumentOutOfRangeException(nameof(ordinal));
}
}
public override int GetOrdinal(string name)
{
switch (name)
{
case "TID":
return 0;
case "TETNKEY":
return 1;
case "TETELINK":
return 2;
case "ATTENDEE":
return 3;
case "ATTENDEE_TYPE":
return 4;
case "ATTENDEE_DETAIL":
return 5;
case "LW_DATE":
return 6;
case "LW_TIME":
return 7;
case "LW_USER":
return 8;
default:
throw new ArgumentOutOfRangeException(nameof(name));
}
}
}
#endregion
}
}
| |
#region [R# naming]
// ReSharper disable ArrangeTypeModifiers
// ReSharper disable UnusedMember.Local
// ReSharper disable FieldCanBeMadeReadOnly.Local
// ReSharper disable ArrangeTypeMemberModifiers
// ReSharper disable InconsistentNaming
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Moq;
using NSpectator.Domain;
using NUnit.Framework;
using FluentAssertions;
namespace NSpectator.Specs
{
[TestFixture]
public class Describe_ContextBuilder
{
protected Mock<ISpecFinder> finderMock;
protected ContextBuilder builder;
protected List<Type> typesForFinder;
protected List<Context> contexts;
[SetUp]
public void SetupBase()
{
typesForFinder = new List<Type>();
finderMock = new Mock<ISpecFinder>();
finderMock.Setup(f => f.SpecClasses()).Returns(typesForFinder);
DefaultConventions conventions = new DefaultConventions();
conventions.Initialize();
builder = new ContextBuilder(finderMock.Object, conventions);
}
public void GivenTypes(params Type[] types)
{
typesForFinder.AddRange(types);
}
public IList<Context> TheContexts()
{
return builder.Contexts();
}
[Test]
public void Should_be_parent_class_and_setup_works()
{
}
}
[TestFixture]
public class When_building_contexts : Describe_ContextBuilder
{
public class Child : Parent { }
public class Sibling : Parent { }
public class Parent : Spec { }
[SetUp]
public void Setup()
{
GivenTypes(typeof(Child), typeof(Sibling), typeof(Parent));
TheContexts();
}
[Test]
public void Should_get_specs_from_specFinder()
{
finderMock.Verify(f => f.SpecClasses());
}
[Test]
public void the_primary_context_Should_be_parent()
{
TheContexts().First().Name.Should().BeEquals(typeof(Parent).Name, StringComparison.InvariantCultureIgnoreCase);
}
[Test]
public void the_parent_Should_have_the_child_context()
{
TheContexts().First().Contexts.First().Name.Should().BeEquals(typeof(Child).Name, StringComparison.InvariantCultureIgnoreCase);
}
[Test]
public void it_should_only_have_the_parent_once()
{
TheContexts().Count().Should().Be(1);
}
[Test]
public void it_should_have_the_sibling()
{
TheContexts().First().Contexts.Should().Contain(c => c.Name.Equals(typeof(Sibling).Name, StringComparison.InvariantCultureIgnoreCase));
}
}
[TestFixture]
public class When_finding_method_level_examples : Describe_ContextBuilder
{
class Class_with_method_level_example : Spec
{
void it_should_be_considered_an_example() { }
void specify_should_be_considered_as_an_example() { }
// -----
async Task it_should_be_considered_an_example_with_async() { await Task.Delay(0); }
async Task<long> it_should_be_considered_an_example_with_async_result() { await Task.Delay(0); return 0L; }
async void it_should_be_considered_an_example_with_async_void() { await Task.Delay(0); }
async Task specify_should_be_considered_as_an_example_with_async() { await Task.Delay(0); }
}
[SetUp]
public void Setup()
{
GivenTypes(typeof(Class_with_method_level_example));
}
[Test]
public void Should_find_method_level_example_if_the_method_name_starts_with_the_word_IT()
{
ShouldContainExample("it should be considered an example");
}
[Test]
public void Should_find_async_method_level_example_if_the_method_name_starts_with_the_word_IT()
{
ShouldContainExample("it should be considered an example with async");
}
[Test]
public void Should_find_async_method_level_example_if_the_method_name_starts_with_the_word_IT_and_it_returns_result()
{
ShouldContainExample("it should be considered an example with async result");
}
[Test]
public void Should_find_async_method_level_example_if_the_method_name_starts_with_the_word_IT_and_it_returns_void()
{
ShouldContainExample("it should be considered an example with async void");
}
[Test]
public void Should_find_method_level_example_if_the_method_starts_with_SPECIFY()
{
ShouldContainExample("specify should be considered as an example");
}
[Test]
public void Should_find_async_method_level_example_if_the_method_starts_with_SPECIFY()
{
ShouldContainExample("specify should be considered as an example with async");
}
[Test]
public void Should_exclude_methods_that_start_with_ITs_from_child_context()
{
TheContexts().First().Contexts.Should().BeEmpty();
}
private void ShouldContainExample(string exampleName)
{
TheContexts().First().Examples.Any(s => s.Spec == exampleName).Should().BeTrue();
}
}
[TestFixture]
public class When_building_method_contexts
{
private Context classContext;
private class SpecClass : Spec
{
public void public_method() { }
void private_method() { }
void before_each() { }
void act_each() { }
}
[SetUp]
public void Setup()
{
var finderMock = new Mock<ISpecFinder>();
DefaultConventions defaultConvention = new DefaultConventions();
defaultConvention.Initialize();
var builder = new ContextBuilder(finderMock.Object, defaultConvention);
classContext = new Context("class");
builder.BuildMethodContexts(classContext, typeof(SpecClass));
}
[Test]
public void it_Should_add_the_public_method_as_a_sub_context()
{
classContext.Contexts.Should().Contain(c => c.Name == "public method");
}
[Test]
public void it_should_not_create_a_sub_context_for_the_private_method()
{
classContext.Contexts.Should().Contain(c => c.Name == "private method");
}
[Test]
public void it_should_disregard_method_called_before_each()
{
classContext.Contexts.Should().NotContain(c => c.Name == "before each");
}
[Test]
public void it_should_disregard_method_called_act_each()
{
classContext.Contexts.Should().NotContain(c => c.Name == "act each");
}
}
[TestFixture]
public class When_building_class_and_method_contexts_with_tag_attributes : Describe_ContextBuilder
{
[Tag("@class-tag")]
class SpecClass : Spec
{
[Tag("@method-tag")]
void public_method() { }
}
[SetUp]
public void setup()
{
GivenTypes(typeof(SpecClass));
}
[Test]
public void it_should_tag_class_context()
{
var classContext = TheContexts()[0];
classContext.Tags.Should_contain_tag("@class-tag");
}
[Test]
public void it_should_tag_method_context()
{
var methodContext = TheContexts()[0].Contexts[0];
methodContext.Tags.Should_contain_tag("@method-tag");
}
}
[TestFixture]
[Category("ContextBuilder")]
public class Describe_second_order_inheritance : Describe_ContextBuilder
{
class Base_spec : Spec { }
class Child_spec : Base_spec { }
class Grand_child_spec : Child_spec { }
[SetUp]
public void Setup()
{
GivenTypes(
typeof(Base_spec),
typeof(Child_spec),
typeof(Grand_child_spec));
}
[Test]
public void the_root_context_Should_be_base_spec()
{
TheContexts().First().Name.ShouldBeConventionTo(typeof(Base_spec));
}
[Test]
public void the_next_context_Should_be_derived_spec()
{
TheContexts().First().Contexts.First().Name.ShouldBeConventionTo(typeof(Child_spec));
}
[Test]
public void the_next_next_context_Should_be_derived_spec()
{
TheContexts().First().Contexts.First().Contexts.First().Name.ShouldBeConventionTo(typeof(Grand_child_spec));
}
}
public static class InheritanceExtentions
{
public static void ShouldBeConventionTo(this string actualName, Type expectedType)
{
expectedType.Name.Replace("_", " ").Should().BeEquals(actualName, StringComparison.InvariantCultureIgnoreCase);
}
}
}
| |
//******************************************
// Copyright (C) 2014-2015 Charles Nurse *
// *
// Licensed under MIT License *
// (see included LICENSE) *
// *
// *****************************************
using System;
using System.IO;
using FamilyTreeProject.GEDCOM.Common;
using FamilyTreeProject.GEDCOM.Records;
// ReSharper disable UseNullPropagation
namespace FamilyTreeProject.GEDCOM.IO
{
/// <summary>
/// GEDCOMReader is a class that can read GEDCOM files
/// </summary>
/// <remarks>
/// This class always reads ahead to the next record (so it can determine whether the next
/// record is a CONT or CONC record or a child record)
/// storing the next record in a buffer until it is needed.
/// </remarks>
public class GEDCOMReader : IDisposable
{
private bool _disposed;
private TextReader _reader;
private GEDCOMRecord _nextRecord;
#region Constructors
/// <summary>
/// This constructor creates a GEDCOMReader from a TextReader
/// </summary>
/// <param name = "reader">The TextReader to use</param>
private GEDCOMReader(TextReader reader)
{
if (reader == null)
{
throw new ArgumentNullException("reader");
}
_reader = reader;
GetNextRecord();
}
/// <summary>
/// This constructor creates a GEDCOMReader that reads from a Stream
/// </summary>
/// <param name = "stream">The Stream to use</param>
private GEDCOMReader(Stream stream)
{
if (stream == null)
{
throw new ArgumentNullException("stream");
}
_reader = new StreamReader(stream);
GetNextRecord();
}
/// <summary>
/// This constructor creates a GEDCOMReader that reads from a String
/// </summary>
/// <param name = "text">The String to use</param>
private GEDCOMReader(String text)
{
if (text == null)
{
throw new ArgumentNullException("text");
}
_reader = new StringReader(text);
GetNextRecord();
}
#endregion
#region Private Methods
/// <summary>
/// GetNextRecord loads the next record of text into the buffer
/// </summary>
private void GetNextRecord()
{
String text = _reader.ReadLine();
_nextRecord = text != null ? new GEDCOMRecord(text) : null;
}
/// <summary>
/// Moves to the next Record of a specified Tag type
/// </summary>
/// <param name = "tag">The type of tag to move to.</param>
/// <param name="level"></param>
/// <returns>true if the reader is positioned on a record, false if the reader is not positioned on a record</returns>
private bool MoveToRecord(GEDCOMTag tag, int level)
{
while (_nextRecord != null && _nextRecord.Level >= level && _nextRecord.TagName != tag)
{
GetNextRecord();
}
//As the nextRecord field always containes the next GEDCOMRecord, return whether this is null.
return (_nextRecord != null && _nextRecord.TagName == tag && _nextRecord.Level == level);
}
/// <summary>
/// ReadRecord - reads the next GEDCOM Record of a specified Tag type
/// </summary>
/// <param name = "tag">The type of tag to read</param>
/// <returns>A GEDCOM Record or null</returns>
private GEDCOMRecord ReadRecord(GEDCOMTag tag)
{
GEDCOMRecord record;
while ((record = ReadRecord()) != null)
{
if (record.TagName == tag)
{
break;
}
}
return record;
}
/// <summary>
/// ReadRecords reads to the end of the source and return all the records
/// of a sepcified Tag type
/// </summary>
/// <returns>A List of GEDCOMRecords.</returns>
private GEDCOMRecordList ReadRecords(GEDCOMTag tag)
{
GEDCOMRecord record;
var lines = new GEDCOMRecordList();
while ((record = ReadRecord()) != null)
{
if (record.TagName == tag || tag == GEDCOMTag.ANY)
{
lines.Add(record);
}
}
return lines;
}
#endregion
#region Public Static Methods
/// <summary>
/// Creates a GEDCOMReader from a TextReader
/// </summary>
/// <param name = "reader">The TextReader to use</param>
public static GEDCOMReader Create(TextReader reader)
{
return new GEDCOMReader(reader);
}
/// <summary>
/// Creates a GEDCOMReader that reads from a Stream
/// </summary>
/// <param name = "stream">The Stream to use</param>
public static GEDCOMReader Create(Stream stream)
{
return new GEDCOMReader(stream);
}
/// <summary>
/// Creates a GEDCOMReader that reads from a String
/// </summary>
/// <param name = "text">The String to use</param>
public static GEDCOMReader Create(String text)
{
return new GEDCOMReader(text);
}
#endregion
#region Public Methods
#region MoveTo Methods
/// <summary>
/// Moves to the next Record
/// </summary>
/// <returns>true if the reader is positioned on a record, false if the reader is not positioned on a record</returns>
public bool MoveToRecord()
{
//As the nextRecord field always containes the next GEDCOMRecord, return whether this is null.
return (_nextRecord != null);
}
/// <summary>
/// Moves to the next Family Record (Tag = FAM)
/// </summary>
/// <returns>true if the reader is positioned on a Family record, false if the reader is not positioned on a Family record</returns>
public bool MoveToFamily()
{
return MoveToRecord(GEDCOMTag.FAM, 0);
}
/// <summary>
/// Moves to the Header Record (Tag = HEAD)
/// </summary>
/// <returns>true if the reader is positioned on a Header record, false if the reader is not positioned on a Header record</returns>
public bool MoveToHeader()
{
return MoveToRecord(GEDCOMTag.HEAD, 0);
}
/// <summary>
/// Moves to the next Individual Record (Tag = INDI)
/// </summary>
/// <returns>true if the reader is positioned on a Individual record, false if the reader is not positioned on a Individual record</returns>
public bool MoveToIndividual()
{
return MoveToRecord(GEDCOMTag.INDI, 0);
}
/// <summary>
/// Moves to the next Multimedia Object Record (Tag = OBJE)
/// </summary>
/// <returns>true if the reader is positioned on a Multimedia Object record, false if the reader is not positioned on a Multimedia Object record</returns>
public bool MoveToMultimedia()
{
return MoveToRecord(GEDCOMTag.OBJE, 0);
}
/// <summary>
/// Moves to the next Note Record (Tag = NOTE)
/// </summary>
/// <returns>true if the reader is positioned on a Note record, false if the reader is not positioned on a Note record</returns>
public bool MoveToNote()
{
return MoveToRecord(GEDCOMTag.NOTE, 0);
}
/// <summary>
/// Moves to the next Repository Record (Tag = REPO)
/// </summary>
/// <returns>true if the reader is positioned on a Repository record, false if the reader is not positioned on a Repository record</returns>
public bool MoveToRepository()
{
return MoveToRecord(GEDCOMTag.REPO, 0);
}
/// <summary>
/// Moves to the next Source Record (Tag = SOUR)
/// </summary>
/// <returns>true if the reader is positioned on a Source record, false if the reader is not positioned on a Source record</returns>
public bool MoveToSource()
{
return MoveToRecord(GEDCOMTag.SOUR, 0);
}
/// <summary>
/// Moves to the next Submitter Record (Tag = SUBM)
/// </summary>
/// <returns>true if the reader is positioned on a Submitter record, false if the reader is not positioned on a Submitter record</returns>
public bool MoveToSubmitter()
{
return MoveToRecord(GEDCOMTag.SUBM, 0);
}
/// <summary>
/// Moves to the Submission Record (Tag = SUBN)
/// </summary>
/// <returns>true if the reader is positioned on a Submission record, false if the reader is not positioned on a Submission record</returns>
public bool MoveToSubmission()
{
return MoveToRecord(GEDCOMTag.SUBN, 0);
}
#endregion
#region Read Method
public GEDCOMRecordList Read()
{
return ReadRecords(GEDCOMTag.ANY);
}
#endregion
#region ReadLine Methods
/// <summary>
/// ReadFamily - reads the next GEDCOM Family (FAM)
/// </summary>
/// <returns>A GEDCOM Family</returns>
public GEDCOMFamilyRecord ReadFamily()
{
return (GEDCOMFamilyRecord) ReadRecord(GEDCOMTag.FAM);
}
/// <summary>
/// ReadHeader - reads the next GEDCOM Header (HEAD)
/// </summary>
/// <returns>A GEDCOM Family</returns>
public GEDCOMHeaderRecord ReadHeader()
{
return (GEDCOMHeaderRecord) ReadRecord(GEDCOMTag.HEAD);
}
/// <summary>
/// ReadIndividual - reads the next GEDCOM Individual (INDI)
/// </summary>
/// <returns>A GEDCOM Individual</returns>
public GEDCOMIndividualRecord ReadIndividual()
{
return (GEDCOMIndividualRecord) ReadRecord(GEDCOMTag.INDI);
}
/// <summary>
/// ReadMultimediaObject - reads the next GEDCOM Multimedia Object (OBJE)
/// </summary>
/// <returns>A GEDCOM MultimediaObject</returns>
public GEDCOMMultimediaRecord ReadMultimediaObject()
{
return GEDCOMRecordFactory.CreateMultimediaRecord(ReadRecord(GEDCOMTag.OBJE));
}
/// <summary>
/// ReadNote - reads the next GEDCOM Note (NOTE)
/// </summary>
/// <returns>A GEDCOM Note</returns>
public GEDCOMNoteRecord ReadNote()
{
return GEDCOMRecordFactory.CreateNoteRecord(ReadRecord(GEDCOMTag.NOTE));
}
/// <summary>
/// ReadLine - reads the next GEDCOM record from the buffer
/// </summary>
/// <returns>A GEDCOM Record</returns>
public GEDCOMRecord ReadRecord()
{
//Declare Variable
GEDCOMRecord record = null;
if (_nextRecord != null)
{
record = _nextRecord;
//Load the next record into the buffer
GetNextRecord();
while (_nextRecord != null)
{
if (_nextRecord.Level == record.Level + 1)
{
switch (_nextRecord.TagName)
{
// Concatenate.
case GEDCOMTag.CONC:
record.AppendData(_nextRecord.Data);
GetNextRecord();
break;
// Continue, add record return and then the text.
case GEDCOMTag.CONT:
record.AppendData("\n" + _nextRecord.Data);
GetNextRecord();
break;
//Add child lines
default:
GEDCOMRecord childLine = ReadRecord();
if (childLine != null)
{
record.ChildRecords.Add(childLine);
}
break;
}
}
else
{
break;
}
}
}
if (record == null)
{
return null;
}
//Pass to RecordFactory to convert the record into the relevant subclass
return GEDCOMRecordFactory.Create(record);
}
/// <summary>
/// ReadRepositoy - reads the next GEDCOM Repositoy (REPO)
/// </summary>
/// <returns>A GEDCOM Repository</returns>
public GEDCOMRepositoryRecord ReadRepository()
{
return GEDCOMRecordFactory.CreateRepositoryRecord(ReadRecord(GEDCOMTag.REPO));
}
/// <summary>
/// ReadSource - reads the next GEDCOM Source (SOUR)
/// </summary>
/// <returns>A GEDCOM Source</returns>
public GEDCOMSourceRecord ReadSource()
{
return GEDCOMRecordFactory.CreateSourceRecord(ReadRecord(GEDCOMTag.SOUR));
}
/// <summary>
/// ReadSubmission - reads the next GEDCOM Submission (SUBN)
/// </summary>
/// <returns>A GEDCOM Submitter</returns>
public GEDCOMSubmissionRecord ReadSubmission()
{
return GEDCOMRecordFactory.CreateSubmissionRecord(ReadRecord(GEDCOMTag.SUBN));
}
/// <summary>
/// ReadSubmitter - reads the next GEDCOM Submitter (SUBM)
/// </summary>
/// <returns>A GEDCOM Submitter</returns>
public GEDCOMSubmitterRecord ReadSubmitter()
{
return GEDCOMRecordFactory.CreateSubmitterRecord(ReadRecord(GEDCOMTag.SUBM));
}
#endregion
#region ReadLines Methods
/// <summary>
/// ReadFamilies reads to the end of the source and return all the Family Lines (FAM)
/// </summary>
/// <returns>A RecordCollection.</returns>
public GEDCOMRecordList ReadFamilies()
{
return ReadRecords(GEDCOMTag.FAM);
}
/// <summary>
/// ReadIndividuals reads to the end of the source and return all the Individual Lines (INDI)
/// </summary>
/// <returns>A RecordCollection.</returns>
public GEDCOMRecordList ReadIndividuals()
{
return ReadRecords(GEDCOMTag.INDI);
}
/// <summary>
/// ReadRecords reads to the end of the source and return all the lines
/// </summary>
/// <returns>A RecordCollection.</returns>
public GEDCOMRecordList ReadRecords()
{
return ReadRecords(GEDCOMTag.ANY);
}
/// <summary>
/// ReadMultimediaObjects reads to the end of the source and return all the Multimedia Object Lines (OBJE)
/// </summary>
/// <returns>A RecordCollection.</returns>
public GEDCOMRecordList ReadMultimediaObjects()
{
return ReadRecords(GEDCOMTag.OBJE);
}
/// <summary>
/// ReadNotes reads to the end of the source and return all the Note Lines (NOTE)
/// </summary>
/// <returns>A RecordCollection.</returns>
public GEDCOMRecordList ReadNotes()
{
return ReadRecords(GEDCOMTag.NOTE);
}
/// <summary>
/// ReadRepositories reads to the end of the source and return all the Repository Lines (REPO)
/// </summary>
/// <returns>A RecordCollection.</returns>
public GEDCOMRecordList ReadRepositories()
{
return ReadRecords(GEDCOMTag.REPO);
}
/// <summary>
/// ReadSources reads to the end of the source and return all the Source Lines (SOUR)
/// </summary>
/// <returns>A RecordCollection.</returns>
public GEDCOMRecordList ReadSources()
{
return ReadRecords(GEDCOMTag.SOUR);
}
/// <summary>
/// ReadSubmitters reads to the end of the source and return all the Submitter Lines (SUBM)
/// </summary>
/// <returns>A RecordCollection.</returns>
public GEDCOMRecordList ReadSubmitters()
{
return ReadRecords(GEDCOMTag.SUBM);
}
#endregion
#endregion
#region IDisposable Implementation
public void Dispose()
{
Dispose(true);
// Use SupressFinalize in case a subclass
// of this type implements a finalizer.
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
// If you need thread safety, use a lock around these
// operations, as well as in your methods that use the resource.
if (!_disposed)
{
if (disposing)
{
if (_reader != null)
{
_reader.Dispose();
}
}
// Indicate that the instance has been disposed.
_reader = null;
_disposed = true;
}
}
#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.Text;
using System.Diagnostics;
using System.Globalization;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Internal.Cryptography;
using Internal.Cryptography.Pal.Native;
using FILETIME = Internal.Cryptography.Pal.Native.FILETIME;
using System.Security.Cryptography;
using SafeX509ChainHandle = Microsoft.Win32.SafeHandles.SafeX509ChainHandle;
using System.Security.Cryptography.X509Certificates;
using static Interop.Crypt32;
namespace Internal.Cryptography.Pal
{
internal sealed partial class CertificatePal : IDisposable, ICertificatePal
{
private SafeCertContextHandle _certContext;
public static ICertificatePal FromHandle(IntPtr handle)
{
if (handle == IntPtr.Zero)
throw new ArgumentException(SR.Arg_InvalidHandle, nameof(handle));
SafeCertContextHandle safeCertContextHandle = Interop.crypt32.CertDuplicateCertificateContext(handle);
if (safeCertContextHandle.IsInvalid)
throw ErrorCode.HRESULT_INVALID_HANDLE.ToCryptographicException();
CRYPTOAPI_BLOB dataBlob;
int cbData = 0;
bool deleteKeyContainer = Interop.crypt32.CertGetCertificateContextProperty(safeCertContextHandle, CertContextPropId.CERT_DELETE_KEYSET_PROP_ID, out dataBlob, ref cbData);
return new CertificatePal(safeCertContextHandle, deleteKeyContainer);
}
/// <summary>
/// Returns the SafeCertContextHandle. Use this instead of FromHandle() when
/// creating another X509Certificate object based on this one to ensure the underlying
/// cert context is not released at the wrong time.
/// </summary>
public static ICertificatePal FromOtherCert(X509Certificate copyFrom)
{
CertificatePal pal = new CertificatePal((CertificatePal)copyFrom.Pal);
return pal;
}
public IntPtr Handle
{
get { return _certContext.DangerousGetHandle(); }
}
public string Issuer
{
get
{
return GetIssuerOrSubject(issuer: true);
}
}
public string Subject
{
get
{
return GetIssuerOrSubject(issuer: false);
}
}
public byte[] Thumbprint
{
get
{
int cbData = 0;
if (!Interop.crypt32.CertGetCertificateContextProperty(_certContext, CertContextPropId.CERT_SHA1_HASH_PROP_ID, null, ref cbData))
throw Marshal.GetHRForLastWin32Error().ToCryptographicException();
byte[] thumbprint = new byte[cbData];
if (!Interop.crypt32.CertGetCertificateContextProperty(_certContext, CertContextPropId.CERT_SHA1_HASH_PROP_ID, thumbprint, ref cbData))
throw Marshal.GetHRForLastWin32Error().ToCryptographicException();;
return thumbprint;
}
}
public string KeyAlgorithm
{
get
{
unsafe
{
CERT_CONTEXT* pCertContext = _certContext.CertContext;
string keyAlgorithm = Marshal.PtrToStringAnsi(pCertContext->pCertInfo->SubjectPublicKeyInfo.Algorithm.pszObjId);
GC.KeepAlive(this);
return keyAlgorithm;
}
}
}
public byte[] KeyAlgorithmParameters
{
get
{
unsafe
{
CERT_CONTEXT* pCertContext = _certContext.CertContext;
string keyAlgorithmOid = Marshal.PtrToStringAnsi(pCertContext->pCertInfo->SubjectPublicKeyInfo.Algorithm.pszObjId);
int algId;
if (keyAlgorithmOid == Oids.RsaRsa)
algId = AlgId.CALG_RSA_KEYX; // Fast-path for the most common case.
else
algId = Interop.Crypt32.FindOidInfo(CryptOidInfoKeyType.CRYPT_OID_INFO_OID_KEY, keyAlgorithmOid, OidGroup.PublicKeyAlgorithm, fallBackToAllGroups: true).AlgId;
unsafe
{
byte* NULL_ASN_TAG = (byte*)0x5;
byte[] keyAlgorithmParameters;
if (algId == AlgId.CALG_DSS_SIGN
&& pCertContext->pCertInfo->SubjectPublicKeyInfo.Algorithm.Parameters.cbData == 0
&& pCertContext->pCertInfo->SubjectPublicKeyInfo.Algorithm.Parameters.pbData == NULL_ASN_TAG)
{
//
// DSS certificates may not have the DSS parameters in the certificate. In this case, we try to build
// the certificate chain and propagate the parameters down from the certificate chain.
//
keyAlgorithmParameters = PropagateKeyAlgorithmParametersFromChain();
}
else
{
keyAlgorithmParameters = pCertContext->pCertInfo->SubjectPublicKeyInfo.Algorithm.Parameters.ToByteArray();
}
GC.KeepAlive(this);
return keyAlgorithmParameters;
}
}
}
}
private byte[] PropagateKeyAlgorithmParametersFromChain()
{
unsafe
{
SafeX509ChainHandle certChainContext = null;
try
{
int cbData = 0;
if (!Interop.crypt32.CertGetCertificateContextProperty(_certContext, CertContextPropId.CERT_PUBKEY_ALG_PARA_PROP_ID, null, ref cbData))
{
CERT_CHAIN_PARA chainPara = new CERT_CHAIN_PARA();
chainPara.cbSize = sizeof(CERT_CHAIN_PARA);
if (!Interop.crypt32.CertGetCertificateChain(ChainEngine.HCCE_CURRENT_USER, _certContext, (FILETIME*)null, SafeCertStoreHandle.InvalidHandle, ref chainPara, CertChainFlags.None, IntPtr.Zero, out certChainContext))
throw Marshal.GetHRForLastWin32Error().ToCryptographicException();;
if (!Interop.crypt32.CertGetCertificateContextProperty(_certContext, CertContextPropId.CERT_PUBKEY_ALG_PARA_PROP_ID, null, ref cbData))
throw Marshal.GetHRForLastWin32Error().ToCryptographicException();;
}
byte[] keyAlgorithmParameters = new byte[cbData];
if (!Interop.crypt32.CertGetCertificateContextProperty(_certContext, CertContextPropId.CERT_PUBKEY_ALG_PARA_PROP_ID, keyAlgorithmParameters, ref cbData))
throw Marshal.GetHRForLastWin32Error().ToCryptographicException();;
return keyAlgorithmParameters;
}
finally
{
if (certChainContext != null)
certChainContext.Dispose();
}
}
}
public byte[] PublicKeyValue
{
get
{
unsafe
{
CERT_CONTEXT* pCertContext = _certContext.CertContext;
byte[] publicKey = pCertContext->pCertInfo->SubjectPublicKeyInfo.PublicKey.ToByteArray();
GC.KeepAlive(this);
return publicKey;
}
}
}
public byte[] SerialNumber
{
get
{
unsafe
{
CERT_CONTEXT* pCertContext = _certContext.CertContext;
byte[] serialNumber = pCertContext->pCertInfo->SerialNumber.ToByteArray();
GC.KeepAlive(this);
return serialNumber;
}
}
}
public string SignatureAlgorithm
{
get
{
unsafe
{
CERT_CONTEXT* pCertContext = _certContext.CertContext;
string signatureAlgorithm = Marshal.PtrToStringAnsi(pCertContext->pCertInfo->SignatureAlgorithm.pszObjId);
GC.KeepAlive(this);
return signatureAlgorithm;
}
}
}
public DateTime NotAfter
{
get
{
unsafe
{
CERT_CONTEXT* pCertContext = _certContext.CertContext;
DateTime notAfter = pCertContext->pCertInfo->NotAfter.ToDateTime();
GC.KeepAlive(this);
return notAfter;
}
}
}
public DateTime NotBefore
{
get
{
unsafe
{
CERT_CONTEXT* pCertContext = _certContext.CertContext;
DateTime notBefore = pCertContext->pCertInfo->NotBefore.ToDateTime();
GC.KeepAlive(this);
return notBefore;
}
}
}
public byte[] RawData
{
get
{
unsafe
{
CERT_CONTEXT* pCertContext = _certContext.CertContext;
int count = pCertContext->cbCertEncoded;
byte[] rawData = new byte[count];
Marshal.Copy((IntPtr)(pCertContext->pbCertEncoded), rawData, 0, count);
GC.KeepAlive(this);
return rawData;
}
}
}
public int Version
{
get
{
unsafe
{
CERT_CONTEXT* pCertContext = _certContext.CertContext;
int version = pCertContext->pCertInfo->dwVersion + 1;
GC.KeepAlive(this);
return version;
}
}
}
public bool Archived
{
get
{
int uninteresting = 0;
bool archivePropertyExists = Interop.crypt32.CertGetCertificateContextProperty(_certContext, CertContextPropId.CERT_ARCHIVED_PROP_ID, null, ref uninteresting);
return archivePropertyExists;
}
set
{
unsafe
{
CRYPTOAPI_BLOB blob = new CRYPTOAPI_BLOB(0, (byte*)null);
CRYPTOAPI_BLOB* pValue = value ? &blob : (CRYPTOAPI_BLOB*)null;
if (!Interop.crypt32.CertSetCertificateContextProperty(_certContext, CertContextPropId.CERT_ARCHIVED_PROP_ID, CertSetPropertyFlags.None, pValue))
throw Marshal.GetLastWin32Error().ToCryptographicException();
}
}
}
public string FriendlyName
{
get
{
int cbData = 0;
if (!Interop.crypt32.CertGetCertificateContextPropertyString(_certContext, CertContextPropId.CERT_FRIENDLY_NAME_PROP_ID, null, ref cbData))
return string.Empty;
StringBuilder sb = new StringBuilder((cbData + 1) / 2);
if (!Interop.crypt32.CertGetCertificateContextPropertyString(_certContext, CertContextPropId.CERT_FRIENDLY_NAME_PROP_ID, sb, ref cbData))
return string.Empty;
return sb.ToString();
}
set
{
string friendlyName = (value == null) ? string.Empty : value;
unsafe
{
IntPtr pFriendlyName = Marshal.StringToHGlobalUni(friendlyName);
try
{
CRYPTOAPI_BLOB blob = new CRYPTOAPI_BLOB(checked(2 * (friendlyName.Length + 1)), (byte*)pFriendlyName);
if (!Interop.crypt32.CertSetCertificateContextProperty(_certContext, CertContextPropId.CERT_FRIENDLY_NAME_PROP_ID, CertSetPropertyFlags.None, &blob))
throw Marshal.GetLastWin32Error().ToCryptographicException();
}
finally
{
Marshal.FreeHGlobal(pFriendlyName);
}
}
}
}
public X500DistinguishedName SubjectName
{
get
{
unsafe
{
byte[] encodedSubjectName = _certContext.CertContext->pCertInfo->Subject.ToByteArray();
X500DistinguishedName subjectName = new X500DistinguishedName(encodedSubjectName);
GC.KeepAlive(this);
return subjectName;
}
}
}
public X500DistinguishedName IssuerName
{
get
{
unsafe
{
byte[] encodedIssuerName = _certContext.CertContext->pCertInfo->Issuer.ToByteArray();
X500DistinguishedName issuerName = new X500DistinguishedName(encodedIssuerName);
GC.KeepAlive(this);
return issuerName;
}
}
}
public IEnumerable<X509Extension> Extensions
{
get
{
unsafe
{
CERT_INFO* pCertInfo = _certContext.CertContext->pCertInfo;
int numExtensions = pCertInfo->cExtension;
X509Extension[] extensions = new X509Extension[numExtensions];
for (int i = 0; i < numExtensions; i++)
{
CERT_EXTENSION* pCertExtension = pCertInfo->rgExtension + i;
string oidValue = Marshal.PtrToStringAnsi(pCertExtension->pszObjId);
Oid oid = new Oid(oidValue);
bool critical = pCertExtension->fCritical != 0;
byte[] rawData = pCertExtension->Value.ToByteArray();
extensions[i] = new X509Extension(oid, rawData, critical);
}
GC.KeepAlive(this);
return extensions;
}
}
}
public string GetNameInfo(X509NameType nameType, bool forIssuer)
{
CertNameType certNameType = MapNameType(nameType);
CertNameFlags certNameFlags = forIssuer ? CertNameFlags.CERT_NAME_ISSUER_FLAG : CertNameFlags.None;
CertNameStrTypeAndFlags strType = CertNameStrTypeAndFlags.CERT_X500_NAME_STR | CertNameStrTypeAndFlags.CERT_NAME_STR_REVERSE_FLAG;
int cchCount = Interop.crypt32.CertGetNameString(_certContext, certNameType, certNameFlags, ref strType, null, 0);
if (cchCount == 0)
throw Marshal.GetLastWin32Error().ToCryptographicException();
StringBuilder sb = new StringBuilder(cchCount);
if (Interop.crypt32.CertGetNameString(_certContext, certNameType, certNameFlags, ref strType, sb, cchCount) == 0)
throw Marshal.GetLastWin32Error().ToCryptographicException();
return sb.ToString();
}
public void AppendPrivateKeyInfo(StringBuilder sb)
{
if (HasPrivateKey)
{
// Similar to the Unix implementation, in UWP merely acknowledge that there -is- a private key.
sb.AppendLine();
sb.AppendLine();
sb.AppendLine("[Private Key]");
}
#if NETNATIVE
// Similar to the Unix implementation, in UWP merely acknowledge that there -is- a private key.
#else
CspKeyContainerInfo cspKeyContainerInfo = null;
try
{
if (HasPrivateKey)
{
CspParameters parameters = GetPrivateKeyCsp();
cspKeyContainerInfo = new CspKeyContainerInfo(parameters);
}
}
// We could not access the key container. Just return.
catch (CryptographicException) { }
// Ephemeral keys will not have container information.
if (cspKeyContainerInfo == null)
return;
sb.Append(Environment.NewLine + " Key Store: ");
sb.Append(cspKeyContainerInfo.MachineKeyStore ? "Machine" : "User");
sb.Append(Environment.NewLine + " Provider Name: ");
sb.Append(cspKeyContainerInfo.ProviderName);
sb.Append(Environment.NewLine + " Provider type: ");
sb.Append(cspKeyContainerInfo.ProviderType);
sb.Append(Environment.NewLine + " Key Spec: ");
sb.Append(cspKeyContainerInfo.KeyNumber);
sb.Append(Environment.NewLine + " Key Container Name: ");
sb.Append(cspKeyContainerInfo.KeyContainerName);
try
{
string uniqueKeyContainer = cspKeyContainerInfo.UniqueKeyContainerName;
sb.Append(Environment.NewLine + " Unique Key Container Name: ");
sb.Append(uniqueKeyContainer);
}
catch (CryptographicException) { }
catch (NotSupportedException) { }
bool b = false;
try
{
b = cspKeyContainerInfo.HardwareDevice;
sb.Append(Environment.NewLine + " Hardware Device: ");
sb.Append(b);
}
catch (CryptographicException) { }
try
{
b = cspKeyContainerInfo.Removable;
sb.Append(Environment.NewLine + " Removable: ");
sb.Append(b);
}
catch (CryptographicException) { }
try
{
b = cspKeyContainerInfo.Protected;
sb.Append(Environment.NewLine + " Protected: ");
sb.Append(b);
}
catch (CryptographicException) { }
catch (NotSupportedException) { }
#endif // #if NETNATIVE / #else
}
public void Dispose()
{
SafeCertContextHandle certContext = _certContext;
_certContext = null;
if (certContext != null && !certContext.IsInvalid)
{
certContext.Dispose();
}
}
internal SafeCertContextHandle CertContext
{
get
{
SafeCertContextHandle certContext = Interop.crypt32.CertDuplicateCertificateContext(_certContext.DangerousGetHandle());
GC.KeepAlive(_certContext);
return certContext;
}
}
private static CertNameType MapNameType(X509NameType nameType)
{
switch (nameType)
{
case X509NameType.SimpleName:
return CertNameType.CERT_NAME_SIMPLE_DISPLAY_TYPE;
case X509NameType.EmailName:
return CertNameType.CERT_NAME_EMAIL_TYPE;
case X509NameType.UpnName:
return CertNameType.CERT_NAME_UPN_TYPE;
case X509NameType.DnsName:
case X509NameType.DnsFromAlternativeName:
return CertNameType.CERT_NAME_DNS_TYPE;
case X509NameType.UrlName:
return CertNameType.CERT_NAME_URL_TYPE;
default:
throw new ArgumentException(SR.Argument_InvalidNameType);
}
}
private string GetIssuerOrSubject(bool issuer)
{
CertNameFlags flags = issuer ? CertNameFlags.CERT_NAME_ISSUER_FLAG : CertNameFlags.None;
CertNameStringType stringType = CertNameStringType.CERT_X500_NAME_STR | CertNameStringType.CERT_NAME_STR_REVERSE_FLAG;
int cchCount = Interop.crypt32.CertGetNameString(_certContext, CertNameType.CERT_NAME_RDN_TYPE, flags, ref stringType, null, 0);
if (cchCount == 0)
throw Marshal.GetHRForLastWin32Error().ToCryptographicException();;
StringBuilder sb = new StringBuilder(cchCount);
cchCount = Interop.crypt32.CertGetNameString(_certContext, CertNameType.CERT_NAME_RDN_TYPE, flags, ref stringType, sb, cchCount);
if (cchCount == 0)
throw Marshal.GetHRForLastWin32Error().ToCryptographicException();;
return sb.ToString();
}
private CertificatePal(CertificatePal copyFrom)
{
// Use _certContext (instead of CertContext) to keep the original context handle from being
// finalized until all cert copies are no longer referenced.
_certContext = new SafeCertContextHandle(copyFrom._certContext);
}
private CertificatePal(SafeCertContextHandle certContext, bool deleteKeyContainer)
{
if (deleteKeyContainer)
{
// We need to delete any associated key container upon disposition. Thus, replace the safehandle we got with a safehandle whose
// Release() method performs the key container deletion.
SafeCertContextHandle oldCertContext = certContext;
certContext = Interop.crypt32.CertDuplicateCertificateContextWithKeyContainerDeletion(oldCertContext.DangerousGetHandle());
GC.KeepAlive(oldCertContext);
}
_certContext = certContext;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.AcceptanceTestsAzureBodyDurationAllSync
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Microsoft.Rest.Serialization;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
/// <summary>
/// Test Infrastructure for AutoRest
/// </summary>
public partial class AutoRestDurationTestServiceClient : ServiceClient<AutoRestDurationTestServiceClient>, IAutoRestDurationTestServiceClient, IAzureClient
{
/// <summary>
/// The base URI of the service.
/// </summary>
public System.Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
public JsonSerializerSettings SerializationSettings { get; private set; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
public JsonSerializerSettings DeserializationSettings { get; private set; }
/// <summary>
/// Credentials needed for the client to connect to Azure.
/// </summary>
public ServiceClientCredentials Credentials { get; private set; }
/// <summary>
/// Gets or sets the preferred language for the response.
/// </summary>
public string AcceptLanguage { get; set; }
/// <summary>
/// Gets or sets the retry timeout in seconds for Long Running Operations.
/// Default value is 30.
/// </summary>
public int? LongRunningOperationRetryTimeout { get; set; }
/// <summary>
/// When set to true a unique x-ms-client-request-id value is generated and
/// included in each request. Default is true.
/// </summary>
public bool? GenerateClientRequestId { get; set; }
/// <summary>
/// Gets the IDurationOperations.
/// </summary>
public virtual IDurationOperations Duration { get; private set; }
/// <summary>
/// Initializes a new instance of the AutoRestDurationTestServiceClient class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected AutoRestDurationTestServiceClient(params DelegatingHandler[] handlers) : base(handlers)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the AutoRestDurationTestServiceClient class.
/// </summary>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected AutoRestDurationTestServiceClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the AutoRestDurationTestServiceClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected AutoRestDurationTestServiceClient(System.Uri baseUri, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the AutoRestDurationTestServiceClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected AutoRestDurationTestServiceClient(System.Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the AutoRestDurationTestServiceClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public AutoRestDurationTestServiceClient(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the AutoRestDurationTestServiceClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public AutoRestDurationTestServiceClient(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the AutoRestDurationTestServiceClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public AutoRestDurationTestServiceClient(System.Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
BaseUri = baseUri;
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the AutoRestDurationTestServiceClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public AutoRestDurationTestServiceClient(System.Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
BaseUri = baseUri;
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// An optional partial-method to perform custom initialization.
/// </summary>
partial void CustomInitialize();
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
Duration = new DurationOperations(this);
BaseUri = new System.Uri("https://localhost");
AcceptLanguage = "en-US";
LongRunningOperationRetryTimeout = 30;
GenerateClientRequestId = true;
SerializationSettings = new JsonSerializerSettings
{
Formatting = Newtonsoft.Json.Formatting.Indented,
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
DeserializationSettings = new JsonSerializerSettings
{
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
CustomInitialize();
DeserializationSettings.Converters.Add(new CloudErrorJsonConverter());
}
}
}
| |
//
// (C) Copyright 2003-2011 by Autodesk, Inc.
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
//
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using Autodesk.Revit;
using Autodesk.Revit.DB;
namespace Revit.SDK.Samples.Reinforcement.CS
{
/// <summary>
/// contain utility methods find or set certain parameter
/// </summary>
public class ParameterUtil
{
/// <summary>
/// find a parameter according to the parameter's name
/// </summary>
/// <param name="element">the host object of the parameter</param>
/// <param name="parameterName">parameter name</param>
/// <param name="value">the value of the parameter with integer type</param>
/// <returns>if find the parameter return true</returns>
public static bool SetParameter(Element element, string parameterName, int value)
{
ParameterSet parameters = element.Parameters;//a set containing all of the parameters
//find a parameter according to the parameter's name
Parameter findParameter = FindParameter(parameters, parameterName);
if (null == findParameter)
{
return false;
}
//judge whether the parameter is readonly before change its value
if (!findParameter.IsReadOnly)
{
//judge whether the type of the value is the same as the parameter's
StorageType parameterType = findParameter.StorageType;
if (StorageType.Integer != parameterType)
{
throw new Exception("The types of value and parameter are different!");
}
findParameter.Set(value);
return true;
}
return false;
}
/// <summary>
/// find a parameter according to the parameter's name
/// </summary>
/// <param name="element">the host object of the parameter</param>
/// <param name="parameterName">parameter name</param>
/// <param name="value">the value of the parameter with double type</param>
/// <returns>if find the parameter return true</returns>
public static bool SetParameter(Element element, string parameterName, double value)
{
ParameterSet parameters = element.Parameters;
Parameter findParameter = FindParameter(parameters, parameterName);
if (null == findParameter)
{
return false;
}
if (!findParameter.IsReadOnly)
{
StorageType parameterType = findParameter.StorageType;
if (StorageType.Double != parameterType)
{
throw new Exception("The types of value and parameter are different!");
}
findParameter.Set(value);
return true;
}
return false;
}
/// <summary>
/// find a parameter according to the parameter's name
/// </summary>
/// <param name="element">the host object of the parameter</param>
/// <param name="parameterName">parameter name</param>
/// <param name="value">the value of the parameter with string type</param>
/// <returns>if find the parameter return true</returns>
public static bool SetParameter(Element element, string parameterName, string value)
{
ParameterSet parameters = element.Parameters;
Parameter findParameter = FindParameter(parameters, parameterName);
if (null == findParameter)
{
return false;
}
if (!findParameter.IsReadOnly)
{
StorageType parameterType = findParameter.StorageType;
if (StorageType.String != parameterType)
{
throw new Exception("The types of value and parameter are different!");
}
findParameter.Set(value);
return true;
}
return false;
}
/// <summary>
/// find a parameter according to the parameter's name
/// </summary>
/// <param name="element">the host object of the parameter</param>
/// <param name="parameterName">parameter name</param>
/// <param name="value">the value of the parameter with Autodesk.Revit.DB.ElementId type</param>
/// <returns>if find the parameter return true</returns>
public static bool SetParameter(Element element, string parameterName, ref Autodesk.Revit.DB.ElementId value)
{
ParameterSet parameters = element.Parameters;
Parameter findParameter = FindParameter(parameters, parameterName);
if (null == findParameter)
{
return false;
}
if (!findParameter.IsReadOnly)
{
StorageType parameterType = findParameter.StorageType;
if (StorageType.ElementId != parameterType)
{
throw new Exception("The types of value and parameter are different!");
}
findParameter.Set(value);
return true;
}
return false;
}
/// <summary>
/// set certain parameter of given element to int value
/// </summary>
/// <param name="element">given element</param>
/// <param name="paraIndex">BuiltInParameter</param>
/// <param name="value">the value of the parameter with integer type</param>
/// <returns>if find the parameter return true</returns>
public static bool SetParameter(Element element, BuiltInParameter paraIndex, int value)
{
//find a parameter according to the builtInParameter name
Parameter parameter = element.get_Parameter(paraIndex);
if (null == parameter)
{
return false;
}
if (!parameter.IsReadOnly)
{
StorageType parameterType = parameter.StorageType;
if (StorageType.Integer != parameterType)
{
throw new Exception("The types of value and parameter are different!");
}
parameter.Set(value);
return true;
}
return false;
}
/// <summary>
/// find a parameter according to the parameter's name
/// </summary>
/// <param name="element">the host object of the parameter</param>
/// <param name="paraIndex">parameter index</param>
/// <param name="value">the value of the parameter with double type</param>
/// <returns>if find the parameter return true</returns>
public static bool SetParameter(Element element, BuiltInParameter paraIndex, double value)
{
Parameter parameter = element.get_Parameter(paraIndex);
if (null == parameter)
{
return false;
}
if (!parameter.IsReadOnly)
{
StorageType parameterType = parameter.StorageType;
if (StorageType.Double != parameterType)
{
throw new Exception("The types of value and parameter are different!");
}
parameter.Set(value);
return true;
}
return false;
}
/// <summary>
/// find a parameter according to the parameter's name
/// </summary>
/// <param name="element">the host object of the parameter</param>
/// <param name="paraIndex">parameter index</param>
/// <param name="value">the value of the parameter with string type</param>
/// <returns>if find the parameter return true</returns>
public static bool SetParameter(Element element, BuiltInParameter paraIndex, string value)
{
Parameter parameter = element.get_Parameter(paraIndex);
if (null == parameter)
{
return false;
}
if (!parameter.IsReadOnly)
{
StorageType parameterType = parameter.StorageType;
if (StorageType.String != parameterType)
{
throw new Exception("The types of value and parameter are different!");
}
parameter.Set(value);
return true;
}
return false;
}
/// <summary>
/// find a parameter according to the parameter's name
/// </summary>
/// <param name="element">the host object of the parameter</param>
/// <param name="paraIndex">parameter index</param>
/// <param name="value">the value of the parameter with Autodesk.Revit.DB.ElementId type</param>
/// <returns>if find the parameter return true</returns>
public static bool SetParameter(Element element,
BuiltInParameter paraIndex, ref Autodesk.Revit.DB.ElementId value)
{
Parameter parameter = element.get_Parameter(paraIndex);
if (null == parameter)
{
return false;
}
if (!parameter.IsReadOnly)
{
StorageType parameterType = parameter.StorageType;
if (StorageType.ElementId != parameterType)
{
throw new Exception("The types of value and parameter are different!");
}
parameter.Set(value);
return true;
}
return false;
}
/// <summary>
/// set null id to a parameter
/// </summary>
/// <param name="parameter">the parameter which wanted to change the value</param>
/// <returns>if set parameter's value successful return true</returns>
public static bool SetParaNullId(Parameter parameter)
{
Autodesk.Revit.DB.ElementId id = new ElementId(-1);
if (!parameter.IsReadOnly)
{
parameter.Set(id);
return true;
}
return false;
}
/// <summary>
/// find a parameter according to the parameter's name
/// </summary>
/// <param name="parameters">parameter set</param>
/// <param name="name">parameter name</param>
/// <returns>found parameter</returns>
public static Parameter FindParameter(ParameterSet parameters, string name)
{
Parameter findParameter = null;
foreach (Parameter parameter in parameters)
{
if (parameter.Definition.Name == name)
{
findParameter = parameter;
}
}
return findParameter;
}
}
}
| |
// 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\General\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.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
namespace JIT.HardwareIntrinsics.General
{
public static partial class Program
{
private static void GetAndWithElementSingle1()
{
var test = new VectorGetAndWithElement__GetAndWithElementSingle1();
// Validates basic functionality works
test.RunBasicScenario();
// Validates calling via reflection works
test.RunReflectionScenario();
// Validates that invalid indices throws ArgumentOutOfRangeException
test.RunArgumentOutOfRangeScenario();
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class VectorGetAndWithElement__GetAndWithElementSingle1
{
private static readonly int LargestVectorSize = 16;
private static readonly int ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single);
public bool Succeeded { get; set; } = true;
public void RunBasicScenario(int imm = 1, bool expectedOutOfRangeException = false)
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario));
Single[] values = new Single[ElementCount];
for (int i = 0; i < ElementCount; i++)
{
values[i] = TestLibrary.Generator.GetSingle();
}
Vector128<Single> value = Vector128.Create(values[0], values[1], values[2], values[3]);
bool succeeded = !expectedOutOfRangeException;
try
{
Single result = value.GetElement(imm);
ValidateGetResult(result, values);
}
catch (ArgumentOutOfRangeException)
{
succeeded = expectedOutOfRangeException;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector128<Single.GetElement({imm}): {nameof(RunBasicScenario)} failed to throw ArgumentOutOfRangeException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
succeeded = !expectedOutOfRangeException;
Single insertedValue = TestLibrary.Generator.GetSingle();
try
{
Vector128<Single> result2 = value.WithElement(imm, insertedValue);
ValidateWithResult(result2, values, insertedValue);
}
catch (ArgumentOutOfRangeException)
{
succeeded = expectedOutOfRangeException;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector128<Single.WithElement({imm}): {nameof(RunBasicScenario)} failed to throw ArgumentOutOfRangeException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
public void RunReflectionScenario(int imm = 1, bool expectedOutOfRangeException = false)
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario));
Single[] values = new Single[ElementCount];
for (int i = 0; i < ElementCount; i++)
{
values[i] = TestLibrary.Generator.GetSingle();
}
Vector128<Single> value = Vector128.Create(values[0], values[1], values[2], values[3]);
bool succeeded = !expectedOutOfRangeException;
try
{
object result = typeof(Vector128)
.GetMethod(nameof(Vector128.GetElement))
.MakeGenericMethod(typeof(Single))
.Invoke(null, new object[] { value, imm });
ValidateGetResult((Single)(result), values);
}
catch (TargetInvocationException e)
{
succeeded = expectedOutOfRangeException
&& e.InnerException is ArgumentOutOfRangeException;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector128<Single.GetElement({imm}): {nameof(RunReflectionScenario)} failed to throw ArgumentOutOfRangeException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
succeeded = !expectedOutOfRangeException;
Single insertedValue = TestLibrary.Generator.GetSingle();
try
{
object result2 = typeof(Vector128)
.GetMethod(nameof(Vector128.WithElement))
.MakeGenericMethod(typeof(Single))
.Invoke(null, new object[] { value, imm, insertedValue });
ValidateWithResult((Vector128<Single>)(result2), values, insertedValue);
}
catch (TargetInvocationException e)
{
succeeded = expectedOutOfRangeException
&& e.InnerException is ArgumentOutOfRangeException;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector128<Single.WithElement({imm}): {nameof(RunReflectionScenario)} failed to throw ArgumentOutOfRangeException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
public void RunArgumentOutOfRangeScenario()
{
RunBasicScenario(1 - ElementCount, expectedOutOfRangeException: true);
RunBasicScenario(1 + ElementCount, expectedOutOfRangeException: true);
RunReflectionScenario(1 - ElementCount, expectedOutOfRangeException: true);
RunReflectionScenario(1 + ElementCount, expectedOutOfRangeException: true);
}
private void ValidateGetResult(Single result, Single[] values, [CallerMemberName] string method = "")
{
if (result != values[1])
{
Succeeded = false;
TestLibrary.TestFramework.LogInformation($"Vector128<Single.GetElement(1): {method} failed:");
TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})");
TestLibrary.TestFramework.LogInformation($" result: ({result})");
TestLibrary.TestFramework.LogInformation(string.Empty);
}
}
private void ValidateWithResult(Vector128<Single> result, Single[] values, Single insertedValue, [CallerMemberName] string method = "")
{
Single[] resultElements = new Single[ElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref resultElements[0]), result);
ValidateWithResult(resultElements, values, insertedValue, method);
}
private void ValidateWithResult(Single[] result, Single[] values, Single insertedValue, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (int i = 0; i < ElementCount; i++)
{
if ((i != 1) && (result[i] != values[i]))
{
succeeded = false;
break;
}
}
if (result[1] != insertedValue)
{
succeeded = false;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector128<Single.WithElement(1): {method} failed:");
TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})");
TestLibrary.TestFramework.LogInformation($" insert: insertedValue");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABILITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Windows.Automation;
using EnvDTE;
using Microsoft.PythonTools;
using Microsoft.PythonTools.Infrastructure;
using Microsoft.PythonTools.Interpreter;
using Microsoft.PythonTools.Options;
using Microsoft.PythonTools.Repl;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.InteractiveWindow.Shell;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.VisualStudioTools;
using TestUtilities.Python;
using Thread = System.Threading.Thread;
namespace TestUtilities.UI.Python {
public class PythonVisualStudioApp : VisualStudioApp {
private bool _deletePerformanceSessions;
private PythonPerfExplorer _perfTreeView;
private PythonPerfToolBar _perfToolBar;
private PythonTestExplorer _testExplorer;
public readonly PythonToolsService PythonToolsService;
public PythonVisualStudioApp(IServiceProvider site)
: base(site) {
var shell = (IVsShell)ServiceProvider.GetService(typeof(SVsShell));
var pkg = new Guid("6dbd7c1e-1f1b-496d-ac7c-c55dae66c783");
IVsPackage pPkg;
ErrorHandler.ThrowOnFailure(shell.LoadPackage(ref pkg, out pPkg));
System.Threading.Thread.Sleep(1000);
PythonToolsService = ServiceProvider.GetPythonToolsService_NotThreadSafe();
Assert.IsNotNull(PythonToolsService, "Failed to get PythonToolsService");
// Disable AutoListIdentifiers for tests
var ao = PythonToolsService.FormattingOptions;
Assert.IsNotNull(ao, "Failed to get AdvancedOptions");
var orwoodProp = Dte.Properties["Environment", "ProjectsAndSolution"].Item("OnRunWhenOutOfDate");
Assert.IsNotNull(orwoodProp, "Failed to get OnRunWhenOutOfDate property");
var oldOrwood = orwoodProp.Value;
orwoodProp.Value = 1;
OnDispose(() => {
orwoodProp.Value = oldOrwood;
});
}
public void InvokeOnMainThread(Action action) => ServiceProvider.GetUIThread().Invoke(action);
protected override void Dispose(bool disposing) {
if (!IsDisposed) {
try {
ServiceProvider.GetUIThread().Invoke(() => {
var iwp = ComponentModel.GetService<InteractiveWindowProvider>();
if (iwp != null) {
foreach (var w in iwp.AllOpenWindows) {
w.InteractiveWindow.Close();
}
}
});
} catch (Exception ex) {
Console.WriteLine("Error while closing all interactive windows");
Console.WriteLine(ex);
}
if (_deletePerformanceSessions) {
try {
dynamic profiling = Dte.GetObject("PythonProfiling");
for (dynamic session = profiling.GetSession(1);
session != null;
session = profiling.GetSession(1)) {
profiling.RemoveSession(session, true);
}
} catch (Exception ex) {
Console.WriteLine("Error while cleaning up profiling sessions");
Console.WriteLine(ex);
}
}
}
base.Dispose(disposing);
}
// Constants for passing to CreateProject
private const string _templateLanguageName = "Python";
public static string TemplateLanguageName {
get {
return _templateLanguageName;
}
}
public const string PythonApplicationTemplate = "ConsoleAppProject";
public const string EmptyWebProjectTemplate = "WebProjectEmpty";
public const string BottleWebProjectTemplate = "WebProjectBottle";
public const string FlaskWebProjectTemplate = "WebProjectFlask";
public const string DjangoWebProjectTemplate = "DjangoProject";
public const string WorkerRoleProjectTemplate = "WorkerRoleProject";
public const string EmptyFileTemplate = "EmptyPyFile";
public const string WebRoleSupportTemplate = "AzureCSWebRole";
public const string WorkerRoleSupportTemplate = "AzureCSWorkerRole";
/// <summary>
/// Opens and activates the solution explorer window.
/// </summary>
public void OpenPythonPerformance() {
try {
_deletePerformanceSessions = true;
Dte.ExecuteCommand("Python.PerformanceExplorer");
} catch {
// If the package is not loaded yet then the command may not
// work. Force load the package by opening the Launch dialog.
using (var dialog = new PythonPerfTarget(OpenDialogWithDteExecuteCommand("Debug.LaunchProfiling"))) {
}
Dte.ExecuteCommand("Python.PerformanceExplorer");
}
}
/// <summary>
/// Opens and activates the solution explorer window.
/// </summary>
public PythonPerfTarget LaunchPythonProfiling() {
_deletePerformanceSessions = true;
return new PythonPerfTarget(OpenDialogWithDteExecuteCommand("Debug.LaunchProfiling"));
}
/// <summary>
/// Provides access to the Python profiling tree view.
/// </summary>
public PythonPerfExplorer PythonPerformanceExplorerTreeView {
get {
if (_perfTreeView == null) {
var element = Element.FindFirst(TreeScope.Descendants,
new AndCondition(
new PropertyCondition(
AutomationElement.ClassNameProperty,
"SysTreeView32"
),
new PropertyCondition(
AutomationElement.NameProperty,
"Python Performance"
)
)
);
_perfTreeView = new PythonPerfExplorer(element);
}
return _perfTreeView;
}
}
/// <summary>
/// Provides access to the Python profiling tool bar
/// </summary>
public PythonPerfToolBar PythonPerformanceExplorerToolBar {
get {
if (_perfToolBar == null) {
var element = Element.FindFirst(TreeScope.Descendants,
new AndCondition(
new PropertyCondition(
AutomationElement.ClassNameProperty,
"ToolBar"
),
new PropertyCondition(
AutomationElement.NameProperty,
"Python Performance"
)
)
);
_perfToolBar = new PythonPerfToolBar(element);
}
return _perfToolBar;
}
}
/// <summary>
/// Opens and activates the test explorer window.
/// </summary>
public PythonTestExplorer OpenTestExplorer() {
Dte.ExecuteCommand("TestExplorer.ShowTestExplorer");
return TestExplorer;
}
public PythonTestExplorer TestExplorer {
get {
if (_testExplorer == null) {
AutomationElement element = null;
for (int i = 0; i < 40 && element == null; i++) {
element = Element.FindFirst(TreeScope.Descendants,
new AndCondition(
new PropertyCondition(
AutomationElement.ClassNameProperty,
"ViewPresenter"
),
new PropertyCondition(
AutomationElement.NameProperty,
"Test Explorer"
)
)
);
if (element == null) {
System.Threading.Thread.Sleep(500);
}
}
Assert.IsNotNull(element, "Missing Text Explorer window");
var testExplorer = new AutomationWrapper(element);
var searchBox = testExplorer.FindByName("Search Test Explorer");
Assert.IsNotNull(searchBox, "Missing Search Bar Textbox");
_testExplorer = new PythonTestExplorer(this, element, new AutomationWrapper(searchBox));
}
return _testExplorer;
}
}
public AutomationElementCollection GetInfoBars() {
return Element.FindAll(
TreeScope.Descendants,
new PropertyCondition(AutomationElement.AutomationIdProperty, "infobarcontrol")
);
}
public AutomationElement FindFirstInfoBar(Condition condition, TimeSpan timeout) {
for (int i = 0; i < timeout.TotalMilliseconds; i += 500) {
var infoBars = GetInfoBars();
foreach (AutomationElement infoBar in infoBars) {
var createLink = infoBar.FindFirst(TreeScope.Descendants, condition);
if (createLink != null) {
return createLink;
}
}
Thread.Sleep(500);
}
return null;
}
public PythonCreateVirtualEnvInfoBar FindCreateVirtualEnvInfoBar(TimeSpan timeout) {
var element = FindFirstInfoBar(PythonCreateVirtualEnvInfoBar.FindCondition, timeout);
return element != null ? new PythonCreateVirtualEnvInfoBar(element) : null;
}
public PythonCreateCondaEnvInfoBar FindCreateCondaEnvInfoBar(TimeSpan timeout) {
var element = FindFirstInfoBar(PythonCreateCondaEnvInfoBar.FindCondition, timeout);
return element != null ? new PythonCreateCondaEnvInfoBar(element) : null;
}
public PythonInstallPackagesInfoBar FindInstallPackagesInfoBar(TimeSpan timeout) {
var element = FindFirstInfoBar(PythonInstallPackagesInfoBar.FindCondition, timeout);
return element != null ? new PythonInstallPackagesInfoBar(element) : null;
}
public ReplWindowProxy ExecuteInInteractive(Project project, ReplWindowProxySettings settings = null) {
// Prepare makes sure that IPython mode is disabled, and that the REPL is reset and cleared
var window = ReplWindowProxy.Prepare(this, settings, project.Name, workspaceName: null);
OpenSolutionExplorer().SelectProject(project);
ExecuteCommand("Python.ExecuteInInteractive");
return window;
}
public void SendToInteractive() {
ExecuteCommand("Python.SendSelectionToInteractive");
}
public void OpenFolder(string folderPath) {
ExecuteCommand("File.OpenFolder", "\"{0}\"".FormatInvariant(folderPath));
}
public ReplWindowProxy WaitForInteractiveWindow(string title, ReplWindowProxySettings settings = null) {
var iwp = GetService<IComponentModel>(typeof(SComponentModel))?.GetService<InteractiveWindowProvider>();
IVsInteractiveWindow window = null;
for (int retries = 20; retries > 0 && window == null; --retries) {
System.Threading.Thread.Sleep(100);
window = iwp?.AllOpenWindows.FirstOrDefault(w => ((ToolWindowPane)w).Caption.StartsWith(title));
}
if (window == null) {
Trace.TraceWarning(
"Failed to find {0} in {1}",
title,
string.Join(", ", iwp?.AllOpenWindows.Select(w => ((ToolWindowPane)w).Caption) ?? Enumerable.Empty<string>())
);
return null;
}
return new ReplWindowProxy(this, window.InteractiveWindow, (ToolWindowPane)window, settings ?? new ReplWindowProxySettings());
}
public ReplWindowProxy GetInteractiveWindow(Project project, ReplWindowProxySettings settings = null) {
return GetInteractiveWindow(project.Name + " Interactive", settings);
}
public ReplWindowProxy GetInteractiveWindow(string title, ReplWindowProxySettings settings = null) {
var iwp = GetService<IComponentModel>(typeof(SComponentModel))?.GetService<InteractiveWindowProvider>();
var window = iwp?.AllOpenWindows.FirstOrDefault(w => ((ToolWindowPane)w).Caption.StartsWith(title));
if (window == null) {
Trace.TraceWarning(
"Failed to find {0} in {1}",
title,
string.Join(", ", iwp?.AllOpenWindows.Select(w => ((ToolWindowPane)w).Caption) ?? Enumerable.Empty<string>())
);
return null;
}
return new ReplWindowProxy(this, window.InteractiveWindow, (ToolWindowPane)window, settings ?? new ReplWindowProxySettings());
}
internal Document WaitForDocument(string docName) {
for (int i = 0; i < 100; i++) {
try {
return Dte.Documents.Item(docName);
} catch {
System.Threading.Thread.Sleep(100);
}
}
throw new InvalidOperationException("Document not opened: " + docName);
}
/// <summary>
/// Selects the given interpreter as the default.
/// </summary>
/// <remarks>
/// This method should always be called as a using block.
/// </remarks>
public DefaultInterpreterSetter SelectDefaultInterpreter(PythonVersion python) {
return new DefaultInterpreterSetter(
InterpreterService.FindInterpreter(python.Id),
ServiceProvider
);
}
/// <summary>
/// Selects the given interpreter as the default.
/// </summary>
/// <remarks>
/// This method should always be called as a using block.
/// </remarks>
public DefaultInterpreterSetter SelectDefaultInterpreter(InterpreterConfiguration python) {
return new DefaultInterpreterSetter(
InterpreterService.FindInterpreter(python.Id),
ServiceProvider
);
}
public DefaultInterpreterSetter SelectDefaultInterpreter(PythonVersion interp, string installPackages) {
interp.AssertInstalled();
var interpreterService = InterpreterService;
var factory = interpreterService.FindInterpreter(interp.Id);
var defaultInterpreterSetter = new DefaultInterpreterSetter(factory, ServiceProvider);
try {
if (!string.IsNullOrEmpty(installPackages)) {
var pm = OptionsService.GetPackageManagers(factory).FirstOrDefault();
var ui = new TestPackageManagerUI();
pm.PrepareAsync(ui, CancellationTokens.After60s).WaitAndUnwrapExceptions();
foreach (var package in installPackages.Split(' ', ',', ';').Select(s => s.Trim()).Where(s => !string.IsNullOrEmpty(s))) {
pm.InstallAsync(new PackageSpec(package), ui, CancellationTokens.After60s).WaitAndUnwrapExceptions();
}
}
Assert.AreEqual(factory.Configuration.Id, OptionsService.DefaultInterpreterId);
var result = defaultInterpreterSetter;
defaultInterpreterSetter = null;
return result;
} finally {
if (defaultInterpreterSetter != null) {
defaultInterpreterSetter.Dispose();
}
}
}
public IInterpreterRegistryService InterpreterService {
get {
var model = GetService<IComponentModel>(typeof(SComponentModel));
var service = model.GetService<IInterpreterRegistryService>();
Assert.IsNotNull(service, "Unable to get IInterpreterRegistryService");
return service;
}
}
public IInterpreterOptionsService OptionsService {
get {
var model = GetService<IComponentModel>(typeof(SComponentModel));
var service = model.GetService<IInterpreterOptionsService>();
Assert.IsNotNull(service, "Unable to get InterpreterOptionsService");
return service;
}
}
public TreeNode CreateProjectCondaEnvironment(EnvDTE.Project project, string packageNames, string envFile, string expectedEnvFile, out string envName, out string envPath) {
var environmentsNode = OpenSolutionExplorer().FindChildOfProject(project, Strings.Environments);
environmentsNode.Select();
envName = ApplyCreateCondaEnvironmentDialog(packageNames, envFile, expectedEnvFile);
var id = CondaEnvironmentFactoryConstants.GetInterpreterId(CondaEnvironmentFactoryProvider.EnvironmentCompanyName, envName);
var config = WaitForEnvironment(id, TimeSpan.FromMinutes(3));
Assert.IsNotNull(config, "Could not find intepreter configuration");
string envLabel = string.Format("{0} ({1}, {2})", envName, config.Version, config.Architecture);
envPath = config.GetPrefixPath();
Console.WriteLine("Expecting environment: {0}", envLabel);
try {
return OpenSolutionExplorer().WaitForChildOfProject(project, Strings.Environments, envLabel);
} finally {
var text = GetOutputWindowText("General");
if (!string.IsNullOrEmpty(text)) {
Console.WriteLine("** Output Window text");
Console.WriteLine(text);
Console.WriteLine("***");
Console.WriteLine();
}
}
}
public void CreateWorkspaceCondaEnvironment(string packageNames, string envFile, string expectedEnvFile, out string envName, out string envPath, out string envDescription) {
envName = ApplyCreateCondaEnvironmentDialog(packageNames, envFile, expectedEnvFile);
var id = CondaEnvironmentFactoryConstants.GetInterpreterId(CondaEnvironmentFactoryProvider.EnvironmentCompanyName, envName);
var config = WaitForEnvironment(id, TimeSpan.FromMinutes(5));
Assert.IsNotNull(config, "Could not find intepreter configuration");
envDescription = string.Format("{0} ({1}, {2})", envName, config.Version, config.Architecture);
envPath = config.GetPrefixPath();
Console.WriteLine("Expecting environment: {0}", envDescription);
}
private string ApplyCreateCondaEnvironmentDialog(string packageNames, string envFile, string expectedEnvFile) {
if (packageNames == null && envFile == null) {
throw new ArgumentException("Must set either package names or environment file");
}
string envName;
var dlg = AddCondaEnvironmentDialogWrapper.FromDte(this);
try {
Assert.AreNotEqual(string.Empty, dlg.EnvName);
envName = "test" + Guid.NewGuid().ToString().Replace("-", "");
dlg.EnvName = envName;
if (packageNames != null) {
dlg.SetPackagesMode();
dlg.Packages = packageNames;
dlg.WaitForPreviewPackage("python", TimeSpan.FromMinutes(2));
} else if (envFile != null) {
if (expectedEnvFile == string.Empty) {
Assert.AreEqual(string.Empty, dlg.EnvFile);
} else if (expectedEnvFile != null) {
Assert.IsTrue(
PathUtils.IsSamePath(dlg.EnvFile, expectedEnvFile),
string.Format("Env file doesn't match.\nExpected: {0}\nActual: {1}", dlg.EnvFile, expectedEnvFile)
);
}
dlg.SetEnvFileMode();
dlg.EnvFile = envFile;
}
Console.WriteLine("Creating conda env");
Console.WriteLine(" Name: {0}", envName);
dlg.ClickAdd();
} catch (Exception) {
dlg.CloseWindow();
throw;
}
return envName;
}
private InterpreterConfiguration WaitForEnvironment(string id, TimeSpan timeout) {
for (int i = 0; i < timeout.TotalMilliseconds; i += 1000) {
var config = InterpreterService.FindConfiguration(id);
if (config != null) {
return config;
}
Thread.Sleep(1000);
}
return null;
}
public TreeNode CreateProjectVirtualEnvironment(EnvDTE.Project project, out string envName) {
return CreateProjectVirtualEnvironment(project, out envName, out _);
}
public TreeNode CreateProjectVirtualEnvironment(EnvDTE.Project project, out string envLabel, out string envPath) {
var environmentsNode = OpenSolutionExplorer().FindChildOfProject(project, Strings.Environments);
environmentsNode.Select();
ApplyVirtualEnvironmentDialog(out string baseInterp, out string location, out string envName);
envLabel = "{0} ({1})".FormatUI(envName, baseInterp);
envPath = Path.Combine(location, envName);
try {
return OpenSolutionExplorer().WaitForChildOfProject(project, TimeSpan.FromMinutes(5), Strings.Environments, envLabel);
} finally {
var text = GetOutputWindowText("General");
if (!string.IsNullOrEmpty(text)) {
Console.WriteLine("** Output Window text");
Console.WriteLine(text);
Console.WriteLine("***");
Console.WriteLine();
}
}
}
public void CreateWorkspaceVirtualEnvironment(out string baseEnvDescription, out string envPath) {
ApplyVirtualEnvironmentDialog(out baseEnvDescription, out string location, out string envName);
envPath = Path.Combine(location, envName);
try {
var id = WorkspaceInterpreterFactoryConstants.GetInterpreterId(WorkspaceInterpreterFactoryConstants.EnvironmentCompanyName, envName);
var config = WaitForEnvironment(id, TimeSpan.FromMinutes(3));
Assert.IsNotNull(config, "Config was not found.");
} finally {
var text = GetOutputWindowText("General");
if (!string.IsNullOrEmpty(text)) {
Console.WriteLine("** Output Window text");
Console.WriteLine(text);
Console.WriteLine("***");
Console.WriteLine();
}
}
}
private void ApplyVirtualEnvironmentDialog(out string baseInterp, out string location, out string envName) {
var dlg = AddVirtualEnvironmentDialogWrapper.FromDte(this);
try {
baseInterp = dlg.BaseInterpreter;
location = dlg.Location;
envName = dlg.EnvName;
Console.WriteLine("Creating virtual env");
Console.WriteLine(" Name: {0}", envName);
Console.WriteLine(" Location: {0}", location);
Console.WriteLine(" Base Interpreter: {0}", baseInterp);
dlg.WaitForReady();
dlg.ClickAdd();
} catch (Exception) {
dlg.CloseWindow();
throw;
}
}
public TreeNode AddExistingEnvironment(EnvDTE.Project project, string envPath, out string envName) {
var environmentsNode = OpenSolutionExplorer().FindChildOfProject(project, Strings.Environments);
environmentsNode.Select();
var factory = InterpreterService.Interpreters.FirstOrDefault(interp => PathUtils.IsSameDirectory(interp.Configuration.GetPrefixPath(), envPath));
envName = string.Format("Python {1} ({2})", PathUtils.GetFileOrDirectoryName(envPath), factory.Configuration.Version, factory.Configuration.Architecture);
ApplyAddExistingEnvironmentDialog(envPath, out envName);
return OpenSolutionExplorer().WaitForChildOfProject(project, Strings.Environments, envName);
}
public void AddWorkspaceExistingEnvironment(string envPath, out string envName) {
ApplyAddExistingEnvironmentDialog(envPath, out envName);
}
private void ApplyAddExistingEnvironmentDialog(string envPath, out string envName) {
var factory = InterpreterService.Interpreters.FirstOrDefault(interp => PathUtils.IsSameDirectory(interp.Configuration.GetPrefixPath(), envPath));
envName = string.Format("Python {1} ({2})", PathUtils.GetFileOrDirectoryName(envPath), factory.Configuration.Version, factory.Configuration.Architecture);
var dlg = AddExistingEnvironmentDialogWrapper.FromDte(this);
try {
dlg.Interpreter = envName;
Console.WriteLine("Adding existing env");
Console.WriteLine(" Name: {0}", envName);
Console.WriteLine(" Prefix: {0}", envPath);
dlg.ClickAdd();
} catch (Exception) {
dlg.CloseWindow();
throw;
}
}
public TreeNode AddProjectLocalCustomEnvironment(EnvDTE.Project project, string envPath, string descriptionOverride, string expectedLangVer, string expectedArch, out string envDescription) {
var environmentsNode = OpenSolutionExplorer().FindChildOfProject(project, Strings.Environments);
environmentsNode.Select();
ApplyAddLocalCustomEnvironmentDialog(envPath, descriptionOverride, expectedLangVer, expectedArch, out envDescription, out _, out _, out _);
return OpenSolutionExplorer().WaitForChildOfProject(project, Strings.Environments, envDescription);
}
public void AddWorkspaceLocalCustomEnvironment(string envPath, string descriptionOverride, string expectedLangVer, string expectedArch) {
ApplyAddLocalCustomEnvironmentDialog(envPath, descriptionOverride, expectedLangVer, expectedArch, out _, out _, out _, out _);
}
private void ApplyAddLocalCustomEnvironmentDialog(string envPath, string descriptionOverride, string expectedLangVer, string expectedArch, out string envDescription, out string envPrefixPath, out string languageVer, out string architecture) {
envDescription = string.Empty;
envPrefixPath = string.Empty;
languageVer = string.Empty;
var dlg = AddExistingEnvironmentDialogWrapper.FromDte(this);
try {
dlg.SelectCustomInterpreter();
dlg.PrefixPath = envPath;
// Need to wait for async auto detect to be finished
dlg.WaitForReady();
if (expectedLangVer != null) {
Assert.AreEqual(expectedLangVer, dlg.LanguageVersion);
}
if (expectedArch != null) {
Assert.AreEqual(expectedArch, dlg.Architecture);
}
dlg.RegisterGlobally = false;
if (descriptionOverride != null) {
dlg.Description = descriptionOverride;
}
envDescription = dlg.Description;
envPrefixPath = dlg.PrefixPath;
languageVer = dlg.LanguageVersion;
architecture = dlg.Architecture;
Console.WriteLine("Adding custom env");
Console.WriteLine(" Description: {0}", envDescription);
Console.WriteLine(" Prefix: {0}", envPrefixPath);
Console.WriteLine(" Version: {0}", languageVer);
Console.WriteLine(" Architecture: {0}", architecture);
dlg.ClickAdd();
} catch (Exception) {
dlg.CloseWindow();
throw;
}
}
public IPythonOptions Options {
get {
return (IPythonOptions)Dte.GetObject("VsPython");
}
}
}
}
| |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the ec2-2015-10-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.EC2.Model
{
/// <summary>
/// Describes a network interface.
/// </summary>
public partial class InstanceNetworkInterface
{
private InstanceNetworkInterfaceAssociation _association;
private InstanceNetworkInterfaceAttachment _attachment;
private string _description;
private List<GroupIdentifier> _groups = new List<GroupIdentifier>();
private string _macAddress;
private string _networkInterfaceId;
private string _ownerId;
private string _privateDnsName;
private string _privateIpAddress;
private List<InstancePrivateIpAddress> _privateIpAddresses = new List<InstancePrivateIpAddress>();
private bool? _sourceDestCheck;
private NetworkInterfaceStatus _status;
private string _subnetId;
private string _vpcId;
/// <summary>
/// Gets and sets the property Association.
/// <para>
/// The association information for an Elastic IP associated with the network interface.
/// </para>
/// </summary>
public InstanceNetworkInterfaceAssociation Association
{
get { return this._association; }
set { this._association = value; }
}
// Check to see if Association property is set
internal bool IsSetAssociation()
{
return this._association != null;
}
/// <summary>
/// Gets and sets the property Attachment.
/// <para>
/// The network interface attachment.
/// </para>
/// </summary>
public InstanceNetworkInterfaceAttachment Attachment
{
get { return this._attachment; }
set { this._attachment = value; }
}
// Check to see if Attachment property is set
internal bool IsSetAttachment()
{
return this._attachment != null;
}
/// <summary>
/// Gets and sets the property Description.
/// <para>
/// The description.
/// </para>
/// </summary>
public string Description
{
get { return this._description; }
set { this._description = value; }
}
// Check to see if Description property is set
internal bool IsSetDescription()
{
return this._description != null;
}
/// <summary>
/// Gets and sets the property Groups.
/// <para>
/// One or more security groups.
/// </para>
/// </summary>
public List<GroupIdentifier> Groups
{
get { return this._groups; }
set { this._groups = value; }
}
// Check to see if Groups property is set
internal bool IsSetGroups()
{
return this._groups != null && this._groups.Count > 0;
}
/// <summary>
/// Gets and sets the property MacAddress.
/// <para>
/// The MAC address.
/// </para>
/// </summary>
public string MacAddress
{
get { return this._macAddress; }
set { this._macAddress = value; }
}
// Check to see if MacAddress property is set
internal bool IsSetMacAddress()
{
return this._macAddress != null;
}
/// <summary>
/// Gets and sets the property NetworkInterfaceId.
/// <para>
/// The ID of the network interface.
/// </para>
/// </summary>
public string NetworkInterfaceId
{
get { return this._networkInterfaceId; }
set { this._networkInterfaceId = value; }
}
// Check to see if NetworkInterfaceId property is set
internal bool IsSetNetworkInterfaceId()
{
return this._networkInterfaceId != null;
}
/// <summary>
/// Gets and sets the property OwnerId.
/// <para>
/// The ID of the AWS account that created the network interface.
/// </para>
/// </summary>
public string OwnerId
{
get { return this._ownerId; }
set { this._ownerId = value; }
}
// Check to see if OwnerId property is set
internal bool IsSetOwnerId()
{
return this._ownerId != null;
}
/// <summary>
/// Gets and sets the property PrivateDnsName.
/// <para>
/// The private DNS name.
/// </para>
/// </summary>
public string PrivateDnsName
{
get { return this._privateDnsName; }
set { this._privateDnsName = value; }
}
// Check to see if PrivateDnsName property is set
internal bool IsSetPrivateDnsName()
{
return this._privateDnsName != null;
}
/// <summary>
/// Gets and sets the property PrivateIpAddress.
/// <para>
/// The IP address of the network interface within the subnet.
/// </para>
/// </summary>
public string PrivateIpAddress
{
get { return this._privateIpAddress; }
set { this._privateIpAddress = value; }
}
// Check to see if PrivateIpAddress property is set
internal bool IsSetPrivateIpAddress()
{
return this._privateIpAddress != null;
}
/// <summary>
/// Gets and sets the property PrivateIpAddresses.
/// <para>
/// The private IP addresses associated with the network interface.
/// </para>
/// </summary>
public List<InstancePrivateIpAddress> PrivateIpAddresses
{
get { return this._privateIpAddresses; }
set { this._privateIpAddresses = value; }
}
// Check to see if PrivateIpAddresses property is set
internal bool IsSetPrivateIpAddresses()
{
return this._privateIpAddresses != null && this._privateIpAddresses.Count > 0;
}
/// <summary>
/// Gets and sets the property SourceDestCheck.
/// <para>
/// Indicates whether to validate network traffic to or from this network interface.
/// </para>
/// </summary>
public bool SourceDestCheck
{
get { return this._sourceDestCheck.GetValueOrDefault(); }
set { this._sourceDestCheck = value; }
}
// Check to see if SourceDestCheck property is set
internal bool IsSetSourceDestCheck()
{
return this._sourceDestCheck.HasValue;
}
/// <summary>
/// Gets and sets the property Status.
/// <para>
/// The status of the network interface.
/// </para>
/// </summary>
public NetworkInterfaceStatus Status
{
get { return this._status; }
set { this._status = value; }
}
// Check to see if Status property is set
internal bool IsSetStatus()
{
return this._status != null;
}
/// <summary>
/// Gets and sets the property SubnetId.
/// <para>
/// The ID of the subnet.
/// </para>
/// </summary>
public string SubnetId
{
get { return this._subnetId; }
set { this._subnetId = value; }
}
// Check to see if SubnetId property is set
internal bool IsSetSubnetId()
{
return this._subnetId != null;
}
/// <summary>
/// Gets and sets the property VpcId.
/// <para>
/// The ID of the VPC.
/// </para>
/// </summary>
public string VpcId
{
get { return this._vpcId; }
set { this._vpcId = value; }
}
// Check to see if VpcId property is set
internal bool IsSetVpcId()
{
return this._vpcId != null;
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) Under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You Under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed Under the License is distributed on an "AS Is" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations Under the License.
==================================================================== */
namespace NPOI.SS.Util
{
using System;
using System.Text;
using System.Text.RegularExpressions;
using NPOI.SS.Formula;
using NPOI.SS.UserModel;
using System.Globalization;
internal enum NameType:int
{
/// <summary>
/// Allow accessing the Initial value.
/// </summary>
None = 0,
CELL = 1,
NAMED_RANGE = 2,
COLUMN = 3,
ROW=4,
BAD_CELL_OR_NAMED_RANGE = -1
}
/**
*
* @author Avik Sengupta
* @author Dennis doubleday (patch to seperateRowColumns())
*/
internal class CellReference
{
/** The character ($) that signifies a row or column value is absolute instead of relative */
private const char ABSOLUTE_REFERENCE_MARKER = '$';
/** The character (!) that Separates sheet names from cell references */
private const char SHEET_NAME_DELIMITER = '!';
/** The character (') used to quote sheet names when they contain special characters */
private const char SPECIAL_NAME_DELIMITER = '\'';
/**
* Matches a run of one or more letters followed by a run of one or more digits.
* The run of letters is group 1 and the run of digits is group 2.
* Each group may optionally be prefixed with a single '$'.
*/
private static string CELL_REF_PATTERN = @"^\$?([A-Za-z]+)\$?([0-9]+)";
/**
* Matches a run of one or more letters. The run of letters is group 1.
* The text may optionally be prefixed with a single '$'.
*/
private static string COLUMN_REF_PATTERN = @"^\$?([A-Za-z]+)$";
/**
* Matches a run of one or more digits. The run of digits is group 1.
* The text may optionally be prefixed with a single '$'.
*/
private static string ROW_REF_PATTERN = @"^\$?([0-9]+)$";
/**
* Named range names must start with a letter or underscore. Subsequent characters may include
* digits or dot. (They can even end in dot).
*/
private static string NAMED_RANGE_NAME_PATTERN = "^[_A-Za-z][_.A-Za-z0-9]*$";
//private static string BIFF8_LAST_COLUMN = "IV";
//private static int BIFF8_LAST_COLUMN_TEXT_LEN = BIFF8_LAST_COLUMN.Length;
//private static string BIFF8_LAST_ROW = (0x10000).ToString();
//private static int BIFF8_LAST_ROW_TEXT_LEN = BIFF8_LAST_ROW.Length;
private int _rowIndex;
private int _colIndex;
private String _sheetName;
private bool _isRowAbs;
private bool _isColAbs;
/**
* Create an cell ref from a string representation. Sheet names containing special characters should be
* delimited and escaped as per normal syntax rules for formulas.
*/
public CellReference(String cellRef)
{
if (cellRef.EndsWith("#REF!", StringComparison.CurrentCulture))
{
throw new ArgumentException("Cell reference invalid: " + cellRef);
}
String[] parts = SeparateRefParts(cellRef);
_sheetName = parts[0];
String colRef = parts[1];
if (colRef.Length < 1)
{
throw new ArgumentException("Invalid Formula cell reference: '" + cellRef + "'");
}
_isColAbs = colRef[0] == '$';
if (_isColAbs)
{
colRef = colRef.Substring(1);
}
_colIndex = ConvertColStringToIndex(colRef);
String rowRef = parts[2];
if (rowRef.Length < 1)
{
throw new ArgumentException("Invalid Formula cell reference: '" + cellRef + "'");
}
_isRowAbs = rowRef[0] == '$';
if (_isRowAbs)
{
rowRef = rowRef.Substring(1);
}
_rowIndex = int.Parse(rowRef, CultureInfo.InvariantCulture) - 1; // -1 to convert 1-based to zero-based
}
public CellReference(ICell cell):this(cell.RowIndex, cell.ColumnIndex, false, false)
{
}
public CellReference(int pRow, int pCol)
: this(pRow, pCol, false, false)
{
}
public CellReference(int pRow, short pCol)
: this(pRow, pCol & 0xFFFF, false, false)
{
}
public CellReference(int pRow, int pCol, bool pAbsRow, bool pAbsCol)
: this(null, pRow, pCol, pAbsRow, pAbsCol)
{
}
public CellReference(String pSheetName, int pRow, int pCol, bool pAbsRow, bool pAbsCol)
{
// TODO - "-1" is a special value being temporarily used for whole row and whole column area references.
// so these Checks are currently N.Q.R.
if (pRow < -1)
{
throw new ArgumentException("row index may not be negative");
}
if (pCol < -1)
{
throw new ArgumentException("column index may not be negative");
}
_sheetName = pSheetName;
_rowIndex = pRow;
_colIndex = pCol;
_isRowAbs = pAbsRow;
_isColAbs = pAbsCol;
}
public int Row
{
get { return _rowIndex; }
}
public short Col
{
get
{
return (short)_colIndex;
}
}
public bool IsRowAbsolute
{
get { return _isRowAbs; }
}
public bool IsColAbsolute
{
get { return _isColAbs; }
}
/**
* @return possibly <c>null</c> if this is a 2D reference. Special characters are not
* escaped or delimited
*/
public String SheetName
{
get { return _sheetName; }
}
/**
* takes in a column reference portion of a CellRef and converts it from
* ALPHA-26 number format to 0-based base 10.
* 'A' -> 0
* 'Z' -> 25
* 'AA' -> 26
* 'IV' -> 255
* @return zero based column index
*/
public static int ConvertColStringToIndex(String ref1)
{
int pos = 0;
int retval = 0;
for (int k = ref1.Length - 1; k >= 0; k--)
{
char thechar = ref1[k];
if (thechar == ABSOLUTE_REFERENCE_MARKER)
{
if (k != 0)
{
throw new ArgumentException("Bad col ref format '"
+ ref1 + "'");
}
break;
}
// Character.getNumericValue() returns the values
// 10-35 for the letter A-Z
int shift = (int)Math.Pow(26, pos);
retval += (NPOI.Util.Character.GetNumericValue(thechar) - 9) * shift;
pos++;
}
return retval - 1;
}
public static bool IsPartAbsolute(String part)
{
return part[0] == ABSOLUTE_REFERENCE_MARKER;
}
public static NameType ClassifyCellReference(String str, SpreadsheetVersion ssVersion)
{
int len = str.Length;
if (len < 1)
{
throw new ArgumentException("Empty string not allowed");
}
char firstChar = str[0];
switch (firstChar)
{
case ABSOLUTE_REFERENCE_MARKER:
case '.':
case '_':
break;
default:
if (!Char.IsLetter(firstChar) && !Char.IsDigit(firstChar))
{
throw new ArgumentException("Invalid first char (" + firstChar
+ ") of cell reference or named range. Letter expected");
}
break;
}
if (!Char.IsDigit(str[len - 1]))
{
// no digits at end of str
return ValidateNamedRangeName(str, ssVersion);
}
Regex cellRefPatternMatcher = new Regex(CELL_REF_PATTERN);
if (!cellRefPatternMatcher.IsMatch(str))
{
return ValidateNamedRangeName(str, ssVersion);
}
MatchCollection matches = cellRefPatternMatcher.Matches(str);
string lettersGroup = matches[0].Groups[1].Value;
string digitsGroup = matches[0].Groups[2].Value;
if (CellReferenceIsWithinRange(lettersGroup, digitsGroup, ssVersion))
{
// valid cell reference
return NameType.CELL;
}
// If str looks like a cell reference, but is out of (row/col) range, it is a valid
// named range name
// This behaviour is a little weird. For example, "IW123" is a valid named range name
// because the column "IW" is beyond the maximum "IV". Note - this behaviour is version
// dependent. In BIFF12, "IW123" is not a valid named range name, but in BIFF8 it is.
if (str.IndexOf(ABSOLUTE_REFERENCE_MARKER) >= 0)
{
// Of course, named range names cannot have '$'
return NameType.BAD_CELL_OR_NAMED_RANGE;
}
return NameType.NAMED_RANGE;
}
private static NameType ValidateNamedRangeName(String str, SpreadsheetVersion ssVersion)
{
Regex colMatcher = new Regex(COLUMN_REF_PATTERN);
if (colMatcher.IsMatch(str))
{
Group colStr = colMatcher.Matches(str)[0].Groups[1];
if (IsColumnWithnRange(colStr.Value, ssVersion))
{
return NameType.COLUMN;
}
}
Regex rowMatcher = new Regex(ROW_REF_PATTERN);
if (rowMatcher.IsMatch(str))
{
Group rowStr = rowMatcher.Matches(str)[0].Groups[1];
if (IsRowWithnRange(rowStr.Value, ssVersion))
{
return NameType.ROW;
}
}
if (!Regex.IsMatch(str, NAMED_RANGE_NAME_PATTERN))
{
return NameType.BAD_CELL_OR_NAMED_RANGE;
}
return NameType.NAMED_RANGE;
}
/**
* Takes in a 0-based base-10 column and returns a ALPHA-26
* representation.
* eg column #3 -> D
*/
public static String ConvertNumToColString(int col)
{
// Excel counts column A as the 1st column, we
// treat it as the 0th one
int excelColNum = col + 1;
String colRef = "";
int colRemain = excelColNum;
while (colRemain > 0)
{
int thisPart = colRemain % 26;
if (thisPart == 0) { thisPart = 26; }
colRemain = (colRemain - thisPart) / 26;
// The letter A is at 65
char colChar = (char)(thisPart + 64);
colRef = colChar + colRef;
}
return colRef;
}
/**
* Separates the row from the columns and returns an array of three Strings. The first element
* is the sheet name. Only the first element may be null. The second element in is the column
* name still in ALPHA-26 number format. The third element is the row.
*/
private static String[] SeparateRefParts(String reference)
{
int plingPos = reference.LastIndexOf(SHEET_NAME_DELIMITER);
String sheetName = ParseSheetName(reference, plingPos);
int start = plingPos + 1;
int Length = reference.Length;
int loc = start;
// skip initial dollars
if (reference[loc] == ABSOLUTE_REFERENCE_MARKER)
{
loc++;
}
// step over column name chars Until first digit (or dollars) for row number.
for (; loc < Length; loc++)
{
char ch = reference[loc];
if (Char.IsDigit(ch) || ch == ABSOLUTE_REFERENCE_MARKER)
{
break;
}
}
return new String[] {
sheetName,
reference.Substring(start,loc-start),
reference.Substring(loc),
};
}
private static String ParseSheetName(String reference, int indexOfSheetNameDelimiter)
{
if (indexOfSheetNameDelimiter < 0)
{
return null;
}
bool IsQuoted = reference[0] == SPECIAL_NAME_DELIMITER;
if (!IsQuoted)
{
return reference.Substring(0, indexOfSheetNameDelimiter);
}
int lastQuotePos = indexOfSheetNameDelimiter - 1;
if (reference[lastQuotePos] != SPECIAL_NAME_DELIMITER)
{
throw new Exception("Mismatched quotes: (" + reference + ")");
}
// TODO - refactor cell reference parsing logic to one place.
// Current known incarnations:
// FormulaParser.Name
// CellReference.ParseSheetName() (here)
// AreaReference.SeparateAreaRefs()
// SheetNameFormatter.format() (inverse)
StringBuilder sb = new StringBuilder(indexOfSheetNameDelimiter);
for (int i = 1; i < lastQuotePos; i++)
{ // Note boundaries - skip outer quotes
char ch = reference[i];
if (ch != SPECIAL_NAME_DELIMITER)
{
sb.Append(ch);
continue;
}
if (i < lastQuotePos)
{
if (reference[i + 1] == SPECIAL_NAME_DELIMITER)
{
// two consecutive quotes is the escape sequence for a single one
i++; // skip this and keep parsing the special name
sb.Append(ch);
continue;
}
}
throw new Exception("Bad sheet name quote escaping: (" + reference + ")");
}
return sb.ToString();
}
/**
* Example return values:
* <table border="0" cellpAdding="1" cellspacing="0" summary="Example return values">
* <tr><th align='left'>Result</th><th align='left'>Comment</th></tr>
* <tr><td>A1</td><td>Cell reference without sheet</td></tr>
* <tr><td>Sheet1!A1</td><td>Standard sheet name</td></tr>
* <tr><td>'O''Brien''s Sales'!A1'</td><td>Sheet name with special characters</td></tr>
* </table>
* @return the text representation of this cell reference as it would appear in a formula.
*/
public String FormatAsString()
{
StringBuilder sb = new StringBuilder(32);
if (_sheetName != null)
{
SheetNameFormatter.AppendFormat(sb, _sheetName);
sb.Append(SHEET_NAME_DELIMITER);
}
AppendCellReference(sb);
return sb.ToString();
}
public override String ToString()
{
StringBuilder sb = new StringBuilder(64);
sb.Append(this.GetType().Name).Append(" [");
sb.Append(FormatAsString());
sb.Append("]");
return sb.ToString();
}
/**
* Returns the three parts of the cell reference, the
* Sheet name (or null if none supplied), the 1 based
* row number, and the A based column letter.
* This will not include any markers for absolute
* references, so use {@link #formatAsString()}
* to properly turn references into strings.
*/
public String[] CellRefParts
{
get
{
return new String[] {
_sheetName,
(_rowIndex+1).ToString(CultureInfo.InvariantCulture),
ConvertNumToColString(_colIndex)
};
}
}
/**
* Appends cell reference with '$' markers for absolute values as required.
* Sheet name is not included.
*/
/* package */
public void AppendCellReference(StringBuilder sb)
{
if (_isColAbs)
{
sb.Append(ABSOLUTE_REFERENCE_MARKER);
}
sb.Append(ConvertNumToColString(_colIndex));
if (_isRowAbs)
{
sb.Append(ABSOLUTE_REFERENCE_MARKER);
}
sb.Append(_rowIndex + 1);
}
/**
* Used to decide whether a name of the form "[A-Z]*[0-9]*" that appears in a formula can be
* interpreted as a cell reference. Names of that form can be also used for sheets and/or
* named ranges, and in those circumstances, the question of whether the potential cell
* reference is valid (in range) becomes important.
* <p/>
* Note - that the maximum sheet size varies across Excel versions:
* <p/>
* <blockquote><table border="0" cellpadding="1" cellspacing="0"
* summary="Notable cases.">
* <tr><th>Version </th><th>File Format </th>
* <th>Last Column </th><th>Last Row</th></tr>
* <tr><td>97-2003</td><td>BIFF8</td><td>"IV" (2^8)</td><td>65536 (2^14)</td></tr>
* <tr><td>2007</td><td>BIFF12</td><td>"XFD" (2^14)</td><td>1048576 (2^20)</td></tr>
* </table></blockquote>
* POI currently targets BIFF8 (Excel 97-2003), so the following behaviour can be observed for
* this method:
* <blockquote><table border="0" cellpadding="1" cellspacing="0"
* summary="Notable cases.">
* <tr><th>Input </th>
* <th>Result </th></tr>
* <tr><td>"A", "1"</td><td>true</td></tr>
* <tr><td>"a", "111"</td><td>true</td></tr>
* <tr><td>"A", "65536"</td><td>true</td></tr>
* <tr><td>"A", "65537"</td><td>false</td></tr>
* <tr><td>"iv", "1"</td><td>true</td></tr>
* <tr><td>"IW", "1"</td><td>false</td></tr>
* <tr><td>"AAA", "1"</td><td>false</td></tr>
* <tr><td>"a", "111"</td><td>true</td></tr>
* <tr><td>"Sheet", "1"</td><td>false</td></tr>
* </table></blockquote>
*
* @param colStr a string of only letter characters
* @param rowStr a string of only digit characters
* @return <c>true</c> if the row and col parameters are within range of a BIFF8 spreadsheet.
*/
public static bool CellReferenceIsWithinRange(String colStr, String rowStr, SpreadsheetVersion ssVersion)
{
if (!IsColumnWithnRange(colStr, ssVersion))
{
return false;
}
return IsRowWithnRange(rowStr, ssVersion);
}
public static bool IsRowWithnRange(String rowStr, SpreadsheetVersion ssVersion)
{
int rowNum = Int32.Parse(rowStr, CultureInfo.InvariantCulture);
if (rowNum < 0)
{
throw new InvalidOperationException("Invalid rowStr '" + rowStr + "'.");
}
if (rowNum == 0)
{
// execution Gets here because caller does first pass of discriminating
// potential cell references using a simplistic regex pattern.
return false;
}
return rowNum <= ssVersion.MaxRows;
}
public static bool IsColumnWithnRange(String colStr, SpreadsheetVersion ssVersion)
{
String lastCol = ssVersion.LastColumnName;
int lastColLength = lastCol.Length;
int numberOfLetters = colStr.Length;
if (numberOfLetters > lastColLength)
{
// "Sheet1" case etc
return false; // that was easy
}
if (numberOfLetters == lastColLength)
{
//if (colStr.ToUpper().CompareTo(lastCol) > 0)
if (string.Compare(colStr.ToUpper(), lastCol, StringComparison.Ordinal) > 0)
{
return false;
}
}
else
{
// apparent column name has less chars than max
// no need to check range
}
return true;
}
public override bool Equals(Object o)
{
if (!(o is CellReference))
{
return false;
}
CellReference cr = (CellReference)o;
return _rowIndex == cr._rowIndex
&& _colIndex == cr._colIndex
&& _isRowAbs == cr._isColAbs
&& _isColAbs == cr._isColAbs;
}
public override int GetHashCode ()
{
return _isRowAbs.GetHashCode () ^ _isColAbs.GetHashCode () ^
_rowIndex ^ _colIndex;
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*=============================================================================
**
** Class: Exception
**
**
** Purpose: The base class for all exceptional conditions.
**
**
=============================================================================*/
namespace System
{
using System;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
////using System.Runtime.Versioning;
////using System.Diagnostics;
////using System.Security.Permissions;
////using System.Security;
////using System.IO;
////using System.Text;
using System.Reflection;
using System.Collections;
using System.Globalization;
////using MethodInfo = System.Reflection.MethodInfo;
////using MethodBase = System.Reflection.MethodBase;
[Serializable]
public class Exception /*: ISerializable*/
{
internal String m_message;
private Exception m_innerException;
//// private Object m_stackTrace;
//// private IDictionary m_data;
//// private String m_helpURL;
//// private String m_className; // Needed for serialization.
//// private MethodBase m_exceptionMethod; // Needed for serialization.
//// private String m_exceptionMethodString; // Needed for serialization.
//// private String m_stackTraceString; // Needed for serialization.
//// private String m_remoteStackTraceString;
//// private int m_remoteStackIndex;
//// private String m_source; // Mainly used by VB.
////
////////#pragma warning disable 414 // Field is not used from managed.
//////// // m_dynamicMethods is an array of System.Resolver objects, used to keep
//////// // DynamicMethodDescs alive for the lifetime of the exception. We do this because
//////// // the m_stackTrace field holds MethodDescs, and a DynamicMethodDesc can be destroyed
//////// // unless a System.Resolver object roots it.
//////// private Object m_dynamicMethods;
////////#pragma warning restore 414
public Exception()
{
m_message = null;
//// m_stackTrace = null;
//// m_dynamicMethods = null;
}
public Exception( String message )
{
m_message = message;
//// m_stackTrace = null;
//// m_dynamicMethods = null;
}
// Creates a new Exception. All derived classes should
// provide this constructor.
// Note: the stack trace is not started until the exception
// is thrown
//
public Exception( String message, Exception innerException )
{
m_message = message;
m_innerException = innerException;
//// m_stackTrace = null;
//// m_dynamicMethods = null;
}
//// protected Exception( SerializationInfo info, StreamingContext context )
//// {
//// if(info == null)
//// {
//// throw new ArgumentNullException( "info" );
//// }
////
//// m_message = info.GetString ( "Message" );
//// m_innerException = (Exception )(info.GetValue ( "InnerException", typeof( Exception ) ));
//// m_data = (IDictionary)(info.GetValueNoThrow( "Data" , typeof( IDictionary ) ));
//// m_helpURL = info.GetString ( "HelpURL" );
//// m_className = info.GetString ( "ClassName" );
//// m_exceptionMethodString = info.GetString ( "ExceptionMethod" );
//// m_stackTraceString = info.GetString ( "StackTraceString" );
//// m_remoteStackTraceString = info.GetString ( "RemoteStackTraceString" );
//// m_remoteStackIndex = info.GetInt32 ( "RemoteStackIndex" );
//// m_source = info.GetString ( "Source" );
////
//// if(m_className == null)
//// {
//// throw new SerializationException( Environment.GetResourceString( "Serialization_InsufficientState" ) );
//// }
////
//// // If we are constructing a new exception after a cross-appdomain call...
//// if(context.State == StreamingContextStates.CrossAppDomain)
//// {
//// // ...this new exception may get thrown. It is logically a re-throw, but
//// // physically a brand-new exception. Since the stack trace is cleared
//// // on a new exception, the "_remoteStackTraceString" is provided to
//// // effectively import a stack trace from a "remote" exception. So,
//// // move the _stackTraceString into the _remoteStackTraceString. Note
//// // that if there is an existing _remoteStackTraceString, it will be
//// // preserved at the head of the new string, so everything works as
//// // expected.
//// // Even if this exception is NOT thrown, things will still work as expected
//// // because the StackTrace property returns the concatenation of the
//// // _remoteStackTraceString and the _stackTraceString.
//// m_remoteStackTraceString = m_remoteStackTraceString + m_stackTraceString;
//// m_stackTraceString = null;
//// }
//// }
public virtual String Message
{
get
{
//// if(m_message == null)
//// {
//// if(m_className == null)
//// {
//// m_className = GetClassName();
//// }
////
//// return String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Exception_WasThrown" ), m_className );
//// }
//// else
//// {
return m_message;
//// }
}
}
//// public virtual IDictionary Data
//// {
//// get
//// {
//// return GetDataInternal();
//// }
//// }
////
//// // This method is internal so that callers can't override which function they call.
//// internal IDictionary GetDataInternal()
//// {
//// if(m_data == null)
//// {
//// if(IsImmutableAgileException( this ))
//// {
//// m_data = new EmptyReadOnlyDictionaryInternal();
//// }
//// else
//// {
//// m_data = new ListDictionaryInternal();
//// }
//// }
////
//// return m_data;
//// }
////
//// [ResourceExposure( ResourceScope.None )]
//// [MethodImpl( MethodImplOptions.InternalCall )]
//// private static extern bool IsImmutableAgileException( Exception e );
////
////
//// [ResourceExposure( ResourceScope.None )]
//// [MethodImpl( MethodImplOptions.InternalCall )]
//// private extern String GetClassName();
// Retrieves the lowest exception (inner most) for the given Exception.
// This will traverse exceptions using the innerException property.
//
public virtual Exception GetBaseException()
{
Exception inner = InnerException;
Exception back = this;
while(inner != null)
{
back = inner;
inner = inner.InnerException;
}
return back;
}
// Returns the inner exception contained in this exception
//
public Exception InnerException
{
get
{
return m_innerException;
}
}
//// [ResourceExposure( ResourceScope.None )]
//// [MethodImpl( MethodImplOptions.InternalCall )]
//// static extern unsafe private void* _InternalGetMethod( Object stackTrace );
////
//// static unsafe private RuntimeMethodHandle InternalGetMethod( Object stackTrace )
//// {
//// return new RuntimeMethodHandle( _InternalGetMethod( stackTrace ) );
//// }
////
////
//// public MethodBase TargetSite
//// {
//// get
//// {
//// return GetTargetSiteInternal();
//// }
//// }
////
////
//// // this function is provided as a private helper to avoid the security demand
//// private MethodBase GetTargetSiteInternal()
//// {
//// if(m_exceptionMethod != null)
//// {
//// return m_exceptionMethod;
//// }
////
//// if(m_stackTrace == null)
//// {
//// return null;
//// }
////
//// if(m_exceptionMethodString != null)
//// {
//// m_exceptionMethod = GetExceptionMethodFromString();
//// }
//// else
//// {
//// RuntimeMethodHandle method = InternalGetMethod( m_stackTrace ).GetTypicalMethodDefinition();
////
//// m_exceptionMethod = RuntimeType.GetMethodBase( method );
//// }
////
//// return m_exceptionMethod;
//// }
////
//// // Returns the stack trace as a string. If no stack trace is
//// // available, null is returned.
//// public virtual String StackTrace
//// {
//// get
//// {
//// // if no stack trace, try to get one
//// if(m_stackTraceString != null)
//// {
//// return m_remoteStackTraceString + m_stackTraceString;
//// }
////
//// if(m_stackTrace == null)
//// {
//// return m_remoteStackTraceString;
//// }
////
//// // Obtain the stack trace string. Note that since Environment.GetStackTrace
//// // will add the path to the source file if the PDB is present and a demand
//// // for PathDiscoveryPermission succeeds, we need to make sure we don't store
//// // the stack trace string in the _stackTraceString member variable.
//// String tempStackTraceString = Environment.GetStackTrace( this, true );
////
//// return m_remoteStackTraceString + tempStackTraceString;
//// }
//// }
////
//// // Sets the help link for this exception.
//// // This should be in a URL/URN form, such as:
//// // "file:///C:/Applications/Bazzal/help.html#ErrorNum42"
//// // Changed to be a read-write String and not return an exception
//// public virtual String HelpLink
//// {
//// get
//// {
//// return m_helpURL;
//// }
////
//// set
//// {
//// m_helpURL = value;
//// }
//// }
////
//// public virtual String Source
//// {
//// get
//// {
//// if(m_source == null)
//// {
//// StackTrace st = new StackTrace( this, true );
////
//// if(st.FrameCount > 0)
//// {
//// StackFrame sf = st.GetFrame( 0 );
//// MethodBase method = sf.GetMethod();
////
//// m_source = method.Module.Assembly.GetSimpleName();
//// }
//// }
////
//// return m_source;
//// }
////
//// set
//// {
//// m_source = value;
//// }
//// }
public override String ToString()
{
return Message;
//// String message = Message;
//// String s;
////
//// if(m_className == null)
//// {
//// m_className = GetClassName();
//// }
////
//// if(message == null || message.Length <= 0)
//// {
//// s = m_className;
//// }
//// else
//// {
//// s = m_className + ": " + message;
//// }
////
//// if(m_innerException != null)
//// {
//// s = s + " ---> " + m_innerException.ToString() + Environment.NewLine + " " + Environment.GetResourceString( "Exception_EndOfInnerExceptionStack" );
//// }
////
////
//// if(StackTrace != null)
//// {
//// s += Environment.NewLine + StackTrace;
//// }
////
//// return s;
}
//// private String GetExceptionMethodString()
//// {
//// MethodBase methBase = GetTargetSiteInternal();
//// if(methBase == null)
//// {
//// return null;
//// }
////
//// // Note that the newline separator is only a separator, chosen such that
//// // it won't (generally) occur in a method name. This string is used
//// // only for serialization of the Exception Method.
//// char separator = '\n';
////
//// StringBuilder result = new StringBuilder();
////
//// if(methBase is ConstructorInfo)
//// {
//// RuntimeConstructorInfo rci = (RuntimeConstructorInfo)methBase;
//// Type t = rci.ReflectedType;
////
//// result.Append( (int)MemberTypes.Constructor );
//// result.Append( separator );
//// result.Append( rci.Name );
////
//// if(t != null)
//// {
//// result.Append( separator );
//// result.Append( t.Assembly.FullName );
//// result.Append( separator );
//// result.Append( t.FullName );
//// }
////
//// result.Append( separator );
//// result.Append( rci.ToString() );
//// }
//// else
//// {
//// BCLDebug.Assert( methBase is MethodInfo, "[Exception.GetExceptionMethodString]methBase is MethodInfo" );
////
//// RuntimeMethodInfo rmi = (RuntimeMethodInfo)methBase;
//// Type t = rmi.DeclaringType;
////
//// result.Append( (int)MemberTypes.Method );
//// result.Append( separator );
//// result.Append( rmi.Name );
//// result.Append( separator );
//// result.Append( rmi.Module.Assembly.FullName );
//// result.Append( separator );
//// if(t != null)
//// {
//// result.Append( t.FullName );
//// result.Append( separator );
//// }
//// result.Append( rmi.ToString() );
//// }
////
//// return result.ToString();
//// }
////
//// private MethodBase GetExceptionMethodFromString()
//// {
//// BCLDebug.Assert( m_exceptionMethodString != null, "Method string cannot be NULL!" );
////
//// String[] args = m_exceptionMethodString.Split( new char[] { '\0', '\n' } );
//// if(args.Length != 5)
//// {
//// throw new SerializationException();
//// }
////
//// SerializationInfo si = new SerializationInfo( typeof( MemberInfoSerializationHolder ), new FormatterConverter() );
////
//// si.AddValue( "MemberType" , (int)Int32.Parse( args[0], CultureInfo.InvariantCulture ), typeof( Int32 ) );
//// si.AddValue( "Name" , args[1], typeof( String ) );
//// si.AddValue( "AssemblyName", args[2], typeof( String ) );
//// si.AddValue( "ClassName" , args[3] );
//// si.AddValue( "Signature" , args[4] );
////
//// MethodBase result;
////
//// StreamingContext sc = new StreamingContext( StreamingContextStates.All );
//// try
//// {
//// result = (MethodBase)new MemberInfoSerializationHolder( si, sc ).GetRealObject( sc );
//// }
//// catch(SerializationException)
//// {
//// result = null;
//// }
//// return result;
//// }
////
//// [SecurityPermissionAttribute( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter )]
//// public virtual void GetObjectData( SerializationInfo info, StreamingContext context )
//// {
//// String tempStackTraceString = m_stackTraceString;
////
//// if(info == null)
//// {
//// throw new ArgumentNullException( "info" );
//// }
////
//// if(m_className == null)
//// {
//// m_className = GetClassName();
//// }
////
//// if(m_stackTrace != null)
//// {
//// if(tempStackTraceString == null)
//// {
//// tempStackTraceString = Environment.GetStackTrace( this, true );
//// }
////
//// if(m_exceptionMethod == null)
//// {
//// RuntimeMethodHandle method = InternalGetMethod( m_stackTrace ).GetTypicalMethodDefinition();
////
//// m_exceptionMethod = RuntimeType.GetMethodBase( method );
//// }
//// }
////
//// if(m_source == null)
//// {
//// m_source = Source; // Set the Source information correctly before serialization
//// }
////
//// info.AddValue( "ClassName" , m_className , typeof( String ) );
//// info.AddValue( "Message" , m_message , typeof( String ) );
//// info.AddValue( "Data" , m_data , typeof( IDictionary ) );
//// info.AddValue( "InnerException" , m_innerException , typeof( Exception ) );
//// info.AddValue( "HelpURL" , m_helpURL , typeof( String ) );
//// info.AddValue( "StackTraceString" , tempStackTraceString , typeof( String ) );
//// info.AddValue( "RemoteStackTraceString", m_remoteStackTraceString , typeof( String ) );
//// info.AddValue( "RemoteStackIndex" , m_remoteStackIndex , typeof( Int32 ) );
//// info.AddValue( "ExceptionMethod" , GetExceptionMethodString(), typeof( String ) );
//// info.AddValue( "Source" , m_source , typeof( String ) );
//// }
////
//// // This is used by remoting to preserve the server side stack trace
//// // by appending it to the message ... before the exception is rethrown
//// // at the client call site.
//// internal Exception PrepForRemoting()
//// {
//// String tmp = null;
////
//// if(m_remoteStackIndex == 0)
//// {
//// tmp = Environment.NewLine + "Server stack trace: " + Environment.NewLine
//// + StackTrace
//// + Environment.NewLine + Environment.NewLine
//// + "Exception rethrown at [" + m_remoteStackIndex + "]: " + Environment.NewLine;
//// }
//// else
//// {
//// tmp = StackTrace
//// + Environment.NewLine + Environment.NewLine
//// + "Exception rethrown at [" + m_remoteStackIndex + "]: " + Environment.NewLine;
//// }
////
//// m_remoteStackTraceString = tmp;
//// m_remoteStackIndex++;
//// return this;
//// }
////
//// // This is used by the runtime when re-throwing a managed exception. It will
//// // copy the stack trace to _remoteStackTraceString.
//// internal void InternalPreserveStackTrace()
//// {
//// string tmpStackTraceString = StackTrace;
////
//// if(tmpStackTraceString != null && tmpStackTraceString.Length > 0)
//// {
//// m_remoteStackTraceString = tmpStackTraceString + Environment.NewLine;
//// }
////
//// m_stackTrace = null;
//// m_stackTraceString = null;
//// }
////
//// internal virtual String InternalToString()
//// {
//// try
//// {
//// SecurityPermission sp = new SecurityPermission( SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy );
//// sp.Assert();
//// }
//// catch
//// {
//// //under normal conditions there should be no exceptions
//// //however if something wrong happens we still can call the usual ToString
//// }
//// return ToString();
//// }
// this method is required so Object.GetType is not made virtual by the compiler
public new Type GetType()
{
return base.GetType();
}
//// internal bool IsTransient
//// {
//// get
//// {
//// return nIsTransient( m_HResult );
//// }
//// }
////
//// [ResourceExposure( ResourceScope.None )]
//// [MethodImpl( MethodImplOptions.InternalCall )]
//// private extern static bool nIsTransient( int hr );
// This piece of infrastructure exists to help avoid deadlocks
// between parts of mscorlib that might throw an exception while
// holding a lock that are also used by mscorlib's ResourceManager
// instance. As a special case of code that may throw while holding
// a lock, we also need to fix our asynchronous exceptions to use
// Win32 resources as well (assuming we ever call a managed
// constructor on instances of them). We should grow this set of
// exception messages as we discover problems, then move the resources
// involved to native code.
internal enum ExceptionMessageKind
{
ThreadAbort = 1,
ThreadInterrupted = 2,
OutOfMemory = 3,
}
// See comment on ExceptionMessageKind
//// [ResourceExposure( ResourceScope.None )]
//// [MethodImpl( MethodImplOptions.InternalCall )]
//// internal static extern String GetMessageFromNativeResources( ExceptionMessageKind kind );
internal static String GetMessageFromNativeResources( ExceptionMessageKind kind )
{
//
// BUGBUG: This needs to be implemented as an internal call.
//
return kind.ToString();
}
}
}
| |
using System;
using Server.Items;
using Server.Network;
namespace Server.Items
{
public abstract class BaseGranite : Item
{
private CraftResource m_Resource;
[CommandProperty(AccessLevel.GameMaster)]
public CraftResource Resource
{
get { return m_Resource; }
set { m_Resource = value; InvalidateProperties(); }
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)1); // version
writer.Write((int)m_Resource);
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
switch (version)
{
case 1:
case 0:
{
m_Resource = (CraftResource)reader.ReadInt();
break;
}
}
if (version < 1)
Stackable = Core.ML;
}
public override double DefaultWeight
{
get { return Core.ML ? 1.0 : 10.0; } // Pub 57
}
public BaseGranite(CraftResource resource)
: base(0x1779)
{
Hue = CraftResources.GetHue(resource);
Stackable = Core.ML;
m_Resource = resource;
}
public BaseGranite(Serial serial)
: base(serial)
{
}
public override int LabelNumber { get { return 1044607; } } // high quality granite
public override void GetProperties(ObjectPropertyList list)
{
base.GetProperties(list);
if (!CraftResources.IsStandard(m_Resource))
{
int num = CraftResources.GetLocalizationNumber(m_Resource);
if (num > 0)
list.Add(num);
else
list.Add(CraftResources.GetName(m_Resource));
}
}
}
public class Granite : BaseGranite
{
[Constructable]
public Granite()
: base(CraftResource.MIron)
{
}
public Granite(Serial serial)
: base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
public class BronzeGranite : BaseGranite
{
[Constructable]
public BronzeGranite()
: base(CraftResource.MBronze)
{
}
public BronzeGranite(Serial serial)
: base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
public class GoldGranite : BaseGranite
{
[Constructable]
public GoldGranite()
: base(CraftResource.MGold)
{
}
public GoldGranite(Serial serial)
: base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
public class CopperGranite : BaseGranite
{
[Constructable]
public CopperGranite()
: base(CraftResource.MCopper)
{
}
public CopperGranite(Serial serial)
: base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
public class OldcopperGranite : BaseGranite
{
[Constructable]
public OldcopperGranite()
: base(CraftResource.MOldcopper)
{
}
public OldcopperGranite(Serial serial)
: base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
public class DullcopperGranite : BaseGranite
{
[Constructable]
public DullcopperGranite()
: base(CraftResource.MDullcopper)
{
}
public DullcopperGranite(Serial serial)
: base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
public class SilverGranite : BaseGranite
{
[Constructable]
public SilverGranite()
: base(CraftResource.MSilver)
{
}
public SilverGranite(Serial serial)
: base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
public class ShadowGranite : BaseGranite
{
[Constructable]
public ShadowGranite()
: base(CraftResource.MShadow)
{
}
public ShadowGranite(Serial serial)
: base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
public class BloodrockGranite : BaseGranite
{
[Constructable]
public BloodrockGranite()
: base(CraftResource.MBloodrock)
{
}
public BloodrockGranite(Serial serial)
: base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
public class BlackrockGranite : BaseGranite
{
[Constructable]
public BlackrockGranite()
: base(CraftResource.MBlackrock)
{
}
public BlackrockGranite(Serial serial)
: base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
public class MytherilGranite : BaseGranite
{
[Constructable]
public MytherilGranite()
: base(CraftResource.MMytheril)
{
}
public MytherilGranite(Serial serial)
: base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
public class RoseGranite : BaseGranite
{
[Constructable]
public RoseGranite()
: base(CraftResource.MRose)
{
}
public RoseGranite(Serial serial)
: base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
public class VeriteGranite : BaseGranite
{
[Constructable]
public VeriteGranite()
: base(CraftResource.MVerite)
{
}
public VeriteGranite(Serial serial)
: base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
public class AgapiteGranite : BaseGranite
{
[Constructable]
public AgapiteGranite()
: base(CraftResource.MAgapite)
{
}
public AgapiteGranite(Serial serial)
: base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
public class RustyGranite : BaseGranite
{
[Constructable]
public RustyGranite()
: base(CraftResource.MRusty)
{
}
public RustyGranite(Serial serial)
: base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
public class ValoriteGranite : BaseGranite
{
[Constructable]
public ValoriteGranite()
: base(CraftResource.MValorite)
{
}
public ValoriteGranite(Serial serial)
: base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
public class DragonGranite : BaseGranite
{
[Constructable]
public DragonGranite()
: base(CraftResource.MDragon)
{
}
public DragonGranite(Serial serial)
: base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
public class TitanGranite : BaseGranite
{
[Constructable]
public TitanGranite()
: base(CraftResource.MTitan)
{
}
public TitanGranite(Serial serial)
: base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
public class CrystalineGranite : BaseGranite
{
[Constructable]
public CrystalineGranite()
: base(CraftResource.MCrystaline)
{
}
public CrystalineGranite(Serial serial)
: base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
public class KryniteGranite : BaseGranite
{
[Constructable]
public KryniteGranite()
: base(CraftResource.MKrynite)
{
}
public KryniteGranite(Serial serial)
: base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
public class VulcanGranite : BaseGranite
{
[Constructable]
public VulcanGranite()
: base(CraftResource.MVulcan)
{
}
public VulcanGranite(Serial serial)
: base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
public class BloodcrestGranite : BaseGranite
{
[Constructable]
public BloodcrestGranite()
: base(CraftResource.MBloodcrest)
{
}
public BloodcrestGranite(Serial serial)
: base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
public class ElvinGranite : BaseGranite
{
[Constructable]
public ElvinGranite()
: base(CraftResource.MElvin)
{
}
public ElvinGranite(Serial serial)
: base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
public class AcidGranite : BaseGranite
{
[Constructable]
public AcidGranite()
: base(CraftResource.MAcid)
{
}
public AcidGranite(Serial serial)
: base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
public class AquaGranite : BaseGranite
{
[Constructable]
public AquaGranite()
: base(CraftResource.MAqua)
{
}
public AquaGranite(Serial serial)
: base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
public class EldarGranite : BaseGranite
{
[Constructable]
public EldarGranite()
: base(CraftResource.MEldar)
{
}
public EldarGranite(Serial serial)
: base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
public class GlowingGranite : BaseGranite
{
[Constructable]
public GlowingGranite()
: base(CraftResource.MGlowing)
{
}
public GlowingGranite(Serial serial)
: base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
public class GorganGranite : BaseGranite
{
[Constructable]
public GorganGranite()
: base(CraftResource.MGorgan)
{
}
public GorganGranite(Serial serial)
: base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
public class SandrockGranite : BaseGranite
{
[Constructable]
public SandrockGranite()
: base(CraftResource.MSandrock)
{
}
public SandrockGranite(Serial serial)
: base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
public class SteelGranite : BaseGranite
{
[Constructable]
public SteelGranite()
: base(CraftResource.MSteel)
{
}
public SteelGranite(Serial serial)
: base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
}
| |
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using DbLocalizationProvider.Abstractions;
using DbLocalizationProvider.Logging;
using DbLocalizationProvider.Sync;
using Xunit;
namespace DbLocalizationProvider.Storage.SqlServer.Tests.ResourceSynchronizedTests
{
public class Tests
{
private readonly Synchronizer _sut;
private static DiscoveredResource DefaultDiscoveredResource => new DiscoveredResource(
null,
"discovered-resource",
new List<DiscoveredTranslation> { new DiscoveredTranslation("English discovered resource", "en") },
"",
null,
null,
false,
false);
private static DiscoveredResource DefaultDiscoveredModel => new DiscoveredResource(
null,
"discovered-model",
new List<DiscoveredTranslation> { new DiscoveredTranslation("English discovered model", "en") },
"",
null,
null,
false,
false);
public Tests()
{
var ctx = new ConfigurationContext();
_sut = new Synchronizer(
new TypeDiscoveryHelper(Enumerable.Empty<IResourceTypeScanner>(), ctx),
new QueryExecutor(ctx.TypeFactory),
new CommandExecutor(ctx.TypeFactory),
new ResourceRepository(ctx),
new NullLogger(),
ctx);
}
[Fact]
public void MergeEmptyLists()
{
var result = _sut.MergeLists(
Enumerable.Empty<LocalizationResource>(),
new List<DiscoveredResource>(),
new List<DiscoveredResource>());
Assert.Empty(result);
}
[Fact]
public void Merge_WhenDiscoveredModelsEmpty_ShouldAddDiscoveredResource()
{
var result = _sut.MergeLists(
Enumerable.Empty<LocalizationResource>(),
new List<DiscoveredResource> { DefaultDiscoveredResource },
new List<DiscoveredResource>())
.ToList();
Assert.NotEmpty(result);
Assert.Single(result);
}
[Fact]
public void Merge_WhenDiscoveredResourcesEmpty_ShouldAddDiscoveredModel()
{
var result = _sut.MergeLists(
Enumerable.Empty<LocalizationResource>(),
new List<DiscoveredResource>(),
new List<DiscoveredResource> { DefaultDiscoveredModel })
.ToList();
Assert.NotEmpty(result);
Assert.Single(result);
}
[Fact]
public void Merge_AllDifferentResources_ShouldKeepAll()
{
var db = new List<LocalizationResource>
{
new LocalizationResource("key-from-db", false)
{
Translations = new LocalizationResourceTranslationCollection(false)
{
new LocalizationResourceTranslation
{
Language = "en", Value = "English from DB"
}
}
}
};
var resources = new List<DiscoveredResource>
{
new DiscoveredResource(null, "discovered-resource", new List<DiscoveredTranslation> { new DiscoveredTranslation("English discovered resource", "en") }, "", null, null, false, false)
};
var models = new List<DiscoveredResource>
{
new DiscoveredResource(null, "discovered-model", new List<DiscoveredTranslation> { new DiscoveredTranslation("English discovered model", "en") }, "", null, null, false, false)
};
var result = _sut.MergeLists(db, resources, models);
Assert.NotEmpty(result);
Assert.Equal(3, result.Count());
}
[Fact]
public void Merge_DatabaseContainsDiscoveredResource_NotModified_ShouldOverwrite_IncludingInvariant()
{
var db = new List<LocalizationResource>
{
new LocalizationResource("resource-key-1", false)
{
Translations = new LocalizationResourceTranslationCollection(false)
{
new LocalizationResourceTranslation
{
Language = string.Empty, Value = "Resource-1 INVARIANT from DB"
},
new LocalizationResourceTranslation
{
Language = "en", Value = "Resource-1 English from DB"
}
}
},
new LocalizationResource("resource-key-2", false)
{
Translations = new LocalizationResourceTranslationCollection(false)
{
new LocalizationResourceTranslation
{
Language = string.Empty, Value = "Resource-2 INVARIANT from DB"
},
new LocalizationResourceTranslation
{
Language = "en", Value = "Resource-2 English from DB"
}
}
}
};
var resources = new List<DiscoveredResource>
{
new DiscoveredResource(null, "resource-key-1", new List<DiscoveredTranslation> { new DiscoveredTranslation("Resource-1 INVARIANT from Discovery", string.Empty), new DiscoveredTranslation("Resource-1 English from Discovery", "en") }, "", null, null, false, false),
new DiscoveredResource(null, "discovered-resource", new List<DiscoveredTranslation> { new DiscoveredTranslation("English discovered resource", "en") }, "", null, null, false, false)
};
var models = new List<DiscoveredResource>
{
new DiscoveredResource(null, "discovered-model", new List<DiscoveredTranslation> { new DiscoveredTranslation("English discovered model", "en") }, "", null, null, false, false),
new DiscoveredResource(null, "resource-key-2", new List<DiscoveredTranslation> { new DiscoveredTranslation("Resource-2 INVARIANT from Discovery", string.Empty), new DiscoveredTranslation("Resource-2 English from Discovery", "en") }, "", null, null, false, false)
};
var result = _sut.MergeLists(db, resources, models);
Assert.NotEmpty(result);
Assert.Equal(4, result.Count());
Assert.Equal("Resource-1 INVARIANT from Discovery", result.First(r => r.ResourceKey == "resource-key-1").Translations.ByLanguage(CultureInfo.InvariantCulture));
Assert.Equal("Resource-1 English from Discovery", result.First(r => r.ResourceKey == "resource-key-1").Translations.ByLanguage("en"));
Assert.Equal("Resource-2 INVARIANT from Discovery", result.First(r => r.ResourceKey == "resource-key-2").Translations.ByLanguage(CultureInfo.InvariantCulture));
Assert.Equal("Resource-2 English from Discovery", result.First(r => r.ResourceKey == "resource-key-2").Translations.ByLanguage("en"));
}
[Fact]
public void Merge_DatabaseContainsDiscoveredResource_Modified_ShouldNotOverwrite_ShouldOverwriteInvariant()
{
var db = new List<LocalizationResource>
{
new LocalizationResource("resource-key-1", false)
{
IsModified = true,
Translations = new LocalizationResourceTranslationCollection(false)
{
new LocalizationResourceTranslation
{
Language = string.Empty, Value = "Resource-1 INVARIANT from DB"
},
new LocalizationResourceTranslation
{
Language = "en", Value = "Resource-1 English from DB"
}
}
},
new LocalizationResource("resource-key-2", false)
{
IsModified = true,
Translations = new LocalizationResourceTranslationCollection(false)
{
new LocalizationResourceTranslation
{
Language = string.Empty, Value = "Resource-2 INVARIANT from DB"
},
new LocalizationResourceTranslation
{
Language = "en", Value = "Resource-2 English from DB"
}
}
}
};
var resources = new List<DiscoveredResource>
{
new DiscoveredResource(null, "resource-key-1", new List<DiscoveredTranslation> { new DiscoveredTranslation("Resource-1 INVARIANT from Discovery", string.Empty), new DiscoveredTranslation("Resource-1 English from Discovery", "en") }, "", null, null, false, false),
new DiscoveredResource(null, "discovered-resource", new List<DiscoveredTranslation> { new DiscoveredTranslation("English discovered resource", "en") }, "", null, null, false, false)
};
var models = new List<DiscoveredResource>
{
new DiscoveredResource(null, "discovered-model", new List<DiscoveredTranslation> { new DiscoveredTranslation("English discovered model", "en") }, "", null, null, false, false),
new DiscoveredResource(null, "resource-key-2", new List<DiscoveredTranslation> { new DiscoveredTranslation("Resource-2 INVARIANT from Discovery", string.Empty), new DiscoveredTranslation("Resource-2 English from Discovery", "en") }, "", null, null, false, false)
};
var result = _sut.MergeLists(db, resources, models);
Assert.NotEmpty(result);
Assert.Equal(4, result.Count());
Assert.Equal("Resource-1 INVARIANT from Discovery", result.First(r => r.ResourceKey == "resource-key-1").Translations.ByLanguage(CultureInfo.InvariantCulture));
Assert.Equal("Resource-1 English from DB", result.First(r => r.ResourceKey == "resource-key-1").Translations.ByLanguage("en"));
Assert.Equal("Resource-2 INVARIANT from Discovery", result.First(r => r.ResourceKey == "resource-key-2").Translations.ByLanguage(CultureInfo.InvariantCulture));
Assert.Equal("Resource-2 English from DB", result.First(r => r.ResourceKey == "resource-key-2").Translations.ByLanguage("en"));
}
}
}
| |
// Copyright (c) 2015-present, Parse, LLC. All rights reserved. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree. An additional grant of patent rights can be found in the PATENTS file in the same directory.
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Parse.Internal;
namespace Parse {
/// <summary>
/// A utility class for sending and receiving push notifications.
/// </summary>
public partial class ParsePush {
private object mutex;
private IPushState state;
/// <summary>
/// Creates a push which will target every device. The Data field must be set before calling SendAsync.
/// </summary>
public ParsePush() {
mutex = new object();
// Default to everyone.
state = new MutablePushState {
Query = ParseInstallation.Query
};
}
#region Properties
/// <summary>
/// An installation query that specifies which installations should receive
/// this push.
/// This should not be used in tandem with Channels.
/// </summary>
public ParseQuery<ParseInstallation> Query {
get { return state.Query; }
set {
MutateState(s => {
if (s.Channels != null && value != null && value.GetConstraint("channels") != null) {
throw new InvalidOperationException("A push may not have both Channels and a Query with a channels constraint");
}
s.Query = value;
});
}
}
/// <summary>
/// A short-hand to set a query which only discriminates on the channels to which a device is subscribed.
/// This is shorthand for:
///
/// <code>
/// var push = new Push();
/// push.Query = ParseInstallation.Query.WhereKeyContainedIn("channels", channels);
/// </code>
///
/// This cannot be used in tandem with Query.
/// </summary>
public IEnumerable<string> Channels {
get { return state.Channels; }
set {
MutateState(s => {
if (value != null && s.Query != null && s.Query.GetConstraint("channels") != null) {
throw new InvalidOperationException("A push may not have both Channels and a Query with a channels constraint");
}
s.Channels = value;
});
}
}
/// <summary>
/// The time at which this push will expire. This should not be used in tandem with ExpirationInterval.
/// </summary>
public DateTime? Expiration {
get { return state.Expiration; }
set {
MutateState(s => {
if (s.ExpirationInterval != null) {
throw new InvalidOperationException("Cannot set Expiration after setting ExpirationInterval");
}
s.Expiration = value;
});
}
}
/// <summary>
/// The time at which this push will be sent.
/// </summary>
public DateTime? PushTime {
get { return state.PushTime; }
set {
MutateState(s => {
DateTime now = DateTime.Now;
if (value < now || value > now.AddDays(14)) {
throw new InvalidOperationException("Cannot set PushTime in the past or more than two weeks later than now");
}
s.PushTime = value;
});
}
}
/// <summary>
/// The time from initial schedul when this push will expire. This should not be used in tandem with Expiration.
/// </summary>
public TimeSpan? ExpirationInterval {
get { return state.ExpirationInterval; }
set {
MutateState(s => {
if (s.Expiration != null) {
throw new InvalidOperationException("Cannot set ExpirationInterval after setting Expiration");
}
s.ExpirationInterval = value;
});
}
}
/// <summary>
/// The contents of this push. Some keys have special meaning. A full list of pre-defined
/// keys can be found in the Parse Push Guide. The following keys affect WinRT devices.
/// Keys which do not start with x-winrt- can be prefixed with x-winrt- to specify an
/// override only sent to winrt devices.
/// alert: the body of the alert text.
/// title: The title of the text.
/// x-winrt-payload: A full XML payload to be sent to WinRT installations instead of
/// the auto-layout.
/// This should not be used in tandem with Alert.
/// </summary>
public IDictionary<string, object> Data {
get { return state.Data; }
set {
MutateState(s => {
if (s.Alert != null && value != null) {
throw new InvalidOperationException("A push may not have both an Alert and Data");
}
s.Data = value;
});
}
}
/// <summary>
/// A convenience method which sets Data to a dictionary with alert as its only field. Equivalent to
///
/// <code>
/// Data = new Dictionary<string, object> {{"alert", alert}};
/// </code>
///
/// This should not be used in tandem with Data.
/// </summary>
public string Alert {
get { return state.Alert; }
set {
MutateState(s => {
if (s.Data != null && value != null) {
throw new InvalidOperationException("A push may not have both an Alert and Data");
}
s.Alert = value;
});
}
}
#endregion
internal IDictionary<string, object> Encode() {
return ParsePushEncoder.Instance.Encode(state);
}
private void MutateState(Action<MutablePushState> func) {
lock (mutex) {
state = state.MutatedClone(func);
}
}
private static IParsePushController PushController {
get {
return ParseCorePlugins.Instance.PushController;
}
}
private static IParsePushChannelsController PushChannelsController {
get {
return ParseCorePlugins.Instance.PushChannelsController;
}
}
#region Sending Push
/// <summary>
/// Request a push to be sent. When this task completes, Parse has successfully acknowledged a request
/// to send push notifications but has not necessarily finished sending all notifications
/// requested. The current status of recent push notifications can be seen in your Push Notifications
/// console on http://parse.com
/// </summary>
/// <returns>A Task for continuation.</returns>
public Task SendAsync() {
return SendAsync(CancellationToken.None);
}
/// <summary>
/// Request a push to be sent. When this task completes, Parse has successfully acknowledged a request
/// to send push notifications but has not necessarily finished sending all notifications
/// requested. The current status of recent push notifications can be seen in your Push Notifications
/// console on http://parse.com
/// </summary>
/// <param name="cancellationToken">CancellationToken to cancel the current operation.</param>
public Task SendAsync(CancellationToken cancellationToken) {
return PushController.SendPushNotificationAsync(state, ParseUser.CurrentSessionToken, cancellationToken);
}
/// <summary>
/// Pushes a simple message to every device. This is shorthand for:
///
/// <code>
/// var push = new ParsePush();
/// push.Data = new Dictionary<string, object>{{"alert", alert}};
/// return push.SendAsync();
/// </code>
/// </summary>
/// <param name="alert">The alert message to send.</param>
public static Task SendAlertAsync(string alert) {
var push = new ParsePush();
push.Alert = alert;
return push.SendAsync();
}
/// <summary>
/// Pushes a simple message to every device subscribed to channel. This is shorthand for:
///
/// <code>
/// var push = new ParsePush();
/// push.Channels = new List<string> { channel };
/// push.Data = new Dictionary<string, object>{{"alert", alert}};
/// return push.SendAsync();
/// </code>
/// </summary>
/// <param name="alert">The alert message to send.</param>
/// <param name="channel">An Installation must be subscribed to channel to receive this Push Notification.</param>
public static Task SendAlertAsync(string alert, string channel) {
var push = new ParsePush();
push.Channels = new List<string> { channel };
push.Alert = alert;
return push.SendAsync();
}
/// <summary>
/// Pushes a simple message to every device subscribed to any of channels. This is shorthand for:
///
/// <code>
/// var push = new ParsePush();
/// push.Channels = channels;
/// push.Data = new Dictionary<string, object>{{"alert", alert}};
/// return push.SendAsync();
/// </code>
/// </summary>
/// <param name="alert">The alert message to send.</param>
/// <param name="channels">An Installation must be subscribed to any of channels to receive this Push Notification.</param>
public static Task SendAlertAsync(string alert, IEnumerable<string> channels) {
var push = new ParsePush();
push.Channels = channels;
push.Alert = alert;
return push.SendAsync();
}
/// <summary>
/// Pushes a simple message to every device matching the target query. This is shorthand for:
///
/// <code>
/// var push = new ParsePush();
/// push.Query = query;
/// push.Data = new Dictionary<string, object>{{"alert", alert}};
/// return push.SendAsync();
/// </code>
/// </summary>
/// <param name="alert">The alert message to send.</param>
/// <param name="query">A query filtering the devices which should receive this Push Notification.</param>
public static Task SendAlertAsync(string alert, ParseQuery<ParseInstallation> query) {
var push = new ParsePush();
push.Query = query;
push.Alert = alert;
return push.SendAsync();
}
/// <summary>
/// Pushes an arbitrary payload to every device. This is shorthand for:
///
/// <code>
/// var push = new ParsePush();
/// push.Data = data;
/// return push.SendAsync();
/// </code>
/// </summary>
/// <param name="data">A push payload. See the ParsePush.Data property for more information.</param>
public static Task SendDataAsync(IDictionary<string, object> data) {
var push = new ParsePush();
push.Data = data;
return push.SendAsync();
}
/// <summary>
/// Pushes an arbitrary payload to every device subscribed to channel. This is shorthand for:
///
/// <code>
/// var push = new ParsePush();
/// push.Channels = new List<string> { channel };
/// push.Data = data;
/// return push.SendAsync();
/// </code>
/// </summary>
/// <param name="data">A push payload. See the ParsePush.Data property for more information.</param>
/// <param name="channel">An Installation must be subscribed to channel to receive this Push Notification.</param>
public static Task SendDataAsync(IDictionary<string, object> data, string channel) {
var push = new ParsePush();
push.Channels = new List<string> { channel };
push.Data = data;
return push.SendAsync();
}
/// <summary>
/// Pushes an arbitrary payload to every device subscribed to any of channels. This is shorthand for:
///
/// <code>
/// var push = new ParsePush();
/// push.Channels = channels;
/// push.Data = data;
/// return push.SendAsync();
/// </code>
/// </summary>
/// <param name="data">A push payload. See the ParsePush.Data property for more information.</param>
/// <param name="channels">An Installation must be subscribed to any of channels to receive this Push Notification.</param>
public static Task SendDataAsync(IDictionary<string, object> data, IEnumerable<string> channels) {
var push = new ParsePush();
push.Channels = channels;
push.Data = data;
return push.SendAsync();
}
/// <summary>
/// Pushes an arbitrary payload to every device matching target. This is shorthand for:
///
/// <code>
/// var push = new ParsePush();
/// push.Query = query
/// push.Data = data;
/// return push.SendAsync();
/// </code>
/// </summary>
/// <param name="data">A push payload. See the ParsePush.Data property for more information.</param>
/// <param name="query">A query filtering the devices which should receive this Push Notification.</param>
public static Task SendDataAsync(IDictionary<string, object> data, ParseQuery<ParseInstallation> query) {
var push = new ParsePush();
push.Query = query;
push.Data = data;
return push.SendAsync();
}
#endregion
#region Receiving Push
/// <summary>
/// An event fired when a push notification is received.
/// </summary>
public static event EventHandler<ParsePushNotificationEventArgs> ParsePushNotificationReceived {
add {
parsePushNotificationReceived.Add(value);
}
remove {
parsePushNotificationReceived.Remove(value);
}
}
internal static readonly SynchronizedEventHandler<ParsePushNotificationEventArgs> parsePushNotificationReceived = new SynchronizedEventHandler<ParsePushNotificationEventArgs>();
#endregion
#region Push Subscription
/// <summary>
/// Subscribe the current installation to this channel. This is shorthand for:
///
/// <code>
/// var installation = ParseInstallation.CurrentInstallation;
/// installation.AddUniqueToList("channels", channel);
/// installation.SaveAsync();
/// </code>
/// </summary>
/// <param name="channel">The channel to which this installation should subscribe.</param>
public static Task SubscribeAsync(string channel) {
return SubscribeAsync(new List<string> { channel }, CancellationToken.None);
}
/// <summary>
/// Subscribe the current installation to this channel. This is shorthand for:
///
/// <code>
/// var installation = ParseInstallation.CurrentInstallation;
/// installation.AddUniqueToList("channels", channel);
/// installation.SaveAsync(cancellationToken);
/// </code>
/// </summary>
/// <param name="channel">The channel to which this installation should subscribe.</param>
/// <param name="cancellationToken">CancellationToken to cancel the current operation.</param>
public static Task SubscribeAsync(string channel, CancellationToken cancellationToken) {
return SubscribeAsync(new List<string> { channel }, cancellationToken);
}
/// <summary>
/// Subscribe the current installation to these channels. This is shorthand for:
///
/// <code>
/// var installation = ParseInstallation.CurrentInstallation;
/// installation.AddRangeUniqueToList("channels", channels);
/// installation.SaveAsync();
/// </code>
/// </summary>
/// <param name="channels">The channels to which this installation should subscribe.</param>
public static Task SubscribeAsync(IEnumerable<string> channels) {
return SubscribeAsync(channels, CancellationToken.None);
}
/// <summary>
/// Subscribe the current installation to these channels. This is shorthand for:
///
/// <code>
/// var installation = ParseInstallation.CurrentInstallation;
/// installation.AddRangeUniqueToList("channels", channels);
/// installation.SaveAsync(cancellationToken);
/// </code>
/// </summary>
/// <param name="channels">The channels to which this installation should subscribe.</param>
/// <param name="cancellationToken">CancellationToken to cancel the current operation.</param>
public static Task SubscribeAsync(IEnumerable<string> channels, CancellationToken cancellationToken) {
return PushChannelsController.SubscribeAsync(channels, cancellationToken);
}
/// <summary>
/// Unsubscribe the current installation from this channel. This is shorthand for:
///
/// <code>
/// var installation = ParseInstallation.CurrentInstallation;
/// installation.Remove("channels", channel);
/// installation.SaveAsync();
/// </code>
/// </summary>
/// <param name="channel">The channel from which this installation should unsubscribe.</param>
public static Task UnsubscribeAsync(string channel) {
return UnsubscribeAsync(new List<string> { channel }, CancellationToken.None);
}
/// <summary>
/// Unsubscribe the current installation from this channel. This is shorthand for:
///
/// <code>
/// var installation = ParseInstallation.CurrentInstallation;
/// installation.Remove("channels", channel);
/// installation.SaveAsync(cancellationToken);
/// </code>
/// </summary>
/// <param name="channel">The channel from which this installation should unsubscribe.</param>
/// <param name="cancellationToken">CancellationToken to cancel the current operation.</param>
public static Task UnsubscribeAsync(string channel, CancellationToken cancellationToken) {
return UnsubscribeAsync(new List<string> { channel }, cancellationToken);
}
/// <summary>
/// Unsubscribe the current installation from these channels. This is shorthand for:
///
/// <code>
/// var installation = ParseInstallation.CurrentInstallation;
/// installation.RemoveAllFromList("channels", channels);
/// installation.SaveAsync();
/// </code>
/// </summary>
/// <param name="channels">The channels from which this installation should unsubscribe.</param>
public static Task UnsubscribeAsync(IEnumerable<string> channels) {
return UnsubscribeAsync(channels, CancellationToken.None);
}
/// <summary>
/// Unsubscribe the current installation from these channels. This is shorthand for:
///
/// <code>
/// var installation = ParseInstallation.CurrentInstallation;
/// installation.RemoveAllFromList("channels", channels);
/// installation.SaveAsync(cancellationToken);
/// </code>
/// </summary>
/// <param name="channels">The channels from which this installation should unsubscribe.</param>
/// <param name="cancellationToken">CancellationToken to cancel the current operation.</param>
public static Task UnsubscribeAsync(IEnumerable<string> channels, CancellationToken cancellationToken) {
return PushChannelsController.UnsubscribeAsync(channels, cancellationToken);
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;
using System.Net.Mail;
using System.Text;
using Xunit;
namespace System.Net.Http.Unit.Tests
{
public class HttpRequestHeadersTest
{
private HttpRequestHeaders headers;
public HttpRequestHeadersTest()
{
headers = new HttpRequestHeaders();
}
#region Request headers
[Fact]
public void Accept_AddInvalidValueUsingUnusualCasing_ParserRetrievedUsingCaseInsensitiveComparison()
{
// Use uppercase header name to make sure the parser gets retrieved using case-insensitive comparison.
Assert.Throws<FormatException>(() => { headers.Add("AcCePt", "this is invalid"); });
}
[Fact]
public void Accept_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
MediaTypeWithQualityHeaderValue value1 = new MediaTypeWithQualityHeaderValue("text/plain");
value1.CharSet = "utf-8";
value1.Quality = 0.5;
value1.Parameters.Add(new NameValueHeaderValue("custom", "value"));
MediaTypeWithQualityHeaderValue value2 = new MediaTypeWithQualityHeaderValue("text/plain");
value2.CharSet = "iso-8859-1";
value2.Quality = 0.3868;
Assert.Equal(0, headers.Accept.Count);
headers.Accept.Add(value1);
headers.Accept.Add(value2);
Assert.Equal(2, headers.Accept.Count);
Assert.Equal(value1, headers.Accept.ElementAt(0));
Assert.Equal(value2, headers.Accept.ElementAt(1));
headers.Accept.Clear();
Assert.Equal(0, headers.Accept.Count);
}
[Fact]
public void Accept_ReadEmptyProperty_EmptyCollection()
{
HttpRequestMessage request = new HttpRequestMessage();
Assert.Equal(0, request.Headers.Accept.Count);
// Copy to another list
List<MediaTypeWithQualityHeaderValue> accepts = request.Headers.Accept.ToList();
Assert.Equal(0, accepts.Count);
accepts = new List<MediaTypeWithQualityHeaderValue>(request.Headers.Accept);
Assert.Equal(0, accepts.Count);
}
[Fact]
public void Accept_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
headers.TryAddWithoutValidation("Accept",
",, , ,,text/plain; charset=iso-8859-1; q=1.0,\r\n */xml; charset=utf-8; q=0.5,,,");
MediaTypeWithQualityHeaderValue value1 = new MediaTypeWithQualityHeaderValue("text/plain");
value1.CharSet = "iso-8859-1";
value1.Quality = 1.0;
MediaTypeWithQualityHeaderValue value2 = new MediaTypeWithQualityHeaderValue("*/xml");
value2.CharSet = "utf-8";
value2.Quality = 0.5;
Assert.Equal(value1, headers.Accept.ElementAt(0));
Assert.Equal(value2, headers.Accept.ElementAt(1));
}
[Fact]
public void Accept_UseAddMethodWithInvalidValue_InvalidValueRecognized()
{
// Add a valid media-type with an invalid quality value
headers.TryAddWithoutValidation("Accept", "text/plain; q=a"); // invalid quality
Assert.NotNull(headers.Accept.First());
Assert.Null(headers.Accept.First().Quality);
Assert.Equal("text/plain; q=a", headers.Accept.First().ToString());
headers.Clear();
headers.TryAddWithoutValidation("Accept", "text/plain application/xml"); // no separator
Assert.Equal(0, headers.Accept.Count);
Assert.Equal(1, headers.GetValues("Accept").Count());
Assert.Equal("text/plain application/xml", headers.GetValues("Accept").First());
}
[Fact]
public void AcceptCharset_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Equal(0, headers.AcceptCharset.Count);
headers.AcceptCharset.Add(new StringWithQualityHeaderValue("iso-8859-5"));
headers.AcceptCharset.Add(new StringWithQualityHeaderValue("unicode-1-1", 0.8));
Assert.Equal(2, headers.AcceptCharset.Count);
Assert.Equal(new StringWithQualityHeaderValue("iso-8859-5"), headers.AcceptCharset.ElementAt(0));
Assert.Equal(new StringWithQualityHeaderValue("unicode-1-1", 0.8), headers.AcceptCharset.ElementAt(1));
headers.AcceptCharset.Clear();
Assert.Equal(0, headers.AcceptCharset.Count);
}
[Fact]
public void AcceptCharset_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
headers.TryAddWithoutValidation("Accept-Charset", ", ,,iso-8859-5 , \r\n utf-8 ; q=0.300 ,,,");
Assert.Equal(new StringWithQualityHeaderValue("iso-8859-5"),
headers.AcceptCharset.ElementAt(0));
Assert.Equal(new StringWithQualityHeaderValue("utf-8", 0.3),
headers.AcceptCharset.ElementAt(1));
}
[Fact]
public void AcceptCharset_UseAddMethodWithInvalidValue_InvalidValueRecognized()
{
headers.TryAddWithoutValidation("Accept-Charset", "iso-8859-5 utf-8"); // no separator
Assert.Equal(0, headers.AcceptCharset.Count);
Assert.Equal(1, headers.GetValues("Accept-Charset").Count());
Assert.Equal("iso-8859-5 utf-8", headers.GetValues("Accept-Charset").First());
headers.Clear();
headers.TryAddWithoutValidation("Accept-Charset", "utf-8; q=1; q=0.3");
Assert.Equal(0, headers.AcceptCharset.Count);
Assert.Equal(1, headers.GetValues("Accept-Charset").Count());
Assert.Equal("utf-8; q=1; q=0.3", headers.GetValues("Accept-Charset").First());
}
[Fact]
public void AcceptCharset_AddMultipleValuesAndGetValueString_AllValuesAddedUsingTheCorrectDelimiter()
{
headers.TryAddWithoutValidation("Accept-Charset", "invalid value");
headers.Add("Accept-Charset", "utf-8");
headers.AcceptCharset.Add(new StringWithQualityHeaderValue("iso-8859-5", 0.5));
foreach (var header in headers.GetHeaderStrings())
{
Assert.Equal("Accept-Charset", header.Key);
Assert.Equal("utf-8, iso-8859-5; q=0.5, invalid value", header.Value);
}
}
[Fact]
public void AcceptEncoding_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Equal(0, headers.AcceptEncoding.Count);
headers.AcceptEncoding.Add(new StringWithQualityHeaderValue("compress", 0.9));
headers.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip"));
Assert.Equal(2, headers.AcceptEncoding.Count);
Assert.Equal(new StringWithQualityHeaderValue("compress", 0.9), headers.AcceptEncoding.ElementAt(0));
Assert.Equal(new StringWithQualityHeaderValue("gzip"), headers.AcceptEncoding.ElementAt(1));
headers.AcceptEncoding.Clear();
Assert.Equal(0, headers.AcceptEncoding.Count);
}
[Fact]
public void AcceptEncoding_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
headers.TryAddWithoutValidation("Accept-Encoding", ", gzip; q=1.0, identity; q=0.5, *;q=0, ");
Assert.Equal(new StringWithQualityHeaderValue("gzip", 1),
headers.AcceptEncoding.ElementAt(0));
Assert.Equal(new StringWithQualityHeaderValue("identity", 0.5),
headers.AcceptEncoding.ElementAt(1));
Assert.Equal(new StringWithQualityHeaderValue("*", 0),
headers.AcceptEncoding.ElementAt(2));
headers.AcceptEncoding.Clear();
headers.TryAddWithoutValidation("Accept-Encoding", "");
Assert.Equal(0, headers.AcceptEncoding.Count);
Assert.False(headers.Contains("Accept-Encoding"));
}
[Fact]
public void AcceptEncoding_UseAddMethodWithInvalidValue_InvalidValueRecognized()
{
headers.TryAddWithoutValidation("Accept-Encoding", "gzip deflate"); // no separator
Assert.Equal(0, headers.AcceptEncoding.Count);
Assert.Equal(1, headers.GetValues("Accept-Encoding").Count());
Assert.Equal("gzip deflate", headers.GetValues("Accept-Encoding").First());
headers.Clear();
headers.TryAddWithoutValidation("Accept-Encoding", "compress; q=1; gzip");
Assert.Equal(0, headers.AcceptEncoding.Count);
Assert.Equal(1, headers.GetValues("Accept-Encoding").Count());
Assert.Equal("compress; q=1; gzip", headers.GetValues("Accept-Encoding").First());
}
[Fact]
public void AcceptLanguage_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Equal(0, headers.AcceptLanguage.Count);
headers.AcceptLanguage.Add(new StringWithQualityHeaderValue("da"));
headers.AcceptLanguage.Add(new StringWithQualityHeaderValue("en-GB", 0.8));
headers.AcceptLanguage.Add(new StringWithQualityHeaderValue("en", 0.7));
Assert.Equal(3, headers.AcceptLanguage.Count);
Assert.Equal(new StringWithQualityHeaderValue("da"), headers.AcceptLanguage.ElementAt(0));
Assert.Equal(new StringWithQualityHeaderValue("en-GB", 0.8), headers.AcceptLanguage.ElementAt(1));
Assert.Equal(new StringWithQualityHeaderValue("en", 0.7), headers.AcceptLanguage.ElementAt(2));
headers.AcceptLanguage.Clear();
Assert.Equal(0, headers.AcceptLanguage.Count);
}
[Fact]
public void AcceptLanguage_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
headers.TryAddWithoutValidation("Accept-Language", " , de-DE;q=0.9,de-AT;q=0.5,*;q=0.010 , ");
Assert.Equal(new StringWithQualityHeaderValue("de-DE", 0.9),
headers.AcceptLanguage.ElementAt(0));
Assert.Equal(new StringWithQualityHeaderValue("de-AT", 0.5),
headers.AcceptLanguage.ElementAt(1));
Assert.Equal(new StringWithQualityHeaderValue("*", 0.01),
headers.AcceptLanguage.ElementAt(2));
headers.AcceptLanguage.Clear();
headers.TryAddWithoutValidation("Accept-Language", "");
Assert.Equal(0, headers.AcceptLanguage.Count);
Assert.False(headers.Contains("Accept-Language"));
}
[Fact]
public void AcceptLanguage_UseAddMethodWithInvalidValue_InvalidValueRecognized()
{
headers.TryAddWithoutValidation("Accept-Language", "de -DE"); // no separator
Assert.Equal(0, headers.AcceptLanguage.Count);
Assert.Equal(1, headers.GetValues("Accept-Language").Count());
Assert.Equal("de -DE", headers.GetValues("Accept-Language").First());
headers.Clear();
headers.TryAddWithoutValidation("Accept-Language", "en; q=0.4,[");
Assert.Equal(0, headers.AcceptLanguage.Count);
Assert.Equal(1, headers.GetValues("Accept-Language").Count());
Assert.Equal("en; q=0.4,[", headers.GetValues("Accept-Language").First());
}
[Fact]
public void Expect_Add100Continue_Success()
{
// use non-default casing to make sure we do case-insensitive comparison.
headers.Expect.Add(new NameValueWithParametersHeaderValue("100-CONTINUE"));
Assert.True(headers.ExpectContinue == true);
Assert.Equal(1, headers.Expect.Count);
}
[Fact]
public void Expect_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Equal(0, headers.Expect.Count);
Assert.Null(headers.ExpectContinue);
headers.Expect.Add(new NameValueWithParametersHeaderValue("custom1"));
headers.Expect.Add(new NameValueWithParametersHeaderValue("custom2"));
headers.ExpectContinue = true;
// Connection collection has 2 values plus '100-Continue'
Assert.Equal(3, headers.Expect.Count);
Assert.Equal(3, headers.GetValues("Expect").Count());
Assert.True(headers.ExpectContinue == true, "ExpectContinue == true");
Assert.Equal(new NameValueWithParametersHeaderValue("custom1"), headers.Expect.ElementAt(0));
Assert.Equal(new NameValueWithParametersHeaderValue("custom2"), headers.Expect.ElementAt(1));
// Remove '100-continue' value from store. But leave other 'Expect' values.
headers.ExpectContinue = false;
Assert.True(headers.ExpectContinue == false, "ExpectContinue == false");
Assert.Equal(2, headers.Expect.Count);
Assert.Equal(new NameValueWithParametersHeaderValue("custom1"), headers.Expect.ElementAt(0));
Assert.Equal(new NameValueWithParametersHeaderValue("custom2"), headers.Expect.ElementAt(1));
headers.ExpectContinue = true;
headers.Expect.Clear();
Assert.True(headers.ExpectContinue == false, "ExpectContinue should be modified by Expect.Clear().");
Assert.Equal(0, headers.Expect.Count);
IEnumerable<string> dummyArray;
Assert.False(headers.TryGetValues("Expect", out dummyArray), "Expect header count after Expect.Clear().");
// Remove '100-continue' value from store. Since there are no other 'Expect' values, remove whole header.
headers.ExpectContinue = false;
Assert.True(headers.ExpectContinue == false, "ExpectContinue == false");
Assert.Equal(0, headers.Expect.Count);
Assert.False(headers.Contains("Expect"));
headers.ExpectContinue = null;
Assert.Null(headers.ExpectContinue);
}
[Fact]
public void Expect_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
headers.TryAddWithoutValidation("Expect",
", , 100-continue, name1 = value1, name2; param2=paramValue2, name3=value3; param3 ,");
// Connection collection has 3 values plus '100-continue'
Assert.Equal(4, headers.Expect.Count);
Assert.Equal(4, headers.GetValues("Expect").Count());
Assert.True(headers.ExpectContinue == true, "ExpectContinue expected to be true.");
Assert.Equal(new NameValueWithParametersHeaderValue("100-continue"),
headers.Expect.ElementAt(0));
Assert.Equal(new NameValueWithParametersHeaderValue("name1", "value1"),
headers.Expect.ElementAt(1));
NameValueWithParametersHeaderValue expected2 = new NameValueWithParametersHeaderValue("name2");
expected2.Parameters.Add(new NameValueHeaderValue("param2", "paramValue2"));
Assert.Equal(expected2, headers.Expect.ElementAt(2));
NameValueWithParametersHeaderValue expected3 = new NameValueWithParametersHeaderValue("name3", "value3");
expected3.Parameters.Add(new NameValueHeaderValue("param3"));
Assert.Equal(expected3, headers.Expect.ElementAt(3));
headers.Expect.Clear();
Assert.Null(headers.ExpectContinue);
Assert.Equal(0, headers.Expect.Count);
IEnumerable<string> dummyArray;
Assert.False(headers.TryGetValues("Expect", out dummyArray), "Expect header count after Expect.Clear().");
}
[Fact]
public void Expect_UseAddMethodWithInvalidValue_InvalidValueRecognized()
{
headers.TryAddWithoutValidation("Expect", "100-continue other"); // no separator
Assert.Equal(0, headers.Expect.Count);
Assert.Equal(1, headers.GetValues("Expect").Count());
Assert.Equal("100-continue other", headers.GetValues("Expect").First());
}
[Fact]
public void Host_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Null(headers.Host);
headers.Host = "host";
Assert.Equal("host", headers.Host);
headers.Host = null;
Assert.Null(headers.Host);
Assert.False(headers.Contains("Host"),
"Header store should not contain a header 'Host' after setting it to null.");
Assert.Throws<FormatException>(() => { headers.Host = "invalid host"; });
}
[Fact]
public void Host_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
headers.TryAddWithoutValidation("Host", "host:80");
Assert.Equal("host:80", headers.Host);
}
[Fact]
public void IfMatch_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Equal(0, headers.IfMatch.Count);
headers.IfMatch.Add(new EntityTagHeaderValue("\"custom1\""));
headers.IfMatch.Add(new EntityTagHeaderValue("\"custom2\"", true));
Assert.Equal(2, headers.IfMatch.Count);
Assert.Equal(2, headers.GetValues("If-Match").Count());
Assert.Equal(new EntityTagHeaderValue("\"custom1\""), headers.IfMatch.ElementAt(0));
Assert.Equal(new EntityTagHeaderValue("\"custom2\"", true), headers.IfMatch.ElementAt(1));
headers.IfMatch.Clear();
Assert.Equal(0, headers.IfMatch.Count);
Assert.False(headers.Contains("If-Match"), "Header store should not contain 'If-Match'");
}
[Fact]
public void IfMatch_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
headers.TryAddWithoutValidation("If-Match", ", , W/\"tag1\", \"tag2\", W/\"tag3\" ,");
Assert.Equal(3, headers.IfMatch.Count);
Assert.Equal(3, headers.GetValues("If-Match").Count());
Assert.Equal(new EntityTagHeaderValue("\"tag1\"", true), headers.IfMatch.ElementAt(0));
Assert.Equal(new EntityTagHeaderValue("\"tag2\"", false), headers.IfMatch.ElementAt(1));
Assert.Equal(new EntityTagHeaderValue("\"tag3\"", true), headers.IfMatch.ElementAt(2));
headers.IfMatch.Clear();
headers.Add("If-Match", "*");
Assert.Equal(1, headers.IfMatch.Count);
Assert.Same(EntityTagHeaderValue.Any, headers.IfMatch.ElementAt(0));
}
[Fact]
public void IfMatch_UseAddMethodWithInvalidInput_PropertyNotUpdated()
{
headers.TryAddWithoutValidation("If-Match", "W/\"tag1\" \"tag2\""); // no separator
Assert.Equal(0, headers.IfMatch.Count);
Assert.Equal(1, headers.GetValues("If-Match").Count());
}
[Fact]
public void IfNoneMatch_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Equal(0, headers.IfNoneMatch.Count);
headers.IfNoneMatch.Add(new EntityTagHeaderValue("\"custom1\""));
headers.IfNoneMatch.Add(new EntityTagHeaderValue("\"custom2\"", true));
Assert.Equal(2, headers.IfNoneMatch.Count);
Assert.Equal(2, headers.GetValues("If-None-Match").Count());
Assert.Equal(new EntityTagHeaderValue("\"custom1\""), headers.IfNoneMatch.ElementAt(0));
Assert.Equal(new EntityTagHeaderValue("\"custom2\"", true), headers.IfNoneMatch.ElementAt(1));
headers.IfNoneMatch.Clear();
Assert.Equal(0, headers.IfNoneMatch.Count);
Assert.False(headers.Contains("If-None-Match"), "Header store should not contain 'If-None-Match'");
}
[Fact]
public void IfNoneMatch_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
headers.TryAddWithoutValidation("If-None-Match", "W/\"tag1\", \"tag2\", W/\"tag3\"");
Assert.Equal(3, headers.IfNoneMatch.Count);
Assert.Equal(3, headers.GetValues("If-None-Match").Count());
Assert.Equal(new EntityTagHeaderValue("\"tag1\"", true), headers.IfNoneMatch.ElementAt(0));
Assert.Equal(new EntityTagHeaderValue("\"tag2\"", false), headers.IfNoneMatch.ElementAt(1));
Assert.Equal(new EntityTagHeaderValue("\"tag3\"", true), headers.IfNoneMatch.ElementAt(2));
headers.IfNoneMatch.Clear();
headers.Add("If-None-Match", "*");
Assert.Equal(1, headers.IfNoneMatch.Count);
Assert.Same(EntityTagHeaderValue.Any, headers.IfNoneMatch.ElementAt(0));
}
[Fact]
public void TE_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
TransferCodingWithQualityHeaderValue value1 = new TransferCodingWithQualityHeaderValue("custom");
value1.Quality = 0.5;
value1.Parameters.Add(new NameValueHeaderValue("name", "value"));
TransferCodingWithQualityHeaderValue value2 = new TransferCodingWithQualityHeaderValue("custom");
value2.Quality = 0.3868;
Assert.Equal(0, headers.TE.Count);
headers.TE.Add(value1);
headers.TE.Add(value2);
Assert.Equal(2, headers.TE.Count);
Assert.Equal(value1, headers.TE.ElementAt(0));
Assert.Equal(value2, headers.TE.ElementAt(1));
headers.TE.Clear();
Assert.Equal(0, headers.TE.Count);
}
[Fact]
public void TE_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
headers.TryAddWithoutValidation("TE",
",custom1; param1=value1; q=1.0,,\r\n custom2; param2=value2; q=0.5 ,");
TransferCodingWithQualityHeaderValue value1 = new TransferCodingWithQualityHeaderValue("custom1");
value1.Parameters.Add(new NameValueHeaderValue("param1", "value1"));
value1.Quality = 1.0;
TransferCodingWithQualityHeaderValue value2 = new TransferCodingWithQualityHeaderValue("custom2");
value2.Parameters.Add(new NameValueHeaderValue("param2", "value2"));
value2.Quality = 0.5;
Assert.Equal(value1, headers.TE.ElementAt(0));
Assert.Equal(value2, headers.TE.ElementAt(1));
headers.Clear();
headers.TryAddWithoutValidation("TE", "");
Assert.False(headers.Contains("TE"), "'TE' header should not be added if it just has empty values.");
}
[Fact]
public void Range_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Null(headers.Range);
RangeHeaderValue value = new RangeHeaderValue(1, 2);
headers.Range = value;
Assert.Equal(value, headers.Range);
headers.Range = null;
Assert.Null(headers.Range);
}
[Fact]
public void Range_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
headers.TryAddWithoutValidation("Range", "custom= , ,1-2, -4 , ");
RangeHeaderValue value = new RangeHeaderValue();
value.Unit = "custom";
value.Ranges.Add(new RangeItemHeaderValue(1, 2));
value.Ranges.Add(new RangeItemHeaderValue(null, 4));
Assert.Equal(value, headers.Range);
}
[Fact]
public void Authorization_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Null(headers.Authorization);
headers.Authorization = new AuthenticationHeaderValue("Basic", "QWxhZGRpbjpvcGVuIHNlc2FtZQ==");
Assert.Equal(new AuthenticationHeaderValue("Basic", "QWxhZGRpbjpvcGVuIHNlc2FtZQ=="), headers.Authorization);
headers.Authorization = null;
Assert.Null(headers.Authorization);
Assert.False(headers.Contains("Authorization"),
"Header store should not contain a header 'Authorization' after setting it to null.");
}
[Fact]
public void Authorization_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
headers.TryAddWithoutValidation("Authorization", "NTLM blob");
Assert.Equal(new AuthenticationHeaderValue("NTLM", "blob"), headers.Authorization);
}
[Fact]
public void ProxyAuthorization_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Null(headers.ProxyAuthorization);
headers.ProxyAuthorization = new AuthenticationHeaderValue("Basic", "QWxhZGRpbjpvcGVuIHNlc2FtZQ==");
Assert.Equal(new AuthenticationHeaderValue("Basic", "QWxhZGRpbjpvcGVuIHNlc2FtZQ=="),
headers.ProxyAuthorization);
headers.ProxyAuthorization = null;
Assert.Null(headers.ProxyAuthorization);
Assert.False(headers.Contains("ProxyAuthorization"),
"Header store should not contain a header 'ProxyAuthorization' after setting it to null.");
}
[Fact]
public void ProxyAuthorization_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
headers.TryAddWithoutValidation("Proxy-Authorization", "NTLM blob");
Assert.Equal(new AuthenticationHeaderValue("NTLM", "blob"), headers.ProxyAuthorization);
}
[Fact]
public void UserAgent_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Equal(0, headers.UserAgent.Count);
headers.UserAgent.Add(new ProductInfoHeaderValue("(custom1)"));
headers.UserAgent.Add(new ProductInfoHeaderValue("custom2", "1.1"));
Assert.Equal(2, headers.UserAgent.Count);
Assert.Equal(2, headers.GetValues("User-Agent").Count());
Assert.Equal(new ProductInfoHeaderValue("(custom1)"), headers.UserAgent.ElementAt(0));
Assert.Equal(new ProductInfoHeaderValue("custom2", "1.1"), headers.UserAgent.ElementAt(1));
headers.UserAgent.Clear();
Assert.Equal(0, headers.UserAgent.Count);
Assert.False(headers.Contains("User-Agent"), "User-Agent header should be removed after calling Clear().");
headers.UserAgent.Add(new ProductInfoHeaderValue("(comment)"));
headers.UserAgent.Remove(new ProductInfoHeaderValue("(comment)"));
Assert.Equal(0, headers.UserAgent.Count);
Assert.False(headers.Contains("User-Agent"), "User-Agent header should be removed after removing last value.");
}
[Fact]
public void UserAgent_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
headers.TryAddWithoutValidation("User-Agent", "Opera/9.80 (Windows NT 6.1; U; en) Presto/2.6.30 Version/10.63");
Assert.Equal(4, headers.UserAgent.Count);
Assert.Equal(4, headers.GetValues("User-Agent").Count());
Assert.Equal(new ProductInfoHeaderValue("Opera", "9.80"), headers.UserAgent.ElementAt(0));
Assert.Equal(new ProductInfoHeaderValue("(Windows NT 6.1; U; en)"), headers.UserAgent.ElementAt(1));
Assert.Equal(new ProductInfoHeaderValue("Presto", "2.6.30"), headers.UserAgent.ElementAt(2));
Assert.Equal(new ProductInfoHeaderValue("Version", "10.63"), headers.UserAgent.ElementAt(3));
headers.UserAgent.Clear();
Assert.Equal(0, headers.UserAgent.Count);
Assert.False(headers.Contains("User-Agent"), "User-Agent header should be removed after calling Clear().");
}
[Fact]
public void UserAgent_UseAddMethodWithInvalidValue_InvalidValueRecognized()
{
headers.TryAddWithoutValidation("User-Agent", "custom\u4F1A");
Assert.Null(headers.GetParsedValues("User-Agent"));
Assert.Equal(1, headers.GetValues("User-Agent").Count());
Assert.Equal("custom\u4F1A", headers.GetValues("User-Agent").First());
headers.Clear();
// Note that "User-Agent" uses whitespaces as separators, so the following is an invalid value
headers.TryAddWithoutValidation("User-Agent", "custom1, custom2");
Assert.Null(headers.GetParsedValues("User-Agent"));
Assert.Equal(1, headers.GetValues("User-Agent").Count());
Assert.Equal("custom1, custom2", headers.GetValues("User-Agent").First());
headers.Clear();
headers.TryAddWithoutValidation("User-Agent", "custom1, ");
Assert.Null(headers.GetParsedValues("User-Agent"));
Assert.Equal(1, headers.GetValues("User-Agent").Count());
Assert.Equal("custom1, ", headers.GetValues("User-Agent").First());
headers.Clear();
headers.TryAddWithoutValidation("User-Agent", ",custom1");
Assert.Null(headers.GetParsedValues("User-Agent"));
Assert.Equal(1, headers.GetValues("User-Agent").Count());
Assert.Equal(",custom1", headers.GetValues("User-Agent").First());
}
[Fact]
public void UserAgent_AddMultipleValuesAndGetValueString_AllValuesAddedUsingTheCorrectDelimiter()
{
headers.TryAddWithoutValidation("User-Agent", "custom\u4F1A");
headers.Add("User-Agent", "custom2/1.1");
headers.UserAgent.Add(new ProductInfoHeaderValue("(comment)"));
foreach (var header in headers.GetHeaderStrings())
{
Assert.Equal("User-Agent", header.Key);
Assert.Equal("custom2/1.1 (comment) custom\u4F1A", header.Value);
}
}
[Fact]
public void IfRange_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Null(headers.IfRange);
headers.IfRange = new RangeConditionHeaderValue("\"x\"");
Assert.Equal(1, headers.GetValues("If-Range").Count());
Assert.Equal(new RangeConditionHeaderValue("\"x\""), headers.IfRange);
headers.IfRange = null;
Assert.Null(headers.IfRange);
Assert.False(headers.Contains("If-Range"), "If-Range header should be removed after calling Clear().");
}
[Fact]
public void IfRange_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
headers.TryAddWithoutValidation("If-Range", " W/\"tag\" ");
Assert.Equal(new RangeConditionHeaderValue(new EntityTagHeaderValue("\"tag\"", true)),
headers.IfRange);
Assert.Equal(1, headers.GetValues("If-Range").Count());
headers.IfRange = null;
Assert.Null(headers.IfRange);
Assert.False(headers.Contains("If-Range"), "If-Range header should be removed after calling Clear().");
}
[Fact]
public void IfRange_UseAddMethodWithInvalidValue_InvalidValueRecognized()
{
headers.TryAddWithoutValidation("If-Range", "\"tag\"\u4F1A");
Assert.Null(headers.GetParsedValues("If-Range"));
Assert.Equal(1, headers.GetValues("If-Range").Count());
Assert.Equal("\"tag\"\u4F1A", headers.GetValues("If-Range").First());
headers.Clear();
headers.TryAddWithoutValidation("If-Range", " \"tag\", ");
Assert.Null(headers.GetParsedValues("If-Range"));
Assert.Equal(1, headers.GetValues("If-Range").Count());
Assert.Equal(" \"tag\", ", headers.GetValues("If-Range").First());
}
[Fact]
public void From_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Null(headers.From);
headers.From = "[email protected]";
Assert.Equal("[email protected]", headers.From);
headers.From = null;
Assert.Null(headers.From);
Assert.False(headers.Contains("From"),
"Header store should not contain a header 'From' after setting it to null.");
Assert.Throws<FormatException>(() => { headers.From = " "; });
Assert.Throws<FormatException>(() => { headers.From = "invalid email address"; });
}
[Fact]
public void From_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
headers.TryAddWithoutValidation("From", " \"My Name\" [email protected] ");
Assert.Equal("\"My Name\" [email protected] ", headers.From);
// The following encoded string represents the character sequence "\u4F1A\u5458\u670D\u52A1".
headers.Clear();
headers.TryAddWithoutValidation("From", "=?utf-8?Q?=E4=BC=9A=E5=91=98=E6=9C=8D=E5=8A=A1?= <[email protected]>");
Assert.Equal("=?utf-8?Q?=E4=BC=9A=E5=91=98=E6=9C=8D=E5=8A=A1?= <[email protected]>", headers.From);
}
[Fact]
public void From_UseAddMethodWithInvalidValue_InvalidValueRecognized()
{
headers.TryAddWithoutValidation("From", " [email protected] ,");
Assert.Null(headers.GetParsedValues("From"));
Assert.Equal(1, headers.GetValues("From").Count());
Assert.Equal(" [email protected] ,", headers.GetValues("From").First());
headers.Clear();
headers.TryAddWithoutValidation("From", "info@");
Assert.Null(headers.GetParsedValues("From"));
Assert.Equal(1, headers.GetValues("From").Count());
Assert.Equal("info@", headers.GetValues("From").First());
}
[Fact]
public void IfModifiedSince_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Null(headers.IfModifiedSince);
DateTimeOffset expected = DateTimeOffset.Now;
headers.IfModifiedSince = expected;
Assert.Equal(expected, headers.IfModifiedSince);
headers.IfModifiedSince = null;
Assert.Null(headers.IfModifiedSince);
Assert.False(headers.Contains("If-Modified-Since"),
"Header store should not contain a header 'IfModifiedSince' after setting it to null.");
}
[Fact]
public void IfModifiedSince_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
headers.TryAddWithoutValidation("If-Modified-Since", " Sun, 06 Nov 1994 08:49:37 GMT ");
Assert.Equal(new DateTimeOffset(1994, 11, 6, 8, 49, 37, TimeSpan.Zero), headers.IfModifiedSince);
headers.Clear();
headers.TryAddWithoutValidation("If-Modified-Since", "Sun, 06 Nov 1994 08:49:37 GMT");
Assert.Equal(new DateTimeOffset(1994, 11, 6, 8, 49, 37, TimeSpan.Zero), headers.IfModifiedSince);
}
[Fact]
public void IfModifiedSince_UseAddMethodWithInvalidValue_InvalidValueRecognized()
{
headers.TryAddWithoutValidation("If-Modified-Since", " Sun, 06 Nov 1994 08:49:37 GMT ,");
Assert.Null(headers.GetParsedValues("If-Modified-Since"));
Assert.Equal(1, headers.GetValues("If-Modified-Since").Count());
Assert.Equal(" Sun, 06 Nov 1994 08:49:37 GMT ,", headers.GetValues("If-Modified-Since").First());
headers.Clear();
headers.TryAddWithoutValidation("If-Modified-Since", " Sun, 06 Nov ");
Assert.Null(headers.GetParsedValues("If-Modified-Since"));
Assert.Equal(1, headers.GetValues("If-Modified-Since").Count());
Assert.Equal(" Sun, 06 Nov ", headers.GetValues("If-Modified-Since").First());
}
[Fact]
public void IfUnmodifiedSince_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Null(headers.IfUnmodifiedSince);
DateTimeOffset expected = DateTimeOffset.Now;
headers.IfUnmodifiedSince = expected;
Assert.Equal(expected, headers.IfUnmodifiedSince);
headers.IfUnmodifiedSince = null;
Assert.Null(headers.IfUnmodifiedSince);
Assert.False(headers.Contains("If-Unmodified-Since"),
"Header store should not contain a header 'IfUnmodifiedSince' after setting it to null.");
}
[Fact]
public void IfUnmodifiedSince_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
headers.TryAddWithoutValidation("If-Unmodified-Since", " Sun, 06 Nov 1994 08:49:37 GMT ");
Assert.Equal(new DateTimeOffset(1994, 11, 6, 8, 49, 37, TimeSpan.Zero), headers.IfUnmodifiedSince);
headers.Clear();
headers.TryAddWithoutValidation("If-Unmodified-Since", "Sun, 06 Nov 1994 08:49:37 GMT");
Assert.Equal(new DateTimeOffset(1994, 11, 6, 8, 49, 37, TimeSpan.Zero), headers.IfUnmodifiedSince);
}
[Fact]
public void IfUnmodifiedSince_UseAddMethodWithInvalidValue_InvalidValueRecognized()
{
headers.TryAddWithoutValidation("If-Unmodified-Since", " Sun, 06 Nov 1994 08:49:37 GMT ,");
Assert.Null(headers.GetParsedValues("If-Unmodified-Since"));
Assert.Equal(1, headers.GetValues("If-Unmodified-Since").Count());
Assert.Equal(" Sun, 06 Nov 1994 08:49:37 GMT ,", headers.GetValues("If-Unmodified-Since").First());
headers.Clear();
headers.TryAddWithoutValidation("If-Unmodified-Since", " Sun, 06 Nov ");
Assert.Null(headers.GetParsedValues("If-Unmodified-Since"));
Assert.Equal(1, headers.GetValues("If-Unmodified-Since").Count());
Assert.Equal(" Sun, 06 Nov ", headers.GetValues("If-Unmodified-Since").First());
}
[Fact]
public void Referrer_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Null(headers.Referrer);
Uri expected = new Uri("http://example.com/path/");
headers.Referrer = expected;
Assert.Equal(expected, headers.Referrer);
headers.Referrer = null;
Assert.Null(headers.Referrer);
Assert.False(headers.Contains("Referer"),
"Header store should not contain a header 'Referrer' after setting it to null.");
}
[Fact]
public void Referrer_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
headers.TryAddWithoutValidation("Referer", " http://www.example.com/path/?q=v ");
Assert.Equal(new Uri("http://www.example.com/path/?q=v"), headers.Referrer);
headers.Clear();
headers.TryAddWithoutValidation("Referer", "/relative/uri/");
Assert.Equal(new Uri("/relative/uri/", UriKind.Relative), headers.Referrer);
}
[Fact]
public void Referrer_UseAddMethodWithInvalidValue_InvalidValueRecognized()
{
headers.TryAddWithoutValidation("Referer", " http://example.com http://other");
Assert.Null(headers.GetParsedValues("Referer"));
Assert.Equal(1, headers.GetValues("Referer").Count());
Assert.Equal(" http://example.com http://other", headers.GetValues("Referer").First());
headers.Clear();
headers.TryAddWithoutValidation("Referer", "http://host /other");
Assert.Null(headers.GetParsedValues("Referer"));
Assert.Equal(1, headers.GetValues("Referer").Count());
Assert.Equal("http://host /other", headers.GetValues("Referer").First());
}
[Fact]
public void MaxForwards_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Null(headers.MaxForwards);
headers.MaxForwards = 15;
Assert.Equal(15, headers.MaxForwards);
headers.MaxForwards = null;
Assert.Null(headers.MaxForwards);
Assert.False(headers.Contains("Max-Forwards"),
"Header store should not contain a header 'MaxForwards' after setting it to null.");
// Make sure the header gets serialized correctly
headers.MaxForwards = 12345;
Assert.Equal("12345", headers.GetValues("Max-Forwards").First());
}
[Fact]
public void MaxForwards_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
headers.TryAddWithoutValidation("Max-Forwards", " 00123 ");
Assert.Equal(123, headers.MaxForwards);
headers.Clear();
headers.TryAddWithoutValidation("Max-Forwards", "0");
Assert.Equal(0, headers.MaxForwards);
}
[Fact]
public void MaxForwards_UseAddMethodWithInvalidValue_InvalidValueRecognized()
{
headers.TryAddWithoutValidation("Max-Forwards", "15,");
Assert.Null(headers.GetParsedValues("Max-Forwards"));
Assert.Equal(1, headers.GetValues("Max-Forwards").Count());
Assert.Equal("15,", headers.GetValues("Max-Forwards").First());
headers.Clear();
headers.TryAddWithoutValidation("Max-Forwards", "1.0");
Assert.Null(headers.GetParsedValues("Max-Forwards"));
Assert.Equal(1, headers.GetValues("Max-Forwards").Count());
Assert.Equal("1.0", headers.GetValues("Max-Forwards").First());
}
[Fact]
public void AddHeaders_SpecialHeaderValuesOnSourceNotOnDestination_Copied()
{
// Positive
HttpRequestHeaders source = new HttpRequestHeaders();
source.ExpectContinue = true;
source.TransferEncodingChunked = true;
source.ConnectionClose = true;
HttpRequestHeaders destination = new HttpRequestHeaders();
Assert.Null(destination.ExpectContinue);
Assert.Null(destination.TransferEncodingChunked);
Assert.Null(destination.ConnectionClose);
destination.AddHeaders(source);
Assert.NotNull(destination.ExpectContinue);
Assert.NotNull(destination.TransferEncodingChunked);
Assert.NotNull(destination.ConnectionClose);
Assert.True(destination.ExpectContinue.Value);
Assert.True(destination.TransferEncodingChunked.Value);
Assert.True(destination.ConnectionClose.Value);
// Negitive
source = new HttpRequestHeaders();
source.ExpectContinue = false;
source.TransferEncodingChunked = false;
source.ConnectionClose = false;
destination = new HttpRequestHeaders();
Assert.Null(destination.ExpectContinue);
Assert.Null(destination.TransferEncodingChunked);
Assert.Null(destination.ConnectionClose);
destination.AddHeaders(source);
Assert.NotNull(destination.ExpectContinue);
Assert.NotNull(destination.TransferEncodingChunked);
Assert.NotNull(destination.ConnectionClose);
Assert.False(destination.ExpectContinue.Value);
Assert.False(destination.TransferEncodingChunked.Value);
Assert.False(destination.ConnectionClose.Value);
}
[Fact]
public void AddHeaders_SpecialHeaderValuesOnDestinationNotOnSource_NotCopied()
{
// Positive
HttpRequestHeaders destination = new HttpRequestHeaders();
destination.ExpectContinue = true;
destination.TransferEncodingChunked = true;
destination.ConnectionClose = true;
Assert.NotNull(destination.ExpectContinue);
Assert.NotNull(destination.TransferEncodingChunked);
Assert.NotNull(destination.ConnectionClose);
Assert.True(destination.ExpectContinue.Value);
Assert.True(destination.TransferEncodingChunked.Value);
Assert.True(destination.ConnectionClose.Value);
HttpRequestHeaders source = new HttpRequestHeaders();
Assert.Null(source.ExpectContinue);
Assert.Null(source.TransferEncodingChunked);
Assert.Null(source.ConnectionClose);
destination.AddHeaders(source);
Assert.Null(source.ExpectContinue);
Assert.Null(source.TransferEncodingChunked);
Assert.Null(source.ConnectionClose);
Assert.NotNull(destination.ExpectContinue);
Assert.NotNull(destination.TransferEncodingChunked);
Assert.NotNull(destination.ConnectionClose);
Assert.True(destination.ExpectContinue.Value);
Assert.True(destination.TransferEncodingChunked.Value);
Assert.True(destination.ConnectionClose.Value);
// Negitive
destination = new HttpRequestHeaders();
destination.ExpectContinue = false;
destination.TransferEncodingChunked = false;
destination.ConnectionClose = false;
Assert.NotNull(destination.ExpectContinue);
Assert.NotNull(destination.TransferEncodingChunked);
Assert.NotNull(destination.ConnectionClose);
Assert.False(destination.ExpectContinue.Value);
Assert.False(destination.TransferEncodingChunked.Value);
Assert.False(destination.ConnectionClose.Value);
source = new HttpRequestHeaders();
Assert.Null(source.ExpectContinue);
Assert.Null(source.TransferEncodingChunked);
Assert.Null(source.ConnectionClose);
destination.AddHeaders(source);
Assert.Null(source.ExpectContinue);
Assert.Null(source.TransferEncodingChunked);
Assert.Null(source.ConnectionClose);
Assert.NotNull(destination.ExpectContinue);
Assert.NotNull(destination.TransferEncodingChunked);
Assert.NotNull(destination.ConnectionClose);
Assert.False(destination.ExpectContinue.Value);
Assert.False(destination.TransferEncodingChunked.Value);
Assert.False(destination.ConnectionClose.Value);
}
#endregion
#region General headers
[Fact]
public void Connection_AddClose_Success()
{
headers.Connection.Add("CLOSE"); // use non-default casing to make sure we do case-insensitive comparison.
Assert.True(headers.ConnectionClose == true);
Assert.Equal(1, headers.Connection.Count);
}
[Fact]
public void Connection_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Equal(0, headers.Connection.Count);
Assert.Null(headers.ConnectionClose);
headers.Connection.Add("custom1");
headers.Connection.Add("custom2");
headers.ConnectionClose = true;
// Connection collection has 2 values plus 'close'
Assert.Equal(3, headers.Connection.Count);
Assert.Equal(3, headers.GetValues("Connection").Count());
Assert.True(headers.ConnectionClose == true, "ConnectionClose");
Assert.Equal("custom1", headers.Connection.ElementAt(0));
Assert.Equal("custom2", headers.Connection.ElementAt(1));
// Remove 'close' value from store. But leave other 'Connection' values.
headers.ConnectionClose = false;
Assert.True(headers.ConnectionClose == false, "ConnectionClose == false");
Assert.Equal(2, headers.Connection.Count);
Assert.Equal("custom1", headers.Connection.ElementAt(0));
Assert.Equal("custom2", headers.Connection.ElementAt(1));
headers.ConnectionClose = true;
headers.Connection.Clear();
Assert.True(headers.ConnectionClose == false,
"ConnectionClose should be modified by Connection.Clear().");
Assert.Equal(0, headers.Connection.Count);
IEnumerable<string> dummyArray;
Assert.False(headers.TryGetValues("Connection", out dummyArray),
"Connection header count after Connection.Clear().");
// Remove 'close' value from store. Since there are no other 'Connection' values, remove whole header.
headers.ConnectionClose = false;
Assert.True(headers.ConnectionClose == false, "ConnectionClose == false");
Assert.Equal(0, headers.Connection.Count);
Assert.False(headers.Contains("Connection"));
headers.ConnectionClose = null;
Assert.Null(headers.ConnectionClose);
}
[Fact]
public void Connection_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
headers.TryAddWithoutValidation("Connection", "custom1, close, custom2, custom3");
// Connection collection has 3 values plus 'close'
Assert.Equal(4, headers.Connection.Count);
Assert.Equal(4, headers.GetValues("Connection").Count());
Assert.True(headers.ConnectionClose == true);
Assert.Equal("custom1", headers.Connection.ElementAt(0));
Assert.Equal("close", headers.Connection.ElementAt(1));
Assert.Equal("custom2", headers.Connection.ElementAt(2));
Assert.Equal("custom3", headers.Connection.ElementAt(3));
headers.Connection.Clear();
Assert.Null(headers.ConnectionClose);
Assert.Equal(0, headers.Connection.Count);
IEnumerable<string> dummyArray;
Assert.False(headers.TryGetValues("Connection", out dummyArray),
"Connection header count after Connection.Clear().");
}
[Fact]
public void Connection_AddInvalidValue_Throw()
{
Assert.Throws<FormatException>(() => { headers.Connection.Add("this is invalid"); });
}
[Fact]
public void TransferEncoding_AddChunked_Success()
{
// use non-default casing to make sure we do case-insensitive comparison.
headers.TransferEncoding.Add(new TransferCodingHeaderValue("CHUNKED"));
Assert.True(headers.TransferEncodingChunked == true);
Assert.Equal(1, headers.TransferEncoding.Count);
}
[Fact]
public void TransferEncoding_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Equal(0, headers.TransferEncoding.Count);
Assert.Null(headers.TransferEncodingChunked);
headers.TransferEncoding.Add(new TransferCodingHeaderValue("custom1"));
headers.TransferEncoding.Add(new TransferCodingHeaderValue("custom2"));
headers.TransferEncodingChunked = true;
// Connection collection has 2 values plus 'chunked'
Assert.Equal(3, headers.TransferEncoding.Count);
Assert.Equal(3, headers.GetValues("Transfer-Encoding").Count());
Assert.Equal(true, headers.TransferEncodingChunked);
Assert.Equal(new TransferCodingHeaderValue("custom1"), headers.TransferEncoding.ElementAt(0));
Assert.Equal(new TransferCodingHeaderValue("custom2"), headers.TransferEncoding.ElementAt(1));
// Remove 'chunked' value from store. But leave other 'Transfer-Encoding' values. Note that according to
// the RFC this is not valid, since 'chunked' must always be present. However this check is done
// in the transport handler since the user can add invalid header values anyways.
headers.TransferEncodingChunked = false;
Assert.True(headers.TransferEncodingChunked == false, "TransferEncodingChunked == false");
Assert.Equal(2, headers.TransferEncoding.Count);
Assert.Equal(new TransferCodingHeaderValue("custom1"), headers.TransferEncoding.ElementAt(0));
Assert.Equal(new TransferCodingHeaderValue("custom2"), headers.TransferEncoding.ElementAt(1));
headers.TransferEncodingChunked = true;
headers.TransferEncoding.Clear();
Assert.True(headers.TransferEncodingChunked == false,
"TransferEncodingChunked should be modified by TransferEncoding.Clear().");
Assert.Equal(0, headers.TransferEncoding.Count);
Assert.False(headers.Contains("Transfer-Encoding"));
// Remove 'chunked' value from store. Since there are no other 'Transfer-Encoding' values, remove whole
// header.
headers.TransferEncodingChunked = false;
Assert.True(headers.TransferEncodingChunked == false, "TransferEncodingChunked == false");
Assert.Equal(0, headers.TransferEncoding.Count);
Assert.False(headers.Contains("Transfer-Encoding"));
headers.TransferEncodingChunked = null;
Assert.Null(headers.TransferEncodingChunked);
}
[Fact]
public void TransferEncoding_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
headers.TryAddWithoutValidation("Transfer-Encoding", " , custom1, , custom2, custom3, chunked ,");
// Connection collection has 3 values plus 'chunked'
Assert.Equal(4, headers.TransferEncoding.Count);
Assert.Equal(4, headers.GetValues("Transfer-Encoding").Count());
Assert.True(headers.TransferEncodingChunked == true, "TransferEncodingChunked expected to be true.");
Assert.Equal(new TransferCodingHeaderValue("custom1"), headers.TransferEncoding.ElementAt(0));
Assert.Equal(new TransferCodingHeaderValue("custom2"), headers.TransferEncoding.ElementAt(1));
Assert.Equal(new TransferCodingHeaderValue("custom3"), headers.TransferEncoding.ElementAt(2));
headers.TransferEncoding.Clear();
Assert.Null(headers.TransferEncodingChunked);
Assert.Equal(0, headers.TransferEncoding.Count);
Assert.False(headers.Contains("Transfer-Encoding"),
"Transfer-Encoding header after TransferEncoding.Clear().");
}
[Fact]
public void TransferEncoding_UseAddMethodWithInvalidValue_InvalidValueRecognized()
{
headers.TryAddWithoutValidation("Transfer-Encoding", "custom\u4F1A");
Assert.Null(headers.GetParsedValues("Transfer-Encoding"));
Assert.Equal(1, headers.GetValues("Transfer-Encoding").Count());
Assert.Equal("custom\u4F1A", headers.GetValues("Transfer-Encoding").First());
headers.Clear();
headers.TryAddWithoutValidation("Transfer-Encoding", "custom1 custom2");
Assert.Null(headers.GetParsedValues("Transfer-Encoding"));
Assert.Equal(1, headers.GetValues("Transfer-Encoding").Count());
Assert.Equal("custom1 custom2", headers.GetValues("Transfer-Encoding").First());
headers.Clear();
headers.TryAddWithoutValidation("Transfer-Encoding", "");
Assert.False(headers.Contains("Transfer-Encoding"), "'Transfer-Encoding' header should not be added if it just has empty values.");
}
[Fact]
public void Upgrade_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Equal(0, headers.Upgrade.Count);
headers.Upgrade.Add(new ProductHeaderValue("custom1"));
headers.Upgrade.Add(new ProductHeaderValue("custom2", "1.1"));
Assert.Equal(2, headers.Upgrade.Count);
Assert.Equal(2, headers.GetValues("Upgrade").Count());
Assert.Equal(new ProductHeaderValue("custom1"), headers.Upgrade.ElementAt(0));
Assert.Equal(new ProductHeaderValue("custom2", "1.1"), headers.Upgrade.ElementAt(1));
headers.Upgrade.Clear();
Assert.Equal(0, headers.Upgrade.Count);
Assert.False(headers.Contains("Upgrade"), "Upgrade header should be removed after calling Clear().");
}
[Fact]
public void Upgrade_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
headers.TryAddWithoutValidation("Upgrade", " , custom1 / 1.0, , custom2, custom3/2.0,");
Assert.Equal(3, headers.Upgrade.Count);
Assert.Equal(3, headers.GetValues("Upgrade").Count());
Assert.Equal(new ProductHeaderValue("custom1", "1.0"), headers.Upgrade.ElementAt(0));
Assert.Equal(new ProductHeaderValue("custom2"), headers.Upgrade.ElementAt(1));
Assert.Equal(new ProductHeaderValue("custom3", "2.0"), headers.Upgrade.ElementAt(2));
headers.Upgrade.Clear();
Assert.Equal(0, headers.Upgrade.Count);
Assert.False(headers.Contains("Upgrade"), "Upgrade header should be removed after calling Clear().");
}
[Fact]
public void Upgrade_UseAddMethodWithInvalidValue_InvalidValueRecognized()
{
headers.TryAddWithoutValidation("Upgrade", "custom\u4F1A");
Assert.Null(headers.GetParsedValues("Upgrade"));
Assert.Equal(1, headers.GetValues("Upgrade").Count());
Assert.Equal("custom\u4F1A", headers.GetValues("Upgrade").First());
headers.Clear();
headers.TryAddWithoutValidation("Upgrade", "custom1 custom2");
Assert.Null(headers.GetParsedValues("Upgrade"));
Assert.Equal(1, headers.GetValues("Upgrade").Count());
Assert.Equal("custom1 custom2", headers.GetValues("Upgrade").First());
}
[Fact]
public void Date_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Null(headers.Date);
DateTimeOffset expected = DateTimeOffset.Now;
headers.Date = expected;
Assert.Equal(expected, headers.Date);
headers.Date = null;
Assert.Null(headers.Date);
Assert.False(headers.Contains("Date"),
"Header store should not contain a header 'Date' after setting it to null.");
// Make sure the header gets serialized correctly
headers.Date = (new DateTimeOffset(1994, 11, 6, 8, 49, 37, TimeSpan.Zero));
Assert.Equal("Sun, 06 Nov 1994 08:49:37 GMT", headers.GetValues("Date").First());
}
[Fact]
public void Date_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
headers.TryAddWithoutValidation("Date", " Sun, 06 Nov 1994 08:49:37 GMT ");
Assert.Equal(new DateTimeOffset(1994, 11, 6, 8, 49, 37, TimeSpan.Zero), headers.Date);
headers.Clear();
headers.TryAddWithoutValidation("Date", "Sun, 06 Nov 1994 08:49:37 GMT");
Assert.Equal(new DateTimeOffset(1994, 11, 6, 8, 49, 37, TimeSpan.Zero), headers.Date);
}
[Fact]
public void Date_UseAddMethodWithInvalidValue_InvalidValueRecognized()
{
headers.TryAddWithoutValidation("Date", " Sun, 06 Nov 1994 08:49:37 GMT ,");
Assert.Null(headers.GetParsedValues("Date"));
Assert.Equal(1, headers.GetValues("Date").Count());
Assert.Equal(" Sun, 06 Nov 1994 08:49:37 GMT ,", headers.GetValues("Date").First());
headers.Clear();
headers.TryAddWithoutValidation("Date", " Sun, 06 Nov ");
Assert.Null(headers.GetParsedValues("Date"));
Assert.Equal(1, headers.GetValues("Date").Count());
Assert.Equal(" Sun, 06 Nov ", headers.GetValues("Date").First());
}
[Fact]
public void Via_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Equal(0, headers.Via.Count);
headers.Via.Add(new ViaHeaderValue("x11", "host"));
headers.Via.Add(new ViaHeaderValue("1.1", "example.com:8080", "HTTP", "(comment)"));
Assert.Equal(2, headers.Via.Count);
Assert.Equal(new ViaHeaderValue("x11", "host"), headers.Via.ElementAt(0));
Assert.Equal(new ViaHeaderValue("1.1", "example.com:8080", "HTTP", "(comment)"),
headers.Via.ElementAt(1));
headers.Via.Clear();
Assert.Equal(0, headers.Via.Count);
}
[Fact]
public void Via_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
headers.TryAddWithoutValidation("Via", ", 1.1 host, WS/1.0 [::1],X/11 192.168.0.1 (c(comment)) ");
Assert.Equal(new ViaHeaderValue("1.1", "host"), headers.Via.ElementAt(0));
Assert.Equal(new ViaHeaderValue("1.0", "[::1]", "WS"), headers.Via.ElementAt(1));
Assert.Equal(new ViaHeaderValue("11", "192.168.0.1", "X", "(c(comment))"), headers.Via.ElementAt(2));
headers.Via.Clear();
headers.TryAddWithoutValidation("Via", "");
Assert.Equal(0, headers.Via.Count);
Assert.False(headers.Contains("Via"));
}
[Fact]
public void Via_UseAddMethodWithInvalidValue_InvalidValueRecognized()
{
headers.TryAddWithoutValidation("Via", "1.1 host1 1.1 host2"); // no separator
Assert.Equal(0, headers.Via.Count);
Assert.Equal(1, headers.GetValues("Via").Count());
Assert.Equal("1.1 host1 1.1 host2", headers.GetValues("Via").First());
headers.Clear();
headers.TryAddWithoutValidation("Via", "X/11 host/1");
Assert.Equal(0, headers.Via.Count);
Assert.Equal(1, headers.GetValues("Via").Count());
Assert.Equal("X/11 host/1", headers.GetValues("Via").First());
}
[Fact]
public void Warning_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Equal(0, headers.Warning.Count);
headers.Warning.Add(new WarningHeaderValue(199, "microsoft.com", "\"Miscellaneous warning\""));
headers.Warning.Add(new WarningHeaderValue(113, "example.com", "\"Heuristic expiration\""));
Assert.Equal(2, headers.Warning.Count);
Assert.Equal(new WarningHeaderValue(199, "microsoft.com", "\"Miscellaneous warning\""),
headers.Warning.ElementAt(0));
Assert.Equal(new WarningHeaderValue(113, "example.com", "\"Heuristic expiration\""),
headers.Warning.ElementAt(1));
headers.Warning.Clear();
Assert.Equal(0, headers.Warning.Count);
}
[Fact]
public void Warning_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
headers.TryAddWithoutValidation("Warning",
"112 example.com \"Disconnected operation\", 111 example.org \"Revalidation failed\"");
Assert.Equal(new WarningHeaderValue(112, "example.com", "\"Disconnected operation\""),
headers.Warning.ElementAt(0));
Assert.Equal(new WarningHeaderValue(111, "example.org", "\"Revalidation failed\""),
headers.Warning.ElementAt(1));
headers.Warning.Clear();
headers.TryAddWithoutValidation("Warning", "");
Assert.Equal(0, headers.Warning.Count);
Assert.False(headers.Contains("Warning"));
}
[Fact]
public void Warning_UseAddMethodWithInvalidValue_InvalidValueRecognized()
{
headers.TryAddWithoutValidation("Warning", "123 host1 \"\" 456 host2 \"\""); // no separator
Assert.Equal(0, headers.Warning.Count);
Assert.Equal(1, headers.GetValues("Warning").Count());
Assert.Equal("123 host1 \"\" 456 host2 \"\"", headers.GetValues("Warning").First());
headers.Clear();
headers.TryAddWithoutValidation("Warning", "123 host1\"text\"");
Assert.Equal(0, headers.Warning.Count);
Assert.Equal(1, headers.GetValues("Warning").Count());
Assert.Equal("123 host1\"text\"", headers.GetValues("Warning").First());
}
[Fact]
public void CacheControl_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Null(headers.CacheControl);
CacheControlHeaderValue value = new CacheControlHeaderValue();
value.NoCache = true;
value.NoCacheHeaders.Add("token1");
value.NoCacheHeaders.Add("token2");
value.MustRevalidate = true;
value.SharedMaxAge = new TimeSpan(1, 2, 3);
headers.CacheControl = value;
Assert.Equal(value, headers.CacheControl);
headers.CacheControl = null;
Assert.Null(headers.CacheControl);
Assert.False(headers.Contains("Cache-Control"),
"Header store should not contain a header 'Cache-Control' after setting it to null.");
}
[Fact]
public void CacheControl_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
headers.TryAddWithoutValidation("Cache-Control", "no-cache=\"token1, token2\", must-revalidate, max-age=3");
headers.Add("Cache-Control", "");
headers.Add("Cache-Control", "public, s-maxage=15");
headers.TryAddWithoutValidation("Cache-Control", "");
CacheControlHeaderValue value = new CacheControlHeaderValue();
value.NoCache = true;
value.NoCacheHeaders.Add("token1");
value.NoCacheHeaders.Add("token2");
value.MustRevalidate = true;
value.MaxAge = new TimeSpan(0, 0, 3);
value.Public = true;
value.SharedMaxAge = new TimeSpan(0, 0, 15);
Assert.Equal(value, headers.CacheControl);
}
[Fact]
public void Trailer_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Equal(0, headers.Trailer.Count);
headers.Trailer.Add("custom1");
headers.Trailer.Add("custom2");
Assert.Equal(2, headers.Trailer.Count);
Assert.Equal(2, headers.GetValues("Trailer").Count());
Assert.Equal("custom1", headers.Trailer.ElementAt(0));
Assert.Equal("custom2", headers.Trailer.ElementAt(1));
headers.Trailer.Clear();
Assert.Equal(0, headers.Trailer.Count);
Assert.False(headers.Contains("Trailer"),
"There should be no Trailer header after calling Clear().");
}
[Fact]
public void Trailer_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
headers.TryAddWithoutValidation("Trailer", ",custom1, custom2, custom3,");
Assert.Equal(3, headers.Trailer.Count);
Assert.Equal(3, headers.GetValues("Trailer").Count());
Assert.Equal("custom1", headers.Trailer.ElementAt(0));
Assert.Equal("custom2", headers.Trailer.ElementAt(1));
Assert.Equal("custom3", headers.Trailer.ElementAt(2));
headers.Trailer.Clear();
Assert.Equal(0, headers.Trailer.Count);
Assert.False(headers.Contains("Trailer"),
"There should be no Trailer header after calling Clear().");
}
[Fact]
public void Trailer_UseAddMethodWithInvalidValue_InvalidValueRecognized()
{
headers.TryAddWithoutValidation("Trailer", "custom1 custom2"); // no separator
Assert.Equal(0, headers.Trailer.Count);
Assert.Equal(1, headers.GetValues("Trailer").Count());
Assert.Equal("custom1 custom2", headers.GetValues("Trailer").First());
}
[Fact]
public void Pragma_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Equal(0, headers.Pragma.Count);
headers.Pragma.Add(new NameValueHeaderValue("custom1", "value1"));
headers.Pragma.Add(new NameValueHeaderValue("custom2"));
Assert.Equal(2, headers.Pragma.Count);
Assert.Equal(2, headers.GetValues("Pragma").Count());
Assert.Equal(new NameValueHeaderValue("custom1", "value1"), headers.Pragma.ElementAt(0));
Assert.Equal(new NameValueHeaderValue("custom2"), headers.Pragma.ElementAt(1));
headers.Pragma.Clear();
Assert.Equal(0, headers.Pragma.Count);
Assert.False(headers.Contains("Pragma"),
"There should be no Pragma header after calling Clear().");
}
[Fact]
public void Pragma_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
headers.TryAddWithoutValidation("Pragma", ",custom1=value1, custom2, custom3=value3,");
Assert.Equal(3, headers.Pragma.Count);
Assert.Equal(3, headers.GetValues("Pragma").Count());
Assert.Equal(new NameValueHeaderValue("custom1", "value1"), headers.Pragma.ElementAt(0));
Assert.Equal(new NameValueHeaderValue("custom2"), headers.Pragma.ElementAt(1));
Assert.Equal(new NameValueHeaderValue("custom3", "value3"), headers.Pragma.ElementAt(2));
headers.Pragma.Clear();
Assert.Equal(0, headers.Pragma.Count);
Assert.False(headers.Contains("Pragma"),
"There should be no Pragma header after calling Clear().");
}
[Fact]
public void Pragma_UseAddMethodWithInvalidValue_InvalidValueRecognized()
{
headers.TryAddWithoutValidation("Pragma", "custom1, custom2=");
Assert.Equal(0, headers.Pragma.Count());
Assert.Equal(1, headers.GetValues("Pragma").Count());
Assert.Equal("custom1, custom2=", headers.GetValues("Pragma").First());
}
#endregion
[Fact]
public void ToString_SeveralRequestHeaders_Success()
{
HttpRequestMessage request = new HttpRequestMessage();
string expected = string.Empty;
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("*/xml"));
expected += HttpKnownHeaderNames.Accept + ": application/xml, */xml\r\n";
request.Headers.Authorization = new AuthenticationHeaderValue("Basic");
expected += HttpKnownHeaderNames.Authorization + ": Basic\r\n";
request.Headers.ExpectContinue = true;
expected += HttpKnownHeaderNames.Expect + ": 100-continue\r\n";
request.Headers.TransferEncodingChunked = true;
expected += HttpKnownHeaderNames.TransferEncoding + ": chunked\r\n";
Assert.Equal(expected, request.Headers.ToString());
}
[Fact]
public void CustomHeaders_ResponseHeadersAsCustomHeaders_Success()
{
// Header names reserved for response headers are permitted as custom request headers.
headers.Add("Accept-Ranges", "v");
headers.TryAddWithoutValidation("age", "v");
headers.Add("ETag", "v");
headers.Add("Location", "v");
headers.Add("Proxy-Authenticate", "v");
headers.Add("Retry-After", "v");
headers.Add("Server", "v");
headers.Add("Vary", "v");
headers.Add("WWW-Authenticate", "v");
}
[Fact]
public void InvalidHeaders_AddContentHeaders_Throw()
{
// Try adding content headers. Use different casing to make sure case-insensitive comparison
// is used.
Assert.Throws<InvalidOperationException>(() => { headers.Add("Allow", "v"); });
Assert.Throws<InvalidOperationException>(() => { headers.Add("Content-Encoding", "v"); });
Assert.Throws<InvalidOperationException>(() => { headers.Add("Content-Language", "v"); });
Assert.Throws<InvalidOperationException>(() => { headers.Add("content-length", "v"); });
Assert.Throws<InvalidOperationException>(() => { headers.Add("Content-Location", "v"); });
Assert.Throws<InvalidOperationException>(() => { headers.Add("Content-MD5", "v"); });
Assert.Throws<InvalidOperationException>(() => { headers.Add("Content-Range", "v"); });
Assert.Throws<InvalidOperationException>(() => { headers.Add("CONTENT-TYPE", "v"); });
Assert.Throws<InvalidOperationException>(() => { headers.Add("Expires", "v"); });
Assert.Throws<InvalidOperationException>(() => { headers.Add("Last-Modified", "v"); });
}
}
}
| |
/*
* Copyright (c) 2009, openmetaverse.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.
* - Neither the name of the openmetaverse.org nor the names
* of its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Net;
using System.Net.Security;
using System.IO;
using System.Text;
using System.Threading;
using System.Security.Cryptography.X509Certificates;
namespace OpenMetaverse.Http
{
public class TrustAllCertificatePolicy : ICertificatePolicy
{
public bool CheckValidationResult(ServicePoint sp, X509Certificate cert, WebRequest req, int problem)
{
return true;
}
public static bool TrustAllCertificateHandler(Object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
return true;
}
}
public static class CapsBase
{
public delegate void OpenWriteEventHandler(HttpWebRequest request);
public delegate void DownloadProgressEventHandler(HttpWebRequest request, HttpWebResponse response, int bytesReceived, int totalBytesToReceive);
public delegate void RequestCompletedEventHandler(HttpWebRequest request, HttpWebResponse response, byte[] responseData, Exception error);
static CapsBase()
{
ServicePointManager.CertificatePolicy = new TrustAllCertificatePolicy();
// Even though this will compile on Mono 2.4, it throws a runtime exception
//ServicePointManager.ServerCertificateValidationCallback = TrustAllCertificatePolicy.TrustAllCertificateHandler;
}
private class RequestState
{
public HttpWebRequest Request;
public byte[] UploadData;
public int MillisecondsTimeout;
public OpenWriteEventHandler OpenWriteCallback;
public DownloadProgressEventHandler DownloadProgressCallback;
public RequestCompletedEventHandler CompletedCallback;
public RequestState(HttpWebRequest request, byte[] uploadData, int millisecondsTimeout, OpenWriteEventHandler openWriteCallback,
DownloadProgressEventHandler downloadProgressCallback, RequestCompletedEventHandler completedCallback)
{
Request = request;
UploadData = uploadData;
MillisecondsTimeout = millisecondsTimeout;
OpenWriteCallback = openWriteCallback;
DownloadProgressCallback = downloadProgressCallback;
CompletedCallback = completedCallback;
}
}
public static HttpWebRequest UploadDataAsync(Uri address, X509Certificate2 clientCert, string contentType, byte[] data,
int millisecondsTimeout, OpenWriteEventHandler openWriteCallback, DownloadProgressEventHandler downloadProgressCallback,
RequestCompletedEventHandler completedCallback)
{
// Create the request
HttpWebRequest request = SetupRequest(address, clientCert);
request.ContentLength = data.Length;
if (!String.IsNullOrEmpty(contentType))
request.ContentType = contentType;
request.Method = "POST";
// Create an object to hold all of the state for this request
RequestState state = new RequestState(request, data, millisecondsTimeout, openWriteCallback,
downloadProgressCallback, completedCallback);
// Start the request for a stream to upload to
IAsyncResult result = request.BeginGetRequestStream(OpenWrite, state);
// Register a timeout for the request
ThreadPool.RegisterWaitForSingleObject(result.AsyncWaitHandle, TimeoutCallback, state, millisecondsTimeout, true);
return request;
}
public static HttpWebRequest DownloadStringAsync(Uri address, X509Certificate2 clientCert, int millisecondsTimeout,
DownloadProgressEventHandler downloadProgressCallback, RequestCompletedEventHandler completedCallback)
{
// Create the request
HttpWebRequest request = SetupRequest(address, clientCert);
request.Method = "GET";
DownloadDataAsync(request, millisecondsTimeout, downloadProgressCallback, completedCallback);
return request;
}
public static void DownloadDataAsync(HttpWebRequest request, int millisecondsTimeout,
DownloadProgressEventHandler downloadProgressCallback, RequestCompletedEventHandler completedCallback)
{
// Create an object to hold all of the state for this request
RequestState state = new RequestState(request, null, millisecondsTimeout, null, downloadProgressCallback,
completedCallback);
// Start the request for the remote server response
IAsyncResult result = request.BeginGetResponse(GetResponse, state);
// Register a timeout for the request
ThreadPool.RegisterWaitForSingleObject(result.AsyncWaitHandle, TimeoutCallback, state, millisecondsTimeout, true);
}
static HttpWebRequest SetupRequest(Uri address, X509Certificate2 clientCert)
{
if (address == null)
throw new ArgumentNullException("address");
// Create the request
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(address);
// Add the client certificate to the request if one was given
if (clientCert != null)
request.ClientCertificates.Add(clientCert);
// Leave idle connections to this endpoint open for up to 60 seconds
request.ServicePoint.MaxIdleTime = 1000 * 60;
// Disable stupid Expect-100: Continue header
request.ServicePoint.Expect100Continue = false;
// Crank up the max number of connections per endpoint (default is 2!)
request.ServicePoint.ConnectionLimit = Math.Max(request.ServicePoint.ConnectionLimit, 32);
// Caps requests are never sent as trickles of data, so Nagle's
// coalescing algorithm won't help us
request.ServicePoint.UseNagleAlgorithm = false;
// If not on mono, set accept-encoding header that allows response compression
request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
return request;
}
static void OpenWrite(IAsyncResult ar)
{
RequestState state = (RequestState)ar.AsyncState;
try
{
// Get the stream to write our upload to
using (Stream uploadStream = state.Request.EndGetRequestStream(ar))
{
// Fire the callback for successfully opening the stream
if (state.OpenWriteCallback != null)
state.OpenWriteCallback(state.Request);
// Write our data to the upload stream
uploadStream.Write(state.UploadData, 0, state.UploadData.Length);
}
// Start the request for the remote server response
IAsyncResult result = state.Request.BeginGetResponse(GetResponse, state);
// Register a timeout for the request
ThreadPool.RegisterWaitForSingleObject(result.AsyncWaitHandle, TimeoutCallback, state,
state.MillisecondsTimeout, true);
}
catch (Exception ex)
{
//Logger.Log.Debug("CapsBase.OpenWrite(): " + ex.Message);
if (state.CompletedCallback != null)
state.CompletedCallback(state.Request, null, null, ex);
}
}
static void GetResponse(IAsyncResult ar)
{
RequestState state = (RequestState)ar.AsyncState;
HttpWebResponse response = null;
byte[] responseData = null;
Exception error = null;
try
{
response = (HttpWebResponse)state.Request.EndGetResponse(ar);
// Get the stream for downloading the response
using (Stream responseStream = response.GetResponseStream())
{
#region Read the response
// If Content-Length is set we create a buffer of the exact size, otherwise
// a MemoryStream is used to receive the response
bool nolength = (response.ContentLength <= 0) || (Type.GetType("Mono.Runtime") != null);
int size = (nolength) ? 8192 : (int)response.ContentLength;
MemoryStream ms = (nolength) ? new MemoryStream() : null;
byte[] buffer = new byte[size];
int bytesRead = 0;
int offset = 0;
int totalBytesRead = 0;
int totalSize = nolength ? 0 : size;
while ((bytesRead = responseStream.Read(buffer, offset, size)) != 0)
{
totalBytesRead += bytesRead;
if (nolength)
{
totalSize += (size - bytesRead);
ms.Write(buffer, 0, bytesRead);
}
else
{
offset += bytesRead;
size -= bytesRead;
}
// Fire the download progress callback for each chunk of received data
if (state.DownloadProgressCallback != null)
state.DownloadProgressCallback(state.Request, response, totalBytesRead, totalSize);
}
if (nolength)
{
responseData = ms.ToArray();
ms.Close();
ms.Dispose();
}
else
{
responseData = buffer;
}
#endregion Read the response
responseStream.Close();
}
}
catch (Exception ex)
{
// Logger.DebugLog("CapsBase.GetResponse(): " + ex.Message);
error = ex;
}
if (state.CompletedCallback != null)
state.CompletedCallback(state.Request, response, responseData, error);
}
static void TimeoutCallback(object state, bool timedOut)
{
if (timedOut)
{
RequestState requestState = state as RequestState;
//Logger.Log.Debug("CapsBase.TimeoutCallback(): Request to " + requestState.Request.RequestUri +
// " timed out after " + requestState.MillisecondsTimeout + " milliseconds");
if (requestState != null && requestState.Request != null)
requestState.Request.Abort();
}
}
}
}
| |
// 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.
// <spec>http://webdata/xml/specs/XslCompiledTransform.xml</spec>
//------------------------------------------------------------------------------
using System.CodeDom.Compiler;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Reflection;
using System.Reflection.Emit;
using System.Security;
using System.Xml.XPath;
using System.Xml.Xsl.Qil;
using System.Xml.Xsl.Runtime;
using System.Xml.Xsl.Xslt;
using System.Runtime.Versioning;
using System.Collections.Generic;
using System.Linq;
namespace System.Xml.Xsl
{
#if ! HIDE_XSL
//----------------------------------------------------------------------------------------------------
// Clarification on null values in this API:
// stylesheet, stylesheetUri - cannot be null
// settings - if null, XsltSettings.Default will be used
// stylesheetResolver - if null, XmlNullResolver will be used for includes/imports.
// However, if the principal stylesheet is given by its URI, that
// URI will be resolved using XmlUrlResolver (for compatibility
// with XslTransform and XmlReader).
// typeBuilder - cannot be null
// scriptAssemblyPath - can be null only if scripts are disabled
// compiledStylesheet - cannot be null
// executeMethod, queryData - cannot be null
// earlyBoundTypes - null means no script types
// documentResolver - if null, XmlNullResolver will be used
// input, inputUri - cannot be null
// arguments - null means no arguments
// results, resultsFile - cannot be null
//----------------------------------------------------------------------------------------------------
public sealed class XslCompiledTransform
{
// Reader settings used when creating XmlReader from inputUri
private static readonly XmlReaderSettings s_readerSettings = null;
// Version for GeneratedCodeAttribute
private readonly string _version = typeof(XslCompiledTransform).Assembly.GetName().Version.ToString();
static XslCompiledTransform()
{
s_readerSettings = new XmlReaderSettings();
}
// Options of compilation
private bool _enableDebug = false;
// Results of compilation
private CompilerErrorCollection _compilerErrorColl = null;
private XmlWriterSettings _outputSettings = null;
private QilExpression _qil = null;
#if FEATURE_COMPILED_XSL
// Executable command for the compiled stylesheet
private XmlILCommand _command = null;
#endif
public XslCompiledTransform() { }
public XslCompiledTransform(bool enableDebug)
{
_enableDebug = enableDebug;
}
/// <summary>
/// This function is called on every recompilation to discard all previous results
/// </summary>
private void Reset()
{
_compilerErrorColl = null;
_outputSettings = null;
_qil = null;
#if FEATURE_COMPILED_XSL
_command = null;
#endif
}
/// <summary>
/// Writer settings specified in the stylesheet
/// </summary>
public XmlWriterSettings OutputSettings
{
get
{
return _outputSettings;
}
}
//------------------------------------------------
// Load methods
//------------------------------------------------
// SxS: This method does not take any resource name and does not expose any resources to the caller.
// It's OK to suppress the SxS warning.
public void Load(XmlReader stylesheet)
{
Reset();
LoadInternal(stylesheet, XsltSettings.Default, CreateDefaultResolver());
}
// SxS: This method does not take any resource name and does not expose any resources to the caller.
// It's OK to suppress the SxS warning.
public void Load(XmlReader stylesheet, XsltSettings settings, XmlResolver stylesheetResolver)
{
Reset();
LoadInternal(stylesheet, settings, stylesheetResolver);
}
// SxS: This method does not take any resource name and does not expose any resources to the caller.
// It's OK to suppress the SxS warning.
public void Load(IXPathNavigable stylesheet)
{
Reset();
LoadInternal(stylesheet, XsltSettings.Default, CreateDefaultResolver());
}
// SxS: This method does not take any resource name and does not expose any resources to the caller.
// It's OK to suppress the SxS warning.
public void Load(IXPathNavigable stylesheet, XsltSettings settings, XmlResolver stylesheetResolver)
{
Reset();
LoadInternal(stylesheet, settings, stylesheetResolver);
}
public void Load(string stylesheetUri)
{
Reset();
if (stylesheetUri == null)
{
throw new ArgumentNullException(nameof(stylesheetUri));
}
LoadInternal(stylesheetUri, XsltSettings.Default, CreateDefaultResolver());
}
public void Load(string stylesheetUri, XsltSettings settings, XmlResolver stylesheetResolver)
{
Reset();
if (stylesheetUri == null)
{
throw new ArgumentNullException(nameof(stylesheetUri));
}
LoadInternal(stylesheetUri, settings, stylesheetResolver);
}
private CompilerErrorCollection LoadInternal(object stylesheet, XsltSettings settings, XmlResolver stylesheetResolver)
{
if (stylesheet == null)
{
throw new ArgumentNullException(nameof(stylesheet));
}
if (settings == null)
{
settings = XsltSettings.Default;
}
CompileXsltToQil(stylesheet, settings, stylesheetResolver);
CompilerError error = GetFirstError();
if (error != null)
{
throw new XslLoadException(error);
}
if (!settings.CheckOnly)
{
CompileQilToMsil(settings);
}
return _compilerErrorColl;
}
private void CompileXsltToQil(object stylesheet, XsltSettings settings, XmlResolver stylesheetResolver)
{
_compilerErrorColl = new Compiler(settings, _enableDebug, null).Compile(stylesheet, stylesheetResolver, out _qil);
}
/// <summary>
/// Returns the first compiler error except warnings
/// </summary>
private CompilerError GetFirstError()
{
foreach (CompilerError error in _compilerErrorColl)
{
if (!error.IsWarning)
{
return error;
}
}
return null;
}
private void CompileQilToMsil(XsltSettings settings)
{
#if FEATURE_COMPILED_XSL
_command = new XmlILGenerator().Generate(_qil, /*typeBuilder:*/null);
_outputSettings = _command.StaticData.DefaultWriterSettings;
_qil = null;
#else
throw new PlatformNotSupportedException(SR.Xslt_NotSupported);
#endif
}
//------------------------------------------------
// Load compiled stylesheet from a Type
//------------------------------------------------
public void Load(Type compiledStylesheet)
{
#if FEATURE_COMPILED_XSL
Reset();
if (compiledStylesheet == null)
throw new ArgumentNullException(nameof(compiledStylesheet));
object[] customAttrs = compiledStylesheet.GetCustomAttributes(typeof(GeneratedCodeAttribute), /*inherit:*/false);
GeneratedCodeAttribute generatedCodeAttr = customAttrs.Length > 0 ? (GeneratedCodeAttribute)customAttrs[0] : null;
// If GeneratedCodeAttribute is not there, it is not a compiled stylesheet class
if (generatedCodeAttr != null && generatedCodeAttr.Tool == typeof(XslCompiledTransform).FullName)
{
if (new Version(_version).CompareTo(new Version(generatedCodeAttr.Version)) < 0)
{
throw new ArgumentException(SR.Format(SR.Xslt_IncompatibleCompiledStylesheetVersion, generatedCodeAttr.Version, _version), nameof(compiledStylesheet));
}
FieldInfo fldData = compiledStylesheet.GetField(XmlQueryStaticData.DataFieldName, BindingFlags.Static | BindingFlags.NonPublic);
FieldInfo fldTypes = compiledStylesheet.GetField(XmlQueryStaticData.TypesFieldName, BindingFlags.Static | BindingFlags.NonPublic);
// If private fields are not there, it is not a compiled stylesheet class
if (fldData != null && fldTypes != null)
{
// Retrieve query static data from the type
byte[] queryData = fldData.GetValue(/*this:*/null) as byte[];
if (queryData != null)
{
MethodInfo executeMethod = compiledStylesheet.GetMethod("Execute", BindingFlags.Static | BindingFlags.NonPublic);
Type[] earlyBoundTypes = (Type[])fldTypes.GetValue(/*this:*/null);
// Load the stylesheet
Load(executeMethod, queryData, earlyBoundTypes);
return;
}
}
}
// Throw an exception if the command was not loaded
if (_command == null)
throw new ArgumentException(SR.Format(SR.Xslt_NotCompiledStylesheet, compiledStylesheet.FullName), nameof(compiledStylesheet));
#else
throw new PlatformNotSupportedException(SR.Xslt_NotSupported);
#endif
}
public void Load(MethodInfo executeMethod, byte[] queryData, Type[] earlyBoundTypes)
{
#if FEATURE_COMPILED_XSL
Reset();
if (executeMethod == null)
throw new ArgumentNullException(nameof(executeMethod));
if (queryData == null)
throw new ArgumentNullException(nameof(queryData));
DynamicMethod dm = executeMethod as DynamicMethod;
Delegate delExec = (dm != null) ? dm.CreateDelegate(typeof(ExecuteDelegate)) : executeMethod.CreateDelegate(typeof(ExecuteDelegate));
_command = new XmlILCommand((ExecuteDelegate)delExec, new XmlQueryStaticData(queryData, earlyBoundTypes));
_outputSettings = _command.StaticData.DefaultWriterSettings;
#else
throw new PlatformNotSupportedException(SR.Xslt_NotSupported);
#endif
}
//------------------------------------------------
// Transform methods which take an IXPathNavigable
//------------------------------------------------
public void Transform(IXPathNavigable input, XmlWriter results)
{
CheckArguments(input, results);
Transform(input, (XsltArgumentList)null, results, CreateDefaultResolver());
}
public void Transform(IXPathNavigable input, XsltArgumentList arguments, XmlWriter results)
{
CheckArguments(input, results);
Transform(input, arguments, results, CreateDefaultResolver());
}
public void Transform(IXPathNavigable input, XsltArgumentList arguments, TextWriter results)
{
CheckArguments(input, results);
using (XmlWriter writer = XmlWriter.Create(results, OutputSettings))
{
Transform(input, arguments, writer, CreateDefaultResolver());
writer.Close();
}
}
public void Transform(IXPathNavigable input, XsltArgumentList arguments, Stream results)
{
CheckArguments(input, results);
using (XmlWriter writer = XmlWriter.Create(results, OutputSettings))
{
Transform(input, arguments, writer, CreateDefaultResolver());
writer.Close();
}
}
//------------------------------------------------
// Transform methods which take an XmlReader
//------------------------------------------------
public void Transform(XmlReader input, XmlWriter results)
{
CheckArguments(input, results);
Transform(input, (XsltArgumentList)null, results, CreateDefaultResolver());
}
public void Transform(XmlReader input, XsltArgumentList arguments, XmlWriter results)
{
CheckArguments(input, results);
Transform(input, arguments, results, CreateDefaultResolver());
}
public void Transform(XmlReader input, XsltArgumentList arguments, TextWriter results)
{
CheckArguments(input, results);
using (XmlWriter writer = XmlWriter.Create(results, OutputSettings))
{
Transform(input, arguments, writer, CreateDefaultResolver());
writer.Close();
}
}
public void Transform(XmlReader input, XsltArgumentList arguments, Stream results)
{
CheckArguments(input, results);
using (XmlWriter writer = XmlWriter.Create(results, OutputSettings))
{
Transform(input, arguments, writer, CreateDefaultResolver());
writer.Close();
}
}
//------------------------------------------------
// Transform methods which take a uri
// SxS Note: Annotations should propagate to the caller to have him either check that
// the passed URIs are SxS safe or decide that they don't have to be SxS safe and
// suppress the message.
//------------------------------------------------
[SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings")]
public void Transform(string inputUri, XmlWriter results)
{
CheckArguments(inputUri, results);
using (XmlReader reader = XmlReader.Create(inputUri, s_readerSettings))
{
Transform(reader, (XsltArgumentList)null, results, CreateDefaultResolver());
}
}
[SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings")]
public void Transform(string inputUri, XsltArgumentList arguments, XmlWriter results)
{
CheckArguments(inputUri, results);
using (XmlReader reader = XmlReader.Create(inputUri, s_readerSettings))
{
Transform(reader, arguments, results, CreateDefaultResolver());
}
}
[SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings")]
public void Transform(string inputUri, XsltArgumentList arguments, TextWriter results)
{
CheckArguments(inputUri, results);
using (XmlReader reader = XmlReader.Create(inputUri, s_readerSettings))
using (XmlWriter writer = XmlWriter.Create(results, OutputSettings))
{
Transform(reader, arguments, writer, CreateDefaultResolver());
writer.Close();
}
}
[SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings")]
public void Transform(string inputUri, XsltArgumentList arguments, Stream results)
{
CheckArguments(inputUri, results);
using (XmlReader reader = XmlReader.Create(inputUri, s_readerSettings))
using (XmlWriter writer = XmlWriter.Create(results, OutputSettings))
{
Transform(reader, arguments, writer, CreateDefaultResolver());
writer.Close();
}
}
[SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings")]
public void Transform(string inputUri, string resultsFile)
{
if (inputUri == null)
throw new ArgumentNullException(nameof(inputUri));
if (resultsFile == null)
throw new ArgumentNullException(nameof(resultsFile));
// SQLBUDT 276415: Prevent wiping out the content of the input file if the output file is the same
using (XmlReader reader = XmlReader.Create(inputUri, s_readerSettings))
using (XmlWriter writer = XmlWriter.Create(resultsFile, OutputSettings))
{
Transform(reader, (XsltArgumentList)null, writer, CreateDefaultResolver());
writer.Close();
}
}
//------------------------------------------------
// Main Transform overloads
//------------------------------------------------
// SxS: This method does not take any resource name and does not expose any resources to the caller.
// It's OK to suppress the SxS warning.
public void Transform(XmlReader input, XsltArgumentList arguments, XmlWriter results, XmlResolver documentResolver)
{
#if FEATURE_COMPILED_XSL
CheckArguments(input, results);
CheckCommand();
_command.Execute((object)input, documentResolver, arguments, results);
#else
throw new PlatformNotSupportedException(SR.Xslt_NotSupported);
#endif
}
// SxS: This method does not take any resource name and does not expose any resources to the caller.
// It's OK to suppress the SxS warning.
public void Transform(IXPathNavigable input, XsltArgumentList arguments, XmlWriter results, XmlResolver documentResolver)
{
#if FEATURE_COMPILED_XSL
CheckArguments(input, results);
CheckCommand();
_command.Execute((object)input.CreateNavigator(), documentResolver, arguments, results);
#else
throw new PlatformNotSupportedException(SR.Xslt_NotSupported);
#endif
}
//------------------------------------------------
// Helper methods
//------------------------------------------------
private static void CheckArguments(object input, object results)
{
if (input == null)
throw new ArgumentNullException(nameof(input));
if (results == null)
throw new ArgumentNullException(nameof(results));
}
private static void CheckArguments(string inputUri, object results)
{
if (inputUri == null)
throw new ArgumentNullException(nameof(inputUri));
if (results == null)
throw new ArgumentNullException(nameof(results));
}
private void CheckCommand()
{
#if FEATURE_COMPILED_XSL
if (_command == null)
{
throw new InvalidOperationException(SR.Xslt_NoStylesheetLoaded);
}
#else
throw new InvalidOperationException(SR.Xslt_NoStylesheetLoaded);
#endif
}
private static XmlResolver CreateDefaultResolver()
{
if (LocalAppContextSwitches.AllowDefaultResolver)
{
return new XmlUrlResolver();
}
else
{
return XmlNullResolver.Singleton;
}
}
//------------------------------------------------
// Test suites entry points
//------------------------------------------------
private QilExpression TestCompile(object stylesheet, XsltSettings settings, XmlResolver stylesheetResolver)
{
Reset();
CompileXsltToQil(stylesheet, settings, stylesheetResolver);
return _qil;
}
private void TestGenerate(XsltSettings settings)
{
Debug.Assert(_qil != null, "You must compile to Qil first");
CompileQilToMsil(settings);
}
#if FEATURE_COMPILED_XSL
private void Transform(string inputUri, XsltArgumentList arguments, XmlWriter results, XmlResolver documentResolver)
{
_command.Execute(inputUri, documentResolver, arguments, results);
}
#endif
}
#endif // ! HIDE_XSL
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Threading;
using Orleans.Internal;
namespace Orleans.TestingHost
{
public class TestClusterPortAllocator : ITestClusterPortAllocator
{
private bool disposed;
private readonly object lockObj = new object();
private readonly Dictionary<int, string> allocatedPorts = new Dictionary<int, string>();
public (int, int) AllocateConsecutivePortPairs(int numPorts = 5)
{
// Evaluate current system tcp connections
IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();
IPEndPoint[] tcpConnInfoArray = ipGlobalProperties.GetActiveTcpListeners();
// each returned port in the pair will have to have at least this amount of available ports following it
return (GetAvailableConsecutiveServerPorts(tcpConnInfoArray, 22300, 30000, numPorts),
GetAvailableConsecutiveServerPorts(tcpConnInfoArray, 40000, 50000, numPorts));
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposed)
{
return;
}
lock (lockObj)
{
if (disposed)
{
return;
}
foreach (var pair in allocatedPorts)
{
MutexManager.Instance.SignalRelease(pair.Value);
}
allocatedPorts.Clear();
disposed = true;
}
}
~TestClusterPortAllocator()
{
Dispose(false);
}
private int GetAvailableConsecutiveServerPorts(IPEndPoint[] tcpConnInfoArray, int portStartRange, int portEndRange, int consecutivePortsToCheck)
{
const int MaxAttempts = 100;
var allocations = new List<(int Port, string Mutex)>();
for (int attempts = 0; attempts < MaxAttempts; attempts++)
{
int basePort = ThreadSafeRandom.Next(portStartRange, portEndRange);
// get ports in buckets, so we don't interfere with parallel runs of this same function
basePort = basePort - (basePort % consecutivePortsToCheck);
int endPort = basePort + consecutivePortsToCheck;
// make sure none of the ports in the sub range are in use
if (tcpConnInfoArray.All(endpoint => endpoint.Port < basePort || endpoint.Port >= endPort))
{
for (var i = 0; i < consecutivePortsToCheck; i++)
{
var port = basePort + i;
var name = $"Global.TestCluster.{port.ToString(CultureInfo.InvariantCulture)}";
if (MutexManager.Instance.Acquire(name))
{
allocations.Add((port, name));
}
else
{
foreach (var allocation in allocations)
{
MutexManager.Instance.SignalRelease(allocation.Mutex);
}
allocations.Clear();
break;
}
}
if (allocations.Count == 0)
{
// Try a different range.
continue;
}
lock (lockObj)
{
foreach (var allocation in allocations)
{
allocatedPorts[allocation.Port] = allocation.Mutex;
}
}
return basePort;
}
}
throw new InvalidOperationException("Cannot find enough free ports to spin up a cluster");
}
private class MutexManager
{
private readonly Dictionary<string, Mutex> _mutexes = new Dictionary<string, Mutex>();
private readonly BlockingCollection<Action> _workItems = new BlockingCollection<Action>();
private readonly Thread _thread;
public static MutexManager Instance { get; } = new MutexManager();
private MutexManager()
{
_thread = new Thread(Run)
{
Name = "MutexManager.Worker",
IsBackground = true,
};
_thread.Start();
AppDomain.CurrentDomain.DomainUnload += this.OnAppDomainUnload;
}
private void OnAppDomainUnload(object sender, EventArgs e)
{
Shutdown();
}
private void Shutdown()
{
_workItems.CompleteAdding();
_thread.Join();
}
public bool Acquire(string name)
{
var result = new [] { 0 };
var signal = new ManualResetEventSlim(initialState: false);
_workItems.Add(() =>
{
try
{
if (!_mutexes.TryGetValue(name, out var mutex))
{
mutex = new Mutex(false, name);
if (mutex.WaitOne(500))
{
// Acquired
_mutexes[name] = mutex;
Interlocked.Increment(ref result[0]);
return;
}
// Failed to acquire: the mutex is already held by another process.
try
{
mutex.ReleaseMutex();
}
finally
{
mutex.Close();
}
}
// Failed to acquire: the mutex is already held by this process.
}
finally
{
signal.Set();
}
});
if (!signal.Wait(TimeSpan.FromSeconds(10)))
{
throw new TimeoutException("Timed out while waiting for MutexManager to acquire mutex.");
}
return result[0] == 1;
}
public void SignalRelease(string name)
{
if (_workItems.IsAddingCompleted) return;
try
{
_workItems.Add(() =>
{
if (_mutexes.TryGetValue(name, out var value))
{
_mutexes.Remove(name);
value.ReleaseMutex();
value.Close();
}
});
}
catch
{
}
}
private void Run()
{
try
{
foreach (var action in _workItems.GetConsumingEnumerable())
{
try
{
action();
}
catch
{
}
}
}
catch
{
}
finally
{
foreach (var mutex in _mutexes.Values)
{
try
{
mutex.ReleaseMutex();
}
catch { }
finally
{
mutex.Close();
}
}
_mutexes.Clear();
}
}
}
}
}
| |
// 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 ShiftRightLogical128BitLaneInt161()
{
var test = new SimpleUnaryOpTest__ShiftRightLogical128BitLaneInt161();
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 works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleUnaryOpTest__ShiftRightLogical128BitLaneInt161
{
private const int VectorSize = 32;
private const int Op1ElementCount = VectorSize / sizeof(Int16);
private const int RetElementCount = VectorSize / sizeof(Int16);
private static Int16[] _data = new Int16[Op1ElementCount];
private static Vector256<Int16> _clsVar;
private Vector256<Int16> _fld;
private SimpleUnaryOpTest__DataTable<Int16, Int16> _dataTable;
static SimpleUnaryOpTest__ShiftRightLogical128BitLaneInt161()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (short)8; }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _clsVar), ref Unsafe.As<Int16, byte>(ref _data[0]), VectorSize);
}
public SimpleUnaryOpTest__ShiftRightLogical128BitLaneInt161()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (short)8; }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _fld), ref Unsafe.As<Int16, byte>(ref _data[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (short)8; }
_dataTable = new SimpleUnaryOpTest__DataTable<Int16, Int16>(_data, new Int16[RetElementCount], VectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Avx2.ShiftRightLogical128BitLane(
Unsafe.Read<Vector256<Int16>>(_dataTable.inArrayPtr),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Avx2.ShiftRightLogical128BitLane(
Avx.LoadVector256((Int16*)(_dataTable.inArrayPtr)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Avx2.ShiftRightLogical128BitLane(
Avx.LoadAlignedVector256((Int16*)(_dataTable.inArrayPtr)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftRightLogical128BitLane), new Type[] { typeof(Vector256<Int16>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Int16>>(_dataTable.inArrayPtr),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftRightLogical128BitLane), new Type[] { typeof(Vector256<Int16>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadVector256((Int16*)(_dataTable.inArrayPtr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftRightLogical128BitLane), new Type[] { typeof(Vector256<Int16>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Int16*)(_dataTable.inArrayPtr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Avx2.ShiftRightLogical128BitLane(
_clsVar,
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var firstOp = Unsafe.Read<Vector256<Int16>>(_dataTable.inArrayPtr);
var result = Avx2.ShiftRightLogical128BitLane(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var firstOp = Avx.LoadVector256((Int16*)(_dataTable.inArrayPtr));
var result = Avx2.ShiftRightLogical128BitLane(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var firstOp = Avx.LoadAlignedVector256((Int16*)(_dataTable.inArrayPtr));
var result = Avx2.ShiftRightLogical128BitLane(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleUnaryOpTest__ShiftRightLogical128BitLaneInt161();
var result = Avx2.ShiftRightLogical128BitLane(test._fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Avx2.ShiftRightLogical128BitLane(_fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector256<Int16> firstOp, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray = new Int16[Op1ElementCount];
Int16[] outArray = new Int16[RetElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray = new Int16[Op1ElementCount];
Int16[] outArray = new Int16[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(Int16[] firstOp, Int16[] result, [CallerMemberName] string method = "")
{
if (result[0] != 2048)
{
Succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((i == 7 || i == 15 ? result[i] != 0 : result[i] != 2048))
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Avx2)}.{nameof(Avx2.ShiftRightLogical128BitLane)}<Int16>(Vector256<Int16><9>): {method} failed:");
Console.WriteLine($" firstOp: ({string.Join(", ", firstOp)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
using System;
using System.Text;
/// <summary>
/// Insert(System.Int32,System.String)
/// </summary>
public class StringBuilderInsert3
{
#region Private Fields
private const int c_LENGTH_OF_STRING = 256;
#endregion
#region Public Methods
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
return retVal;
}
#region Positive Test Cases
public bool PosTest1()
{
bool retVal = true;
string randString = null;
TestLibrary.TestFramework.BeginScenario("PosTest1: Call insert on empty string builder instance");
try
{
randString = TestLibrary.Generator.GetString(-55, false, c_LENGTH_OF_STRING, c_LENGTH_OF_STRING);
StringBuilder builder = new StringBuilder();
StringBuilder newBuilder = builder.Insert(0, randString);
string actualString = newBuilder.ToString();
if (!randString.Equals(actualString))
{
TestLibrary.TestFramework.LogError("001.1", "Calling insert on empty string builder instance returns wrong string builder instance");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLES] randString = " + randString + ", actualString = " + actualString);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("001.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLES] randString = " + randString);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
string randString = null;
int randIndex = 0;
TestLibrary.TestFramework.BeginScenario("PosTest2: Call insert on a non empty string builder instance");
try
{
randString = TestLibrary.Generator.GetString(-55, false, c_LENGTH_OF_STRING, c_LENGTH_OF_STRING);
randIndex = TestLibrary.Generator.GetByte(-55);
StringBuilder builder = new StringBuilder(randString);
StringBuilder newBuilder = builder.Insert(randIndex, randString);
string actualString = newBuilder.ToString();
char[] characters = new char[randString.Length + randString.Length];
int index = 0;
for (int i = 0; i < randIndex; ++i)
{
characters[index++] = randString[i];
}
for (int i = 0; i < randString.Length; ++i)
{
characters[index++] = randString[i];
}
for (int i = randIndex; i < randString.Length; ++i)
{
characters[index++] = randString[i];
}
string desiredString = new string(characters);
if (!desiredString.Equals(actualString))
{
TestLibrary.TestFramework.LogError("002.1", "Calling insert on a non empty string builder instance returns wrong string builder instance");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLES] randString = " + randString + ", actualString = " + actualString + ", desiredString = " + desiredString + ", randIndex = " + randIndex);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLES] randString = " + randString + ", randIndex = " + randIndex);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest3: Call insert on empty string builder instance with value is null reference");
try
{
StringBuilder builder = new StringBuilder();
StringBuilder newBuilder = builder.Insert(0, null as string);
string actualString = newBuilder.ToString();
if (!actualString.Equals(String.Empty))
{
TestLibrary.TestFramework.LogError("003.1", "Calling insert on empty string builder instance with value is null reference returns wrong string builder instance");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLES] actualString = " + actualString);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("003.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest4: Call insert on empty string builder instance with value is String.Empty");
try
{
StringBuilder builder = new StringBuilder();
StringBuilder newBuilder = builder.Insert(0, String.Empty);
string actualString = newBuilder.ToString();
if (!actualString.Equals(String.Empty))
{
TestLibrary.TestFramework.LogError("004.1", "Calling insert on empty string builder instance with value is String.Empty returns wrong string builder instance");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLES] actualString = " + actualString);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
#endregion
#region Nagetive Test Cases
public bool NegTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest1: ArgumentOutOfRangeException should be thrown when index is less than zero");
try
{
StringBuilder builder = new StringBuilder();
builder.Insert(-1, String.Empty);
TestLibrary.TestFramework.LogError("101.1", "ArgumentOutOfRangeException is not thrown when index is less than zero");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("101.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest2: ArgumentOutOfRangeException should be thrown when index is greater than the current length of this instance.");
try
{
StringBuilder builder = new StringBuilder();
builder.Insert(1, String.Empty);
TestLibrary.TestFramework.LogError("102.1", "ArgumentOutOfRangeException is not thrown when index is greater than the current length of this instance.");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("102.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
#endregion
#endregion
public static int Main()
{
StringBuilderInsert3 test = new StringBuilderInsert3();
TestLibrary.TestFramework.BeginTestCase("StringBuilderInsert3");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
}
| |
/*
* 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.Collections.Specialized;
using System.IO;
using System.Net;
using System.Web;
using DotNetOpenId;
using DotNetOpenId.Provider;
using OpenSim.Framework;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
namespace OpenSim.Grid.AgentDomain.Modules
{
/// <summary>
/// Temporary, in-memory store for OpenID associations
/// </summary>
public class ProviderMemoryStore : IAssociationStore<AssociationRelyingPartyType>
{
private class AssociationItem
{
public AssociationRelyingPartyType DistinguishingFactor;
public string Handle;
public DateTime Expires;
public byte[] PrivateData;
}
Dictionary<string, AssociationItem> m_store = new Dictionary<string, AssociationItem>();
SortedList<DateTime, AssociationItem> m_sortedStore = new SortedList<DateTime, AssociationItem>();
object m_syncRoot = new object();
#region IAssociationStore<AssociationRelyingPartyType> Members
public void StoreAssociation(AssociationRelyingPartyType distinguishingFactor, Association assoc)
{
AssociationItem item = new AssociationItem();
item.DistinguishingFactor = distinguishingFactor;
item.Handle = assoc.Handle;
item.Expires = assoc.Expires.ToLocalTime();
item.PrivateData = assoc.SerializePrivateData();
lock (m_syncRoot)
{
m_store[item.Handle] = item;
m_sortedStore[item.Expires] = item;
}
}
public Association GetAssociation(AssociationRelyingPartyType distinguishingFactor)
{
lock (m_syncRoot)
{
if (m_sortedStore.Count > 0)
{
AssociationItem item = m_sortedStore.Values[m_sortedStore.Count - 1];
return Association.Deserialize(item.Handle, item.Expires.ToUniversalTime(), item.PrivateData);
}
else
{
return null;
}
}
}
public Association GetAssociation(AssociationRelyingPartyType distinguishingFactor, string handle)
{
AssociationItem item;
bool success = false;
lock (m_syncRoot)
success = m_store.TryGetValue(handle, out item);
if (success)
return Association.Deserialize(item.Handle, item.Expires.ToUniversalTime(), item.PrivateData);
else
return null;
}
public bool RemoveAssociation(AssociationRelyingPartyType distinguishingFactor, string handle)
{
lock (m_syncRoot)
{
for (int i = 0; i < m_sortedStore.Values.Count; i++)
{
AssociationItem item = m_sortedStore.Values[i];
if (item.Handle == handle)
{
m_sortedStore.RemoveAt(i);
break;
}
}
return m_store.Remove(handle);
}
}
public void ClearExpiredAssociations()
{
lock (m_syncRoot)
{
List<AssociationItem> itemsCopy = new List<AssociationItem>(m_sortedStore.Values);
DateTime now = DateTime.Now;
for (int i = 0; i < itemsCopy.Count; i++)
{
AssociationItem item = itemsCopy[i];
if (item.Expires <= now)
{
m_sortedStore.RemoveAt(i);
m_store.Remove(item.Handle);
}
}
}
}
#endregion
}
public class OpenIdStreamHandler : IStreamHandler
{
#region HTML
/// <summary>Login form used to authenticate OpenID requests</summary>
const string LOGIN_PAGE =
@"<html>
<head><title>OpenSim OpenID Login</title></head>
<body>
<h3>OpenSim Login</h3>
<form method=""post"">
<label for=""first"">First Name:</label> <input readonly type=""text"" name=""first"" id=""first"" value=""{0}""/>
<label for=""last"">Last Name:</label> <input readonly type=""text"" name=""last"" id=""last"" value=""{1}""/>
<label for=""pass"">Password:</label> <input type=""password"" name=""pass"" id=""pass""/>
<input type=""submit"" value=""Login"">
</form>
</body>
</html>";
/// <summary>Page shown for a valid OpenID identity</summary>
const string OPENID_PAGE =
@"<html>
<head>
<title>{2} {3}</title>
<link rel=""openid2.provider openid.server"" href=""{0}://{1}/openid/server/""/>
</head>
<body>OpenID identifier for {2} {3}</body>
</html>
";
/// <summary>Page shown for an invalid OpenID identity</summary>
const string INVALID_OPENID_PAGE =
@"<html><head><title>Identity not found</title></head>
<body>Invalid OpenID identity</body></html>";
/// <summary>Page shown if the OpenID endpoint is requested directly</summary>
const string ENDPOINT_PAGE =
@"<html><head><title>OpenID Endpoint</title></head><body>
This is an OpenID server endpoint, not a human-readable resource.
For more information, see <a href='http://openid.net/'>http://openid.net/</a>.
</body></html>";
#endregion HTML
public string ContentType { get { return m_contentType; } }
public string HttpMethod { get { return m_httpMethod; } }
public string Path { get { return m_path; } }
string m_contentType;
string m_httpMethod;
string m_path;
UserLoginService m_loginService;
ProviderMemoryStore m_openidStore = new ProviderMemoryStore();
/// <summary>
/// Constructor
/// </summary>
public OpenIdStreamHandler(string httpMethod, string path, UserLoginService loginService)
{
m_loginService = loginService;
m_httpMethod = httpMethod;
m_path = path;
m_contentType = "text/html";
}
/// <summary>
/// Handles all GET and POST requests for OpenID identifier pages and endpoint
/// server communication
/// </summary>
public void Handle(string path, Stream request, Stream response, OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{
Uri providerEndpoint = new Uri(String.Format("{0}://{1}{2}", httpRequest.Url.Scheme, httpRequest.Url.Authority, httpRequest.Url.AbsolutePath));
// Defult to returning HTML content
m_contentType = "text/html";
try
{
NameValueCollection postQuery = HttpUtility.ParseQueryString(new StreamReader(httpRequest.InputStream).ReadToEnd());
NameValueCollection getQuery = HttpUtility.ParseQueryString(httpRequest.Url.Query);
NameValueCollection openIdQuery = (postQuery.GetValues("openid.mode") != null ? postQuery : getQuery);
OpenIdProvider provider = new OpenIdProvider(m_openidStore, providerEndpoint, httpRequest.Url, openIdQuery);
if (provider.Request != null)
{
if (!provider.Request.IsResponseReady && provider.Request is IAuthenticationRequest)
{
IAuthenticationRequest authRequest = (IAuthenticationRequest)provider.Request;
string[] passwordValues = postQuery.GetValues("pass");
UserProfileData profile;
if (TryGetProfile(new Uri(authRequest.ClaimedIdentifier.ToString()), out profile))
{
// Check for form POST data
if (passwordValues != null && passwordValues.Length == 1)
{
if (profile != null && m_loginService.AuthenticateUser(profile, passwordValues[0]))
authRequest.IsAuthenticated = true;
else
authRequest.IsAuthenticated = false;
}
else
{
// Authentication was requested, send the client a login form
using (StreamWriter writer = new StreamWriter(response))
writer.Write(String.Format(LOGIN_PAGE, profile.FirstName, profile.SurName));
return;
}
}
else
{
// Cannot find an avatar matching the claimed identifier
authRequest.IsAuthenticated = false;
}
}
// Add OpenID headers to the response
foreach (string key in provider.Request.Response.Headers.Keys)
httpResponse.AddHeader(key, provider.Request.Response.Headers[key]);
string[] contentTypeValues = provider.Request.Response.Headers.GetValues("Content-Type");
if (contentTypeValues != null && contentTypeValues.Length == 1)
m_contentType = contentTypeValues[0];
// Set the response code and document body based on the OpenID result
httpResponse.StatusCode = (int)provider.Request.Response.Code;
response.Write(provider.Request.Response.Body, 0, provider.Request.Response.Body.Length);
response.Close();
}
else if (httpRequest.Url.AbsolutePath.Contains("/openid/server"))
{
// Standard HTTP GET was made on the OpenID endpoint, send the client the default error page
using (StreamWriter writer = new StreamWriter(response))
writer.Write(ENDPOINT_PAGE);
}
else
{
// Try and lookup this avatar
UserProfileData profile;
if (TryGetProfile(httpRequest.Url, out profile))
{
using (StreamWriter writer = new StreamWriter(response))
{
// TODO: Print out a full profile page for this avatar
writer.Write(String.Format(OPENID_PAGE, httpRequest.Url.Scheme,
httpRequest.Url.Authority, profile.FirstName, profile.SurName));
}
}
else
{
// Couldn't parse an avatar name, or couldn't find the avatar in the user server
using (StreamWriter writer = new StreamWriter(response))
writer.Write(INVALID_OPENID_PAGE);
}
}
}
catch (Exception ex)
{
httpResponse.StatusCode = (int)HttpStatusCode.InternalServerError;
using (StreamWriter writer = new StreamWriter(response))
writer.Write(ex.Message);
}
}
/// <summary>
/// Parse a URL with a relative path of the form /users/First_Last and try to
/// retrieve the profile matching that avatar name
/// </summary>
/// <param name="requestUrl">URL to parse for an avatar name</param>
/// <param name="profile">Profile data for the avatar</param>
/// <returns>True if the parse and lookup were successful, otherwise false</returns>
bool TryGetProfile(Uri requestUrl, out UserProfileData profile)
{
if (requestUrl.Segments.Length == 3 && requestUrl.Segments[1] == "users/")
{
// Parse the avatar name from the path
string username = requestUrl.Segments[requestUrl.Segments.Length - 1];
string[] name = username.Split('_');
if (name.Length == 2)
{
profile = m_loginService.GetTheUser(name[0], name[1]);
return (profile != null);
}
}
profile = null;
return false;
}
}
}
| |
// 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.Linq;
using Xunit;
namespace System.Reflection.Emit.Tests
{
public class EnumBuilderMethodTests
{
public static IEnumerable<object[]> DefineLiteral_TestData()
{
yield return new object[] { typeof(byte), (byte)0 };
yield return new object[] { typeof(byte), (byte)1 };
yield return new object[] { typeof(sbyte), (sbyte)0 };
yield return new object[] { typeof(sbyte), (sbyte)1 };
yield return new object[] { typeof(ushort), (ushort)0 };
yield return new object[] { typeof(ushort), (ushort)1 };
yield return new object[] { typeof(short), (short)0 };
yield return new object[] { typeof(short), (short)1 };
yield return new object[] { typeof(uint), (uint)0 };
yield return new object[] { typeof(uint), (uint)1 };
yield return new object[] { typeof(int), 0 };
yield return new object[] { typeof(int), 1 };
yield return new object[] { typeof(ulong), (ulong)0 };
yield return new object[] { typeof(ulong), (ulong)1 };
yield return new object[] { typeof(long), (long)0 };
yield return new object[] { typeof(long), (long)1 };
yield return new object[] { typeof(char), (char)0 };
yield return new object[] { typeof(char), (char)1 };
yield return new object[] { typeof(bool), true };
yield return new object[] { typeof(bool), false };
yield return new object[] { typeof(float), 0f };
yield return new object[] { typeof(float), 1.1f };
yield return new object[] { typeof(double), 0d };
yield return new object[] { typeof(double), 1.1d };
}
[Theory]
[MemberData(nameof(DefineLiteral_TestData))]
public void DefineLiteral(Type underlyingType, object literalValue)
{
EnumBuilder enumBuilder = Helpers.DynamicEnum(TypeAttributes.Public, underlyingType);
FieldBuilder literal = enumBuilder.DefineLiteral("FieldOne", literalValue);
Assert.Equal("FieldOne", literal.Name);
Assert.Equal(enumBuilder.Name, literal.DeclaringType.Name);
Assert.Equal(FieldAttributes.Public | FieldAttributes.Static | FieldAttributes.Literal, literal.Attributes);
Assert.Equal(enumBuilder.AsType(), literal.FieldType);
Type createdEnum = enumBuilder.CreateTypeInfo().AsType();
FieldInfo createdLiteral = createdEnum.GetField("FieldOne");
Assert.Equal(createdEnum, createdLiteral.FieldType);
if (literalValue is bool || literalValue is float || literalValue is double)
{
// EnumBuilder generates invalid data for non-integer enums
Assert.Throws<FormatException>(() => createdLiteral.GetValue(null));
}
else
{
Assert.Equal(Enum.ToObject(createdEnum, literalValue), createdLiteral.GetValue(null));
}
}
[Fact]
public void DefineLiteral_NullLiteralName_ThrowsArgumentNullException()
{
EnumBuilder enumBuilder = Helpers.DynamicEnum(TypeAttributes.Public, typeof(int));
AssertExtensions.Throws<ArgumentNullException>("fieldName", () => enumBuilder.DefineLiteral(null, 1));
}
[Theory]
[InlineData("")]
[InlineData("\0")]
[InlineData("\0abc")]
public void DefineLiteral_EmptyLiteralName_ThrowsArgumentException(string literalName)
{
EnumBuilder enumBuilder = Helpers.DynamicEnum(TypeAttributes.Public, typeof(int));
AssertExtensions.Throws<ArgumentException>("fieldName", () => enumBuilder.DefineLiteral(literalName, 1));
}
public static IEnumerable<object[]> DefineLiteral_InvalidLiteralValue_ThrowsArgumentException_TestData()
{
yield return new object[] { typeof(int), null };
yield return new object[] { typeof(int), (short)1 };
yield return new object[] { typeof(short), 1 };
yield return new object[] { typeof(float), 1d };
yield return new object[] { typeof(double), 1f };
yield return new object[] { typeof(IntPtr), (IntPtr)1 };
yield return new object[] { typeof(UIntPtr), (UIntPtr)1 };
yield return new object[] { typeof(int).MakePointerType(), 1 };
yield return new object[] { typeof(int).MakeByRefType(), 1 };
yield return new object[] { typeof(int[]), new int[] { 1 } };
yield return new object[] { typeof(int?), 1 };
yield return new object[] { typeof(int?), null };
yield return new object[] { typeof(string), null };
}
[Theory]
[MemberData(nameof(DefineLiteral_InvalidLiteralValue_ThrowsArgumentException_TestData))]
public void DefineLiteral_InvalidLiteralValue_ThrowsArgumentException(Type underlyingType, object literalValue)
{
EnumBuilder enumBuilder = Helpers.DynamicEnum(TypeAttributes.Public, underlyingType);
AssertExtensions.Throws<ArgumentException>(null, () => enumBuilder.DefineLiteral("LiteralName", literalValue));
}
public static IEnumerable<object[]> DefineLiteral_InvalidLiteralValue_ThrowsTypeLoadExceptionOnCreation_TestData()
{
yield return new object[] { typeof(DateTime), DateTime.Now };
yield return new object[] { typeof(string), "" }; ;
}
[Theory]
[MemberData(nameof(DefineLiteral_InvalidLiteralValue_ThrowsTypeLoadExceptionOnCreation_TestData))]
public void DefineLiteral_InvalidLiteralValue_ThrowsTypeLoadExceptionOnCreation(Type underlyingType, object literalValue)
{
EnumBuilder enumBuilder = Helpers.DynamicEnum(TypeAttributes.Public, underlyingType);
FieldBuilder literal = enumBuilder.DefineLiteral("LiteralName", literalValue);
Assert.Throws<TypeLoadException>(() => enumBuilder.CreateTypeInfo());
}
[Fact]
public void IsAssignableFrom()
{
EnumBuilder enumBuilder = Helpers.DynamicEnum(TypeAttributes.Public, typeof(int));
Assert.False(enumBuilder.IsAssignableFrom(null));
Assert.True(enumBuilder.IsAssignableFrom(typeof(int).GetTypeInfo()));
Assert.False(enumBuilder.IsAssignableFrom(typeof(short).GetTypeInfo()));
}
[Fact]
public void GetElementType_ThrowsNotSupportedException()
{
EnumBuilder enumBuilder = Helpers.DynamicEnum(TypeAttributes.Public, typeof(int));
Assert.Throws<NotSupportedException>(() => enumBuilder.GetElementType());
}
[Fact]
public void MakeArrayType()
{
EnumBuilder enumBuilder = Helpers.DynamicEnum(TypeAttributes.Public, typeof(int), enumName: "TestEnum");
Type arrayType = enumBuilder.MakeArrayType();
Assert.Equal(typeof(Array), arrayType.GetTypeInfo().BaseType);
Assert.Equal("TestEnum[]", arrayType.Name);
}
[Theory]
[InlineData(1)]
[InlineData(2)]
[InlineData(260)]
public void MakeArrayType_Int(int rank)
{
EnumBuilder enumBuilder = Helpers.DynamicEnum(TypeAttributes.Public, typeof(int), enumName: "TestEnum");
Type arrayType = enumBuilder.MakeArrayType(rank);
string ranks = rank == 1 ? "*" : string.Empty;
for (int i = 1; i < rank; i++)
{
ranks += ",";
}
Assert.Equal(typeof(Array), arrayType.GetTypeInfo().BaseType);
Assert.Equal($"TestEnum[{ranks}]", arrayType.Name);
}
[Theory]
[InlineData(0)]
[InlineData(-1)]
public void MakeArrayType_Int_RankLessThanOne_ThrowsIndexOutOfRange(int rank)
{
EnumBuilder enumBuilder = Helpers.DynamicEnum(TypeAttributes.Public, typeof(int), enumName: "TestEnum");
Assert.Throws<IndexOutOfRangeException>(() => enumBuilder.MakeArrayType(rank));
}
[Fact]
public void MakeByRefType()
{
EnumBuilder enumBuilder = Helpers.DynamicEnum(TypeAttributes.Public, typeof(int), enumName: "TestEnum");
Type arrayType = enumBuilder.MakeByRefType();
Assert.Equal(typeof(Array), arrayType.GetTypeInfo().BaseType);
Assert.Equal("TestEnum&", arrayType.Name);
}
[Fact]
public void MakePointerType()
{
EnumBuilder enumBuilder = Helpers.DynamicEnum(TypeAttributes.Public, typeof(int), enumName: "TestEnum");
Type arrayType = enumBuilder.MakePointerType();
Assert.Equal(typeof(Array), arrayType.GetTypeInfo().BaseType);
Assert.Equal("TestEnum*", arrayType.Name);
}
[Fact]
public void SetCustomAttribute_ConstructorInfo_ByteArray()
{
EnumBuilder enumBuilder = Helpers.DynamicEnum(TypeAttributes.Public, typeof(int));
enumBuilder.CreateTypeInfo().AsType();
ConstructorInfo attributeConstructor = typeof(BoolAttribute).GetConstructor(new Type[] { typeof(bool) });
enumBuilder.SetCustomAttribute(attributeConstructor, new byte[] { 01, 00, 01 });
Attribute[] objVals = (Attribute[])CustomAttributeExtensions.GetCustomAttributes(enumBuilder, true).ToArray();
Assert.Equal(new BoolAttribute(true), objVals[0]);
}
[Fact]
public void SetCustomAttribute_CustomAttributeBuilder()
{
EnumBuilder enumBuilder = Helpers.DynamicEnum(TypeAttributes.Public, typeof(int));
enumBuilder.CreateTypeInfo().AsType();
ConstructorInfo attributeConstructor = typeof(BoolAttribute).GetConstructor(new Type[] { typeof(bool) });
CustomAttributeBuilder attributeBuilder = new CustomAttributeBuilder(attributeConstructor, new object[] { true });
enumBuilder.SetCustomAttribute(attributeBuilder);
object[] objVals = enumBuilder.GetCustomAttributes(true).ToArray();
Assert.Equal(new BoolAttribute(true), objVals[0]);
}
public class BoolAttribute : Attribute
{
private bool _b;
public BoolAttribute(bool myBool) { _b = myBool; }
}
}
}
| |
using System;
using System.Globalization;
namespace ClosedXML.Excel
{
public enum XLScope
{
Workbook,
Worksheet
}
public interface IXLRangeBase : IXLAddressable
{
IXLWorksheet Worksheet { get; }
/// <summary>
/// Sets a value to every cell in this range.
/// <para>If the object is an IEnumerable ClosedXML will copy the collection's data into a table starting from each cell.</para>
/// <para>If the object is a range ClosedXML will copy the range starting from each cell.</para>
/// <para>Setting the value to an object (not IEnumerable/range) will call the object's ToString() method.</para>
/// <para>ClosedXML will try to translate it to the corresponding type, if it can't then the value will be left as a string.</para>
/// </summary>
/// <value>
/// The object containing the value(s) to set.
/// </value>
Object Value { set; }
/// <summary>
/// Sets the type of the cells' data.
/// <para>Changing the data type will cause ClosedXML to covert the current value to the new data type.</para>
/// <para>An exception will be thrown if the current value cannot be converted to the new data type.</para>
/// </summary>
/// <value>
/// The type of the cell's data.
/// </value>
/// <exception cref = "ArgumentException"></exception>
XLDataType DataType { set; }
/// <summary>
/// Sets the cells' formula with A1 references.
/// </summary>
/// <value>The formula with A1 references.</value>
String FormulaA1 { set; }
/// <summary>
/// Sets the cells' formula with R1C1 references.
/// </summary>
/// <value>The formula with R1C1 references.</value>
String FormulaR1C1 { set; }
IXLStyle Style { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this cell's text should be shared or not.
/// </summary>
/// <value>
/// If false the cell's text will not be shared and stored as an inline value.
/// </value>
Boolean ShareString { set; }
IXLHyperlinks Hyperlinks { get; }
/// <summary>
/// Returns the collection of cells.
/// </summary>
IXLCells Cells();
IXLCells Cells(Boolean usedCellsOnly);
[Obsolete("Use the overload with XLCellsUsedOptions")]
IXLCells Cells(Boolean usedCellsOnly, Boolean includeFormats);
IXLCells Cells(Boolean usedCellsOnly, XLCellsUsedOptions options);
IXLCells Cells(String cells);
IXLCells Cells(Func<IXLCell, Boolean> predicate);
/// <summary>
/// Returns the collection of cells that have a value. Formats are ignored.
/// </summary>
IXLCells CellsUsed();
/// <summary>
/// Returns the collection of cells that have a value.
/// </summary>
/// <param name = "includeFormats">if set to <c>true</c> will return all cells with a value or a style different than the default.</param>
[Obsolete("Use the overload with XLCellsUsedOptions")]
IXLCells CellsUsed(Boolean includeFormats);
IXLCells CellsUsed(XLCellsUsedOptions options);
IXLCells CellsUsed(Func<IXLCell, Boolean> predicate);
[Obsolete("Use the overload with XLCellsUsedOptions")]
IXLCells CellsUsed(Boolean includeFormats, Func<IXLCell, Boolean> predicate);
IXLCells CellsUsed(XLCellsUsedOptions options, Func<IXLCell, Boolean> predicate);
/// <summary>
/// Searches the cells' contents for a given piece of text
/// </summary>
/// <param name="searchText">The search text.</param>
/// <param name="compareOptions">The compare options.</param>
/// <param name="searchFormulae">if set to <c>true</c> search formulae instead of cell values.</param>
/// <returns></returns>
IXLCells Search(String searchText, CompareOptions compareOptions = CompareOptions.Ordinal, Boolean searchFormulae = false);
/// <summary>
/// Returns the first cell of this range.
/// </summary>
IXLCell FirstCell();
/// <summary>
/// Returns the first cell with a value of this range. Formats are ignored.
/// <para>The cell's address is going to be ([First Row with a value], [First Column with a value])</para>
/// </summary>
IXLCell FirstCellUsed();
/// <summary>
/// Returns the first cell with a value of this range.
/// </summary>
/// <para>The cell's address is going to be ([First Row with a value], [First Column with a value])</para>
/// <param name = "includeFormats">if set to <c>true</c> will return all cells with a value or a style different than the default.</param>
[Obsolete("Use the overload with XLCellsUsedOptions")]
IXLCell FirstCellUsed(Boolean includeFormats);
IXLCell FirstCellUsed(XLCellsUsedOptions options);
IXLCell FirstCellUsed(Func<IXLCell, Boolean> predicate);
[Obsolete("Use the overload with XLCellsUsedOptions")]
IXLCell FirstCellUsed(Boolean includeFormats, Func<IXLCell, Boolean> predicate);
IXLCell FirstCellUsed(XLCellsUsedOptions options, Func<IXLCell, Boolean> predicate);
/// <summary>
/// Returns the last cell of this range.
/// </summary>
IXLCell LastCell();
/// <summary>
/// Returns the last cell with a value of this range. Formats are ignored.
/// <para>The cell's address is going to be ([Last Row with a value], [Last Column with a value])</para>
/// </summary>
IXLCell LastCellUsed();
/// <summary>
/// Returns the last cell with a value of this range.
/// </summary>
/// <para>The cell's address is going to be ([Last Row with a value], [Last Column with a value])</para>
/// <param name = "includeFormats">if set to <c>true</c> will return all cells with a value or a style different than the default.</param>
[Obsolete("Use the overload with XLCellsUsedOptions")]
IXLCell LastCellUsed(Boolean includeFormats);
IXLCell LastCellUsed(XLCellsUsedOptions options);
IXLCell LastCellUsed(Func<IXLCell, Boolean> predicate);
[Obsolete("Use the overload with XLCellsUsedOptions")]
IXLCell LastCellUsed(Boolean includeFormats, Func<IXLCell, Boolean> predicate);
IXLCell LastCellUsed(XLCellsUsedOptions options, Func<IXLCell, Boolean> predicate);
/// <summary>
/// Determines whether this range contains the specified range (completely).
/// <para>For partial matches use the range.Intersects method.</para>
/// </summary>
/// <param name = "rangeAddress">The range address.</param>
/// <returns>
/// <c>true</c> if this range contains the specified range; otherwise, <c>false</c>.
/// </returns>
Boolean Contains(String rangeAddress);
/// <summary>
/// Determines whether this range contains the specified range (completely).
/// <para>For partial matches use the range.Intersects method.</para>
/// </summary>
/// <param name = "range">The range to match.</param>
/// <returns>
/// <c>true</c> if this range contains the specified range; otherwise, <c>false</c>.
/// </returns>
Boolean Contains(IXLRangeBase range);
Boolean Contains(IXLCell cell);
/// <summary>
/// Determines whether this range intersects the specified range.
/// <para>For whole matches use the range.Contains method.</para>
/// </summary>
/// <param name = "rangeAddress">The range address.</param>
/// <returns>
/// <c>true</c> if this range intersects the specified range; otherwise, <c>false</c>.
/// </returns>
Boolean Intersects(String rangeAddress);
/// <summary>
/// Determines whether this range contains the specified range.
/// <para>For whole matches use the range.Contains method.</para>
/// </summary>
/// <param name = "range">The range to match.</param>
/// <returns>
/// <c>true</c> if this range intersects the specified range; otherwise, <c>false</c>.
/// </returns>
Boolean Intersects(IXLRangeBase range);
/// <summary>
/// Unmerges this range.
/// </summary>
IXLRange Unmerge();
/// <summary>
/// Merges this range.
/// <para>The contents and style of the merged cells will be equal to the first cell.</para>
/// </summary>
IXLRange Merge();
IXLRange Merge(Boolean checkIntersect);
/// <summary>
/// Creates a named range out of this range.
/// <para>If the named range exists, it will add this range to that named range.</para>
/// <para>The default scope for the named range is Workbook.</para>
/// </summary>
/// <param name = "rangeName">Name of the range.</param>
IXLRange AddToNamed(String rangeName);
/// <summary>
/// Creates a named range out of this range.
/// <para>If the named range exists, it will add this range to that named range.</para>
/// <param name = "rangeName">Name of the range.</param>
/// <param name = "scope">The scope for the named range.</param>
/// </summary>
IXLRange AddToNamed(String rangeName, XLScope scope);
/// <summary>
/// Creates a named range out of this range.
/// <para>If the named range exists, it will add this range to that named range.</para>
/// <param name = "rangeName">Name of the range.</param>
/// <param name = "scope">The scope for the named range.</param>
/// <param name = "comment">The comments for the named range.</param>
/// </summary>
IXLRange AddToNamed(String rangeName, XLScope scope, String comment);
/// <summary>
/// Clears the contents of this range.
/// </summary>
/// <param name="clearOptions">Specify what you want to clear.</param>
IXLRangeBase Clear(XLClearOptions clearOptions = XLClearOptions.All);
/// <summary>
/// Deletes the cell comments from this range.
/// </summary>
void DeleteComments();
IXLRangeBase SetValue<T>(T value);
/// <summary>
/// Converts this object to a range.
/// </summary>
IXLRange AsRange();
Boolean IsMerged();
Boolean IsEmpty();
[Obsolete("Use the overload with XLCellsUsedOptions")]
Boolean IsEmpty(Boolean includeFormats);
Boolean IsEmpty(XLCellsUsedOptions options);
/// <summary>
/// Determines whether range address spans the entire column.
/// </summary>
/// <returns>
/// <c>true</c> if is entire column; otherwise, <c>false</c>.
/// </returns>
Boolean IsEntireColumn();
/// <summary>
/// Determines whether range address spans the entire row.
/// </summary>
/// <returns>
/// <c>true</c> if is entire row; otherwise, <c>false</c>.
/// </returns>
Boolean IsEntireRow();
/// <summary>
/// Determines whether the range address spans the entire worksheet.
/// </summary>
/// <returns>
/// <c>true</c> if is entire sheet; otherwise, <c>false</c>.
/// </returns>
Boolean IsEntireSheet();
IXLPivotTable CreatePivotTable(IXLCell targetCell, String name);
//IXLChart CreateChart(Int32 firstRow, Int32 firstColumn, Int32 lastRow, Int32 lastColumn);
IXLAutoFilter SetAutoFilter();
IXLAutoFilter SetAutoFilter(Boolean value);
/// <summary>
/// Returns a data validation rule assigned to the range, if any, or creates a new instance of data validation rule if no rule exists.
/// </summary>
IXLDataValidation GetDataValidation();
/// <summary>
/// Creates a new data validation rule for the range, replacing the existing one.
/// </summary>
IXLDataValidation CreateDataValidation();
[Obsolete("Use GetDataValidation() to access the existing rule, or CreateDataValidation() to create a new one.")]
IXLDataValidation SetDataValidation();
IXLConditionalFormat AddConditionalFormat();
void Select();
/// <summary>
/// Grows this the current range by one cell to each side
/// </summary>
IXLRangeBase Grow();
/// <summary>
/// Grows this the current range by the specified number of cells to each side.
/// </summary>
/// <param name="growCount">The grow count.</param>
/// <returns></returns>
IXLRangeBase Grow(Int32 growCount);
/// <summary>
/// Shrinks this current range by one cell.
/// </summary>
IXLRangeBase Shrink();
/// <summary>
/// Shrinks the current range by the specified number of cells from each side.
/// </summary>
/// <param name="shrinkCount">The shrink count.</param>
/// <returns></returns>
IXLRangeBase Shrink(Int32 shrinkCount);
/// <summary>
/// Returns the intersection of this range with another range on the same worksheet.
/// </summary>
/// <param name="otherRange">The other range.</param>
/// <param name="thisRangePredicate">Predicate applied to this range's cells.</param>
/// <param name="otherRangePredicate">Predicate applied to the other range's cells.</param>
/// <returns>The range address of the intersection</returns>
IXLRangeAddress Intersection(IXLRangeBase otherRange, Func<IXLCell, Boolean> thisRangePredicate = null, Func<IXLCell, Boolean> otherRangePredicate = null);
/// <summary>
/// Returns the set of cells surrounding the current range.
/// </summary>
/// <param name="predicate">The predicate to apply on the resulting set of cells.</param>
IXLCells SurroundingCells(Func<IXLCell, Boolean> predicate = null);
/// <summary>
/// Calculates the union of two ranges on the same worksheet.
/// </summary>
/// <param name="otherRange">The other range.</param>
/// <param name="thisRangePredicate">Predicate applied to this range's cells.</param>
/// <param name="otherRangePredicate">Predicate applied to the other range's cells.</param>
/// <returns>
/// The union
/// </returns>
IXLCells Union(IXLRangeBase otherRange, Func<IXLCell, Boolean> thisRangePredicate = null, Func<IXLCell, Boolean> otherRangePredicate = null);
/// <summary>
/// Returns all cells in the current range that are not in the other range.
/// </summary>
/// <param name="otherRange">The other range.</param>
/// <param name="thisRangePredicate">Predicate applied to this range's cells.</param>
/// <param name="otherRangePredicate">Predicate applied to the other range's cells.</param>
/// <returns></returns>
IXLCells Difference(IXLRangeBase otherRange, Func<IXLCell, Boolean> thisRangePredicate = null, Func<IXLCell, Boolean> otherRangePredicate = null);
/// <summary>
/// Returns a range so that its offset from the target base range is equal to the offset of the current range to the source base range.
/// For example, if the current range is D4:E4, the source base range is A1:C3, then the relative range to the target base range B10:D13 is E14:F14
/// </summary>
/// <param name="sourceBaseRange">The source base range.</param>
/// <param name="targetBaseRange">The target base range.</param>
/// <returns>The relative range</returns>
IXLRangeBase Relative(IXLRangeBase sourceBaseRange, IXLRangeBase targetBaseRange);
}
}
| |
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.txt file at the root of this distribution.
*
* You must not remove this notice, or any other, from this software.
*
* ***************************************************************************/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell.Interop;
using MSBuild = Microsoft.Build.Evaluation;
using OleConstants = Microsoft.VisualStudio.OLE.Interop.Constants;
using VsCommands = Microsoft.VisualStudio.VSConstants.VSStd97CmdID;
using VsCommands2K = Microsoft.VisualStudio.VSConstants.VSStd2KCmdID;
using XSharpModel;
using Microsoft.VisualStudio.Shell;
namespace Microsoft.VisualStudio.Project
{
[CLSCompliant(false), ComVisible(true)]
public class ReferenceContainerNodeProperties : NodeProperties
{
#region properties
[SRCategoryAttribute(Microsoft.VisualStudio.Project.SR.Misc)]
[LocDisplayName(Microsoft.VisualStudio.Project.SR.FolderName)]
[SRDescriptionAttribute(Microsoft.VisualStudio.Project.SR.FolderNameDescription)]
[AutomationBrowsable( false )]
public string FolderName
{
get
{
return this.Node.Caption;
}
}
#endregion
#region ctors
public ReferenceContainerNodeProperties( HierarchyNode node )
: base( node )
{
}
#endregion
#region overridden methods
public override string GetClassName()
{
return Microsoft.VisualStudio.Project.SR.GetString(Microsoft.VisualStudio.Project.SR.FolderProperties, CultureInfo.CurrentUICulture);
}
#endregion
}
[CLSCompliant(false), ComVisible(true)]
public class ReferenceContainerNode : HierarchyNode, IReferenceContainer
{
#region fields
internal const string ReferencesNodeVirtualName = "References";
#endregion
#region ctor
public ReferenceContainerNode(ProjectNode root)
: base(root)
{
this.VirtualNodeName = ReferencesNodeVirtualName;
this.ExcludeNodeFromScc = true;
}
#endregion
#region Properties
private static string[] supportedReferenceTypes = new string[] {
ProjectFileConstants.ProjectReference,
ProjectFileConstants.Reference,
ProjectFileConstants.COMReference
};
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
protected virtual string[] SupportedReferenceTypes
{
get { return supportedReferenceTypes; }
}
#endregion
#region overridden properties
public override int SortPriority
{
get
{
return DefaultSortOrderNode.ReferenceContainerNode;
}
}
public override int MenuCommandId
{
get { return VsMenus.IDM_VS_CTXT_REFERENCEROOT; }
}
public override Guid ItemTypeGuid
{
get { return VSConstants.GUID_ItemType_VirtualFolder; }
}
public override string Url
{
get { return this.VirtualNodeName; }
}
public override string Caption
{
get
{
return SR.GetString(SR.ReferencesNodeName, CultureInfo.CurrentUICulture);
}
}
private Automation.OAReferences references;
public override object Object
{
get
{
if(null == references)
{
references = new Automation.OAReferences(this, ProjectMgr);
}
return references;
}
}
#endregion
#region overridden methods
// Added this so ReferenceFolder nodes return a properties object.
// Otherwise OAProjectItem.Properties returns null instead of an EnvDTE.Properies
// object. This causes the WPF designer to blow chunks, for example when the cursor is
// placed over the 'Cursor' property in the properties window while a WPF form has focus.
// The WPF desginer checks the properties collection on each hierarchy node looking for
// something, and when it hits the ReferenceContainerNode it blows chunks because
// it calls MoveNext() on what it expected to be a EnvDTE.Properties collection, but
// it is null.
protected override NodeProperties CreatePropertiesObject()
{
return new ReferenceContainerNodeProperties( this );
}
/// <summary>
/// Returns an instance of the automation object for ReferenceContainerNode
/// </summary>
/// <returns>An intance of the Automation.OAReferenceFolderItem type if succeeeded</returns>
public override object GetAutomationObject()
{
if(this.ProjectMgr == null || this.ProjectMgr.IsClosed)
{
return null;
}
return new Automation.OAReferenceFolderItem(this.ProjectMgr.GetAutomationObject() as Automation.OAProject, this);
}
/// <summary>
/// Disable inline editing of Caption of a ReferendeContainerNode
/// </summary>
/// <returns>null</returns>
public override string GetEditLabel()
{
return null;
}
public override object GetIconHandle(bool open)
{
return this.ProjectMgr.ImageHandler.GetIconHandle(open ? (int)ProjectNode.ImageName.OpenReferenceFolder : (int)ProjectNode.ImageName.ReferenceFolder);
}
/// <summary>
/// References node cannot be dragged.
/// </summary>
/// <returns>A stringbuilder.</returns>
protected internal override StringBuilder PrepareSelectedNodesForClipBoard()
{
return null;
}
/// <summary>
/// Not supported.
/// </summary>
protected override int ExcludeFromProject()
{
return (int)OleConstants.OLECMDERR_E_NOTSUPPORTED;
}
protected override int QueryStatusOnNode(Guid cmdGroup, uint cmd, IntPtr pCmdText, ref QueryStatusResult result)
{
if(cmdGroup == VsMenus.guidStandardCommandSet97)
{
switch((VsCommands)cmd)
{
case VsCommands.AddNewItem:
case VsCommands.AddExistingItem:
result |= QueryStatusResult.SUPPORTED | QueryStatusResult.ENABLED;
return VSConstants.S_OK;
}
}
else if(cmdGroup == VsMenus.guidStandardCommandSet2K)
{
if((VsCommands2K)cmd == VsCommands2K.ADDREFERENCE)
{
result |= QueryStatusResult.SUPPORTED | QueryStatusResult.ENABLED;
return VSConstants.S_OK;
}
}
else
{
return (int)OleConstants.OLECMDERR_E_UNKNOWNGROUP;
}
return base.QueryStatusOnNode(cmdGroup, cmd, pCmdText, ref result);
}
protected override int ExecCommandOnNode(Guid cmdGroup, uint cmd, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut)
{
ThreadHelper.ThrowIfNotOnUIThread();
if (cmdGroup == VsMenus.guidStandardCommandSet2K)
{
switch((VsCommands2K)cmd)
{
case VsCommands2K.ADDREFERENCE:
return this.ProjectMgr.AddProjectReference();
case VsCommands2K.ADDWEBREFERENCE:
return this.ProjectMgr.AddWebReference();
}
}
return base.ExecCommandOnNode(cmdGroup, cmd, nCmdexecopt, pvaIn, pvaOut);
}
protected override bool CanDeleteItem(__VSDELETEITEMOPERATION deleteOperation)
{
return false;
}
/// <summary>
/// Defines whether this node is valid node for painting the refererences icon.
/// </summary>
/// <returns></returns>
protected override bool CanShowDefaultIcon()
{
if(!String.IsNullOrEmpty(this.VirtualNodeName))
{
return true;
}
return false;
}
#endregion
#region IReferenceContainer
public IList<ReferenceNode> EnumReferences()
{
List<ReferenceNode> refs = new List<ReferenceNode>();
for(HierarchyNode node = this.FirstChild; node != null; node = node.NextSibling)
{
ReferenceNode refNode = node as ReferenceNode;
if(refNode != null)
{
refs.Add(refNode);
}
}
return refs;
}
/// <summary>
/// Adds references to this container from a MSBuild project.
/// </summary>
public void LoadReferencesFromBuildProject(MSBuild.Project buildProject)
{
ThreadHelper.ThrowIfNotOnUIThread();
List<ReferenceNode> duplicatedNode = new List<ReferenceNode>();
BuildResult buildResult = this.ProjectMgr.Build(MsBuildTarget.ResolveAssemblyReferences);
var children = new List<ReferenceNode>();
foreach (string referenceType in SupportedReferenceTypes)
{
bool isAssemblyReference = referenceType == ProjectFileConstants.Reference;
if (isAssemblyReference && !buildResult.IsSuccessful)
{
continue;
}
foreach (var item in MSBuildProject.GetItems(buildProject, referenceType))
{
ProjectElement element = new ProjectElement(this.ProjectMgr, item, false);
ReferenceNode node = CreateReferenceNode(referenceType, element);
if(node != null)
{
// Make sure that we do not want to add the item twice to the ui hierarchy
// We are using here the UI representation of the Node namely the Caption to find that out, in order to
// avoid different representation problems.
// Example :<Reference Include="EnvDTE80, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
// <Reference Include="EnvDTE80" />
bool found = false;
for(HierarchyNode n = this.FirstChild; n != null && !found; n = n.NextSibling)
{
if(String.Compare(n.Caption, node.Caption, StringComparison.OrdinalIgnoreCase) == 0)
{
found = true;
break;
}
}
if(!found)
{
this.AddChild(node);
children.Add(node);
}
else
{
duplicatedNode.Add(node);
}
}
}
}
// Now manage duplicates
if (duplicatedNode.Count > 0)
{
foreach (ReferenceNode node in duplicatedNode)
{
node.Remove(false);
}
if (this.ProjectMgr.QueryEditProjectFile(true))
{
buildProject.Save();
}
}
var references = buildResult.ProjectInstance.GetItems(ProjectFileConstants.ReferencePath);
//var references = MSBuildProjectInstance.GetItems(buildResult.ProjectInstance, ProjectFileConstants.ReferencePath);
foreach (var reference in references)
{
string fullName = MSBuildItem.GetEvaluatedInclude(reference);
string name = Path.GetFileNameWithoutExtension(fullName);
foreach (var child in children)
{
if (child is AssemblyReferenceNode && child.Caption == name)
{
var xChild = child as AssemblyReferenceNode;
xChild.AssemblyPath = fullName;
xChild.SetHintPathAndPrivateValue(buildResult.ProjectInstance, reference);
}
}
}
}
/// <summary>
/// Adds a reference to this container using the selector data structure to identify it.
/// </summary>
/// <param name="selectorData">data describing selected component</param>
/// <returns>Reference in case of a valid reference node has been created. Otherwise null</returns>
public virtual ReferenceNode AddReferenceFromSelectorData(VSCOMPONENTSELECTORDATA selectorData, string wrapperTool = null)
{
//Make sure we can edit the project file
ThreadHelper.ThrowIfNotOnUIThread();
if (!this.ProjectMgr.QueryEditProjectFile(false))
{
throw Marshal.GetExceptionForHR(VSConstants.OLE_E_PROMPTSAVECANCELLED);
}
//Create the reference node
ReferenceNode node = null;
try
{
node = CreateReferenceNode(selectorData, wrapperTool);
}
catch(ArgumentException)
{
// Some selector data was not valid.
}
//Add the reference node to the project if we have a valid reference node
if(node != null)
{
// Does such a reference already exist in the project?
ReferenceNode existingNode;
if (node.IsAlreadyAdded(out existingNode))
{
return existingNode;
}
// This call will find if the reference is in the project and, in this case
// will not add it again, so the parent node will not be set.
node.AddReference();
if(null == node.Parent)
{
// The reference was not added, so we can not return this item because it
// is not inside the project.
return null;
}
}
return node;
}
#endregion
#region virtual methods
protected virtual ReferenceNode CreateReferenceNode(string referenceType, ProjectElement element)
{
ReferenceNode node = null;
try
{
if (referenceType == ProjectFileConstants.COMReference)
{
node = this.CreateComReferenceNode(element);
}
else if (referenceType == ProjectFileConstants.Reference)
{
node = this.CreateAssemblyReferenceNode(element);
}
else if (referenceType == ProjectFileConstants.ProjectReference)
{
node = this.CreateProjectReferenceNode(element);
}
}
catch (Exception ex)
{
if (System.Diagnostics.Debugger.IsAttached)
Debug.WriteLine(ex.ToString());
}
return node;
}
protected virtual ReferenceNode CreateReferenceNode(VSCOMPONENTSELECTORDATA selectorData, string wrapperTool = null)
{
ReferenceNode node = null;
switch(selectorData.type)
{
case VSCOMPONENTTYPE.VSCOMPONENTTYPE_Project:
node = this.CreateProjectReferenceNode(selectorData);
break;
case VSCOMPONENTTYPE.VSCOMPONENTTYPE_File:
// This is the case for managed assembly
case VSCOMPONENTTYPE.VSCOMPONENTTYPE_ComPlus:
node = this.CreateFileComponent(selectorData, wrapperTool);
break;
case VSCOMPONENTTYPE.VSCOMPONENTTYPE_Com2:
node = this.CreateComReferenceNode(selectorData, wrapperTool);
break;
}
return node;
}
#endregion
#region Helper functions to add references
/// <summary>
/// Creates a project reference node given an existing project element.
/// </summary>
protected virtual ProjectReferenceNode CreateProjectReferenceNode(ProjectElement element)
{
return new ProjectReferenceNode(this.ProjectMgr, element);
}
/// <summary>
/// Create a Project to Project reference given a VSCOMPONENTSELECTORDATA structure
/// </summary>
protected virtual ProjectReferenceNode CreateProjectReferenceNode(VSCOMPONENTSELECTORDATA selectorData)
{
return new ProjectReferenceNode(this.ProjectMgr, selectorData.bstrTitle, selectorData.bstrFile, selectorData.bstrProjRef);
}
/// <summary>
/// Creates an assemby or com reference node given a selector data.
/// </summary>
protected virtual ReferenceNode CreateFileComponent(VSCOMPONENTSELECTORDATA selectorData, string wrapperTool = null)
{
if(null == selectorData.bstrFile)
{
throw new ArgumentNullException("selectorData");
}
// refer to http://social.msdn.microsoft.com/Forums/en-US/vsx/thread/50af4ee8-1431-4d27-86c4-7db799c3f085
if ( selectorData.bstrFile[0] == '*' )
{
selectorData.bstrFile = selectorData.bstrFile.Substring( 1 );
}
// We have a path to a file, it could be anything
// First see if it is a managed assembly
bool tryToCreateAnAssemblyReference = true;
if(File.Exists(selectorData.bstrFile))
{
try
{
// We should not load the assembly in the current appdomain.
// If we do not do it like that and we load the assembly in the current appdomain then the assembly cannot be unloaded again.
// The following problems might arose in that case.
// 1. Assume that a user is extending the MPF and his project is creating a managed assembly dll.
// 2. The user opens VS and creates a project and builds it.
// 3. Then the user opens VS creates another project and adds a reference to the previously built assembly. This will load the assembly in the appdomain had we been using Assembly.ReflectionOnlyLoadFrom.
// 4. Then he goes back to the first project modifies it an builds it. A build error is issued that the assembly is used.
// GetAssemblyName is assured not to load the assembly.
tryToCreateAnAssemblyReference = (AssemblyName.GetAssemblyName(selectorData.bstrFile) != null);
}
catch(BadImageFormatException)
{
// We have found the file and it is not a .NET assembly; no need to try to
// load it again.
tryToCreateAnAssemblyReference = false;
}
catch(FileLoadException)
{
// We must still try to load from here because this exception is thrown if we want
// to add the same assembly reference from different locations.
tryToCreateAnAssemblyReference = true;
}
}
ReferenceNode node = null;
if(tryToCreateAnAssemblyReference)
{
// This might be a candidate for an assembly reference node. Try to load it.
// CreateAssemblyReferenceNode will suppress BadImageFormatException if the node cannot be created.
node = this.CreateAssemblyReferenceNode(selectorData.bstrFile);
}
// If no node has been created try to create a com reference node.
if(node == null)
{
if(!File.Exists(selectorData.bstrFile))
{
return null;
}
node = this.CreateComReferenceNode(selectorData, wrapperTool);
}
return node;
}
/// <summary>
/// Creates an assembly reference node from a project element.
/// </summary>
protected virtual AssemblyReferenceNode CreateAssemblyReferenceNode(ProjectElement element)
{
AssemblyReferenceNode node = null;
try
{
node = new AssemblyReferenceNode(this.ProjectMgr, element);
}
catch(Exception e)
{
XSettings.LogException(e, "CreateAssemblyReferenceNode");
}
return node;
}
/// <summary>
/// Creates an assembly reference node from a file path.
/// </summary>
protected virtual AssemblyReferenceNode CreateAssemblyReferenceNode(string fileName)
{
AssemblyReferenceNode node = null;
try
{
node = new AssemblyReferenceNode(this.ProjectMgr, fileName);
}
catch(Exception e)
{
XSettings.LogException(e, "CreateAssemblyReferenceNode");
}
return node;
}
/// <summary>
/// Creates a com reference node from the project element.
/// </summary>
protected virtual ComReferenceNode CreateComReferenceNode(ProjectElement reference)
{
return new ComReferenceNode(this.ProjectMgr, reference);
}
/// <summary>
/// Creates a com reference node from a selector data.
/// </summary>
protected virtual ComReferenceNode CreateComReferenceNode(Microsoft.VisualStudio.Shell.Interop.VSCOMPONENTSELECTORDATA selectorData, string wrapperTool = null)
{
ComReferenceNode node = new ComReferenceNode(this.ProjectMgr, selectorData, wrapperTool);
return node;
}
#endregion
}
}
| |
/*
* XmlSchema.cs - Implementation of "XmlSchema" class
*
* Copyright (C) 2003 Southern Storm Software, Pty Ltd.
*
* Contributed by Gopal.V
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
using System;
using System.IO;
using System.Xml;
namespace System.Xml.Schema
{
public class XmlSchema: XmlSchemaObject
{
public const String InstanceNamespace="http://www.w3.org/2001/XMLSchema-instance";
public const String Namespace="http://www.w3.org/2001/XMLSchema";
[TODO]
public XmlSchema()
{
throw new NotImplementedException(".ctor");
}
[TODO]
public void Compile(ValidationEventHandler handler)
{
throw new NotImplementedException("Compile");
}
[TODO]
public static XmlSchema Read(TextReader reader,
ValidationEventHandler validationEventHandler)
{
throw new NotImplementedException("Read");
}
[TODO]
public static XmlSchema Read(Stream stream,
ValidationEventHandler validationEventHandler)
{
throw new NotImplementedException("Read");
}
[TODO]
public static XmlSchema Read(XmlReader rdr,
ValidationEventHandler validationEventHandler)
{
throw new NotImplementedException("Read");
}
[TODO]
public void Write(Stream stream)
{
throw new NotImplementedException("Write");
}
[TODO]
public void Write(TextWriter writer)
{
throw new NotImplementedException("Write");
}
[TODO]
public void Write(XmlWriter writer)
{
throw new NotImplementedException("Write");
}
[TODO]
public void Write(Stream stream, XmlNamespaceManager namespaceManager)
{
throw new NotImplementedException("Write");
}
[TODO]
public void Write(TextWriter writer, XmlNamespaceManager namespaceManager)
{
throw new NotImplementedException("Write");
}
[TODO]
public void Write(XmlWriter writer, XmlNamespaceManager namespaceManager)
{
throw new NotImplementedException("Write");
}
[TODO]
public XmlSchemaForm AttributeFormDefault
{
get
{
throw new NotImplementedException("AttributeFormDefault");
}
set
{
throw new NotImplementedException("AttributeFormDefault");
}
}
[TODO]
public XmlSchemaObjectTable AttributeGroups
{
get
{
throw new NotImplementedException("AttributeGroups");
}
}
[TODO]
public XmlSchemaObjectTable Attributes
{
get
{
throw new NotImplementedException("Attributes");
}
}
[TODO]
public XmlSchemaDerivationMethod BlockDefault
{
get
{
throw new NotImplementedException("BlockDefault");
}
set
{
throw new NotImplementedException("BlockDefault");
}
}
[TODO]
public XmlSchemaForm ElementFormDefault
{
get
{
throw new NotImplementedException("ElementFormDefault");
}
set
{
throw new NotImplementedException("ElementFormDefault");
}
}
[TODO]
public XmlSchemaObjectTable Elements
{
get
{
throw new NotImplementedException("Elements");
}
}
[TODO]
public XmlSchemaDerivationMethod FinalDefault
{
get
{
throw new NotImplementedException("FinalDefault");
}
set
{
throw new NotImplementedException("FinalDefault");
}
}
[TODO]
public XmlSchemaObjectTable Groups
{
get
{
throw new NotImplementedException("Groups");
}
}
[TODO]
public String Id
{
get
{
throw new NotImplementedException("Id");
}
set
{
throw new NotImplementedException("Id");
}
}
[TODO]
public XmlSchemaObjectCollection Includes
{
get
{
throw new NotImplementedException("Includes");
}
}
[TODO]
public bool IsCompiled
{
get
{
throw new NotImplementedException("IsCompiled");
}
}
[TODO]
public XmlSchemaObjectCollection Items
{
get
{
throw new NotImplementedException("Items");
}
}
[TODO]
public String Language
{
get
{
throw new NotImplementedException("Language");
}
set
{
throw new NotImplementedException("Language");
}
}
[TODO]
public XmlSchemaObjectTable Notations
{
get
{
throw new NotImplementedException("Notations");
}
}
[TODO]
public XmlSchemaObjectTable SchemaTypes
{
get
{
throw new NotImplementedException("SchemaTypes");
}
}
[TODO]
public String TargetNamespace
{
get
{
throw new NotImplementedException("TargetNamespace");
}
set
{
throw new NotImplementedException("TargetNamespace");
}
}
[TODO]
public XmlAttribute[] UnhandledAttributes
{
get
{
throw new NotImplementedException("UnhandledAttributes");
}
set
{
throw new NotImplementedException("UnhandledAttributes");
}
}
[TODO]
public String Version
{
get
{
throw new NotImplementedException("Version");
}
set
{
throw new NotImplementedException("Version");
}
}
}
}//namespace
| |
//
// Authors:
// Christian Hergert <[email protected]>
// Ben Motmans <[email protected]>
//
// Copyright (C) 2005 Mosaix Communications, Inc.
// Copyright (c) 2007 Ben Motmans
//
// 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.Threading;
using System.Collections.Generic;
using MonoDevelop.Database.Sql;
using MonoDevelop.Database.Designer;
using MonoDevelop.Core;
using MonoDevelop.Ide;
using MonoDevelop.Ide.Gui.Pads;
using MonoDevelop.Components.Commands;
using MonoDevelop.Ide.Gui.Components;
namespace MonoDevelop.Database.ConnectionManager
{
public class UserNodeBuilder : TypeNodeBuilder
{
public UserNodeBuilder ()
: base ()
{
}
public override Type NodeDataType {
get { return typeof (UserNode); }
}
public override string ContextMenuAddinPath {
get { return "/MonoDevelop/Database/ContextMenu/ConnectionManagerPad/UserNode"; }
}
public override Type CommandHandlerType {
get { return typeof (UserNodeCommandHandler); }
}
public override void GetNodeAttributes (ITreeNavigator treeNavigator, object dataObject, ref NodeAttributes attributes)
{
attributes |= NodeAttributes.AllowRename;
}
public override string GetNodeName (ITreeNavigator thisNode, object dataObject)
{
UserNode node = dataObject as UserNode;
return node.User.Name;
}
public override void BuildNode (ITreeBuilder builder, object dataObject, NodeInfo nodeInfo)
{
UserNode node = dataObject as UserNode;
// node.RefreshEvent += (EventHandler)DispatchService.GuiDispatch (RefreshHandler);
nodeInfo.Label = node.User.Name;
nodeInfo.Icon = Context.GetIcon ("md-db-user");
}
public override bool HasChildNodes (ITreeBuilder builder, object dataObject)
{
return false;
}
}
public class UserNodeCommandHandler : NodeCommandHandler
{
public override DragOperation CanDragNode ()
{
return DragOperation.None;
}
public override void RenameItem (string newName)
{
UserNode node = (UserNode)CurrentNode.DataItem;
if (node.User.Name != newName)
ThreadPool.QueueUserWorkItem (new WaitCallback (RenameItemThreaded), new object[]{ node, newName });
}
private void RenameItemThreaded (object state)
{
object[] objs = state as object[];
UserNode node = objs[0] as UserNode;
string newName = objs[1] as string;
IEditSchemaProvider provider = (IEditSchemaProvider)node.User.SchemaProvider;
if (provider.IsValidName (newName)) {
provider.RenameUser (node.User, newName);
node.Refresh ();
} else {
DispatchService.GuiDispatch (delegate () {
MessageService.ShowError (String.Format (
"Unable to rename user '{0}' to '{1}'!",
node.User.Name, newName
));
});
}
node.Refresh ();
}
protected void OnRefreshParent ()
{
if (CurrentNode.MoveToParent ()) {
BaseNode node = CurrentNode.DataItem as BaseNode;
node.Refresh ();
}
}
[CommandHandler (ConnectionManagerCommands.AlterUser)]
protected void OnAlterUser ()
{
UserNode node = CurrentNode.DataItem as UserNode;
IDbFactory fac = node.ConnectionContext.DbFactory;
IEditSchemaProvider schemaProvider = (IEditSchemaProvider)node.ConnectionContext.SchemaProvider;
if (fac.GuiProvider.ShowUserEditorDialog (schemaProvider, node.User, false))
ThreadPool.QueueUserWorkItem (new WaitCallback (OnAlterUserThreaded), CurrentNode.DataItem);
}
private void OnAlterUserThreaded (object state)
{
// UserNode node = (UserNode)state;
// IEditSchemaProvider provider = (IEditSchemaProvider)node.ConnectionContext.SchemaProvider;
//
// provider.AlterUser (node.User);
}
[CommandHandler (ConnectionManagerCommands.DropUser)]
protected void OnDropUser ()
{
UserNode node = (UserNode)CurrentNode.DataItem;
AlertButton dropButton = new AlertButton (AddinCatalog.GetString ("Drop"), Gtk.Stock.Delete);
if (MessageService.Confirm (
AddinCatalog.GetString ("Are you sure you want to drop user '{0}'", node.User.Name),
dropButton
)) {
ThreadPool.QueueUserWorkItem (new WaitCallback (OnDropUserThreaded), CurrentNode.DataItem);
}
}
private void OnDropUserThreaded (object state)
{
UserNode node = (UserNode)state;
IEditSchemaProvider provider = (IEditSchemaProvider)node.ConnectionContext.SchemaProvider;
provider.DropUser (node.User);
OnRefreshParent ();
}
[CommandHandler (MonoDevelop.Ide.Commands.EditCommands.Rename)]
protected void OnRenameUser ()
{
Tree.StartLabelEdit ();
}
[CommandUpdateHandler (ConnectionManagerCommands.DropUser)]
protected void OnUpdateDropUser (CommandInfo info)
{
BaseNode node = (BaseNode)CurrentNode.DataItem;
info.Enabled = node.ConnectionContext.SchemaProvider.IsSchemaActionSupported (SchemaType.User, SchemaActions.Drop);
}
[CommandUpdateHandler (MonoDevelop.Ide.Commands.EditCommands.Rename)]
protected void OnUpdateRenameUser (CommandInfo info)
{
BaseNode node = (BaseNode)CurrentNode.DataItem;
info.Enabled = node.ConnectionContext.SchemaProvider.IsSchemaActionSupported (SchemaType.User, SchemaActions.Rename);
}
[CommandUpdateHandler (ConnectionManagerCommands.AlterUser)]
protected void OnUpdateAlterUser (CommandInfo info)
{
BaseNode node = (BaseNode)CurrentNode.DataItem;
info.Enabled = node.ConnectionContext.SchemaProvider.IsSchemaActionSupported (SchemaType.User, SchemaActions.Alter);
}
}
}
| |
// 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.Collections.ObjectModel;
using System.ComponentModel.Composition.Factories;
using System.ComponentModel.Composition.Hosting;
using System.ComponentModel.Composition.Primitives;
using System.Linq;
using System.UnitTesting;
using Xunit;
namespace System.ComponentModel.Composition
{
public class CompositionBatchTests
{
[Fact]
public void Constructor1_PropertiesShouldBeSetAndEmpty()
{
CompositionBatch batch = new CompositionBatch();
Assert.NotNull(batch.PartsToAdd);
Assert.Empty(batch.PartsToAdd);
Assert.NotNull(batch.PartsToRemove);
Assert.Empty(batch.PartsToRemove);
}
[Fact]
public void Constructor2_PropertiesShouldBeSetAndMatchArguments()
{
ComposablePart[] partsToAdd = new ComposablePart[] { PartFactory.Create(), PartFactory.Create(), PartFactory.Create() };
ComposablePart[] partsToRemove = new ComposablePart[] { PartFactory.Create(), PartFactory.Create(), PartFactory.Create() };
CompositionBatch batch = new CompositionBatch(partsToAdd, partsToRemove);
Assert.NotNull(batch.PartsToAdd);
Assert.NotNull(batch.PartsToRemove);
EqualityExtensions.CheckEquals(batch.PartsToAdd, partsToAdd);
EqualityExtensions.CheckEquals(batch.PartsToRemove, partsToRemove);
}
[Fact]
public void Constructor2_PartsToAddAsNull_PartsToAddShouldBeEmpty()
{
ComposablePart[] partsToRemove = new ComposablePart[] { PartFactory.Create(), PartFactory.Create(), PartFactory.Create() };
var batch = new CompositionBatch(null, partsToRemove);
Assert.Equal(0, batch.PartsToAdd.Count);
Assert.Equal(partsToRemove.Length, batch.PartsToRemove.Count);
}
[Fact]
public void Constructor2_PartsToRemoveAsNull_PartsToRemoveShouldBeEmpty()
{
ComposablePart[] partsToAdd = new ComposablePart[] { PartFactory.Create(), PartFactory.Create(), PartFactory.Create() };
var batch = new CompositionBatch(partsToAdd, null);
Assert.Equal(partsToAdd.Length, batch.PartsToAdd.Count);
Assert.Equal(0, batch.PartsToRemove.Count);
}
[Fact]
public void Constructor2_PartsToAddHasNull_ShouldThrowArgumentNullException()
{
ComposablePart[] partsToAdd = new ComposablePart[] { PartFactory.Create(), null, PartFactory.Create() };
ComposablePart[] partsToRemove = new ComposablePart[] { PartFactory.Create(), PartFactory.Create(), PartFactory.Create() };
Assert.Throws<ArgumentException>("partsToAdd", () =>
{
new CompositionBatch(partsToAdd, partsToRemove);
});
}
[Fact]
public void Constructor2_PartsToRemoveHasNull_ShouldThrowArgumentNullException()
{
ComposablePart[] partsToAdd = new ComposablePart[] { PartFactory.Create(), PartFactory.Create(), PartFactory.Create() };
ComposablePart[] partsToRemove = new ComposablePart[] { PartFactory.Create(), null, PartFactory.Create() };
Assert.Throws<ArgumentException>("partsToRemove", () =>
{
new CompositionBatch(partsToAdd, partsToRemove);
});
}
[Fact]
public void AddPart_PartIsInPartsToAdd()
{
CompositionBatch batch = new CompositionBatch();
ComposablePart part = PartFactory.Create();
batch.AddPart(part);
Assert.Equal(1, batch.PartsToAdd.Count);
Assert.Same(part, batch.PartsToAdd[0]);
Assert.Empty(batch.PartsToRemove);
}
[Fact]
public void AddPart_PartAsNull_ShouldThrowArgumentNullException()
{
CompositionBatch batch = new CompositionBatch();
Assert.Throws<ArgumentNullException>("part", () =>
{
batch.AddPart(null);
});
}
[Fact]
public void RemovePart_PartIsInPartsToRemove()
{
CompositionBatch batch = new CompositionBatch();
ComposablePart part = PartFactory.Create();
batch.RemovePart(part);
Assert.Equal(1, batch.PartsToRemove.Count);
Assert.Same(part, batch.PartsToRemove[0]);
Assert.Empty(batch.PartsToAdd);
}
[Fact]
public void RemovePart_PartAsNull_ShouldThrowArgumentNullException()
{
CompositionBatch batch = new CompositionBatch();
Assert.Throws<ArgumentNullException>("part", () =>
{
batch.RemovePart(null);
});
}
[Fact]
public void PartsToAdd_ShouldGetCopiedAfterAdd()
{
CompositionBatch batch = new CompositionBatch();
ComposablePart part1 = PartFactory.Create();
ComposablePart part2 = PartFactory.Create();
batch.AddPart(part1);
Assert.True(batch.PartsToAdd.Contains(part1));
ReadOnlyCollection<ComposablePart> partsToAddBeforeCopy = batch.PartsToAdd;
Assert.Same(partsToAddBeforeCopy, batch.PartsToAdd);
Assert.Equal(1, partsToAddBeforeCopy.Count);
Assert.True(partsToAddBeforeCopy.Contains(part1));
batch.AddPart(part2);
ReadOnlyCollection<ComposablePart> partsToAddAfterCopy = batch.PartsToAdd;
Assert.Same(partsToAddAfterCopy, batch.PartsToAdd);
Assert.Equal(2, partsToAddAfterCopy.Count);
Assert.True(partsToAddAfterCopy.Contains(part1));
Assert.True(partsToAddAfterCopy.Contains(part2));
Assert.NotSame(partsToAddBeforeCopy, partsToAddAfterCopy);
}
[Fact]
public void PartsToRemove_ShouldGetCopiedAfterRemove()
{
CompositionBatch batch = new CompositionBatch();
ComposablePart part1 = PartFactory.Create();
ComposablePart part2 = PartFactory.Create();
batch.RemovePart(part1);
Assert.True(batch.PartsToRemove.Contains(part1));
ReadOnlyCollection<ComposablePart> partsToRemoveBeforeCopy = batch.PartsToRemove;
Assert.Same(partsToRemoveBeforeCopy, batch.PartsToRemove);
Assert.Equal(1, partsToRemoveBeforeCopy.Count);
Assert.True(partsToRemoveBeforeCopy.Contains(part1));
batch.RemovePart(part2);
ReadOnlyCollection<ComposablePart> partsToRemoveAfterCopy = batch.PartsToRemove;
Assert.Same(partsToRemoveAfterCopy, batch.PartsToRemove);
Assert.Equal(2, partsToRemoveAfterCopy.Count);
Assert.True(partsToRemoveAfterCopy.Contains(part1));
Assert.True(partsToRemoveAfterCopy.Contains(part2));
Assert.NotSame(partsToRemoveBeforeCopy, partsToRemoveAfterCopy);
}
[Fact]
public void AddExportedValue_NullAsContractNameArgument_ShouldThrowArgumentNull()
{
CompositionBatch batch = new CompositionBatch();
Assert.Throws<ArgumentNullException>("contractName", () =>
{
batch.AddExportedValue((string)null, "Value");
});
}
[Fact]
public void AddExportedValue_EmptyStringAsContractNameArgument_ShouldThrowArgument()
{
CompositionBatch batch = new CompositionBatch();
Assert.Throws<ArgumentException>("contractName", () =>
{
batch.AddExportedValue("", "Value");
});
}
[Fact]
public void AddExport_NullAsExportArgument_ShouldThrowArgumentNull()
{
CompositionBatch batch = new CompositionBatch();
Assert.Throws<ArgumentNullException>("export", () =>
{
batch.AddExport((Export)null);
});
}
[Fact]
public void AddExport_ExportWithNullExportedValueAsExportArgument_CanBeExported()
{
CompositionBatch batch = new CompositionBatch();
var export = ExportFactory.Create("Contract", (object)null);
batch.AddExport(export);
Assert.Equal(1, batch.PartsToAdd.Count);
var result = this.GetSingleExport(batch.PartsToAdd[0], "Contract");
Assert.NotNull(result);
Assert.Null(result.Value);
}
[Fact]
public void AddExportedValueOfT_NullAsExportedValueArgument_CanBeExported()
{
CompositionBatch batch = new CompositionBatch();
batch.AddExportedValue<string>((string)null);
Assert.Equal(1, batch.PartsToAdd.Count);
var result = this.GetSingleLazy<string>(batch.PartsToAdd[0]);
Assert.NotNull(result);
Assert.Null(result.Value);
}
[Fact]
public void AddExportedValue_NullAsExportedValueArgument_CanBeExported()
{
CompositionBatch batch = new CompositionBatch();
batch.AddExportedValue("Contract", (string)null);
Assert.Equal(1, batch.PartsToAdd.Count);
var result = this.GetSingleExport(batch.PartsToAdd[0], "Contract");
Assert.NotNull(result);
Assert.Null(result.Value);
}
[Fact]
public void AddExport_ExportWithEmptyMetadata_IsExportedWithEmptyMetadata()
{
CompositionBatch batch = new CompositionBatch();
var export = ExportFactory.Create("Contract", "Value", new Dictionary<string, object>());
Assert.Equal(0, export.Metadata.Count);
batch.AddExport(export);
Assert.Equal(1, batch.PartsToAdd.Count);
var result = this.GetSingleExport(batch.PartsToAdd[0], "Contract");
Assert.Equal(0, result.Metadata.Count);
}
[Fact]
public void AddExportedValueOfT_IsExportedWithEmptyMetadata()
{
CompositionBatch batch = new CompositionBatch();
batch.AddExportedValue<string>("Value");
Assert.Equal(1, batch.PartsToAdd.Count);
var result = this.GetSingleLazy<string>(batch.PartsToAdd[0]);
Assert.Equal(1, result.Metadata.Count); // contains type identity
}
[Fact]
public void AddExportedValue_IsExportedWithEmptyMetadata()
{
CompositionBatch batch = new CompositionBatch();
batch.AddExportedValue("Contract", "Value");
Assert.Equal(1, batch.PartsToAdd.Count);
var result = this.GetSingleExport(batch.PartsToAdd[0], "Contract");
Assert.Equal(1, result.Metadata.Count); // contains type identity
}
[Fact]
public void AddExport_ReturnedComposablePart_IsInAddedPartsCollection()
{
CompositionBatch batch = new CompositionBatch();
var export = ExportFactory.Create("Contract", "Value");
var part = batch.AddExport(export);
Assert.Equal(1, batch.PartsToAdd.Count);
Assert.Equal("Value", this.GetSingleExport(batch.PartsToAdd[0], "Contract").Value);
Assert.True(batch.PartsToAdd.Contains(part));
}
[Fact]
public void AddExportedValueOfT_ReturnedComposablePart_IsInAddedPartsCollection()
{
CompositionBatch batch = new CompositionBatch();
var part = batch.AddExportedValue<string>("Value");
Assert.Equal(1, batch.PartsToAdd.Count);
Assert.Equal("Value", this.GetSingleLazy<string>(batch.PartsToAdd[0]).Value);
Assert.True(batch.PartsToAdd.Contains(part));
}
[Fact]
public void AddExportedValue_ReturnedComposablePart_IsInAddedPartsCollection()
{
CompositionBatch batch = new CompositionBatch();
var part = batch.AddExportedValue("Contract", "Value");
Assert.Equal(1, batch.PartsToAdd.Count);
Assert.Equal("Value", this.GetSingleExport(batch.PartsToAdd[0], "Contract").Value);
Assert.True(batch.PartsToAdd.Contains(part));
}
[Fact]
public void AddExportedValueOfT_ExportAsExportedValueArgument_ShouldBeWrappedInExport()
{
CompositionBatch batch = new CompositionBatch();
var export = ExportFactory.Create("Contract", "Value");
batch.AddExportedValue<object>(export);
Assert.Equal(1, batch.PartsToAdd.Count);
Assert.Same(export, this.GetSingleLazy<object>(batch.PartsToAdd[0]).Value);
}
[Fact]
public void AddExportedValue_ExportAsExportedValueArgument_ShouldBeWrappedInExport()
{
CompositionBatch batch = new CompositionBatch();
var export = ExportFactory.Create("Contract", "Value");
batch.AddExportedValue(export);
Assert.Equal(1, batch.PartsToAdd.Count);
Assert.Same(export, this.GetSingleLazy<Export>(batch.PartsToAdd[0]).Value);
}
[Fact]
public void AddExport_ReturnedComposablePart_NullAsDefinitionArgumentToGetExportedValue_ShouldThrowArgumentNull()
{
CompositionBatch batch = new CompositionBatch();
var export = ExportFactory.Create("Contract", "Value");
var part = batch.AddExport(export);
Assert.Equal(1, batch.PartsToAdd.Count);
Assert.Throws<ArgumentNullException>("definition", () =>
{
part.GetExportedValue((ExportDefinition)null);
});
}
[Fact]
public void AddExport_ReturnedComposablePart_WrongDefinitionAsDefinitionArgumentToGetExportedValue_ShouldThrowArgument()
{
CompositionBatch batch = new CompositionBatch();
var export = ExportFactory.Create("Contract", "Value");
var part = batch.AddExport(export);
var definition = ExportDefinitionFactory.Create();
Assert.Equal(1, batch.PartsToAdd.Count);
Assert.Throws<ArgumentException>("definition", () =>
{
part.GetExportedValue(definition);
});
}
[Fact]
public void AddExport_ReturnedComposablePart_NullAsDefinitionArgumentToSetImports_ShouldThrowArgumentNull()
{
CompositionBatch batch = new CompositionBatch();
var export = ExportFactory.Create("Contract", "Value");
var part = batch.AddExport(export);
Assert.Equal(1, batch.PartsToAdd.Count);
Assert.Throws<ArgumentNullException>("definition", () =>
{
part.SetImport((ImportDefinition)null, Enumerable.Empty<Export>());
});
}
[Fact]
public void AddExport_ReturnedComposablePart_NullAsExportsArgumentToSetImports_ShouldThrowArgumentNull()
{
CompositionBatch batch = new CompositionBatch();
var export = ExportFactory.Create("Contract", "Value");
var part = batch.AddExport(export);
var definition = ImportDefinitionFactory.Create();
Assert.Equal(1, batch.PartsToAdd.Count);
Assert.Throws<ArgumentNullException>("exports", () =>
{
part.SetImport(definition, (IEnumerable<Export>)null);
});
}
[Fact]
public void AddExport_ReturnedComposablePart_ExportsArrayWithNullElementAsExportsArgumentToSetImports_ShouldThrowArgument()
{
CompositionBatch batch = new CompositionBatch();
var export = ExportFactory.Create("Contract", "Value");
var part = batch.AddExport(export);
var definition = ImportDefinitionFactory.Create();
Assert.Equal(1, batch.PartsToAdd.Count);
Assert.Throws<ArgumentException>("exports", () =>
{
part.SetImport(definition, new Export[] { null });
});
}
[Fact]
public void AddExport_ReturnedComposablePart_SetImports_ShouldThrowArgument()
{
CompositionBatch batch = new CompositionBatch();
var export = ExportFactory.Create("Contract", "Value");
var part = batch.AddExport(export);
var definition = ImportDefinitionFactory.Create();
Assert.Equal(1, batch.PartsToAdd.Count);
Assert.Throws<ArgumentException>("definition", () =>
{
part.SetImport(definition, Enumerable.Empty<Export>());
});
}
[Fact]
public void AddExport_ReturnedComposablePart_ContainsExportDefinitionRepresentingExport()
{
var metadata = new Dictionary<string, object>();
metadata["Name"] = "Value";
CompositionBatch batch = new CompositionBatch();
var export = ExportFactory.Create("Contract", "Value", metadata);
var part = batch.AddExport(export);
Assert.Equal(1, batch.PartsToAdd.Count);
var definition = part.ExportDefinitions.Single();
Assert.Equal("Contract", definition.ContractName);
Assert.Equal("Value", part.GetExportedValue(definition));
EnumerableAssert.AreEqual(metadata, definition.Metadata);
}
[Fact]
public void AddExportedValueOfT_ReturnedComposablePart_ImportDefinitionsPropertyIsEmpty()
{
CompositionBatch batch = new CompositionBatch();
var part = batch.AddExportedValue<string>("Value");
Assert.Equal(1, batch.PartsToAdd.Count);
Assert.Equal(0, part.ImportDefinitions.Count());
}
[Fact]
public void AddExportedValueOfT_ReturnedComposablePart_MetadataPropertyIsEmpty()
{
CompositionBatch batch = new CompositionBatch();
var part = batch.AddExportedValue<string>("Value");
Assert.Equal(1, batch.PartsToAdd.Count);
Assert.Equal(0, part.Metadata.Count);
}
[Fact]
public void AddExportedValueOfT_ReturnedComposablePart_NullAsDefinitionArgumentToGetExportedValue_ShouldThrowArgumentNull()
{
CompositionBatch batch = new CompositionBatch();
var part = batch.AddExportedValue<string>("Value");
Assert.Equal(1, batch.PartsToAdd.Count);
Assert.Throws<ArgumentNullException>("definition", () =>
{
part.GetExportedValue((ExportDefinition)null);
});
}
[Fact]
public void AddExportedValueOfT_ReturnedComposablePart_WrongDefinitionAsDefinitionArgumentToGetExportedValue_ShouldThrowArgument()
{
CompositionBatch batch = new CompositionBatch();
var part = batch.AddExportedValue<string>("Value");
var definition = ExportDefinitionFactory.Create();
Assert.Equal(1, batch.PartsToAdd.Count);
Assert.Throws<ArgumentException>("definition", () =>
{
part.GetExportedValue(definition);
});
}
[Fact]
public void AddExportedValueOfT_ReturnedComposablePart_NullAsDefinitionArgumentToSetImports_ShouldThrowArgumentNull()
{
CompositionBatch batch = new CompositionBatch();
var part = batch.AddExportedValue<string>("Value");
Assert.Equal(1, batch.PartsToAdd.Count);
Assert.Throws<ArgumentNullException>("definition", () =>
{
part.SetImport((ImportDefinition)null, Enumerable.Empty<Export>());
});
}
[Fact]
public void AddExportedValueOfT_ReturnedComposablePart_NullAsExportsArgumentToSetImports_ShouldThrowArgumentNull()
{
CompositionBatch batch = new CompositionBatch();
var part = batch.AddExportedValue<string>("Value");
var definition = ImportDefinitionFactory.Create();
Assert.Equal(1, batch.PartsToAdd.Count);
Assert.Throws<ArgumentNullException>("exports", () =>
{
part.SetImport(definition, (IEnumerable<Export>)null);
});
}
[Fact]
public void AddExportedValueOfT_ReturnedComposablePart_ExportsArrayWithNullElementAsExportsArgumentToSetImports_ShouldThrowArgument()
{
CompositionBatch batch = new CompositionBatch();
var part = batch.AddExportedValue<string>("Value");
var definition = ImportDefinitionFactory.Create();
Assert.Throws<ArgumentException>("exports", () =>
{
part.SetImport(definition, new Export[] { null });
});
}
[Fact]
public void AddExportedValueOfT_ReturnedComposablePart_SetImports_ShouldThrowArgument()
{
CompositionBatch batch = new CompositionBatch();
var part = batch.AddExportedValue<string>("Value");
var definition = ImportDefinitionFactory.Create();
Assert.Equal(1, batch.PartsToAdd.Count);
Assert.Throws<ArgumentException>("definition", () =>
{
part.SetImport(definition, Enumerable.Empty<Export>());
});
}
[Fact]
public void AddExportedValueOfT_ReturnedComposablePart_ContainsExportDefinitionRepresentingExport()
{
CompositionBatch batch = new CompositionBatch();
var part = batch.AddExportedValue<string>("Value");
Assert.Equal(1, batch.PartsToAdd.Count);
var definition = part.ExportDefinitions.Single();
Assert.Equal(NameForType<string>(), definition.ContractName);
Assert.Equal("Value", part.GetExportedValue(definition));
Assert.Equal(1, definition.Metadata.Count); // contains type identity
}
[Fact]
public void AddExportedValue_ReturnedComposablePart_ImportDefinitionsPropertyIsEmpty()
{
CompositionBatch batch = new CompositionBatch();
var part = batch.AddExportedValue("Contract", "Value");
Assert.Equal(1, batch.PartsToAdd.Count);
Assert.Equal(0, part.ImportDefinitions.Count());
}
[Fact]
public void AddExportedValue_ReturnedComposablePart_MetadataPropertyIsEmpty()
{
CompositionBatch batch = new CompositionBatch();
var part = batch.AddExportedValue("Contract", "Value");
Assert.Equal(1, batch.PartsToAdd.Count);
Assert.Equal(0, part.Metadata.Count);
}
[Fact]
public void AddExportedValue_ReturnedComposablePart_NullAsDefinitionArgumentToGetExportedValue_ShouldThrowArgumentNull()
{
CompositionBatch batch = new CompositionBatch();
var part = batch.AddExportedValue("Contract", "Value");
Assert.Equal(1, batch.PartsToAdd.Count);
Assert.Throws<ArgumentNullException>("definition", () =>
{
part.GetExportedValue((ExportDefinition)null);
});
}
[Fact]
public void AddExportedValue_ReturnedComposablePart_WrongDefinitionAsDefinitionArgumentToGetExportedValue_ShouldThrowArgument()
{
CompositionBatch batch = new CompositionBatch();
var part = batch.AddExportedValue("Contract", "Value");
var definition = ExportDefinitionFactory.Create();
Assert.Equal(1, batch.PartsToAdd.Count);
Assert.Throws<ArgumentException>("definition", () =>
{
part.GetExportedValue(definition);
});
}
[Fact]
public void AddExportedValue_ReturnedComposablePart_NullAsDefinitionArgumentToSetImports_ShouldThrowArgumentNull()
{
CompositionBatch batch = new CompositionBatch();
var part = batch.AddExportedValue("Contract", "Value");
Assert.Equal(1, batch.PartsToAdd.Count);
Assert.Throws<ArgumentNullException>("definition", () =>
{
part.SetImport((ImportDefinition)null, Enumerable.Empty<Export>());
});
}
[Fact]
public void AddExportedValue_ReturnedComposablePart_NullAsExportsArgumentToSetImports_ShouldThrowArgumentNull()
{
CompositionBatch batch = new CompositionBatch();
var part = batch.AddExportedValue("Contract", "Value");
var definition = ImportDefinitionFactory.Create();
Assert.Equal(1, batch.PartsToAdd.Count);
Assert.Throws<ArgumentNullException>("exports", () =>
{
part.SetImport(definition, (IEnumerable<Export>)null);
});
}
[Fact]
public void AddExportedValue_ReturnedComposablePart_ExportsArrayWithNullElementAsExportsArgumentToSetImports_ShouldThrowArgument()
{
CompositionBatch batch = new CompositionBatch();
var part = batch.AddExportedValue("Contract", "Value");
var definition = ImportDefinitionFactory.Create();
Assert.Equal(1, batch.PartsToAdd.Count);
Assert.Throws<ArgumentException>("exports", () =>
{
part.SetImport(definition, new Export[] { null });
});
}
[Fact]
public void AddExportedValue_ReturnedComposablePart_WrongDefinitionAsDefinitionArgumentToSetImports_ShouldThrowArgument()
{
CompositionBatch batch = new CompositionBatch();
var part = batch.AddExportedValue("Contract", "Value");
var definition = ImportDefinitionFactory.Create();
Assert.Equal(1, batch.PartsToAdd.Count);
Assert.Throws<ArgumentException>("definition", () =>
{
part.SetImport(definition, Enumerable.Empty<Export>());
});
}
[Fact]
public void AddExportedValue_ReturnedComposablePart_ContainsExportDefinitionRepresentingExport()
{
CompositionBatch batch = new CompositionBatch();
var part = batch.AddExportedValue("Contract", "Value");
Assert.Equal(1, batch.PartsToAdd.Count);
var definition = part.ExportDefinitions.Single();
Assert.Equal("Contract", definition.ContractName);
Assert.Equal("Value", part.GetExportedValue(definition));
Assert.Equal(1, definition.Metadata.Count); // containts type identity
}
[Fact]
public void AddPart_Int32ValueTypeAsAttributedPartArgument_ShouldThrowArgument()
{
CompositionBatch batch = new CompositionBatch();
Assert.Throws<ArgumentException>("attributedPart", () =>
{
batch.AddPart((object)10);
});
}
[Fact]
public void AddPart_ReturnedComposablePart_NullAsDefinitionArgumentToGetExportedValue_ShouldThrowArgumentNull()
{
CompositionBatch batch = new CompositionBatch();
var part = batch.AddPart(new Int32Importer());
Assert.Equal(1, batch.PartsToAdd.Count);
Assert.Throws<ArgumentNullException>("definition", () =>
{
part.GetExportedValue((ExportDefinition)null);
});
}
[Fact]
public void AddPart_ReturnedComposablePart_WrongDefinitionAsDefinitionArgumentToGetExportedValue_ShouldThrowArgument()
{
CompositionBatch batch = new CompositionBatch();
var part = batch.AddPart(new Int32Importer());
var definition = ExportDefinitionFactory.Create();
Assert.Equal(1, batch.PartsToAdd.Count);
Assert.Throws<ArgumentException>("definition", () =>
{
part.GetExportedValue(definition);
});
}
[Fact]
public void AddPart_ReturnedComposablePart_NullAsDefinitionArgumentToSetImports_ShouldThrowArgumentNull()
{
CompositionBatch batch = new CompositionBatch();
var part = batch.AddPart(new Int32Importer());
Assert.Equal(1, batch.PartsToAdd.Count);
Assert.Throws<ArgumentNullException>("definition", () =>
{
part.SetImport((ImportDefinition)null, Enumerable.Empty<Export>());
});
}
[Fact]
public void AddPart_ReturnedComposablePart_NullAsExportsArgumentToSetImports_ShouldThrowArgumentNull()
{
CompositionBatch batch = new CompositionBatch();
var part = batch.AddPart(new Int32Importer());
var definition = ImportDefinitionFactory.Create();
Assert.Equal(1, batch.PartsToAdd.Count);
Assert.Throws<ArgumentNullException>("exports", () =>
{
part.SetImport(definition, (IEnumerable<Export>)null);
});
}
[Fact]
public void AddPart_ReturnedComposablePart_ExportsArrayWithNullElementAsExportsArgumentToSetImports_ShouldThrowArgument()
{
CompositionBatch batch = new CompositionBatch();
var part = batch.AddPart(new Int32Importer());
var definition = part.ImportDefinitions.First();
Assert.Equal(1, batch.PartsToAdd.Count);
Assert.Throws<ArgumentException>("exports", () =>
{
part.SetImport(definition, new Export[] { null });
});
}
[Fact]
public void AddPart_ReturnedComposablePart_WrongDefinitionAsDefinitionArgumentToSetImports_ShouldThrowArgument()
{
CompositionBatch batch = new CompositionBatch();
var part = batch.AddPart(new Int32Importer());
var definition = ImportDefinitionFactory.Create();
Assert.Equal(1, batch.PartsToAdd.Count);
Assert.Throws<ArgumentException>("definition", () =>
{
part.SetImport(definition, Enumerable.Empty<Export>());
});
}
private Export GetSingleLazy<T>(ComposablePart part)
{
return this.GetSingleExport(part, AttributedModelServices.GetContractName(typeof(T)));
}
private Export GetSingleExport(ComposablePart part, string contractName)
{
Assert.NotNull(part);
Assert.Equal(0, part.Metadata.Count);
Assert.Equal(1, part.ExportDefinitions.Count());
Assert.Equal(0, part.ImportDefinitions.Count());
ExportDefinition exportDefinition = part.ExportDefinitions.First();
Assert.Equal(contractName, exportDefinition.ContractName);
part.Activate();
return new Export(exportDefinition, () => part.GetExportedValue(exportDefinition));
}
private static string NameForType<T>()
{
return AttributedModelServices.GetContractName(typeof(T));
}
}
}
| |
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.Linq;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Input.Bindings;
using osu.Framework.Lists;
using osu.Framework.Threading;
using osu.Game.Beatmaps;
using osu.Game.Beatmaps.ControlPoints;
using osu.Game.Configuration;
using osu.Game.Extensions;
using osu.Game.Input.Bindings;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Timing;
using osu.Game.Rulesets.UI.Scrolling.Algorithms;
namespace osu.Game.Rulesets.UI.Scrolling
{
/// <summary>
/// A type of <see cref="DrawableRuleset{TObject}"/> that supports a <see cref="ScrollingPlayfield"/>.
/// <see cref="HitObject"/>s inside this <see cref="DrawableRuleset{TObject}"/> will scroll within the playfield.
/// </summary>
public abstract class DrawableScrollingRuleset<TObject> : DrawableRuleset<TObject>, IKeyBindingHandler<GlobalAction>
where TObject : HitObject
{
/// <summary>
/// The default span of time visible by the length of the scrolling axes.
/// This is clamped between <see cref="time_span_min"/> and <see cref="time_span_max"/>.
/// </summary>
private const double time_span_default = 1500;
/// <summary>
/// The minimum span of time that may be visible by the length of the scrolling axes.
/// </summary>
private const double time_span_min = 50;
/// <summary>
/// The maximum span of time that may be visible by the length of the scrolling axes.
/// </summary>
private const double time_span_max = 20000;
/// <summary>
/// The step increase/decrease of the span of time visible by the length of the scrolling axes.
/// </summary>
private const double time_span_step = 200;
protected readonly Bindable<ScrollingDirection> Direction = new Bindable<ScrollingDirection>();
/// <summary>
/// The span of time that is visible by the length of the scrolling axes.
/// For example, only hit objects with start time less than or equal to 1000 will be visible with <see cref="TimeRange"/> = 1000.
/// </summary>
protected readonly BindableDouble TimeRange = new BindableDouble(time_span_default)
{
Default = time_span_default,
MinValue = time_span_min,
MaxValue = time_span_max
};
protected virtual ScrollVisualisationMethod VisualisationMethod => ScrollVisualisationMethod.Sequential;
/// <summary>
/// Whether the player can change <see cref="TimeRange"/>.
/// </summary>
protected virtual bool UserScrollSpeedAdjustment => true;
/// <summary>
/// Whether <see cref="TimingControlPoint"/> beat lengths should scale relative to the most common beat length in the <see cref="Beatmap"/>.
/// </summary>
protected virtual bool RelativeScaleBeatLengths => false;
/// <summary>
/// The <see cref="MultiplierControlPoint"/>s that adjust the scrolling rate of <see cref="HitObject"/>s inside this <see cref="DrawableRuleset{TObject}"/>.
/// </summary>
protected readonly SortedList<MultiplierControlPoint> ControlPoints = new SortedList<MultiplierControlPoint>(Comparer<MultiplierControlPoint>.Default);
protected IScrollingInfo ScrollingInfo => scrollingInfo;
[Cached(Type = typeof(IScrollingInfo))]
private readonly LocalScrollingInfo scrollingInfo;
protected DrawableScrollingRuleset(Ruleset ruleset, IBeatmap beatmap, IReadOnlyList<Mod> mods = null)
: base(ruleset, beatmap, mods)
{
scrollingInfo = new LocalScrollingInfo();
scrollingInfo.Direction.BindTo(Direction);
scrollingInfo.TimeRange.BindTo(TimeRange);
}
[BackgroundDependencyLoader]
private void load()
{
switch (VisualisationMethod)
{
case ScrollVisualisationMethod.Sequential:
scrollingInfo.Algorithm = new SequentialScrollAlgorithm(ControlPoints);
break;
case ScrollVisualisationMethod.Overlapping:
scrollingInfo.Algorithm = new OverlappingScrollAlgorithm(ControlPoints);
break;
case ScrollVisualisationMethod.Constant:
scrollingInfo.Algorithm = new ConstantScrollAlgorithm();
break;
}
double lastObjectTime = Objects.LastOrDefault()?.GetEndTime() ?? double.MaxValue;
double baseBeatLength = TimingControlPoint.DEFAULT_BEAT_LENGTH;
if (RelativeScaleBeatLengths)
{
IReadOnlyList<TimingControlPoint> timingPoints = Beatmap.ControlPointInfo.TimingPoints;
double maxDuration = 0;
for (int i = 0; i < timingPoints.Count; i++)
{
if (timingPoints[i].Time > lastObjectTime)
break;
double endTime = i < timingPoints.Count - 1 ? timingPoints[i + 1].Time : lastObjectTime;
double duration = endTime - timingPoints[i].Time;
if (duration > maxDuration)
{
maxDuration = duration;
// The slider multiplier is post-multiplied to determine the final velocity, but for relative scale beat lengths
// the multiplier should not affect the effective timing point (the longest in the beatmap), so it is factored out here
baseBeatLength = timingPoints[i].BeatLength / Beatmap.BeatmapInfo.BaseDifficulty.SliderMultiplier;
}
}
}
// Merge sequences of timing and difficulty control points to create the aggregate "multiplier" control point
var lastTimingPoint = new TimingControlPoint();
var lastDifficultyPoint = new DifficultyControlPoint();
var allPoints = new SortedList<ControlPoint>(Comparer<ControlPoint>.Default);
allPoints.AddRange(Beatmap.ControlPointInfo.TimingPoints);
allPoints.AddRange(Beatmap.ControlPointInfo.DifficultyPoints);
// Generate the timing points, making non-timing changes use the previous timing change and vice-versa
var timingChanges = allPoints.Select(c =>
{
if (c is TimingControlPoint timingPoint)
lastTimingPoint = timingPoint;
else if (c is DifficultyControlPoint difficultyPoint)
lastDifficultyPoint = difficultyPoint;
return new MultiplierControlPoint(c.Time)
{
Velocity = Beatmap.BeatmapInfo.BaseDifficulty.SliderMultiplier,
BaseBeatLength = baseBeatLength,
TimingPoint = lastTimingPoint,
DifficultyPoint = lastDifficultyPoint
};
});
// Trim unwanted sequences of timing changes
timingChanges = timingChanges
// Collapse sections after the last hit object
.Where(s => s.StartTime <= lastObjectTime)
// Collapse sections with the same start time
.GroupBy(s => s.StartTime).Select(g => g.Last()).OrderBy(s => s.StartTime);
ControlPoints.AddRange(timingChanges);
if (ControlPoints.Count == 0)
ControlPoints.Add(new MultiplierControlPoint { Velocity = Beatmap.BeatmapInfo.BaseDifficulty.SliderMultiplier });
}
protected override void LoadComplete()
{
base.LoadComplete();
if (!(Playfield is ScrollingPlayfield))
throw new ArgumentException($"{nameof(Playfield)} must be a {nameof(ScrollingPlayfield)} when using {nameof(DrawableScrollingRuleset<TObject>)}.");
}
/// <summary>
/// Adjusts the scroll speed of <see cref="HitObject"/>s.
/// </summary>
/// <param name="amount">The amount to adjust by. Greater than 0 if the scroll speed should be increased, less than 0 if it should be decreased.</param>
protected virtual void AdjustScrollSpeed(int amount) => this.TransformBindableTo(TimeRange, TimeRange.Value - amount * time_span_step, 200, Easing.OutQuint);
public bool OnPressed(GlobalAction action)
{
if (!UserScrollSpeedAdjustment)
return false;
switch (action)
{
case GlobalAction.IncreaseScrollSpeed:
scheduleScrollSpeedAdjustment(1);
return true;
case GlobalAction.DecreaseScrollSpeed:
scheduleScrollSpeedAdjustment(-1);
return true;
}
return false;
}
private ScheduledDelegate scheduledScrollSpeedAdjustment;
public void OnReleased(GlobalAction action)
{
scheduledScrollSpeedAdjustment?.Cancel();
scheduledScrollSpeedAdjustment = null;
}
private void scheduleScrollSpeedAdjustment(int amount)
{
scheduledScrollSpeedAdjustment?.Cancel();
scheduledScrollSpeedAdjustment = this.BeginKeyRepeat(Scheduler, () => AdjustScrollSpeed(amount));
}
private class LocalScrollingInfo : IScrollingInfo
{
public IBindable<ScrollingDirection> Direction { get; } = new Bindable<ScrollingDirection>();
public IBindable<double> TimeRange { get; } = new BindableDouble();
public IScrollAlgorithm Algorithm { get; set; }
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;
using System.Text;
using Xunit;
namespace System.Net.Http.Tests
{
public class HttpContentHeadersTest
{
private HttpContentHeaders _headers;
public HttpContentHeadersTest()
{
_headers = new HttpContentHeaders(null);
}
[Fact]
public void ContentLength_AddInvalidValueUsingUnusualCasing_ParserRetrievedUsingCaseInsensitiveComparison()
{
_headers = new HttpContentHeaders(() => { return 15; });
// Use uppercase header name to make sure the parser gets retrieved using case-insensitive comparison.
Assert.Throws<FormatException>(() => { _headers.Add("CoNtEnT-LeNgTh", "this is invalid"); });
}
[Fact]
public void ContentLength_ReadValue_DelegateInvoked()
{
_headers = new HttpContentHeaders(() => { return 15; });
// The delegate is invoked to return the length.
Assert.Equal(15, _headers.ContentLength);
Assert.Equal((long)15, _headers.GetParsedValues(HttpKnownHeaderNames.ContentLength));
// After getting the calculated content length, set it to null.
_headers.ContentLength = null;
Assert.Equal(null, _headers.ContentLength);
Assert.False(_headers.Contains(HttpKnownHeaderNames.ContentLength));
_headers.ContentLength = 27;
Assert.Equal((long)27, _headers.ContentLength);
Assert.Equal((long)27, _headers.GetParsedValues(HttpKnownHeaderNames.ContentLength));
}
[Fact]
public void ContentLength_SetCustomValue_DelegateNotInvoked()
{
_headers = new HttpContentHeaders(() => { throw new ShouldNotBeInvokedException(); });
_headers.ContentLength = 27;
Assert.Equal((long)27, _headers.ContentLength);
Assert.Equal((long)27, _headers.GetParsedValues(HttpKnownHeaderNames.ContentLength));
// After explicitly setting the content length, set it to null.
_headers.ContentLength = null;
Assert.Equal(null, _headers.ContentLength);
Assert.False(_headers.Contains(HttpKnownHeaderNames.ContentLength));
// Make sure the header gets serialized correctly
_headers.ContentLength = 12345;
Assert.Equal("12345", _headers.GetValues("Content-Length").First());
}
[Fact]
public void ContentLength_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
_headers = new HttpContentHeaders(() => { throw new ShouldNotBeInvokedException(); });
_headers.TryAddWithoutValidation(HttpKnownHeaderNames.ContentLength, " 68 \r\n ");
Assert.Equal(68, _headers.ContentLength);
}
[Fact]
public void ContentType_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
MediaTypeHeaderValue value = new MediaTypeHeaderValue("text/plain");
value.CharSet = "utf-8";
value.Parameters.Add(new NameValueHeaderValue("custom", "value"));
Assert.Null(_headers.ContentType);
_headers.ContentType = value;
Assert.Same(value, _headers.ContentType);
_headers.ContentType = null;
Assert.Null(_headers.ContentType);
}
[Fact]
public void ContentType_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
_headers.TryAddWithoutValidation("Content-Type", "text/plain; charset=utf-8; custom=value");
MediaTypeHeaderValue value = new MediaTypeHeaderValue("text/plain");
value.CharSet = "utf-8";
value.Parameters.Add(new NameValueHeaderValue("custom", "value"));
Assert.Equal(value, _headers.ContentType);
}
[Fact]
public void ContentType_UseAddMethodWithInvalidValue_InvalidValueRecognized()
{
_headers.TryAddWithoutValidation("Content-Type", "text/plain; charset=utf-8; custom=value, other/type");
Assert.Null(_headers.ContentType);
Assert.Equal(1, _headers.GetValues("Content-Type").Count());
Assert.Equal("text/plain; charset=utf-8; custom=value, other/type",
_headers.GetValues("Content-Type").First());
_headers.Clear();
_headers.TryAddWithoutValidation("Content-Type", ",text/plain"); // leading separator
Assert.Null(_headers.ContentType);
Assert.Equal(1, _headers.GetValues("Content-Type").Count());
Assert.Equal(",text/plain", _headers.GetValues("Content-Type").First());
_headers.Clear();
_headers.TryAddWithoutValidation("Content-Type", "text/plain,"); // trailing separator
Assert.Null(_headers.ContentType);
Assert.Equal(1, _headers.GetValues("Content-Type").Count());
Assert.Equal("text/plain,", _headers.GetValues("Content-Type").First());
}
[Fact]
public void ContentRange_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Null(_headers.ContentRange);
ContentRangeHeaderValue value = new ContentRangeHeaderValue(1, 2, 3);
_headers.ContentRange = value;
Assert.Equal(value, _headers.ContentRange);
_headers.ContentRange = null;
Assert.Null(_headers.ContentRange);
}
[Fact]
public void ContentRange_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
_headers.TryAddWithoutValidation("Content-Range", "custom 1-2/*");
ContentRangeHeaderValue value = new ContentRangeHeaderValue(1, 2);
value.Unit = "custom";
Assert.Equal(value, _headers.ContentRange);
}
[Fact]
public void ContentLocation_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Null(_headers.ContentLocation);
Uri expected = new Uri("http://example.com/path/");
_headers.ContentLocation = expected;
Assert.Equal(expected, _headers.ContentLocation);
_headers.ContentLocation = null;
Assert.Null(_headers.ContentLocation);
Assert.False(_headers.Contains("Content-Location"));
}
[Fact]
public void ContentLocation_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
_headers.TryAddWithoutValidation("Content-Location", " http://www.example.com/path/?q=v ");
Assert.Equal(new Uri("http://www.example.com/path/?q=v"), _headers.ContentLocation);
_headers.Clear();
_headers.TryAddWithoutValidation("Content-Location", "/relative/uri/");
Assert.Equal(new Uri("/relative/uri/", UriKind.Relative), _headers.ContentLocation);
}
[Fact]
public void ContentLocation_UseAddMethodWithInvalidValue_InvalidValueRecognized()
{
_headers.TryAddWithoutValidation("Content-Location", " http://example.com http://other");
Assert.Null(_headers.GetParsedValues("Content-Location"));
Assert.Equal(1, _headers.GetValues("Content-Location").Count());
Assert.Equal(" http://example.com http://other", _headers.GetValues("Content-Location").First());
_headers.Clear();
_headers.TryAddWithoutValidation("Content-Location", "http://host /other");
Assert.Null(_headers.GetParsedValues("Content-Location"));
Assert.Equal(1, _headers.GetValues("Content-Location").Count());
Assert.Equal("http://host /other", _headers.GetValues("Content-Location").First());
}
[Fact]
public void ContentEncoding_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Equal(0, _headers.ContentEncoding.Count);
_headers.ContentEncoding.Add("custom1");
_headers.ContentEncoding.Add("custom2");
Assert.Equal(2, _headers.ContentEncoding.Count);
Assert.Equal(2, _headers.GetValues("Content-Encoding").Count());
Assert.Equal("custom1", _headers.ContentEncoding.ElementAt(0));
Assert.Equal("custom2", _headers.ContentEncoding.ElementAt(1));
_headers.ContentEncoding.Clear();
Assert.Equal(0, _headers.ContentEncoding.Count);
Assert.False(_headers.Contains("Content-Encoding"));
}
[Fact]
public void ContentEncoding_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
_headers.TryAddWithoutValidation("Content-Encoding", ",custom1, custom2, custom3,");
Assert.Equal(3, _headers.ContentEncoding.Count);
Assert.Equal(3, _headers.GetValues("Content-Encoding").Count());
Assert.Equal("custom1", _headers.ContentEncoding.ElementAt(0));
Assert.Equal("custom2", _headers.ContentEncoding.ElementAt(1));
Assert.Equal("custom3", _headers.ContentEncoding.ElementAt(2));
_headers.ContentEncoding.Clear();
Assert.Equal(0, _headers.ContentEncoding.Count);
Assert.False(_headers.Contains("Content-Encoding"));
}
[Fact]
public void ContentEncoding_UseAddMethodWithInvalidValue_InvalidValueRecognized()
{
_headers.TryAddWithoutValidation("Content-Encoding", "custom1 custom2"); // no separator
Assert.Equal(0, _headers.ContentEncoding.Count);
Assert.Equal(1, _headers.GetValues("Content-Encoding").Count());
Assert.Equal("custom1 custom2", _headers.GetValues("Content-Encoding").First());
}
[Fact]
public void ContentLanguage_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Equal(0, _headers.ContentLanguage.Count);
// Note that Content-Language for us is just a list of tokens. We don't verify if the format is a valid
// language tag. Users will pass the language tag to other classes like Encoding.GetEncoding() to retrieve
// an encoding. These classes will do not only syntax checking but also verify if the language tag exists.
_headers.ContentLanguage.Add("custom1");
_headers.ContentLanguage.Add("custom2");
Assert.Equal(2, _headers.ContentLanguage.Count);
Assert.Equal(2, _headers.GetValues("Content-Language").Count());
Assert.Equal("custom1", _headers.ContentLanguage.ElementAt(0));
Assert.Equal("custom2", _headers.ContentLanguage.ElementAt(1));
_headers.ContentLanguage.Clear();
Assert.Equal(0, _headers.ContentLanguage.Count);
Assert.False(_headers.Contains("Content-Language"));
}
[Fact]
public void ContentLanguage_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
_headers.TryAddWithoutValidation("Content-Language", ",custom1, custom2, custom3,");
Assert.Equal(3, _headers.ContentLanguage.Count);
Assert.Equal(3, _headers.GetValues("Content-Language").Count());
Assert.Equal("custom1", _headers.ContentLanguage.ElementAt(0));
Assert.Equal("custom2", _headers.ContentLanguage.ElementAt(1));
Assert.Equal("custom3", _headers.ContentLanguage.ElementAt(2));
_headers.ContentLanguage.Clear();
Assert.Equal(0, _headers.ContentLanguage.Count);
Assert.False(_headers.Contains("Content-Language"));
}
[Fact]
public void ContentLanguage_UseAddMethodWithInvalidValue_InvalidValueRecognized()
{
_headers.TryAddWithoutValidation("Content-Language", "custom1 custom2"); // no separator
Assert.Equal(0, _headers.ContentLanguage.Count);
Assert.Equal(1, _headers.GetValues("Content-Language").Count());
Assert.Equal("custom1 custom2", _headers.GetValues("Content-Language").First());
}
[Fact]
public void ContentMD5_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Null(_headers.ContentMD5);
byte[] expected = new byte[] { 1, 2, 3, 4, 5, 6, 7 };
_headers.ContentMD5 = expected;
Assert.Equal(expected, _headers.ContentMD5); // must be the same object reference
// Make sure the header gets serialized correctly
Assert.Equal("AQIDBAUGBw==", _headers.GetValues("Content-MD5").First());
_headers.ContentMD5 = null;
Assert.Null(_headers.ContentMD5);
Assert.False(_headers.Contains("Content-MD5"));
}
[Fact]
public void ContentMD5_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
_headers.TryAddWithoutValidation("Content-MD5", " lvpAKQ== ");
Assert.Equal(new byte[] { 150, 250, 64, 41 }, _headers.ContentMD5);
_headers.Clear();
_headers.TryAddWithoutValidation("Content-MD5", "+dIkS/MnOP8=");
Assert.Equal(new byte[] { 249, 210, 36, 75, 243, 39, 56, 255 }, _headers.ContentMD5);
}
[Fact]
public void ContentMD5_UseAddMethodWithInvalidValue_InvalidValueRecognized()
{
_headers.TryAddWithoutValidation("Content-MD5", "AQ--");
Assert.Null(_headers.GetParsedValues("Content-MD5"));
Assert.Equal(1, _headers.GetValues("Content-MD5").Count());
Assert.Equal("AQ--", _headers.GetValues("Content-MD5").First());
_headers.Clear();
_headers.TryAddWithoutValidation("Content-MD5", "AQ==, CD");
Assert.Null(_headers.GetParsedValues("Content-MD5"));
Assert.Equal(1, _headers.GetValues("Content-MD5").Count());
Assert.Equal("AQ==, CD", _headers.GetValues("Content-MD5").First());
}
[Fact]
public void Allow_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Equal(0, _headers.Allow.Count);
_headers.Allow.Add("custom1");
_headers.Allow.Add("custom2");
Assert.Equal(2, _headers.Allow.Count);
Assert.Equal(2, _headers.GetValues("Allow").Count());
Assert.Equal("custom1", _headers.Allow.ElementAt(0));
Assert.Equal("custom2", _headers.Allow.ElementAt(1));
_headers.Allow.Clear();
Assert.Equal(0, _headers.Allow.Count);
Assert.False(_headers.Contains("Allow"));
}
[Fact]
public void Allow_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
_headers.TryAddWithoutValidation("Allow", ",custom1, custom2, custom3,");
Assert.Equal(3, _headers.Allow.Count);
Assert.Equal(3, _headers.GetValues("Allow").Count());
Assert.Equal("custom1", _headers.Allow.ElementAt(0));
Assert.Equal("custom2", _headers.Allow.ElementAt(1));
Assert.Equal("custom3", _headers.Allow.ElementAt(2));
_headers.Allow.Clear();
Assert.Equal(0, _headers.Allow.Count);
Assert.False(_headers.Contains("Allow"));
}
[Fact]
public void Allow_UseAddMethodWithInvalidValue_InvalidValueRecognized()
{
_headers.TryAddWithoutValidation("Allow", "custom1 custom2"); // no separator
Assert.Equal(0, _headers.Allow.Count);
Assert.Equal(1, _headers.GetValues("Allow").Count());
Assert.Equal("custom1 custom2", _headers.GetValues("Allow").First());
}
[Fact]
public void Expires_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Null(_headers.Expires);
DateTimeOffset expected = DateTimeOffset.Now;
_headers.Expires = expected;
Assert.Equal(expected, _headers.Expires);
_headers.Expires = null;
Assert.Null(_headers.Expires);
Assert.False(_headers.Contains("Expires"));
}
[Fact]
public void Expires_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
_headers.TryAddWithoutValidation("Expires", " Sun, 06 Nov 1994 08:49:37 GMT ");
Assert.Equal(new DateTimeOffset(1994, 11, 6, 8, 49, 37, TimeSpan.Zero), _headers.Expires);
_headers.Clear();
_headers.TryAddWithoutValidation("Expires", "Sun, 06 Nov 1994 08:49:37 GMT");
Assert.Equal(new DateTimeOffset(1994, 11, 6, 8, 49, 37, TimeSpan.Zero), _headers.Expires);
}
[Fact]
public void Expires_UseAddMethodWithInvalidValue_InvalidValueRecognized()
{
_headers.TryAddWithoutValidation("Expires", " Sun, 06 Nov 1994 08:49:37 GMT ,");
Assert.Null(_headers.GetParsedValues("Expires"));
Assert.Equal(1, _headers.GetValues("Expires").Count());
Assert.Equal(" Sun, 06 Nov 1994 08:49:37 GMT ,", _headers.GetValues("Expires").First());
_headers.Clear();
_headers.TryAddWithoutValidation("Expires", " Sun, 06 Nov ");
Assert.Null(_headers.GetParsedValues("Expires"));
Assert.Equal(1, _headers.GetValues("Expires").Count());
Assert.Equal(" Sun, 06 Nov ", _headers.GetValues("Expires").First());
}
[Fact]
public void LastModified_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Null(_headers.LastModified);
DateTimeOffset expected = DateTimeOffset.Now;
_headers.LastModified = expected;
Assert.Equal(expected, _headers.LastModified);
_headers.LastModified = null;
Assert.Null(_headers.LastModified);
Assert.False(_headers.Contains("Last-Modified"));
}
[Fact]
public void LastModified_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
_headers.TryAddWithoutValidation("Last-Modified", " Sun, 06 Nov 1994 08:49:37 GMT ");
Assert.Equal(new DateTimeOffset(1994, 11, 6, 8, 49, 37, TimeSpan.Zero), _headers.LastModified);
_headers.Clear();
_headers.TryAddWithoutValidation("Last-Modified", "Sun, 06 Nov 1994 08:49:37 GMT");
Assert.Equal(new DateTimeOffset(1994, 11, 6, 8, 49, 37, TimeSpan.Zero), _headers.LastModified);
}
[Fact]
public void LastModified_UseAddMethodWithInvalidValue_InvalidValueRecognized()
{
_headers.TryAddWithoutValidation("Last-Modified", " Sun, 06 Nov 1994 08:49:37 GMT ,");
Assert.Null(_headers.GetParsedValues("Last-Modified"));
Assert.Equal(1, _headers.GetValues("Last-Modified").Count());
Assert.Equal(" Sun, 06 Nov 1994 08:49:37 GMT ,", _headers.GetValues("Last-Modified").First());
_headers.Clear();
_headers.TryAddWithoutValidation("Last-Modified", " Sun, 06 Nov ");
Assert.Null(_headers.GetParsedValues("Last-Modified"));
Assert.Equal(1, _headers.GetValues("Last-Modified").Count());
Assert.Equal(" Sun, 06 Nov ", _headers.GetValues("Last-Modified").First());
}
[Fact]
public void InvalidHeaders_AddRequestAndResponseHeaders_Throw()
{
// Try adding request, response, and general _headers. Use different casing to make sure case-insensitive
// comparison is used.
Assert.Throws<InvalidOperationException>(() => { _headers.Add("Accept-Ranges", "v"); });
Assert.Throws<InvalidOperationException>(() => { _headers.Add("age", "v"); });
Assert.Throws<InvalidOperationException>(() => { _headers.Add("ETag", "v"); });
Assert.Throws<InvalidOperationException>(() => { _headers.Add("Location", "v"); });
Assert.Throws<InvalidOperationException>(() => { _headers.Add("Proxy-Authenticate", "v"); });
Assert.Throws<InvalidOperationException>(() => { _headers.Add("Retry-After", "v"); });
Assert.Throws<InvalidOperationException>(() => { _headers.Add("Server", "v"); });
Assert.Throws<InvalidOperationException>(() => { _headers.Add("Vary", "v"); });
Assert.Throws<InvalidOperationException>(() => { _headers.Add("WWW-Authenticate", "v"); });
Assert.Throws<InvalidOperationException>(() => { _headers.Add("Accept", "v"); });
Assert.Throws<InvalidOperationException>(() => { _headers.Add("Accept-Charset", "v"); });
Assert.Throws<InvalidOperationException>(() => { _headers.Add("Accept-Encoding", "v"); });
Assert.Throws<InvalidOperationException>(() => { _headers.Add("Accept-Language", "v"); });
Assert.Throws<InvalidOperationException>(() => { _headers.Add("Authorization", "v"); });
Assert.Throws<InvalidOperationException>(() => { _headers.Add("Expect", "v"); });
Assert.Throws<InvalidOperationException>(() => { _headers.Add("From", "v"); });
Assert.Throws<InvalidOperationException>(() => { _headers.Add("Host", "v"); });
Assert.Throws<InvalidOperationException>(() => { _headers.Add("If-Match", "v"); });
Assert.Throws<InvalidOperationException>(() => { _headers.Add("If-Modified-Since", "v"); });
Assert.Throws<InvalidOperationException>(() => { _headers.Add("If-None-Match", "v"); });
Assert.Throws<InvalidOperationException>(() => { _headers.Add("If-Range", "v"); });
Assert.Throws<InvalidOperationException>(() => { _headers.Add("If-Unmodified-Since", "v"); });
Assert.Throws<InvalidOperationException>(() => { _headers.Add("Max-Forwards", "v"); });
Assert.Throws<InvalidOperationException>(() => { _headers.Add("Proxy-Authorization", "v"); });
Assert.Throws<InvalidOperationException>(() => { _headers.Add("Range", "v"); });
Assert.Throws<InvalidOperationException>(() => { _headers.Add("Referer", "v"); });
Assert.Throws<InvalidOperationException>(() => { _headers.Add("TE", "v"); });
Assert.Throws<InvalidOperationException>(() => { _headers.Add("User-Agent", "v"); });
Assert.Throws<InvalidOperationException>(() => { _headers.Add("Cache-Control", "v"); });
Assert.Throws<InvalidOperationException>(() => { _headers.Add("Connection", "v"); });
Assert.Throws<InvalidOperationException>(() => { _headers.Add("Date", "v"); });
Assert.Throws<InvalidOperationException>(() => { _headers.Add("Pragma", "v"); });
Assert.Throws<InvalidOperationException>(() => { _headers.Add("Trailer", "v"); });
Assert.Throws<InvalidOperationException>(() => { _headers.Add("Transfer-Encoding", "v"); });
Assert.Throws<InvalidOperationException>(() => { _headers.Add("Upgrade", "v"); });
Assert.Throws<InvalidOperationException>(() => { _headers.Add("Via", "v"); });
Assert.Throws<InvalidOperationException>(() => { _headers.Add("Warning", "v"); });
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Collections;
using System.Globalization;
using Xunit;
using SortedList_SortedListUtils;
namespace SortedListCtorIDicIKeyComp
{
public class Driver<KeyType, ValueType>
{
private Test m_test;
public Driver(Test test)
{
m_test = test;
}
private static CultureInfo s_english = new CultureInfo("en");
private static CultureInfo s_german = new CultureInfo("de");
private static CultureInfo s_danish = new CultureInfo("da");
private static CultureInfo s_turkish = new CultureInfo("tr");
//CompareString lcid_en-US, EMPTY_FLAGS, "AE", 0, 2, "\u00C4", 0, 1, 1, NULL_STRING
//CompareString 0x10407, EMPTY_FLAGS, "AE", 0, 2, "\u00C4", 0, 1, 0, NULL_STRING
//CompareString lcid_da-DK, "NORM_IGNORECASE", "aA", 0, 2, "Aa", 0, 2, -1, NULL_STRING
//CompareString lcid_en-US, "NORM_IGNORECASE", "aA", 0, 2, "Aa", 0, 2, 0, NULL_STRING
//CompareString lcid_tr-TR, "NORM_IGNORECASE", "\u0131", 0, 1, "\u0049", 0, 1, 0, NULL_STRING
private const String strAE = "AE";
private const String strUC4 = "\u00C4";
private const String straA = "aA";
private const String strAa = "Aa";
private const String strI = "I";
private const String strTurkishUpperI = "\u0131";
private const String strBB = "BB";
private const String strbb = "bb";
private const String value = "Default_Value";
public void TestEnum(IDictionary<String, String> idic)
{
SortedList<String, String> _dic;
IComparer<String> comparer;
String[] keys = new String[idic.Count];
idic.Keys.CopyTo(keys, 0);
String[] values = new String[idic.Count];
idic.Values.CopyTo(values, 0);
IComparer<String>[] predefinedComparers = new IComparer<String>[] {
StringComparer.CurrentCulture,
StringComparer.CurrentCultureIgnoreCase,
StringComparer.OrdinalIgnoreCase,
StringComparer.Ordinal};
foreach (IComparer<String> predefinedComparer in predefinedComparers)
{
_dic = new SortedList<String, String>(idic, predefinedComparer);
m_test.Eval(_dic.Comparer == predefinedComparer, String.Format("Err_4568aijueud! Comparer differ expected: {0} actual: {1}", predefinedComparer, _dic.Comparer));
m_test.Eval(_dic.Count == idic.Count, String.Format("Err_23497sg! Count different: {0}", _dic.Count));
m_test.Eval(_dic.Keys.Count == idic.Count, String.Format("Err_25ag! Count different: {0}", _dic.Keys.Count));
m_test.Eval(_dic.Values.Count == idic.Count, String.Format("Err_23agd! Count different: {0}", _dic.Values.Count));
for (int i = 0; i < idic.Keys.Count; i++)
{
m_test.Eval(_dic.ContainsKey(keys[i]), String.Format("Err_234afs! key not found: {0}", keys[i]));
m_test.Eval(_dic.ContainsValue(values[i]), String.Format("Err_3497sg! value not found: {0}", values[i]));
}
}
//Current culture
CultureInfo.DefaultThreadCurrentCulture = s_english;
comparer = StringComparer.CurrentCulture;
_dic = new SortedList<String, String>(idic, comparer);
m_test.Eval(_dic.Comparer == comparer, String.Format("Err_58484aheued! Comparer differ expected: {0} actual: {1}", comparer, _dic.Comparer));
_dic.Add(strAE, value);
m_test.Eval(!_dic.ContainsKey(strUC4), String.Format("Err_235rdag! Wrong result returned: {0}", _dic.ContainsKey(strUC4)));
//bug #11263 in NDPWhidbey
CultureInfo.DefaultThreadCurrentCulture = s_german;
comparer = StringComparer.CurrentCulture;
_dic = new SortedList<String, String>(idic, comparer);
m_test.Eval(_dic.Comparer == comparer, String.Format("Err_5468ahiede! Comparer differ expected: {0} actual: {1}", comparer, _dic.Comparer));
_dic.Add(strAE, value);
// same result in Desktop
m_test.Eval(!_dic.ContainsKey(strUC4), String.Format("Err_23r7ag! Wrong result returned: {0}", _dic.ContainsKey(strUC4)));
//CurrentCultureIgnoreCase
CultureInfo.DefaultThreadCurrentCulture = s_english;
comparer = StringComparer.CurrentCultureIgnoreCase;
_dic = new SortedList<String, String>(idic, comparer);
m_test.Eval(_dic.Comparer == comparer, String.Format("Err_4488ajede! Comparer differ expected: {0} actual: {1}", comparer, _dic.Comparer));
_dic.Add(straA, value);
m_test.Eval(_dic.ContainsKey(strAa), String.Format("Err_237g! Wrong result returned: {0}", _dic.ContainsKey(strAa)));
CultureInfo.DefaultThreadCurrentCulture = s_danish;
comparer = StringComparer.CurrentCultureIgnoreCase;
_dic = new SortedList<String, String>(idic, comparer);
m_test.Eval(_dic.Comparer == comparer, String.Format("Err_6884ahnjed! Comparer differ expected: {0} actual: {1}", comparer, _dic.Comparer));
_dic.Add(straA, value);
m_test.Eval(!_dic.ContainsKey(strAa), String.Format("Err_0723f! Wrong result returned: {0}", _dic.ContainsKey(strAa)));
//OrdinalIgnoreCase
CultureInfo.DefaultThreadCurrentCulture = s_english;
comparer = StringComparer.OrdinalIgnoreCase;
_dic = new SortedList<String, String>(idic, comparer);
m_test.Eval(_dic.Comparer == comparer, String.Format("Err_95877ahiez! Comparer differ expected: {0} actual: {1}", comparer, _dic.Comparer));
_dic.Add(strI, value);
m_test.Eval(!_dic.ContainsKey(strTurkishUpperI), String.Format("Err_234qf! Wrong result returned: {0}", _dic.ContainsKey(strTurkishUpperI)));
CultureInfo.DefaultThreadCurrentCulture = s_turkish;
comparer = StringComparer.OrdinalIgnoreCase;
_dic = new SortedList<String, String>(idic, comparer);
m_test.Eval(_dic.Comparer == comparer, String.Format("Err_50548haied! Comparer differ expected: {0} actual: {1}", comparer, _dic.Comparer));
_dic.Add(strI, value);
m_test.Eval(!_dic.ContainsKey(strTurkishUpperI), String.Format("Err_234ra7g! Wrong result returned: {0}", _dic.ContainsKey(strTurkishUpperI)));
//Ordinal - not that many meaningful test
CultureInfo.DefaultThreadCurrentCulture = s_english;
comparer = StringComparer.Ordinal;
_dic = new SortedList<String, String>(idic, comparer);
m_test.Eval(_dic.Comparer == comparer, String.Format("Err_1407hizbd! Comparer differ expected: {0} actual: {1}", comparer, _dic.Comparer));
_dic.Add(strBB, value);
m_test.Eval(!_dic.ContainsKey(strbb), String.Format("Err_1244sd! Wrong result returned: {0}", _dic.ContainsKey(strbb)));
CultureInfo.DefaultThreadCurrentCulture = s_danish;
comparer = StringComparer.Ordinal;
_dic = new SortedList<String, String>(idic, comparer);
m_test.Eval(_dic.Comparer == comparer, String.Format("Err_5088aied! Comparer differ expected: {0} actual: {1}", comparer, _dic.Comparer));
_dic.Add(strBB, value);
m_test.Eval(!_dic.ContainsKey(strbb), String.Format("Err_235aeg! Wrong result returned: {0}", _dic.ContainsKey(strbb)));
}
public void TestParm()
{
//passing null will revert to the default comparison mechanism
SortedList<String, String> _dic;
IComparer<String> comparer = null;
SortedList<String, String> dic1 = new SortedList<String, String>();
try
{
CultureInfo.DefaultThreadCurrentCulture = s_english;
_dic = new SortedList<String, String>(dic1, comparer);
_dic.Add(straA, value);
m_test.Eval(!_dic.ContainsKey(strAa), String.Format("Err_9237g! Wrong result returned: {0}", _dic.ContainsKey(strAa)));
CultureInfo.DefaultThreadCurrentCulture = s_danish;
_dic = new SortedList<String, String>(dic1, comparer);
_dic.Add(straA, value);
m_test.Eval(!_dic.ContainsKey(strAa), String.Format("Err_90723f! Wrong result returned: {0}", _dic.ContainsKey(strAa)));
}
catch (Exception ex)
{
m_test.Eval(false, String.Format("Err_387tsg! Wrong exception thrown: {0}", ex));
}
comparer = StringComparer.CurrentCulture;
dic1 = null;
try
{
CultureInfo.DefaultThreadCurrentCulture = s_english;
_dic = new SortedList<String, String>(dic1, comparer);
m_test.Eval(false, String.Format("Err_387tsg! exception not thrown"));
}
catch (ArgumentNullException)
{
}
catch (Exception ex)
{
m_test.Eval(false, String.Format("Err_387tsg! Wrong exception thrown: {0}", ex));
}
}
public void IkeyComparerOwnImplementation(IDictionary<String, String> idic)
{
//This just ensure that we can call our own implementation
SortedList<String, String> _dic;
IComparer<String> comparer = new MyOwnIKeyImplementation<String>();
try
{
CultureInfo.DefaultThreadCurrentCulture = s_english;
_dic = new SortedList<String, String>(idic, comparer);
_dic.Add(straA, value);
m_test.Eval(!_dic.ContainsKey(strAa), String.Format("Err_0237g! Wrong result returned: {0}", _dic.ContainsKey(strAa)));
CultureInfo.DefaultThreadCurrentCulture = s_danish;
_dic = new SortedList<String, String>(idic, comparer);
_dic.Add(straA, value);
m_test.Eval(!_dic.ContainsKey(strAa), String.Format("Err_00723f! Wrong result returned: {0}", _dic.ContainsKey(strAa)));
}
catch (Exception ex)
{
m_test.Eval(false, String.Format("Err_387tsg! Wrong exception thrown: {0}", ex));
}
}
}
public class Constructor_IDictionary_IKeyComparer
{
[Fact]
[ActiveIssue(846, PlatformID.AnyUnix)]
public static void RunTests()
{
//This mostly follows the format established by the original author of these tests
Test test = new Test();
Driver<String, String> driver1 = new Driver<String, String>(test);
Driver<SimpleRef<int>, SimpleRef<String>> driver2 = new Driver<SimpleRef<int>, SimpleRef<String>>(test);
Driver<SimpleRef<String>, SimpleRef<int>> driver3 = new Driver<SimpleRef<String>, SimpleRef<int>>(test);
Driver<SimpleRef<int>, SimpleRef<int>> driver4 = new Driver<SimpleRef<int>, SimpleRef<int>>(test);
Driver<SimpleRef<String>, SimpleRef<String>> driver5 = new Driver<SimpleRef<String>, SimpleRef<String>>(test);
int count;
SimpleRef<int>[] simpleInts;
SimpleRef<String>[] simpleStrings;
String[] strings;
SortedList<String, String> dic1;
count = 10;
strings = new String[count];
for (int i = 0; i < count; i++)
strings[i] = i.ToString();
simpleInts = GetSimpleInts(count);
simpleStrings = GetSimpleStrings(count);
dic1 = FillValues(strings, strings);
//Scenario 1: Pass all the enum values and ensure that the behavior is correct
driver1.TestEnum(dic1);
//Scenario 2: Parm validation: null
driver1.TestParm();
//Scenario 3: Implement our own IKeyComparer and check
driver1.IkeyComparerOwnImplementation(dic1);
//Scenario 5: ensure that SortedList items from the passed IDictionary object use the interface IKeyComparer's Equals and GetHashCode APIs.
//Ex. Pass the case invariant IKeyComparer and check
//@TODO!!!
//Scenario 6: Contradictory values and check: ex. IDictionary is case insensitive but IKeyComparer is not
Assert.True(test.result);
}
private static SortedList<KeyType, ValueType> FillValues<KeyType, ValueType>(KeyType[] keys, ValueType[] values)
{
SortedList<KeyType, ValueType> _dic = new SortedList<KeyType, ValueType>();
for (int i = 0; i < keys.Length; i++)
_dic.Add(keys[i], values[i]);
return _dic;
}
private static SimpleRef<int>[] GetSimpleInts(int count)
{
SimpleRef<int>[] simpleInts = new SimpleRef<int>[count];
for (int i = 0; i < count; i++)
simpleInts[i] = new SimpleRef<int>(i);
return simpleInts;
}
private static SimpleRef<String>[] GetSimpleStrings(int count)
{
SimpleRef<String>[] simpleStrings = new SimpleRef<String>[count];
for (int i = 0; i < count; i++)
simpleStrings[i] = new SimpleRef<String>(i.ToString());
return simpleStrings;
}
}
//[Serializable]
internal class MyOwnIKeyImplementation<KeyType> : IComparer<KeyType> where KeyType : IComparable<KeyType>
{
public int GetHashCode(KeyType key)
{
if (null == key)
return 0;
//We cannot get the hascode that is culture aware here since TextInfo doesn't expose this functionality publicly
return key.GetHashCode();
}
public int Compare(KeyType key1, KeyType key2)
{
if (null == key1)
{
if (null == key2)
return 0;
return -1;
}
return key1.CompareTo(key2);
}
public bool Equals(KeyType key1, KeyType key2)
{
if (null == key1)
return null == key2;
return key1.Equals(key2);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.