context stringlengths 2.52k 185k | gt stringclasses 1 value |
|---|---|
//------------------------------------------------------------------------------
// <copyright file="Shape.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">derekdb</owner>
//------------------------------------------------------------------------------
#if ENABLEDATABINDING
using System;
using System.Xml;
using System.Xml.Schema;
using System.Xml.XPath;
using System.Collections;
using System.Diagnostics;
using System.ComponentModel;
using System.Text;
namespace System.Xml.XPath.DataBinding
{
internal enum BindingType {
Text,
Element,
Attribute,
ElementNested,
Repeat,
Sequence,
Choice,
All
}
internal sealed class Shape
{
string name;
BindingType bindingType;
ArrayList particles; // XmlSchemaElement or XmlSchemaAttribute
ArrayList subShapes;
Shape nestedShape;
PropertyDescriptor[] propertyDescriptors;
XmlSchemaElement containerDecl;
static object[] emptyIList = new object[0];
public Shape(string name, BindingType bindingType)
{
this.name = name;
this.bindingType = bindingType;
}
public string Name {
get { return this.name; }
set { this.name = value; }
}
public BindingType BindingType {
get { return this.bindingType; }
set { this.bindingType = value; }
}
public XmlSchemaElement ContainerDecl {
get { return this.containerDecl; }
set { this.containerDecl = value; }
}
public bool IsNestedTable {
get {
switch (this.BindingType) {
case BindingType.ElementNested:
case BindingType.Repeat:
case BindingType.Sequence:
case BindingType.Choice:
case BindingType.All:
return true;
default:
return false;
}
}
}
public bool IsGroup {
get {
switch (this.BindingType) {
case BindingType.Sequence:
case BindingType.Choice:
case BindingType.All:
return true;
default:
return false;
}
}
}
public XmlSchemaType SchemaType {
get {
switch (this.bindingType) {
case BindingType.Text:
case BindingType.Element:
case BindingType.ElementNested: {
Debug.Assert(this.particles.Count == 1);
XmlSchemaElement xse = (XmlSchemaElement)this.particles[0];
return xse.ElementSchemaType;
}
case BindingType.Attribute: {
Debug.Assert(this.particles.Count == 1);
XmlSchemaAttribute xsa = (XmlSchemaAttribute)this.particles[0];
return xsa.AttributeSchemaType;
}
default:
return null;
}
}
}
public XmlSchemaElement XmlSchemaElement {
get {
switch (this.bindingType) {
case BindingType.Text:
case BindingType.Element:
case BindingType.ElementNested: {
Debug.Assert(this.particles.Count == 1);
return (XmlSchemaElement)this.particles[0];
}
default:
return this.containerDecl;
}
}
}
public IList Particles {
get {
if (null == this.particles)
return emptyIList;
return this.particles;
}
}
public IList SubShapes {
get {
if (null == this.subShapes)
return emptyIList;
return this.subShapes;
}
}
public Shape SubShape(int i) {
return (Shape)SubShapes[i];
}
public Shape NestedShape {
get {
//Debug.Assert(this.bindingType == BindingType.ElementNested);
return this.nestedShape;
}
set {
this.nestedShape = value;
}
}
public XmlQualifiedName AttributeName {
get {
Debug.Assert(this.bindingType == BindingType.Attribute);
XmlSchemaAttribute xsa = (XmlSchemaAttribute)this.particles[0];
return xsa.QualifiedName;
}
}
public void Clear() {
if (this.subShapes != null) {
this.subShapes.Clear();
this.subShapes = null;
}
if (this.particles != null) {
this.particles.Clear();
this.particles = null;
}
}
public void AddParticle(XmlSchemaElement elem) {
if (null == this.particles)
this.particles = new ArrayList();
Debug.Assert(this.bindingType != BindingType.Attribute);
this.particles.Add(elem);
}
public void AddParticle(XmlSchemaAttribute elem) {
Debug.Assert(this.bindingType == BindingType.Attribute);
Debug.Assert(this.particles == null);
this.particles = new ArrayList();
this.particles.Add(elem);
}
public void AddSubShape(Shape shape) {
if (null == this.subShapes)
this.subShapes = new ArrayList();
this.subShapes.Add(shape);
foreach (object p in shape.Particles) {
XmlSchemaElement xse = p as XmlSchemaElement;
if (null != xse)
AddParticle(xse);
}
}
public void AddAttrShapeAt(Shape shape, int pos) {
if (null == this.subShapes)
this.subShapes = new ArrayList();
this.subShapes.Insert(pos, shape);
}
public string[] SubShapeNames() {
string[] names = new string[SubShapes.Count];
for (int i=0; i<SubShapes.Count; i++)
names[i] = this.SubShape(i).Name;
return names;
}
public PropertyDescriptor[] PropertyDescriptors {
get {
if (null == this.propertyDescriptors) {
PropertyDescriptor[] descs;
switch (this.BindingType) {
case BindingType.Element:
case BindingType.Text:
case BindingType.Attribute:
case BindingType.Repeat:
descs = new PropertyDescriptor[1];
descs[0] = new XPathNodeViewPropertyDescriptor(this);
break;
case BindingType.ElementNested:
descs = this.nestedShape.PropertyDescriptors;
break;
case BindingType.Sequence:
case BindingType.Choice:
case BindingType.All:
descs = new PropertyDescriptor[SubShapes.Count];
for (int i=0; i < descs.Length; i++) {
descs[i] = new XPathNodeViewPropertyDescriptor(this, this.SubShape(i), i);
}
break;
default:
throw new NotSupportedException();
}
this.propertyDescriptors = descs;
}
return this.propertyDescriptors;
}
}
public int FindNamedSubShape(string name) {
for (int i=0; i<SubShapes.Count; i++) {
Shape shape = SubShape(i);
if (shape.Name == name)
return i;
}
return -1;
}
public int FindMatchingSubShape(object particle) {
for (int i=0; i<SubShapes.Count; i++) {
Shape shape = SubShape(i);
if (shape.IsParticleMatch(particle))
return i;
}
return -1;
}
public bool IsParticleMatch(object particle) {
for (int i=0; i<this.particles.Count; i++) {
if (particle == this.particles[i])
return true;
}
return false;
}
#if DEBUG
public string DebugDump() {
StringBuilder sb = new StringBuilder();
DebugDump(sb,"");
return sb.ToString();
}
void DebugDump(StringBuilder sb, String indent) {
sb.AppendFormat("{0}{1} '{2}'", indent, this.BindingType.ToString(), this.Name);
if (this.subShapes != null) {
sb.AppendLine(" {");
string subindent = String.Concat(indent, " ");
foreach (Shape s in this.SubShapes) {
s.DebugDump(sb, subindent);
}
sb.Append(indent);
sb.Append('}');
}
sb.AppendLine();
}
#endif
}
}
#endif
| |
//
// Layer.cs
//
// Author:
// Jonathan Pobst <monkey@jpobst.com>
//
// Copyright (c) 2010 Jonathan Pobst
//
// 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.ComponentModel;
using System.Collections.Specialized;
using Cairo;
using Gdk;
namespace Pinta.Core
{
public class Layer : ObservableObject
{
private double opacity;
private bool hidden;
private string name;
private BlendMode blend_mode;
private Matrix transform = new Matrix();
public Layer () : this (null)
{
}
public Layer (ImageSurface surface) : this (surface, false, 1f, "")
{
}
public Layer (ImageSurface surface, bool hidden, double opacity, string name)
{
Surface = surface;
this.hidden = hidden;
this.opacity = opacity;
this.name = name;
this.blend_mode = BlendMode.Normal;
}
public ImageSurface Surface { get; set; }
public bool Tiled { get; set; }
public Matrix Transform { get { return transform; } }
public static readonly string OpacityProperty = "Opacity";
public static readonly string HiddenProperty = "Hidden";
public static readonly string NameProperty = "Name";
public static readonly string BlendModeProperty = "BlendMode";
public double Opacity {
get { return opacity; }
set { if (opacity != value) SetValue (OpacityProperty, ref opacity, value); }
}
public bool Hidden {
get { return hidden; }
set { if (hidden != value) SetValue (HiddenProperty, ref hidden, value); }
}
public string Name {
get { return name; }
set { if (name != value) SetValue (NameProperty, ref name, value); }
}
public BlendMode BlendMode {
get { return blend_mode; }
set { if (blend_mode != value) SetValue (BlendModeProperty, ref blend_mode, value); }
}
public void Clear ()
{
Surface.Clear ();
}
public void FlipHorizontal ()
{
Layer dest = PintaCore.Layers.CreateLayer ();
using (Cairo.Context g = new Cairo.Context (dest.Surface)) {
g.Matrix = new Matrix (-1, 0, 0, 1, Surface.Width, 0);
g.SetSource (Surface);
g.Paint ();
}
Surface old = Surface;
Surface = dest.Surface;
(old as IDisposable).Dispose ();
}
public void FlipVertical ()
{
Layer dest = PintaCore.Layers.CreateLayer ();
using (Cairo.Context g = new Cairo.Context (dest.Surface)) {
g.Matrix = new Matrix (1, 0, 0, -1, 0, Surface.Height);
g.SetSource (Surface);
g.Paint ();
}
Surface old = Surface;
Surface = dest.Surface;
(old as IDisposable).Dispose ();
}
public void Draw(Context ctx)
{
Draw(ctx, Surface, Opacity);
}
public void Draw(Context ctx, ImageSurface surface, double opacity)
{
ctx.Save();
ctx.Transform(Transform);
ctx.SetSourceSurface(surface, 0, 0);
ctx.PaintWithAlpha(opacity);
ctx.Restore();
}
/// <summary>
/// Rotates layer by the specified angle (in degrees).
/// </summary>
/// <param name='angle'>
/// Angle (in degrees).
/// </param>
public virtual void Rotate (double angle)
{
int w = PintaCore.Workspace.ImageSize.Width;
int h = PintaCore.Workspace.ImageSize.Height;
double radians = (angle / 180d) * Math.PI;
double cos = Math.Cos (radians);
double sin = Math.Sin (radians);
var newSize = RotateDimensions (PintaCore.Workspace.ImageSize, angle);
Layer dest = PintaCore.Layers.CreateLayer (string.Empty, newSize.Width, newSize.Height);
using (Cairo.Context g = new Cairo.Context (dest.Surface)) {
g.Matrix = new Matrix (cos, sin, -sin, cos, newSize.Width / 2.0, newSize.Height / 2.0);
g.Translate (-w / 2.0, -h / 2.0);
g.SetSource (Surface);
g.Paint ();
}
Surface old = Surface;
Surface = dest.Surface;
(old as IDisposable).Dispose ();
}
public static Gdk.Size RotateDimensions (Gdk.Size originalSize, double angle)
{
double radians = (angle / 180d) * Math.PI;
double cos = Math.Abs (Math.Cos (radians));
double sin = Math.Abs (Math.Sin (radians));
int w = originalSize.Width;
int h = originalSize.Height;
return new Gdk.Size ((int)(w * cos + h * sin), (int)(w * sin + h * cos));
}
public unsafe void HueSaturation (int hueDelta, int satDelta, int lightness)
{
ImageSurface dest = Surface.Clone ();
ColorBgra* dstPtr = (ColorBgra*)dest.DataPtr;
int len = Surface.Data.Length / 4;
// map the range [0,100] -> [0,100] and the range [101,200] -> [103,400]
if (satDelta > 100)
satDelta = ((satDelta - 100) * 3) + 100;
UnaryPixelOp op;
if (hueDelta == 0 && satDelta == 100 && lightness == 0)
op = new UnaryPixelOps.Identity ();
else
op = new UnaryPixelOps.HueSaturationLightness (hueDelta, satDelta, lightness);
op.Apply (dstPtr, len);
using (Context g = new Context (Surface)) {
g.AppendPath (PintaCore.Workspace.ActiveDocument.Selection.SelectionPath);
g.FillRule = Cairo.FillRule.EvenOdd;
g.Clip ();
g.SetSource (dest);
g.Paint ();
}
(dest as IDisposable).Dispose ();
}
public virtual void Resize (int width, int height)
{
ImageSurface dest = new ImageSurface (Format.Argb32, width, height);
Pixbuf pb = Surface.ToPixbuf();
Pixbuf pbScaled = pb.ScaleSimple (width, height, InterpType.Bilinear);
using (Context g = new Context (dest)) {
CairoHelper.SetSourcePixbuf (g, pbScaled, 0, 0);
g.Paint ();
}
(Surface as IDisposable).Dispose ();
(pb as IDisposable).Dispose ();
(pbScaled as IDisposable).Dispose ();
Surface = dest;
}
public virtual void ResizeCanvas (int width, int height, Anchor anchor)
{
ImageSurface dest = new ImageSurface (Format.Argb32, width, height);
int delta_x = Surface.Width - width;
int delta_y = Surface.Height - height;
using (Context g = new Context (dest)) {
switch (anchor) {
case Anchor.NW:
g.SetSourceSurface (Surface, 0, 0);
break;
case Anchor.N:
g.SetSourceSurface (Surface, -delta_x / 2, 0);
break;
case Anchor.NE:
g.SetSourceSurface (Surface, -delta_x, 0);
break;
case Anchor.E:
g.SetSourceSurface (Surface, -delta_x, -delta_y / 2);
break;
case Anchor.SE:
g.SetSourceSurface (Surface, -delta_x, -delta_y);
break;
case Anchor.S:
g.SetSourceSurface (Surface, -delta_x / 2, -delta_y);
break;
case Anchor.SW:
g.SetSourceSurface (Surface, 0, -delta_y);
break;
case Anchor.W:
g.SetSourceSurface (Surface, 0, -delta_y / 2);
break;
case Anchor.Center:
g.SetSourceSurface (Surface, -delta_x / 2, -delta_y / 2);
break;
}
g.Paint ();
}
(Surface as IDisposable).Dispose ();
Surface = dest;
}
public virtual void Crop (Gdk.Rectangle rect, Path path)
{
ImageSurface dest = new ImageSurface (Format.Argb32, rect.Width, rect.Height);
using (Context g = new Context (dest)) {
// Move the selected content to the upper left
g.Translate (-rect.X, -rect.Y);
g.Antialias = Antialias.None;
// Respect the selected path
g.AppendPath (path);
g.FillRule = Cairo.FillRule.EvenOdd;
g.Clip ();
g.SetSource (Surface);
g.Paint ();
}
(Surface as IDisposable).Dispose ();
Surface = dest;
}
}
}
| |
//
// Copyright (C) 2009 Amr Hassan
//
// 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 3 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, see <http://www.gnu.org/licenses/>.
//
using System;
using System.Collections.Generic;
using System.Xml;
namespace UB.LastFM.Services
{
/// <summary>
/// A Last.fm track.
/// </summary>
public class Track : Base, IEquatable<Track>, IShareable, ITaggable, IHasURL
{
/// <summary>
/// The track title.
/// </summary>
public string Title {get; private set;}
/// <summary>
/// The artist.
/// </summary>
public Artist Artist {get; private set;}
/// <summary>
/// The track wiki on Last.fm.
/// </summary>
public Wiki Wiki
{ get { return new TrackWiki(this, Session); } }
public Track(string artistName, string title, Session session)
:base(session)
{
Title = title;
Artist = new Artist(artistName, Session);
}
public Track(Artist artist, string title, Session session)
:base(session)
{
Title = title;
Artist = artist;
}
/// <summary>
/// String representation of the object.
/// </summary>
/// <returns>
/// A <see cref="System.String"/>
/// </returns>
public override string ToString ()
{
return this.Artist + " - " + this.Title;
}
internal override RequestParameters getParams ()
{
RequestParameters p = new RequestParameters();
p["artist"] = Artist.Name;
p["track"] = Title;
return p;
}
/// <summary>
/// A unique Last.fm ID.
/// </summary>
/// <returns>
/// A <see cref="System.Int32"/>
/// </returns>
public int GetID()
{
XmlDocument doc = request("track.getInfo");
var id = extract(doc, "id");
if (String.IsNullOrEmpty(id))
return -1;
else
return Int32.Parse(id);
}
/// <summary>
/// Returns the duration.
/// </summary>
/// <returns>
/// A <see cref="TimeSpan"/>
/// </returns>
public TimeSpan GetDuration()
{
XmlDocument doc = request("track.getInfo");
// Duration is returned in milliseconds.
return new TimeSpan(0, 0, 0, 0, Int32.Parse(extract(doc, "duration")));
}
/// <summary>
/// Returns true if the track is available for streaming.
/// </summary>
/// <returns>
/// A <see cref="System.Boolean"/>
/// </returns>
public bool IsStreamable()
{
XmlDocument doc = request("track.getInfo");
int value = Int32.Parse(extract(doc, "streamable"));
if (value == 1)
return true;
else
return false;
}
/// <summary>
/// Returns the album of this track.
/// </summary>
/// <returns>
/// A <see cref="Album"/>
/// </returns>
public Album GetAlbum()
{
XmlDocument doc = request("track.getInfo");
if (doc.GetElementsByTagName("album").Count > 0)
{
XmlNode n = doc.GetElementsByTagName("album")[0];
string artist = extract(n, "artist");
string title = extract(n, "title");
return new Album(artist, title, Session);
}else{
return null;
}
}
/// <summary>
/// Ban this track.
/// </summary>
public void Ban()
{
//This method requires authentication
requireAuthentication();
request("track.ban");
}
/// <summary>
/// Return similar tracks.
/// </summary>
/// <returns>
/// A <see cref="Track"/>
/// </returns>
public Track[] GetSimilar()
{
XmlDocument doc = request("track.getSimilar");
List<Track> list = new List<Track>();
foreach(XmlNode n in doc.GetElementsByTagName("track"))
{
list.Add(new Track(extract(n, "name", 1), extract(n, "name"), Session));
}
return list.ToArray();
}
/// <summary>
/// Love this track.
/// </summary>
public void Love()
{
//This method requires authentication
requireAuthentication();
request("track.love");
}
/// <summary>
/// Check to see if this object equals another.
/// </summary>
/// <param name="track">
/// A <see cref="Track"/>
/// </param>
/// <returns>
/// A <see cref="System.Boolean"/>
/// </returns>
public bool Equals(Track track)
{
return(track.Title == this.Title && track.Artist.Name == this.Artist.Name);
}
/// <summary>
/// Share this track with others.
/// </summary>
/// <param name="recipients">
/// A <see cref="Recipients"/>
/// </param>
/// <param name="message">
/// A <see cref="System.String"/>
/// </param>
public void Share(Recipients recipients, string message)
{
if (recipients.Count > 1)
{
foreach(string recipient in recipients)
{
Recipients r = new Recipients();
r.Add(recipient);
Share(r, message);
}
return;
}
requireAuthentication();
RequestParameters p = getParams();
p["recipient"] = recipients[0];
p["message"] = message;
request("track.Share", p);
}
/// <summary>
/// Share this track with others.
/// </summary>
/// <param name="recipients">
/// A <see cref="Recipients"/>
/// </param>
public void Share(Recipients recipients)
{
if (recipients.Count > 1)
{
foreach(string recipient in recipients)
{
Recipients r = new Recipients();
r.Add(recipient);
Share(r);
}
return;
}
requireAuthentication();
RequestParameters p = getParams();
p["recipient"] = recipients[0];
request("track.Share", p);
}
/// <summary>
/// Search for tracks on Last.fm.
/// </summary>
/// <param name="artist">
/// A <see cref="System.String"/>
/// </param>
/// <param name="title">
/// A <see cref="System.String"/>
/// </param>
/// <param name="session">
/// A <see cref="Session"/>
/// </param>
/// <returns>
/// A <see cref="TrackSearch"/>
/// </returns>
public static TrackSearch Search(string artist, string title, Session session)
{
return new TrackSearch(artist, title, session);
}
/// <summary>
/// Search for tracks on Last.fm.
/// </summary>
/// <param name="title">
/// A <see cref="System.String"/>
/// </param>
/// <param name="session">
/// A <see cref="Session"/>
/// </param>
/// <returns>
/// A <see cref="TrackSearch"/>
/// </returns>
public static TrackSearch Search(string title, Session session)
{
return new TrackSearch(title, session);
}
/// <summary>
/// Add tags to this track.
/// </summary>
/// <param name="tags">
/// A <see cref="Tag"/>
/// </param>
public void AddTags(params Tag[] tags)
{
//This method requires authentication
requireAuthentication();
foreach(Tag tag in tags)
{
RequestParameters p = getParams();
p["tags"] = tag.Name;
request("track.addTags", p);
}
}
/// <summary>
/// Add tags to this track.
/// </summary>
/// <param name="tags">
/// A <see cref="System.String"/>
/// </param>
public void AddTags(params string[] tags)
{
foreach(string tag in tags)
AddTags(new Tag(tag, Session));
}
/// <summary>
/// Add tags to this track.
/// </summary>
/// <param name="tags">
/// A <see cref="TagCollection"/>
/// </param>
public void AddTags(TagCollection tags)
{
foreach(Tag tag in tags)
AddTags(tag);
}
/// <summary>
/// Returns the tags set by the authenticated user to this track.
/// </summary>
/// <returns>
/// A <see cref="Tag"/>
/// </returns>
public Tag[] GetTags()
{
//This method requires authentication
requireAuthentication();
XmlDocument doc = request("track.getTags");
TagCollection collection = new TagCollection(Session);
foreach(string name in this.extractAll(doc, "name"))
collection.Add(name);
return collection.ToArray();
}
/// <summary>
/// Return the top tags.
/// </summary>
/// <returns>
/// A <see cref="TopTag"/>
/// </returns>
public TopTag[] GetTopTags()
{
XmlDocument doc = request("track.getTopTags");
List<TopTag> list = new List<TopTag>();
foreach(XmlNode n in doc.GetElementsByTagName("tag"))
list.Add(new TopTag(new Tag(extract(n, "name"), Session), Int32.Parse(extract(n, "count"))));
return list.ToArray();
}
/// <summary>
/// Returns the top tags.
/// </summary>
/// <param name="limit">
/// A <see cref="System.Int32"/>
/// </param>
/// <returns>
/// A <see cref="TopTag"/>
/// </returns>
public TopTag[] GetTopTags(int limit)
{
return this.sublist<TopTag>(GetTopTags(), limit);
}
/// <summary>
/// Remove a bunch of tags from this track.
/// </summary>
/// <param name="tags">
/// A <see cref="Tag"/>
/// </param>
public void RemoveTags(params Tag[] tags)
{
//This method requires authentication
requireAuthentication();
foreach(Tag tag in tags)
{
RequestParameters p = getParams();
p["tag"] = tag.Name;
request("track.removeTag", p);
}
}
/// <summary>
/// Remove a bunch of tags from this track.
/// </summary>
/// <param name="tags">
/// A <see cref="System.String"/>
/// </param>
public void RemoveTags(params string[] tags)
{
//This method requires authentication
requireAuthentication();
foreach(string tag in tags)
RemoveTags(new Tag(tag, Session));
}
/// <summary>
/// Remove a bunch of tags from this track.
/// </summary>
/// <param name="tags">
/// A <see cref="TagCollection"/>
/// </param>
public void RemoveTags(TagCollection tags)
{
foreach(Tag tag in tags)
RemoveTags(tag);
}
/// <summary>
/// Set the tags of this tracks to only those tags.
/// </summary>
/// <param name="tags">
/// A <see cref="System.String"/>
/// </param>
public void SetTags(string[] tags)
{
List<Tag> list = new List<Tag>();
foreach(string name in tags)
list.Add(new Tag(name, Session));
SetTags(list.ToArray());
}
/// <summary>
/// Set the tags of this tracks to only those tags.
/// </summary>
/// <param name="tags">
/// A <see cref="Tag"/>
/// </param>
public void SetTags(Tag[] tags)
{
List<Tag> newSet = new List<Tag>(tags);
List<Tag> current = new List<Tag>(GetTags());
List<Tag> toAdd = new List<Tag>();
List<Tag> toRemove = new List<Tag>();
foreach(Tag tag in newSet)
if(!current.Contains(tag))
toAdd.Add(tag);
foreach(Tag tag in current)
if(!newSet.Contains(tag))
toRemove.Add(tag);
if (toAdd.Count > 0)
AddTags(toAdd.ToArray());
if (toRemove.Count > 0)
RemoveTags(toRemove.ToArray());
}
/// <summary>
/// Set the tags of this tracks to only those tags.
/// </summary>
/// <param name="tags">
/// A <see cref="TagCollection"/>
/// </param>
public void SetTags(TagCollection tags)
{
SetTags(tags.ToArray());
}
/// <summary>
/// Clear all the tags from this track.
/// </summary>
public void ClearTags()
{
foreach(Tag tag in GetTags())
RemoveTags(tag);
}
/// <summary>
/// Returns the top fans.
/// </summary>
/// <returns>
/// A <see cref="TopFan"/>
/// </returns>
public TopFan[] GetTopFans()
{
XmlDocument doc = request("track.getTopFans");
List<TopFan> list = new List<TopFan>();
foreach(XmlNode node in doc.GetElementsByTagName("user"))
list.Add(new TopFan(new User(extract(node, "name"), Session), Int32.Parse(extract(node, "weight"))));
return list.ToArray();
}
/// <summary>
/// Returns the top fans.
/// </summary>
/// <param name="limit">
/// A <see cref="System.Int32"/>
/// </param>
/// <returns>
/// A <see cref="TopFan"/>
/// </returns>
public TopFan[] GetTopFans(int limit)
{
return sublist<TopFan>(GetTopFans(), limit);
}
/// <summary>
/// Returns the track's MusicBrainz id.
/// </summary>
/// <returns>
/// A <see cref="System.String"/>
/// </returns>
public string GetMBID()
{
XmlDocument doc = request("track.getInfo");
return doc.GetElementsByTagName("mbid")[0].InnerText;
}
/// <summary>
/// Returns a track by its MusicBrainz id.
/// </summary>
/// <param name="mbid">
/// A <see cref="System.String"/>
/// </param>
/// <param name="session">
/// A <see cref="Session"/>
/// </param>
/// <returns>
/// A <see cref="Track"/>
/// </returns>
public static Track GetByMBID(string mbid, Session session)
{
RequestParameters p = new RequestParameters();
p["mbid"] = mbid;
XmlDocument doc = (new Request("track.getInfo", session, p)).execute();
string title = doc.GetElementsByTagName("name")[0].InnerText;
string artist = doc.GetElementsByTagName("name")[1].InnerText;
return new Track(artist, title, session);
}
/// <summary>
/// Returns the Last.fm page of this object.
/// </summary>
/// <param name="language">
/// A <see cref="SiteLanguage"/>
/// </param>
/// <returns>
/// A <see cref="System.String"/>
/// </returns>
public string GetURL(SiteLanguage language)
{
string domain = getSiteDomain(language);
return "http://" + domain + "/music/" + urlSafe(Artist.Name) + "/_/" + urlSafe(Title);
}
/// <summary>
/// The object's Last.fm page url.
/// </summary>
public string URL
{ get { return GetURL(SiteLanguage.English); } }
/// <summary>
/// Add this track to a <see cref="Playlist"/>
/// </summary>
/// <param name="playlist">
/// A <see cref="Playlist"/>
/// </param>
public void AddToPlaylist(Playlist playlist)
{
playlist.AddTrack(this);
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Network
{
using Azure;
using Management;
using Rest;
using Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// SubnetsOperations operations.
/// </summary>
internal partial class SubnetsOperations : IServiceOperations<NetworkManagementClient>, ISubnetsOperations
{
/// <summary>
/// Initializes a new instance of the SubnetsOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal SubnetsOperations(NetworkManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the NetworkManagementClient
/// </summary>
public NetworkManagementClient Client { get; private set; }
/// <summary>
/// Deletes the specified subnet.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='subnetName'>
/// The name of the subnet.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, string subnetName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send request
AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync(resourceGroupName, virtualNetworkName, subnetName, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the specified subnet by virtual network and resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='subnetName'>
/// The name of the subnet.
/// </param>
/// <param name='expand'>
/// Expands referenced resources.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<Subnet>> GetWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, string subnetName, string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (virtualNetworkName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetworkName");
}
if (subnetName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "subnetName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2016-09-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("virtualNetworkName", virtualNetworkName);
tracingParameters.Add("subnetName", subnetName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("expand", expand);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/subnets/{subnetName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{virtualNetworkName}", System.Uri.EscapeDataString(virtualNetworkName));
_url = _url.Replace("{subnetName}", System.Uri.EscapeDataString(subnetName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (expand != null)
{
_queryParameters.Add(string.Format("$expand={0}", System.Uri.EscapeDataString(expand)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _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 (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<Subnet>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Subnet>(_responseContent, Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Creates or updates a subnet in the specified virtual network.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='subnetName'>
/// The name of the subnet.
/// </param>
/// <param name='subnetParameters'>
/// Parameters supplied to the create or update subnet operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<Subnet>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, string subnetName, Subnet subnetParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send Request
AzureOperationResponse<Subnet> _response = await BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, virtualNetworkName, subnetName, subnetParameters, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets all subnets in a virtual network.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<Subnet>>> ListWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (virtualNetworkName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetworkName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2016-09-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("virtualNetworkName", virtualNetworkName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/subnets").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{virtualNetworkName}", System.Uri.EscapeDataString(virtualNetworkName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new 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 (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<Subnet>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<Subnet>>(_responseContent, Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Deletes the specified subnet.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='subnetName'>
/// The name of the subnet.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, string subnetName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (virtualNetworkName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetworkName");
}
if (subnetName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "subnetName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2016-09-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("virtualNetworkName", virtualNetworkName);
tracingParameters.Add("subnetName", subnetName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/subnets/{subnetName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{virtualNetworkName}", System.Uri.EscapeDataString(virtualNetworkName));
_url = _url.Replace("{subnetName}", System.Uri.EscapeDataString(subnetName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("DELETE");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 204 && (int)_statusCode != 202)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_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)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Creates or updates a subnet in the specified virtual network.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='subnetName'>
/// The name of the subnet.
/// </param>
/// <param name='subnetParameters'>
/// Parameters supplied to the create or update subnet operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<Subnet>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, string subnetName, Subnet subnetParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (virtualNetworkName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetworkName");
}
if (subnetName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "subnetName");
}
if (subnetParameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "subnetParameters");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2016-09-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("virtualNetworkName", virtualNetworkName);
tracingParameters.Add("subnetName", subnetName);
tracingParameters.Add("subnetParameters", subnetParameters);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdate", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/subnets/{subnetName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{virtualNetworkName}", System.Uri.EscapeDataString(virtualNetworkName));
_url = _url.Replace("{subnetName}", System.Uri.EscapeDataString(subnetName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new 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 (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(subnetParameters != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(subnetParameters, 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 (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 201)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<Subnet>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Subnet>(_responseContent, Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
// Deserialize Response
if ((int)_statusCode == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Subnet>(_responseContent, Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets all subnets in a virtual network.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<Subnet>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new 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 (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<Subnet>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<Subnet>>(_responseContent, Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
namespace System.Linq.Expressions.Tests
{
public class ReferenceNotEqual : ReferenceEqualityTests
{
[Theory]
[PerCompilationType(nameof(ReferenceObjectsData))]
public void FalseOnSame(object item, bool useInterpreter)
{
Expression exp = Expression.ReferenceNotEqual(
Expression.Constant(item, item.GetType()),
Expression.Constant(item, item.GetType())
);
Assert.False(Expression.Lambda<Func<bool>>(exp).Compile(useInterpreter)());
}
[Theory]
[PerCompilationType(nameof(ReferenceTypesData))]
public void FalseOnBothNull(Type type, bool useInterpreter)
{
Expression exp = Expression.ReferenceNotEqual(
Expression.Constant(null, type),
Expression.Constant(null, type)
);
Assert.False(Expression.Lambda<Func<bool>>(exp).Compile(useInterpreter)());
}
[Theory]
[PerCompilationType(nameof(ReferenceObjectsData))]
public void TrueIfLeftNull(object item, bool useInterpreter)
{
Expression exp = Expression.ReferenceNotEqual(
Expression.Constant(null, item.GetType()),
Expression.Constant(item, item.GetType())
);
Assert.True(Expression.Lambda<Func<bool>>(exp).Compile(useInterpreter)());
}
[Theory]
[PerCompilationType(nameof(ReferenceObjectsData))]
public void TrueIfRightNull(object item, bool useInterpreter)
{
Expression exp = Expression.ReferenceNotEqual(
Expression.Constant(item, item.GetType()),
Expression.Constant(null, item.GetType())
);
Assert.True(Expression.Lambda<Func<bool>>(exp).Compile(useInterpreter)());
}
[Theory]
[PerCompilationType(nameof(DifferentObjects))]
public void TrueIfDifferentObjectsAsObject(object x, object y, bool useInterpreter)
{
Expression exp = Expression.ReferenceNotEqual(
Expression.Constant(x, typeof(object)),
Expression.Constant(y, typeof(object))
);
Assert.True(Expression.Lambda<Func<bool>>(exp).Compile(useInterpreter)());
}
[Theory]
[PerCompilationType(nameof(DifferentObjects))]
public void TrueIfDifferentObjectsOwnType(object x, object y, bool useInterpreter)
{
Expression exp = Expression.ReferenceNotEqual(
Expression.Constant(x),
Expression.Constant(y)
);
Assert.True(Expression.Lambda<Func<bool>>(exp).Compile(useInterpreter)());
}
[Theory]
[MemberData(nameof(LeftValueType))]
[MemberData(nameof(RightValueType))]
[MemberData(nameof(BothValueType))]
public void ThrowsOnValueTypeArguments(object x, object y)
{
Expression xExp = Expression.Constant(x);
Expression yExp = Expression.Constant(y);
Assert.Throws<InvalidOperationException>(() => Expression.ReferenceNotEqual(xExp, yExp));
}
[Theory]
[MemberData(nameof(UnassignablePairs))]
public void ThrowsOnUnassignablePairs(object x, object y)
{
Expression xExp = Expression.Constant(x);
Expression yExp = Expression.Constant(y);
Assert.Throws<InvalidOperationException>(() => Expression.ReferenceNotEqual(xExp, yExp));
}
[Theory]
[PerCompilationType(nameof(ComparableValuesData))]
public void FalseOnSameViaInterface(object item, bool useInterpreter)
{
Expression exp = Expression.ReferenceNotEqual(
Expression.Constant(item, typeof(IComparable)),
Expression.Constant(item, typeof(IComparable))
);
Assert.False(Expression.Lambda<Func<bool>>(exp).Compile(useInterpreter)());
}
[Theory]
[PerCompilationType(nameof(DifferentComparableValues))]
public void TrueOnDifferentViaInterface(object x, object y, bool useInterpreter)
{
Expression exp = Expression.ReferenceNotEqual(
Expression.Constant(x, typeof(IComparable)),
Expression.Constant(y, typeof(IComparable))
);
Assert.True(Expression.Lambda<Func<bool>>(exp).Compile(useInterpreter)());
}
[Theory]
[PerCompilationType(nameof(ComparableReferenceTypesData))]
public void FalseOnSameLeftViaInterface(object item, bool useInterpreter)
{
Expression exp = Expression.ReferenceNotEqual(
Expression.Constant(item, typeof(IComparable)),
Expression.Constant(item)
);
Assert.False(Expression.Lambda<Func<bool>>(exp).Compile(useInterpreter)());
}
[Theory]
[PerCompilationType(nameof(ComparableReferenceTypesData))]
public void FalseOnSameRightViaInterface(object item, bool useInterpreter)
{
Expression exp = Expression.ReferenceNotEqual(
Expression.Constant(item),
Expression.Constant(item, typeof(IComparable))
);
Assert.False(Expression.Lambda<Func<bool>>(exp).Compile(useInterpreter)());
}
[Fact]
public void CannotReduce()
{
Expression exp = Expression.ReferenceNotEqual(Expression.Constant(""), Expression.Constant(""));
Assert.False(exp.CanReduce);
Assert.Same(exp, exp.Reduce());
Assert.Throws<ArgumentException>(null, () => exp.ReduceAndCheck());
}
[Fact]
public void ThrowsOnLeftNull()
{
AssertExtensions.Throws<ArgumentNullException>("left", () => Expression.ReferenceNotEqual(null, Expression.Constant("")));
}
[Fact]
public void ThrowsOnRightNull()
{
AssertExtensions.Throws<ArgumentNullException>("right", () => Expression.ReferenceNotEqual(Expression.Constant(""), null));
}
[Fact]
public static void ThrowsOnLeftUnreadable()
{
Expression value = Expression.Property(null, typeof(Unreadable<string>), "WriteOnly");
AssertExtensions.Throws<ArgumentException>("left", () => Expression.ReferenceNotEqual(value, Expression.Constant("")));
}
[Fact]
public static void ThrowsOnRightUnreadable()
{
Expression value = Expression.Property(null, typeof(Unreadable<string>), "WriteOnly");
AssertExtensions.Throws<ArgumentException>("right", () => Expression.ReferenceNotEqual(Expression.Constant(""), value));
}
[Fact]
public void Update()
{
Expression e1 = Expression.Constant("bar");
Expression e2 = Expression.Constant("foo");
Expression e3 = Expression.Constant("qux");
BinaryExpression ne = Expression.ReferenceNotEqual(e1, e2);
Assert.Same(ne, ne.Update(e1, null, e2));
BinaryExpression ne1 = ne.Update(e1, null, e3);
Assert.Equal(ExpressionType.NotEqual, ne1.NodeType);
Assert.Same(e1, ne1.Left);
Assert.Same(e3, ne1.Right);
Assert.Null(ne1.Conversion);
Assert.Null(ne1.Method);
BinaryExpression ne2 = ne.Update(e3, null, e2);
Assert.Equal(ExpressionType.NotEqual, ne2.NodeType);
Assert.Same(e3, ne2.Left);
Assert.Same(e2, ne2.Right);
Assert.Null(ne2.Conversion);
Assert.Null(ne2.Method);
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gagvc = Google.Ads.GoogleAds.V8.Common;
using gagve = Google.Ads.GoogleAds.V8.Enums;
using gagvr = Google.Ads.GoogleAds.V8.Resources;
using gaxgrpc = Google.Api.Gax.Grpc;
using gr = Google.Rpc;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using NUnit.Framework;
using Google.Ads.GoogleAds.V8.Services;
namespace Google.Ads.GoogleAds.Tests.V8.Services
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedCampaignFeedServiceClientTest
{
[Category("Autogenerated")][Test]
public void GetCampaignFeedRequestObject()
{
moq::Mock<CampaignFeedService.CampaignFeedServiceClient> mockGrpcClient = new moq::Mock<CampaignFeedService.CampaignFeedServiceClient>(moq::MockBehavior.Strict);
GetCampaignFeedRequest request = new GetCampaignFeedRequest
{
ResourceNameAsCampaignFeedName = gagvr::CampaignFeedName.FromCustomerCampaignFeed("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[FEED_ID]"),
};
gagvr::CampaignFeed expectedResponse = new gagvr::CampaignFeed
{
ResourceNameAsCampaignFeedName = gagvr::CampaignFeedName.FromCustomerCampaignFeed("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[FEED_ID]"),
PlaceholderTypes =
{
gagve::PlaceholderTypeEnum.Types.PlaceholderType.AdCustomizer,
},
MatchingFunction = new gagvc::MatchingFunction(),
Status = gagve::FeedLinkStatusEnum.Types.FeedLinkStatus.Enabled,
FeedAsFeedName = gagvr::FeedName.FromCustomerFeed("[CUSTOMER_ID]", "[FEED_ID]"),
CampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"),
};
mockGrpcClient.Setup(x => x.GetCampaignFeed(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CampaignFeedServiceClient client = new CampaignFeedServiceClientImpl(mockGrpcClient.Object, null);
gagvr::CampaignFeed response = client.GetCampaignFeed(request);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GetCampaignFeedRequestObjectAsync()
{
moq::Mock<CampaignFeedService.CampaignFeedServiceClient> mockGrpcClient = new moq::Mock<CampaignFeedService.CampaignFeedServiceClient>(moq::MockBehavior.Strict);
GetCampaignFeedRequest request = new GetCampaignFeedRequest
{
ResourceNameAsCampaignFeedName = gagvr::CampaignFeedName.FromCustomerCampaignFeed("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[FEED_ID]"),
};
gagvr::CampaignFeed expectedResponse = new gagvr::CampaignFeed
{
ResourceNameAsCampaignFeedName = gagvr::CampaignFeedName.FromCustomerCampaignFeed("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[FEED_ID]"),
PlaceholderTypes =
{
gagve::PlaceholderTypeEnum.Types.PlaceholderType.AdCustomizer,
},
MatchingFunction = new gagvc::MatchingFunction(),
Status = gagve::FeedLinkStatusEnum.Types.FeedLinkStatus.Enabled,
FeedAsFeedName = gagvr::FeedName.FromCustomerFeed("[CUSTOMER_ID]", "[FEED_ID]"),
CampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"),
};
mockGrpcClient.Setup(x => x.GetCampaignFeedAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::CampaignFeed>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CampaignFeedServiceClient client = new CampaignFeedServiceClientImpl(mockGrpcClient.Object, null);
gagvr::CampaignFeed responseCallSettings = await client.GetCampaignFeedAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::CampaignFeed responseCancellationToken = await client.GetCampaignFeedAsync(request, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void GetCampaignFeed()
{
moq::Mock<CampaignFeedService.CampaignFeedServiceClient> mockGrpcClient = new moq::Mock<CampaignFeedService.CampaignFeedServiceClient>(moq::MockBehavior.Strict);
GetCampaignFeedRequest request = new GetCampaignFeedRequest
{
ResourceNameAsCampaignFeedName = gagvr::CampaignFeedName.FromCustomerCampaignFeed("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[FEED_ID]"),
};
gagvr::CampaignFeed expectedResponse = new gagvr::CampaignFeed
{
ResourceNameAsCampaignFeedName = gagvr::CampaignFeedName.FromCustomerCampaignFeed("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[FEED_ID]"),
PlaceholderTypes =
{
gagve::PlaceholderTypeEnum.Types.PlaceholderType.AdCustomizer,
},
MatchingFunction = new gagvc::MatchingFunction(),
Status = gagve::FeedLinkStatusEnum.Types.FeedLinkStatus.Enabled,
FeedAsFeedName = gagvr::FeedName.FromCustomerFeed("[CUSTOMER_ID]", "[FEED_ID]"),
CampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"),
};
mockGrpcClient.Setup(x => x.GetCampaignFeed(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CampaignFeedServiceClient client = new CampaignFeedServiceClientImpl(mockGrpcClient.Object, null);
gagvr::CampaignFeed response = client.GetCampaignFeed(request.ResourceName);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GetCampaignFeedAsync()
{
moq::Mock<CampaignFeedService.CampaignFeedServiceClient> mockGrpcClient = new moq::Mock<CampaignFeedService.CampaignFeedServiceClient>(moq::MockBehavior.Strict);
GetCampaignFeedRequest request = new GetCampaignFeedRequest
{
ResourceNameAsCampaignFeedName = gagvr::CampaignFeedName.FromCustomerCampaignFeed("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[FEED_ID]"),
};
gagvr::CampaignFeed expectedResponse = new gagvr::CampaignFeed
{
ResourceNameAsCampaignFeedName = gagvr::CampaignFeedName.FromCustomerCampaignFeed("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[FEED_ID]"),
PlaceholderTypes =
{
gagve::PlaceholderTypeEnum.Types.PlaceholderType.AdCustomizer,
},
MatchingFunction = new gagvc::MatchingFunction(),
Status = gagve::FeedLinkStatusEnum.Types.FeedLinkStatus.Enabled,
FeedAsFeedName = gagvr::FeedName.FromCustomerFeed("[CUSTOMER_ID]", "[FEED_ID]"),
CampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"),
};
mockGrpcClient.Setup(x => x.GetCampaignFeedAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::CampaignFeed>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CampaignFeedServiceClient client = new CampaignFeedServiceClientImpl(mockGrpcClient.Object, null);
gagvr::CampaignFeed responseCallSettings = await client.GetCampaignFeedAsync(request.ResourceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::CampaignFeed responseCancellationToken = await client.GetCampaignFeedAsync(request.ResourceName, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void GetCampaignFeedResourceNames()
{
moq::Mock<CampaignFeedService.CampaignFeedServiceClient> mockGrpcClient = new moq::Mock<CampaignFeedService.CampaignFeedServiceClient>(moq::MockBehavior.Strict);
GetCampaignFeedRequest request = new GetCampaignFeedRequest
{
ResourceNameAsCampaignFeedName = gagvr::CampaignFeedName.FromCustomerCampaignFeed("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[FEED_ID]"),
};
gagvr::CampaignFeed expectedResponse = new gagvr::CampaignFeed
{
ResourceNameAsCampaignFeedName = gagvr::CampaignFeedName.FromCustomerCampaignFeed("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[FEED_ID]"),
PlaceholderTypes =
{
gagve::PlaceholderTypeEnum.Types.PlaceholderType.AdCustomizer,
},
MatchingFunction = new gagvc::MatchingFunction(),
Status = gagve::FeedLinkStatusEnum.Types.FeedLinkStatus.Enabled,
FeedAsFeedName = gagvr::FeedName.FromCustomerFeed("[CUSTOMER_ID]", "[FEED_ID]"),
CampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"),
};
mockGrpcClient.Setup(x => x.GetCampaignFeed(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CampaignFeedServiceClient client = new CampaignFeedServiceClientImpl(mockGrpcClient.Object, null);
gagvr::CampaignFeed response = client.GetCampaignFeed(request.ResourceNameAsCampaignFeedName);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GetCampaignFeedResourceNamesAsync()
{
moq::Mock<CampaignFeedService.CampaignFeedServiceClient> mockGrpcClient = new moq::Mock<CampaignFeedService.CampaignFeedServiceClient>(moq::MockBehavior.Strict);
GetCampaignFeedRequest request = new GetCampaignFeedRequest
{
ResourceNameAsCampaignFeedName = gagvr::CampaignFeedName.FromCustomerCampaignFeed("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[FEED_ID]"),
};
gagvr::CampaignFeed expectedResponse = new gagvr::CampaignFeed
{
ResourceNameAsCampaignFeedName = gagvr::CampaignFeedName.FromCustomerCampaignFeed("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[FEED_ID]"),
PlaceholderTypes =
{
gagve::PlaceholderTypeEnum.Types.PlaceholderType.AdCustomizer,
},
MatchingFunction = new gagvc::MatchingFunction(),
Status = gagve::FeedLinkStatusEnum.Types.FeedLinkStatus.Enabled,
FeedAsFeedName = gagvr::FeedName.FromCustomerFeed("[CUSTOMER_ID]", "[FEED_ID]"),
CampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"),
};
mockGrpcClient.Setup(x => x.GetCampaignFeedAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::CampaignFeed>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CampaignFeedServiceClient client = new CampaignFeedServiceClientImpl(mockGrpcClient.Object, null);
gagvr::CampaignFeed responseCallSettings = await client.GetCampaignFeedAsync(request.ResourceNameAsCampaignFeedName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::CampaignFeed responseCancellationToken = await client.GetCampaignFeedAsync(request.ResourceNameAsCampaignFeedName, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void MutateCampaignFeedsRequestObject()
{
moq::Mock<CampaignFeedService.CampaignFeedServiceClient> mockGrpcClient = new moq::Mock<CampaignFeedService.CampaignFeedServiceClient>(moq::MockBehavior.Strict);
MutateCampaignFeedsRequest request = new MutateCampaignFeedsRequest
{
CustomerId = "customer_id3b3724cb",
Operations =
{
new CampaignFeedOperation(),
},
PartialFailure = false,
ValidateOnly = true,
ResponseContentType = gagve::ResponseContentTypeEnum.Types.ResponseContentType.ResourceNameOnly,
};
MutateCampaignFeedsResponse expectedResponse = new MutateCampaignFeedsResponse
{
Results =
{
new MutateCampaignFeedResult(),
},
PartialFailureError = new gr::Status(),
};
mockGrpcClient.Setup(x => x.MutateCampaignFeeds(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CampaignFeedServiceClient client = new CampaignFeedServiceClientImpl(mockGrpcClient.Object, null);
MutateCampaignFeedsResponse response = client.MutateCampaignFeeds(request);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task MutateCampaignFeedsRequestObjectAsync()
{
moq::Mock<CampaignFeedService.CampaignFeedServiceClient> mockGrpcClient = new moq::Mock<CampaignFeedService.CampaignFeedServiceClient>(moq::MockBehavior.Strict);
MutateCampaignFeedsRequest request = new MutateCampaignFeedsRequest
{
CustomerId = "customer_id3b3724cb",
Operations =
{
new CampaignFeedOperation(),
},
PartialFailure = false,
ValidateOnly = true,
ResponseContentType = gagve::ResponseContentTypeEnum.Types.ResponseContentType.ResourceNameOnly,
};
MutateCampaignFeedsResponse expectedResponse = new MutateCampaignFeedsResponse
{
Results =
{
new MutateCampaignFeedResult(),
},
PartialFailureError = new gr::Status(),
};
mockGrpcClient.Setup(x => x.MutateCampaignFeedsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateCampaignFeedsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CampaignFeedServiceClient client = new CampaignFeedServiceClientImpl(mockGrpcClient.Object, null);
MutateCampaignFeedsResponse responseCallSettings = await client.MutateCampaignFeedsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
MutateCampaignFeedsResponse responseCancellationToken = await client.MutateCampaignFeedsAsync(request, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void MutateCampaignFeeds()
{
moq::Mock<CampaignFeedService.CampaignFeedServiceClient> mockGrpcClient = new moq::Mock<CampaignFeedService.CampaignFeedServiceClient>(moq::MockBehavior.Strict);
MutateCampaignFeedsRequest request = new MutateCampaignFeedsRequest
{
CustomerId = "customer_id3b3724cb",
Operations =
{
new CampaignFeedOperation(),
},
};
MutateCampaignFeedsResponse expectedResponse = new MutateCampaignFeedsResponse
{
Results =
{
new MutateCampaignFeedResult(),
},
PartialFailureError = new gr::Status(),
};
mockGrpcClient.Setup(x => x.MutateCampaignFeeds(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CampaignFeedServiceClient client = new CampaignFeedServiceClientImpl(mockGrpcClient.Object, null);
MutateCampaignFeedsResponse response = client.MutateCampaignFeeds(request.CustomerId, request.Operations);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task MutateCampaignFeedsAsync()
{
moq::Mock<CampaignFeedService.CampaignFeedServiceClient> mockGrpcClient = new moq::Mock<CampaignFeedService.CampaignFeedServiceClient>(moq::MockBehavior.Strict);
MutateCampaignFeedsRequest request = new MutateCampaignFeedsRequest
{
CustomerId = "customer_id3b3724cb",
Operations =
{
new CampaignFeedOperation(),
},
};
MutateCampaignFeedsResponse expectedResponse = new MutateCampaignFeedsResponse
{
Results =
{
new MutateCampaignFeedResult(),
},
PartialFailureError = new gr::Status(),
};
mockGrpcClient.Setup(x => x.MutateCampaignFeedsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateCampaignFeedsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CampaignFeedServiceClient client = new CampaignFeedServiceClientImpl(mockGrpcClient.Object, null);
MutateCampaignFeedsResponse responseCallSettings = await client.MutateCampaignFeedsAsync(request.CustomerId, request.Operations, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
MutateCampaignFeedsResponse responseCancellationToken = await client.MutateCampaignFeedsAsync(request.CustomerId, request.Operations, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
using System;
using System.Linq;
using Google.ProtocolBuffers;
using Rhino.DistributedHashTable.Internal;
using Rhino.DistributedHashTable.Parameters;
using Rhino.DistributedHashTable.Protocol;
using Rhino.PersistentHashTable;
using NodeEndpoint = Rhino.DistributedHashTable.Protocol.NodeEndpoint;
using Segment = Rhino.DistributedHashTable.Internal.Segment;
using Value = Rhino.PersistentHashTable.Value;
using ValueVersion = Rhino.PersistentHashTable.ValueVersion;
namespace Rhino.DistributedHashTable.Util
{
public static class PrtoBufConverter
{
public static Topology GetTopology(this TopologyResultMessage topology)
{
var segments = topology.SegmentsList.Select(x => GetSegment(x));
return new Topology(segments.ToArray(), topology.Version)
{
Timestamp = DateTime.FromOADate(topology.TimestampAsDouble)
};
}
public static Segment GetSegment(this Protocol.Segment x)
{
return new Segment
{
AssignedEndpoint = x.AssignedEndpoint.GetNodeEndpoint(),
InProcessOfMovingToEndpoint = x.InProcessOfMovingToEndpoint.GetNodeEndpoint(),
Index = x.Index,
PendingBackups = x.PendingBackupsList.Select(b => b.GetNodeEndpoint()).ToSet(),
Backups = x.BackupsList.Select(b => b.GetNodeEndpoint()).ToSet()
};
}
public static ExtendedGetRequest GetGetRequest(this GetRequestMessage x)
{
return new ExtendedGetRequest
{
Segment = x.Segment,
Key = x.Key,
SpecifiedVersion = GetVersion(x.SpecificVersion),
};
}
public static GetResponseMessage GetGetResponse(this Value[] x)
{
return new GetResponseMessage.Builder
{
ValuesList =
{
x.Select(v => new Protocol.Value.Builder
{
Data = ByteString.CopyFrom(v.Data),
ExpiresAtAsDouble = v.ExpiresAt != null ? v.ExpiresAt.Value.ToOADate() : (double?) null,
Key = v.Key,
ReadOnly = v.ReadOnly,
Sha256Hash = ByteString.CopyFrom(v.Sha256Hash),
Version = GetVersion(v.Version),
Tag = v.Tag,
TimeStampAsDouble = v.Timestamp.ToOADate(),
}.Build())
}
}.Build();
}
public static PutResponseMessage GetPutResponse(this PutResult x)
{
return new PutResponseMessage.Builder
{
Version = GetVersion(x.Version),
ConflictExists = x.ConflictExists
}.Build();
}
public static ExtendedPutRequest GetPutRequest(this PutRequestMessage x)
{
return new ExtendedPutRequest
{
Bytes = x.Bytes.ToByteArray(),
ExpiresAt = x.HasExpiresAtAsDouble
?
DateTime.FromOADate(x.ExpiresAtAsDouble.Value)
:
(DateTime?)null,
IsReadOnly = x.IsReadOnly,
IsReplicationRequest = x.IsReplicationRequest,
Key = x.Key,
OptimisticConcurrency = x.OptimisticConcurrency,
ParentVersions = x.ParentVersionsList.Select(y => GetVersion(y)).ToArray(),
ReplicationTimeStamp = x.HasReplicationTimeStampAsDouble
?
DateTime.FromOADate(x.ReplicationTimeStampAsDouble.Value)
:
(DateTime?)null,
ReplicationVersion = GetVersion(x.ReplicationVersion),
Segment = x.Segment,
Tag = x.Tag
};
}
public static ExtendedRemoveRequest GetRemoveRequest(this RemoveRequestMessage x)
{
return
new ExtendedRemoveRequest
{
Segment = x.Segment,
Key = x.Key,
SpecificVersion = GetVersion(x.SpecificVersion),
IsReplicationRequest = x.IsReplicationRequest
};
}
public static RemoveRequestMessage GetRemoveRequest(this ExtendedRemoveRequest x)
{
return new RemoveRequestMessage.Builder
{
IsReplicationRequest = x.IsReplicationRequest,
Key = x.Key,
Segment = x.Segment,
SpecificVersion = GetVersion(x.SpecificVersion)
}.Build();
}
public static PutRequestMessage GetPutRequest(this ExtendedPutRequest x)
{
var builder = new PutRequestMessage.Builder
{
Bytes = ByteString.CopyFrom(x.Bytes),
IsReadOnly = x.IsReadOnly,
IsReplicationRequest = x.IsReplicationRequest,
Key = x.Key,
OptimisticConcurrency = x.OptimisticConcurrency,
Segment = x.Segment,
Tag = x.Tag,
};
if (x.ExpiresAt != null)
builder.ExpiresAtAsDouble = x.ExpiresAt.Value.ToOADate();
if (x.ReplicationTimeStamp != null)
builder.ReplicationTimeStampAsDouble = x.ReplicationTimeStamp.Value.ToOADate();
if (x.ReplicationVersion != null)
{
builder.ReplicationVersion = GetVersion(x.ReplicationVersion);
}
return builder.Build();
}
public static Internal.NodeEndpoint GetNodeEndpoint(this NodeEndpoint endpoint)
{
if (endpoint == null || endpoint == NodeEndpoint.DefaultInstance)
return null;
return new Internal.NodeEndpoint()
{
Async = new Uri(endpoint.Async),
Sync = new Uri(endpoint.Sync)
};
}
public static NodeEndpoint GetNodeEndpoint(this Internal.NodeEndpoint endpoint)
{
return new NodeEndpoint.Builder
{
Async = endpoint.Async.ToString(),
Sync = endpoint.Sync.ToString()
}.Build();
}
public static ValueVersion GetVersion(Protocol.ValueVersion version)
{
if (version == Protocol.ValueVersion.DefaultInstance)
return null;
return new ValueVersion
{
InstanceId = new Guid(version.InstanceId.ToByteArray()),
Number = version.Number
};
}
public static Protocol.ValueVersion GetVersion(ValueVersion version)
{
if (version == null)
return Protocol.ValueVersion.DefaultInstance;
return new Protocol.ValueVersion.Builder
{
InstanceId = ByteString.CopyFrom(version.InstanceId.ToByteArray()),
Number = version.Number
}.Build();
}
public static TopologyResultMessage GetTopology(this Topology topology)
{
return new TopologyResultMessage.Builder
{
Version = topology.Version,
TimestampAsDouble = topology.Timestamp.ToOADate(),
SegmentsList = { topology.Segments.Select(x => x.GetSegment()) }
}.Build();
}
public static Protocol.Segment GetSegment(this Internal.Segment segment)
{
var builder = new Protocol.Segment.Builder
{
Index = segment.Index,
BackupsList = { segment.Backups.Select(x => x.GetNodeEndpoint()) },
PendingBackupsList = { segment.PendingBackups.Select(x => x.GetNodeEndpoint()) }
};
if (segment.AssignedEndpoint != null)
{
builder.AssignedEndpoint = new Protocol.NodeEndpoint.Builder
{
Async = segment.AssignedEndpoint.Async.ToString(),
Sync = segment.AssignedEndpoint.Sync.ToString()
}.Build();
}
if (segment.InProcessOfMovingToEndpoint != null)
{
builder.InProcessOfMovingToEndpoint = new Protocol.NodeEndpoint.Builder
{
Async = segment.InProcessOfMovingToEndpoint.Async.ToString(),
Sync = segment.InProcessOfMovingToEndpoint.Sync.ToString(),
}.Build();
}
return builder.Build();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.EventHubs;
using Microsoft.Extensions.Logging;
using Orleans.Configuration;
using Orleans.Providers.Streams.Common;
using Orleans.Runtime;
using Orleans.Streams;
using Orleans.ServiceBus.Providers.Testing;
using Orleans.Hosting;
namespace Orleans.ServiceBus.Providers
{
/// <summary>
/// Event Hub Partition settings
/// </summary>
public class EventHubPartitionSettings
{
/// <summary>
/// Eventhub settings
/// </summary>
public EventHubOptions Hub { get; set; }
public EventHubReceiverOptions ReceiverOptions { get; set; }
/// <summary>
/// Partition name
/// </summary>
public string Partition { get; set; }
}
internal class EventHubAdapterReceiver : IQueueAdapterReceiver, IQueueCache
{
public const int MaxMessagesPerRead = 1000;
private static readonly TimeSpan ReceiveTimeout = TimeSpan.FromSeconds(5);
private readonly EventHubPartitionSettings settings;
private readonly Func<string, IStreamQueueCheckpointer<string>, ILoggerFactory, ITelemetryProducer, IEventHubQueueCache> cacheFactory;
private readonly Func<string, Task<IStreamQueueCheckpointer<string>>> checkpointerFactory;
private readonly ILoggerFactory loggerFactory;
private readonly ILogger logger;
private readonly IQueueAdapterReceiverMonitor monitor;
private readonly ITelemetryProducer telemetryProducer;
private readonly LoadSheddingOptions loadSheddingOptions;
private IEventHubQueueCache cache;
private IEventHubReceiver receiver;
private Func<EventHubPartitionSettings, string, ILogger, ITelemetryProducer, IEventHubReceiver> eventHubReceiverFactory;
private IStreamQueueCheckpointer<string> checkpointer;
private AggregatedQueueFlowController flowController;
// Receiver life cycle
private int recieverState = ReceiverShutdown;
private const int ReceiverShutdown = 0;
private const int ReceiverRunning = 1;
public int GetMaxAddCount()
{
return this.flowController.GetMaxAddCount();
}
public EventHubAdapterReceiver(EventHubPartitionSettings settings,
Func<string, IStreamQueueCheckpointer<string>, ILoggerFactory, ITelemetryProducer, IEventHubQueueCache> cacheFactory,
Func<string, Task<IStreamQueueCheckpointer<string>>> checkpointerFactory,
ILoggerFactory loggerFactory,
IQueueAdapterReceiverMonitor monitor,
LoadSheddingOptions loadSheddingOptions,
ITelemetryProducer telemetryProducer,
Func<EventHubPartitionSettings, string, ILogger, ITelemetryProducer, IEventHubReceiver> eventHubReceiverFactory = null)
{
this.settings = settings ?? throw new ArgumentNullException(nameof(settings));
this.cacheFactory = cacheFactory ?? throw new ArgumentNullException(nameof(cacheFactory));
this.checkpointerFactory = checkpointerFactory ?? throw new ArgumentNullException(nameof(checkpointerFactory));
this.loggerFactory = loggerFactory ?? throw new ArgumentNullException(nameof(loggerFactory));
this.logger = this.loggerFactory.CreateLogger($"{this.GetType().FullName}.{settings.Hub.Path}.{settings.Partition}");
this.monitor = monitor ?? throw new ArgumentNullException(nameof(monitor));
this.telemetryProducer = telemetryProducer ?? throw new ArgumentNullException(nameof(telemetryProducer));
this.loadSheddingOptions = loadSheddingOptions ?? throw new ArgumentNullException(nameof(loadSheddingOptions));
this.eventHubReceiverFactory = eventHubReceiverFactory == null ? EventHubAdapterReceiver.CreateReceiver : eventHubReceiverFactory;
}
public Task Initialize(TimeSpan timeout)
{
this.logger.Info("Initializing EventHub partition {0}-{1}.", this.settings.Hub.Path, this.settings.Partition);
// if receiver was already running, do nothing
return ReceiverRunning == Interlocked.Exchange(ref this.recieverState, ReceiverRunning)
? Task.CompletedTask
: Initialize();
}
/// <summary>
/// Initialization of EventHub receiver is performed at adapter receiver initialization, but if it fails,
/// it will be retried when messages are requested
/// </summary>
/// <returns></returns>
private async Task Initialize()
{
var watch = Stopwatch.StartNew();
try
{
this.checkpointer = await this.checkpointerFactory(this.settings.Partition);
if(this.cache != null)
{
this.cache.Dispose();
this.cache = null;
}
this.cache = this.cacheFactory(this.settings.Partition, this.checkpointer, this.loggerFactory, this.telemetryProducer);
this.flowController = new AggregatedQueueFlowController(MaxMessagesPerRead) { this.cache, LoadShedQueueFlowController.CreateAsPercentOfLoadSheddingLimit(this.loadSheddingOptions) };
string offset = await this.checkpointer.Load();
this.receiver = this.eventHubReceiverFactory(this.settings, offset, this.logger, this.telemetryProducer);
watch.Stop();
this.monitor?.TrackInitialization(true, watch.Elapsed, null);
}
catch (Exception ex)
{
watch.Stop();
this.monitor?.TrackInitialization(false, watch.Elapsed, ex);
throw;
}
}
public async Task<IList<IBatchContainer>> GetQueueMessagesAsync(int maxCount)
{
if (this.recieverState == ReceiverShutdown || maxCount <= 0)
{
return new List<IBatchContainer>();
}
// if receiver initialization failed, retry
if (this.receiver == null)
{
this.logger.Warn(OrleansServiceBusErrorCode.FailedPartitionRead,
"Retrying initialization of EventHub partition {0}-{1}.", this.settings.Hub.Path, this.settings.Partition);
await Initialize();
if (this.receiver == null)
{
// should not get here, should throw instead, but just incase.
return new List<IBatchContainer>();
}
}
var watch = Stopwatch.StartNew();
List<EventData> messages;
try
{
messages = (await this.receiver.ReceiveAsync(maxCount, ReceiveTimeout))?.ToList();
watch.Stop();
this.monitor?.TrackRead(true, watch.Elapsed, null);
}
catch (Exception ex)
{
watch.Stop();
this.monitor?.TrackRead(false, watch.Elapsed, ex);
this.logger.Warn(OrleansServiceBusErrorCode.FailedPartitionRead,
"Failed to read from EventHub partition {0}-{1}. : Exception: {2}.", this.settings.Hub.Path,
this.settings.Partition, ex);
throw;
}
var batches = new List<IBatchContainer>();
if (messages == null || messages.Count == 0)
{
this.monitor?.TrackMessagesReceived(0, null, null);
return batches;
}
// monitor message age
var dequeueTimeUtc = DateTime.UtcNow;
DateTime oldestMessageEnqueueTime = messages[0].SystemProperties.EnqueuedTimeUtc;
DateTime newestMessageEnqueueTime = messages[messages.Count - 1].SystemProperties.EnqueuedTimeUtc;
this.monitor?.TrackMessagesReceived(messages.Count, oldestMessageEnqueueTime, newestMessageEnqueueTime);
List<StreamPosition> messageStreamPositions = this.cache.Add(messages, dequeueTimeUtc);
foreach (var streamPosition in messageStreamPositions)
{
batches.Add(new StreamActivityNotificationBatch(streamPosition));
}
if (!this.checkpointer.CheckpointExists)
{
this.checkpointer.Update(
messages[0].SystemProperties.Offset,
DateTime.UtcNow);
}
return batches;
}
public void AddToCache(IList<IBatchContainer> messages)
{
// do nothing, we add data directly into cache. No need for agent involvement
}
public bool TryPurgeFromCache(out IList<IBatchContainer> purgedItems)
{
purgedItems = null;
//if not under pressure, signal the cache to do a time based purge
//if under pressure, which means consuming speed is less than producing speed, then shouldn't purge, and don't read more message into the cache
if (!this.IsUnderPressure())
this.cache.SignalPurge();
return false;
}
public IQueueCacheCursor GetCacheCursor(IStreamIdentity streamIdentity, StreamSequenceToken token)
{
return new Cursor(this.cache, streamIdentity, token);
}
public bool IsUnderPressure()
{
return this.GetMaxAddCount() <= 0;
}
public Task MessagesDeliveredAsync(IList<IBatchContainer> messages)
{
return Task.CompletedTask;
}
public async Task Shutdown(TimeSpan timeout)
{
var watch = Stopwatch.StartNew();
try
{
// if receiver was already shutdown, do nothing
if (ReceiverShutdown == Interlocked.Exchange(ref this.recieverState, ReceiverShutdown))
{
return;
}
this.logger.Info("Stopping reading from EventHub partition {0}-{1}", this.settings.Hub.Path, this.settings.Partition);
// clear cache and receiver
IEventHubQueueCache localCache = Interlocked.Exchange(ref this.cache, null);
var localReceiver = Interlocked.Exchange(ref this.receiver, null);
// start closing receiver
Task closeTask = Task.CompletedTask;
if (localReceiver != null)
{
closeTask = localReceiver.CloseAsync();
}
// dispose of cache
localCache?.Dispose();
// finish return receiver closing task
await closeTask;
watch.Stop();
this.monitor?.TrackShutdown(true, watch.Elapsed, null);
}
catch (Exception ex)
{
watch.Stop();
this.monitor?.TrackShutdown(false, watch.Elapsed, ex);
throw;
}
}
private static IEventHubReceiver CreateReceiver(EventHubPartitionSettings partitionSettings, string offset, ILogger logger, ITelemetryProducer telemetryProducer)
{
var connectionStringBuilder = new EventHubsConnectionStringBuilder(partitionSettings.Hub.ConnectionString)
{
EntityPath = partitionSettings.Hub.Path
};
EventHubClient client = EventHubClient.CreateFromConnectionString(connectionStringBuilder.ToString());
EventPosition eventPosition;
// If we have a starting offset, read from offset
if (offset != EventHubConstants.StartOfStream)
{
logger.Info("Starting to read from EventHub partition {0}-{1} at offset {2}", partitionSettings.Hub.Path, partitionSettings.Partition, offset);
eventPosition = EventPosition.FromOffset(offset, true);
}
// else, if configured to start from now, start reading from most recent data
else if (partitionSettings.ReceiverOptions.StartFromNow)
{
eventPosition = EventPosition.FromEnd();
logger.Info("Starting to read latest messages from EventHub partition {0}-{1}.", partitionSettings.Hub.Path, partitionSettings.Partition);
} else
// else, start reading from begining of the partition
{
eventPosition = EventPosition.FromStart();
logger.Info("Starting to read messages from begining of EventHub partition {0}-{1}.", partitionSettings.Hub.Path, partitionSettings.Partition);
}
PartitionReceiver receiver = client.CreateReceiver(partitionSettings.Hub.ConsumerGroup, partitionSettings.Partition, eventPosition);
if (partitionSettings.ReceiverOptions.PrefetchCount.HasValue)
receiver.PrefetchCount = partitionSettings.ReceiverOptions.PrefetchCount.Value;
return new EventHubReceiverProxy(receiver);
}
/// <summary>
/// For test purpose. ConfigureDataGeneratorForStream will configure a data generator for the stream
/// </summary>
/// <param name="streamId"></param>
internal void ConfigureDataGeneratorForStream(IStreamIdentity streamId)
{
(this.receiver as EventHubPartitionGeneratorReceiver)?.ConfigureDataGeneratorForStream(streamId);
}
internal void StopProducingOnStream(IStreamIdentity streamId)
{
(this.receiver as EventHubPartitionGeneratorReceiver)?.StopProducingOnStream(streamId);
}
private class StreamActivityNotificationBatch : IBatchContainer
{
public StreamPosition Position { get; }
public Guid StreamGuid => this.Position.StreamIdentity.Guid;
public string StreamNamespace => this.Position.StreamIdentity.Namespace;
public StreamSequenceToken SequenceToken => this.Position.SequenceToken;
public StreamActivityNotificationBatch(StreamPosition position)
{
this.Position = position;
}
public IEnumerable<Tuple<T, StreamSequenceToken>> GetEvents<T>() { throw new NotSupportedException(); }
public bool ImportRequestContext() { throw new NotSupportedException(); }
public bool ShouldDeliver(IStreamIdentity stream, object filterData, StreamFilterPredicate shouldReceiveFunc) { throw new NotSupportedException(); }
}
private class Cursor : IQueueCacheCursor
{
private readonly IEventHubQueueCache cache;
private readonly object cursor;
private IBatchContainer current;
public Cursor(IEventHubQueueCache cache, IStreamIdentity streamIdentity, StreamSequenceToken token)
{
this.cache = cache;
this.cursor = cache.GetCursor(streamIdentity, token);
}
public void Dispose()
{
}
public IBatchContainer GetCurrent(out Exception exception)
{
exception = null;
return this.current;
}
public bool MoveNext()
{
IBatchContainer next;
if (!this.cache.TryGetNextMessage(this.cursor, out next))
{
return false;
}
this.current = next;
return true;
}
public void Refresh(StreamSequenceToken token)
{
}
public void RecordDeliveryFailure()
{
}
}
}
}
| |
// 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.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Analyzer.Utilities;
using Analyzer.Utilities.Extensions;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Operations;
namespace Microsoft.CodeQuality.Analyzers.QualityGuidelines
{
/// <summary>
/// CA1822: Mark members as static
/// </summary>
public abstract class MarkMembersAsStaticFixer : CodeFixProvider
{
private static readonly SyntaxAnnotation s_annotationForFixedDeclaration = new();
protected abstract IEnumerable<SyntaxNode>? GetTypeArguments(SyntaxNode node);
protected abstract SyntaxNode? GetExpressionOfInvocation(SyntaxNode invocation);
protected virtual SyntaxNode GetSyntaxNodeToReplace(IMemberReferenceOperation memberReference)
=> memberReference.Syntax;
public sealed override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(MarkMembersAsStaticAnalyzer.RuleId);
public sealed override FixAllProvider GetFixAllProvider()
{
return WellKnownFixAllProviders.BatchFixer;
}
public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
{
var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
var node = root.FindNode(context.Span);
if (node == null)
{
return;
}
context.RegisterCodeFix(
new MarkMembersAsStaticAction(
MicrosoftCodeQualityAnalyzersResources.MarkMembersAsStaticCodeFix,
ct => MakeStaticAsync(context.Document, root, node, ct)),
context.Diagnostics);
}
private async Task<Solution> MakeStaticAsync(Document document, SyntaxNode root, SyntaxNode node, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
// Add syntax annotation to definition to be made static so we can update it after fixing references.
document = document.WithSyntaxRoot(root.ReplaceNode(node, node.WithAdditionalAnnotations(s_annotationForFixedDeclaration)));
var solution = document.Project.Solution;
// Update references, if any.
root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
node = root.GetAnnotatedNodes(s_annotationForFixedDeclaration).Single();
var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var symbol = semanticModel.GetDeclaredSymbol(node, cancellationToken);
if (symbol != null)
{
var (newSolution, allReferencesFixed) = await UpdateReferencesAsync(symbol, solution, cancellationToken).ConfigureAwait(false);
solution = newSolution;
if (!allReferencesFixed)
{
// We could not fix all references, so add a warning annotation that users need to manually fix these.
document = await AddWarningAnnotation(solution.GetDocument(document.Id)!, symbol, cancellationToken).ConfigureAwait(false);
solution = document.Project.Solution;
}
}
// Update definition to add static modifier.
document = solution.GetDocument(document.Id)!;
root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
node = root.GetAnnotatedNodes(s_annotationForFixedDeclaration).Single();
var syntaxGenerator = SyntaxGenerator.GetGenerator(document);
var oldModifiersAndStatic = syntaxGenerator.GetModifiers(node).WithIsStatic(true);
var newNode = syntaxGenerator.WithModifiers(node, oldModifiersAndStatic);
return document.WithSyntaxRoot(root.ReplaceNode(node, newNode)).Project.Solution;
}
/// <summary>
/// Returns the updated solution and a flag indicating if all references were fixed or not.
/// </summary>
private async Task<(Solution newSolution, bool allReferencesFixed)> UpdateReferencesAsync(ISymbol symbol, Solution solution, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
var references = await SymbolFinder.FindReferencesAsync(symbol, solution, cancellationToken).ConfigureAwait(false);
// Filter out cascaded symbol references. For example, accessor references for property symbol.
references = references.Where(r => symbol.Equals(r.Definition));
if (!references.HasExactly(1))
{
return (newSolution: solution, allReferencesFixed: !references.Any());
}
var allReferencesFixed = true;
// Group references by document and fix references in each document.
foreach (var referenceLocationGroup in references.Single().Locations.GroupBy(r => r.Document))
{
// Get document in current solution
var document = solution.GetDocument(referenceLocationGroup.Key.Id);
// Skip references in projects with different language.
// https://github.com/dotnet/roslyn-analyzers/issues/1986 tracks handling them.
if (document == null ||
!document.Project.Language.Equals(symbol.Language, StringComparison.Ordinal))
{
allReferencesFixed = false;
continue;
}
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
// Compute replacements
var editor = new SyntaxEditor(root, solution.Workspace);
foreach (var referenceLocation in referenceLocationGroup)
{
cancellationToken.ThrowIfCancellationRequested();
var referenceNode = root.FindNode(referenceLocation.Location.SourceSpan, getInnermostNodeForTie: true);
if (referenceNode == null)
{
allReferencesFixed = false;
continue;
}
var operation = semanticModel.GetOperationWalkingUpParentChain(referenceNode, cancellationToken);
SyntaxNode? nodeToReplace = null;
switch (operation)
{
case IMemberReferenceOperation memberReference:
if (IsReplacableOperation(memberReference.Instance))
{
nodeToReplace = GetSyntaxNodeToReplace(memberReference);
}
break;
case IInvocationOperation invocation:
if (IsReplacableOperation(invocation.Instance))
{
nodeToReplace = GetExpressionOfInvocation(invocation.Syntax);
}
break;
}
if (nodeToReplace == null)
{
allReferencesFixed = false;
continue;
}
// Fetch the symbol for the node to replace - note that this might be
// different from the original symbol due to generic type arguments.
var symbolForNodeToReplace = GetSymbolForNodeToReplace(nodeToReplace, semanticModel);
if (symbolForNodeToReplace == null)
{
allReferencesFixed = false;
continue;
}
SyntaxNode memberName;
var typeArguments = GetTypeArguments(referenceNode);
memberName = typeArguments != null ?
editor.Generator.GenericName(symbolForNodeToReplace.Name, typeArguments) :
editor.Generator.IdentifierName(symbolForNodeToReplace.Name);
var newNode = editor.Generator.MemberAccessExpression(
expression: editor.Generator.TypeExpression(symbolForNodeToReplace.ContainingType),
memberName: memberName)
.WithLeadingTrivia(nodeToReplace.GetLeadingTrivia())
.WithTrailingTrivia(nodeToReplace.GetTrailingTrivia())
.WithAdditionalAnnotations(Formatter.Annotation);
editor.ReplaceNode(nodeToReplace, newNode);
}
document = document.WithSyntaxRoot(editor.GetChangedRoot());
solution = document.Project.Solution;
}
return (solution, allReferencesFixed);
// Local functions.
static bool IsReplacableOperation(IOperation operation)
{
if (operation == null)
{
// Null instance is replaceable. For example, null instance for a static field/property reference which is used to invoke an instance member, say "SomeType.StaticField.InstanceMethod();"
return true;
}
// We only replace reference operations whose removal cannot change semantics.
switch (operation.Kind)
{
case OperationKind.InstanceReference:
case OperationKind.ParameterReference:
case OperationKind.LocalReference:
return true;
case OperationKind.FieldReference:
case OperationKind.PropertyReference:
return IsReplacableOperation(((IMemberReferenceOperation)operation).Instance);
default:
return false;
}
}
ISymbol? GetSymbolForNodeToReplace(SyntaxNode nodeToReplace, SemanticModel semanticModel)
{
var symbolInfo = semanticModel.GetSymbolInfo(nodeToReplace, cancellationToken);
var symbolForNodeToReplace = symbolInfo.Symbol;
if (symbolForNodeToReplace == null &&
symbolInfo.CandidateReason == CandidateReason.StaticInstanceMismatch &&
symbolInfo.CandidateSymbols.Length == 1)
{
return symbolInfo.CandidateSymbols[0];
}
return symbolForNodeToReplace;
}
}
private static async Task<Document> AddWarningAnnotation(Document document, ISymbol symbolFromEarlierSnapshot, CancellationToken cancellationToken)
{
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var fixedDeclaration = root.GetAnnotatedNodes(s_annotationForFixedDeclaration).Single();
var annotation = WarningAnnotation.Create(string.Format(CultureInfo.CurrentCulture, MicrosoftCodeQualityAnalyzersResources.MarkMembersAsStaticCodeFix_WarningAnnotation, symbolFromEarlierSnapshot.Name));
return document.WithSyntaxRoot(root.ReplaceNode(fixedDeclaration, fixedDeclaration.WithAdditionalAnnotations(annotation)));
}
private class MarkMembersAsStaticAction : SolutionChangeAction
{
public MarkMembersAsStaticAction(string title, Func<CancellationToken, Task<Solution>> createChangedSolution)
: base(title, createChangedSolution, equivalenceKey: title)
{
}
}
}
}
| |
using System;
using System.Collections;
using System.Linq;
using UnityEngine;
using UnityWeld.Binding.Exceptions;
using UnityWeld.Binding.Internal;
namespace UnityWeld.Binding
{
/// <summary>
/// Binds a property in the view-model that is a collection and instantiates copies
/// of template objects to bind to the items of the collection.
///
/// Creates and destroys child objects when items are added and removed from a
/// collection that implements INotifyCollectionChanged, like ObservableList.
/// </summary>
[AddComponentMenu("Unity Weld/Collection Binding")]
[HelpURL("https://github.com/Real-Serious-Games/Unity-Weld")]
public class CollectionBinding : AbstractTemplateSelector
{
/// <summary>
/// Collection that we have bound to.
/// </summary>
private IEnumerable viewModelCollectionValue;
public override void Connect()
{
Disconnect();
string propertyName;
object newViewModel;
ParseViewModelEndPointReference(
ViewModelPropertyName,
out propertyName,
out newViewModel
);
viewModel = newViewModel;
viewModelPropertyWatcher = new PropertyWatcher(
newViewModel,
propertyName,
NotifyPropertyChanged_PropertyChanged
);
BindCollection();
}
public override void Disconnect()
{
UnbindCollection();
if (viewModelPropertyWatcher != null)
{
viewModelPropertyWatcher.Dispose();
viewModelPropertyWatcher = null;
}
viewModel = null;
}
private void NotifyPropertyChanged_PropertyChanged()
{
RebindCollection();
}
private void Collection_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
switch (e.Action)
{
case NotifyCollectionChangedAction.Add:
// Add items that were added to the bound collection.
if (e.NewItems != null)
{
var list = viewModelCollectionValue as IList;
foreach (var item in e.NewItems)
{
int index;
if (list == null)
{
// Default to adding the new object at the last index.
index = transform.childCount;
}
else
{
index = list.IndexOf(item);
}
InstantiateTemplate(item, index);
}
}
break;
case NotifyCollectionChangedAction.Remove:
// TODO: respect item order
// Remove items that have been deleted.
if (e.OldItems != null)
{
foreach (var item in e.OldItems)
{
DestroyTemplate(item);
}
}
break;
case NotifyCollectionChangedAction.Reset:
DestroyAllTemplates();
break;
default:
throw new ArgumentOutOfRangeException();
}
}
/// <summary>
/// Bind to the view model collection so we can monitor it for changes.
/// </summary>
private void BindCollection()
{
// Bind view model.
var viewModelType = viewModel.GetType();
string propertyName;
string viewModelName;
ParseEndPointReference(
ViewModelPropertyName,
out propertyName,
out viewModelName
);
var viewModelCollectionProperty = viewModelType.GetProperty(propertyName);
if (viewModelCollectionProperty == null)
{
throw new MemberNotFoundException(
"Expected property "
+ ViewModelPropertyName + ", but it wasn't found on type "
+ viewModelType + "."
);
}
// Get value from view model.
var viewModelValue = viewModelCollectionProperty.GetValue(viewModel, null);
if (viewModelValue == null)
{
throw new PropertyNullException(
"Cannot bind to null property in view: "
+ ViewModelPropertyName
);
}
viewModelCollectionValue = viewModelValue as IEnumerable;
if (viewModelCollectionValue == null)
{
throw new InvalidTypeException(
"Property "
+ ViewModelPropertyName
+ " is not a collection and cannot be used to bind collections."
);
}
// Generate children
var collectionAsList = viewModelCollectionValue.Cast<object>().ToList();
for (var index = 0; index < collectionAsList.Count; index++)
{
InstantiateTemplate(collectionAsList[index], index);
}
// Subscribe to collection changed events.
var collectionChanged = viewModelCollectionValue as INotifyCollectionChanged;
if (collectionChanged != null)
{
collectionChanged.CollectionChanged += Collection_CollectionChanged;
}
}
/// <summary>
/// Unbind from the collection, stop monitoring it for changes.
/// </summary>
private void UnbindCollection()
{
DestroyAllTemplates();
// Unsubscribe from collection changed events.
if (viewModelCollectionValue != null)
{
var collectionChanged = viewModelCollectionValue as INotifyCollectionChanged;
if (collectionChanged != null)
{
collectionChanged.CollectionChanged -= Collection_CollectionChanged;
}
viewModelCollectionValue = null;
}
}
/// <summary>
/// Rebind to the collection when it has changed on the view-model.
/// </summary>
private void RebindCollection()
{
UnbindCollection();
BindCollection();
}
}
}
| |
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using IdentitySample.Services;
using Microsoft.AspNetCore.Identity;
using System.IO;
using Microsoft.Extensions.Options;
using System.Security.Claims;
using MongoDB.Driver;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.DataProtection;
using AspNetCore.Identity.MongoDB;
using StackExchange.Redis;
using System.Net;
using System.Linq;
namespace IdentitySample
{
public class MongoDbSettings
{
public string ConnectionString { get; set; }
public string DatabaseName { get; set; }
}
public class Startup
{
private readonly IHostingEnvironment _env;
public Startup(IHostingEnvironment env)
{
// Set up configuration sources.
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
builder.AddEnvironmentVariables("WebApp_");
Configuration = builder.Build();
_env = env;
}
public IConfigurationRoot Configuration { get; set; }
/// <summary>
/// see: https://github.com/aspnet/Identity/blob/79dbed5a924e96a22b23ae6c84731e0ac806c2b5/src/Microsoft.AspNetCore.Identity/IdentityServiceCollectionExtensions.cs#L46-L68
/// </summary>
public void ConfigureServices(IServiceCollection services)
{
// sad but a giant hack :(
// https://github.com/StackExchange/StackExchange.Redis/issues/410#issuecomment-220829614
var redisHost = Configuration.GetValue<string>("Redis:Host");
var redisPort = Configuration.GetValue<int>("Redis:Port");
var redisIpAddress = Dns.GetHostEntryAsync(redisHost).Result.AddressList.Last();
var redis = ConnectionMultiplexer.Connect($"{redisIpAddress}:{redisPort}");
services.AddDataProtection().PersistKeysToRedis(redis, "DataProtection-Keys");
services.AddOptions();
services.Configure<MongoDbSettings>(Configuration.GetSection("MongoDb"));
services.AddSingleton<IUserStore<MongoIdentityUser>>(provider =>
{
var options = provider.GetService<IOptions<MongoDbSettings>>();
var client = new MongoClient(options.Value.ConnectionString);
var database = client.GetDatabase(options.Value.DatabaseName);
var loggerFactory = provider.GetService<ILoggerFactory>();
return new MongoUserStore<MongoIdentityUser>(database, loggerFactory);
});
services.Configure<IdentityOptions>(options =>
{
options.Cookies.ApplicationCookie.AuthenticationScheme = "ApplicationCookie";
options.Lockout.AllowedForNewUsers = true;
});
// Services used by identity
services.AddAuthentication(options =>
{
// This is the Default value for ExternalCookieAuthenticationScheme
options.SignInScheme = new IdentityCookieOptions().ExternalCookieAuthenticationScheme;
});
// Hosting doesn't add IHttpContextAccessor by default
services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.TryAddSingleton<IdentityMarkerService>();
services.TryAddSingleton<IUserValidator<MongoIdentityUser>, UserValidator<MongoIdentityUser>>();
services.TryAddSingleton<IPasswordValidator<MongoIdentityUser>, PasswordValidator<MongoIdentityUser>>();
services.TryAddSingleton<IPasswordHasher<MongoIdentityUser>, PasswordHasher<MongoIdentityUser>>();
services.TryAddSingleton<ILookupNormalizer, UpperInvariantLookupNormalizer>();
services.TryAddSingleton<IdentityErrorDescriber>();
services.TryAddSingleton<ISecurityStampValidator, SecurityStampValidator<MongoIdentityUser>>();
services.TryAddSingleton<IUserClaimsPrincipalFactory<MongoIdentityUser>, UserClaimsPrincipalFactory<MongoIdentityUser>>();
services.TryAddScoped<UserManager<MongoIdentityUser>, UserManager<MongoIdentityUser>>();
services.TryAddScoped<SignInManager<MongoIdentityUser>, SignInManager<MongoIdentityUser>>();
AddDefaultTokenProviders(services);
services.AddMvc();
// Add application services.
services.AddTransient<IEmailSender, AuthMessageSender>();
services.AddTransient<ISmsSender, AuthMessageSender>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
// To configure external authentication please see http://go.microsoft.com/fwlink/?LinkID=532715
app.UseIdentity()
.UseFacebookAuthentication(new FacebookOptions
{
AppId = "901611409868059",
AppSecret = "4aa3c530297b1dcebc8860334b39668b"
})
.UseGoogleAuthentication(new GoogleOptions
{
ClientId = "514485782433-fr3ml6sq0imvhi8a7qir0nb46oumtgn9.apps.googleusercontent.com",
ClientSecret = "V2nDD9SkFbvLTqAUBWBBxYAL"
})
.UseTwitterAuthentication(new TwitterOptions
{
ConsumerKey = "BSdJJ0CrDuvEhpkchnukXZBUv",
ConsumerSecret = "xKUNuKhsRdHD03eLn67xhPAyE1wFFEndFo1X2UJaK2m1jdAxf4"
});
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
private void AddDefaultTokenProviders(IServiceCollection services)
{
var dataProtectionProviderType = typeof(DataProtectorTokenProvider<>).MakeGenericType(typeof(MongoIdentityUser));
var phoneNumberProviderType = typeof(PhoneNumberTokenProvider<>).MakeGenericType(typeof(MongoIdentityUser));
var emailTokenProviderType = typeof(EmailTokenProvider<>).MakeGenericType(typeof(MongoIdentityUser));
AddTokenProvider(services, TokenOptions.DefaultProvider, dataProtectionProviderType);
AddTokenProvider(services, TokenOptions.DefaultEmailProvider, emailTokenProviderType);
AddTokenProvider(services, TokenOptions.DefaultPhoneProvider, phoneNumberProviderType);
}
private void AddTokenProvider(IServiceCollection services, string providerName, Type provider)
{
services.Configure<IdentityOptions>(options =>
{
options.Tokens.ProviderMap[providerName] = new TokenProviderDescriptor(provider);
});
services.AddSingleton(provider);
}
public class UserClaimsPrincipalFactory<TUser> : Microsoft.AspNetCore.Identity.IUserClaimsPrincipalFactory<TUser>
where TUser : class
{
public UserClaimsPrincipalFactory(
UserManager<TUser> userManager,
IOptions<IdentityOptions> optionsAccessor)
{
if (userManager == null)
{
throw new ArgumentNullException(nameof(userManager));
}
if (optionsAccessor == null || optionsAccessor.Value == null)
{
throw new ArgumentNullException(nameof(optionsAccessor));
}
UserManager = userManager;
Options = optionsAccessor.Value;
}
public UserManager<TUser> UserManager { get; private set; }
public IdentityOptions Options { get; private set; }
public virtual async Task<ClaimsPrincipal> CreateAsync(TUser user)
{
if (user == null)
{
throw new ArgumentNullException(nameof(user));
}
var userId = await UserManager.GetUserIdAsync(user);
var userName = await UserManager.GetUserNameAsync(user);
var id = new ClaimsIdentity(Options.Cookies.ApplicationCookieAuthenticationScheme,
Options.ClaimsIdentity.UserNameClaimType,
Options.ClaimsIdentity.RoleClaimType);
id.AddClaim(new Claim(Options.ClaimsIdentity.UserIdClaimType, userId));
id.AddClaim(new Claim(Options.ClaimsIdentity.UserNameClaimType, userName));
if (UserManager.SupportsUserSecurityStamp)
{
id.AddClaim(new Claim(Options.ClaimsIdentity.SecurityStampClaimType,
await UserManager.GetSecurityStampAsync(user)));
}
if (UserManager.SupportsUserRole)
{
var roles = await UserManager.GetRolesAsync(user);
foreach (var roleName in roles)
{
id.AddClaim(new Claim(Options.ClaimsIdentity.RoleClaimType, roleName));
}
}
if (UserManager.SupportsUserClaim)
{
id.AddClaims(await UserManager.GetClaimsAsync(user));
}
return new ClaimsPrincipal(id);
}
}
}
}
| |
/*
* This file is part of UniERM ReportDesigner, based on reportFU by Josh Wilson,
* the work of Kim Sheffield and the fyiReporting project.
*
* Prior Copyrights:
* _________________________________________________________
* |Copyright (C) 2010 devFU Pty Ltd, Josh Wilson and Others|
* | (http://reportfu.org) |
* =========================================================
* _________________________________________________________
* |Copyright (C) 2004-2008 fyiReporting Software, LLC |
* |For additional information, email info@fyireporting.com |
* |or visit the website www.fyiReporting.com. |
* =========================================================
*
* License:
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
using System.Xml;
namespace Reporting.RdlDesign
{
/// <summary>
/// Summary description for StyleCtl.
/// </summary>
internal class BackgroundCtl : System.Windows.Forms.UserControl, IProperty
{
private List<XmlNode> _ReportItems;
private DesignXmlDraw _Draw;
// flags for controlling whether syntax changed for a particular property
private bool fEndColor, fBackColor, fGradient, fBackImage;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Button bBackColor;
private System.Windows.Forms.Label label10;
private System.Windows.Forms.Label label15;
private System.Windows.Forms.ComboBox cbEndColor;
private System.Windows.Forms.ComboBox cbBackColor;
private System.Windows.Forms.Button bEndColor;
private System.Windows.Forms.ComboBox cbGradient;
private System.Windows.Forms.Button bGradient;
private System.Windows.Forms.Button bExprBackColor;
private System.Windows.Forms.Button bExprEndColor;
private GroupBox groupBox2;
private Button bExternalExpr;
private Button bEmbeddedExpr;
private Button bMimeExpr;
private Button bDatabaseExpr;
private Button bEmbedded;
private Button bExternal;
private TextBox tbValueExternal;
private ComboBox cbValueDatabase;
private ComboBox cbMIMEType;
private ComboBox cbValueEmbedded;
private RadioButton rbDatabase;
private RadioButton rbEmbedded;
private RadioButton rbExternal;
private RadioButton rbNone;
private ComboBox cbRepeat;
private Label label1;
private Button bRepeatExpr;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
private string[] _names;
internal BackgroundCtl(DesignXmlDraw dxDraw, string[] names, List<XmlNode> reportItems)
{
_ReportItems = reportItems;
_Draw = dxDraw;
_names = names;
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
// Initialize form using the style node values
InitValues(_ReportItems[0]);
}
private void InitValues(XmlNode node)
{
cbEndColor.Items.AddRange(StaticLists.ColorList);
cbBackColor.Items.AddRange(StaticLists.ColorList);
cbGradient.Items.AddRange(StaticLists.GradientList);
if (_names != null)
{
node = _Draw.FindCreateNextInHierarchy(node, _names);
}
XmlNode sNode = _Draw.GetNamedChildNode(node, "Style");
this.cbBackColor.Text = _Draw.GetElementValue(sNode, "BackgroundColor", "");
this.cbEndColor.Text = _Draw.GetElementValue(sNode, "BackgroundGradientEndColor", "");
this.cbGradient.Text = _Draw.GetElementValue(sNode, "BackgroundGradientType", "None");
if (node.Name != "Chart")
{ // only chart support gradients
this.cbEndColor.Enabled = bExprEndColor.Enabled =
cbGradient.Enabled = bGradient.Enabled =
this.bEndColor.Enabled = bExprEndColor.Enabled = false;
}
cbValueEmbedded.Items.AddRange(_Draw.ReportNames.EmbeddedImageNames);
string[] flds = _Draw.GetReportItemDataRegionFields(node, true);
if (flds != null)
this.cbValueDatabase.Items.AddRange(flds);
XmlNode iNode = _Draw.GetNamedChildNode(sNode, "BackgroundImage");
if (iNode != null)
{
string source = _Draw.GetElementValue(iNode, "Source", "Embedded");
string val = _Draw.GetElementValue(iNode, "Value", "");
switch (source)
{
case "Embedded":
this.rbEmbedded.Checked = true;
this.cbValueEmbedded.Text = val;
break;
case "Database":
this.rbDatabase.Checked = true;
this.cbValueDatabase.Text = val;
this.cbMIMEType.Text = _Draw.GetElementValue(iNode, "MIMEType", "image/png");
break;
case "External":
default:
this.rbExternal.Checked = true;
this.tbValueExternal.Text = val;
break;
}
this.cbRepeat.Text = _Draw.GetElementValue(iNode, "BackgroundRepeat", "Repeat");
}
else
this.rbNone.Checked = true;
rbSource_CheckedChanged(null, null);
// nothing has changed now
fEndColor = fBackColor = fGradient = fBackImage = false;
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(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()
{
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.bGradient = new System.Windows.Forms.Button();
this.bExprBackColor = new System.Windows.Forms.Button();
this.bExprEndColor = new System.Windows.Forms.Button();
this.bEndColor = new System.Windows.Forms.Button();
this.cbBackColor = new System.Windows.Forms.ComboBox();
this.cbEndColor = new System.Windows.Forms.ComboBox();
this.label15 = new System.Windows.Forms.Label();
this.cbGradient = new System.Windows.Forms.ComboBox();
this.label10 = new System.Windows.Forms.Label();
this.bBackColor = new System.Windows.Forms.Button();
this.label3 = new System.Windows.Forms.Label();
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.bRepeatExpr = new System.Windows.Forms.Button();
this.rbNone = new System.Windows.Forms.RadioButton();
this.cbRepeat = new System.Windows.Forms.ComboBox();
this.label1 = new System.Windows.Forms.Label();
this.bExternalExpr = new System.Windows.Forms.Button();
this.bEmbeddedExpr = new System.Windows.Forms.Button();
this.bMimeExpr = new System.Windows.Forms.Button();
this.bDatabaseExpr = new System.Windows.Forms.Button();
this.bEmbedded = new System.Windows.Forms.Button();
this.bExternal = new System.Windows.Forms.Button();
this.tbValueExternal = new System.Windows.Forms.TextBox();
this.cbValueDatabase = new System.Windows.Forms.ComboBox();
this.cbMIMEType = new System.Windows.Forms.ComboBox();
this.cbValueEmbedded = new System.Windows.Forms.ComboBox();
this.rbDatabase = new System.Windows.Forms.RadioButton();
this.rbEmbedded = new System.Windows.Forms.RadioButton();
this.rbExternal = new System.Windows.Forms.RadioButton();
this.groupBox1.SuspendLayout();
this.groupBox2.SuspendLayout();
this.SuspendLayout();
//
// groupBox1
//
this.groupBox1.Controls.Add(this.bGradient);
this.groupBox1.Controls.Add(this.bExprBackColor);
this.groupBox1.Controls.Add(this.bExprEndColor);
this.groupBox1.Controls.Add(this.bEndColor);
this.groupBox1.Controls.Add(this.cbBackColor);
this.groupBox1.Controls.Add(this.cbEndColor);
this.groupBox1.Controls.Add(this.label15);
this.groupBox1.Controls.Add(this.cbGradient);
this.groupBox1.Controls.Add(this.label10);
this.groupBox1.Controls.Add(this.bBackColor);
this.groupBox1.Controls.Add(this.label3);
this.groupBox1.Location = new System.Drawing.Point(16, 8);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(432, 80);
this.groupBox1.TabIndex = 0;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Background";
//
// bGradient
//
this.bGradient.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.bGradient.Location = new System.Drawing.Point(253, 40);
this.bGradient.Name = "bGradient";
this.bGradient.Size = new System.Drawing.Size(24, 21);
this.bGradient.TabIndex = 4;
this.bGradient.Tag = "bgradient";
this.bGradient.Text = "fx";
this.bGradient.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.bGradient.Click += new System.EventHandler(this.bExpr_Click);
//
// bExprBackColor
//
this.bExprBackColor.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.bExprBackColor.Location = new System.Drawing.Point(102, 40);
this.bExprBackColor.Name = "bExprBackColor";
this.bExprBackColor.Size = new System.Drawing.Size(24, 21);
this.bExprBackColor.TabIndex = 1;
this.bExprBackColor.Tag = "bcolor";
this.bExprBackColor.Text = "fx";
this.bExprBackColor.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.bExprBackColor.Click += new System.EventHandler(this.bExpr_Click);
//
// bExprEndColor
//
this.bExprEndColor.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.bExprEndColor.Location = new System.Drawing.Point(377, 40);
this.bExprEndColor.Name = "bExprEndColor";
this.bExprEndColor.Size = new System.Drawing.Size(24, 21);
this.bExprEndColor.TabIndex = 6;
this.bExprEndColor.Tag = "bendcolor";
this.bExprEndColor.Text = "fx";
this.bExprEndColor.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.bExprEndColor.Click += new System.EventHandler(this.bExpr_Click);
//
// bEndColor
//
this.bEndColor.Location = new System.Drawing.Point(404, 40);
this.bEndColor.Name = "bEndColor";
this.bEndColor.Size = new System.Drawing.Size(24, 21);
this.bEndColor.TabIndex = 7;
this.bEndColor.Text = "...";
this.bEndColor.Click += new System.EventHandler(this.bColor_Click);
//
// cbBackColor
//
this.cbBackColor.Location = new System.Drawing.Point(8, 40);
this.cbBackColor.Name = "cbBackColor";
this.cbBackColor.Size = new System.Drawing.Size(88, 21);
this.cbBackColor.TabIndex = 0;
this.cbBackColor.SelectedIndexChanged += new System.EventHandler(this.cbBackColor_SelectedIndexChanged);
this.cbBackColor.TextChanged += new System.EventHandler(this.cbBackColor_SelectedIndexChanged);
//
// cbEndColor
//
this.cbEndColor.Location = new System.Drawing.Point(286, 40);
this.cbEndColor.Name = "cbEndColor";
this.cbEndColor.Size = new System.Drawing.Size(88, 21);
this.cbEndColor.TabIndex = 5;
this.cbEndColor.SelectedIndexChanged += new System.EventHandler(this.cbEndColor_SelectedIndexChanged);
this.cbEndColor.TextChanged += new System.EventHandler(this.cbEndColor_SelectedIndexChanged);
//
// label15
//
this.label15.Location = new System.Drawing.Point(286, 24);
this.label15.Name = "label15";
this.label15.Size = new System.Drawing.Size(56, 16);
this.label15.TabIndex = 5;
this.label15.Text = "End Color";
//
// cbGradient
//
this.cbGradient.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cbGradient.Location = new System.Drawing.Point(161, 40);
this.cbGradient.Name = "cbGradient";
this.cbGradient.Size = new System.Drawing.Size(88, 21);
this.cbGradient.TabIndex = 3;
this.cbGradient.SelectedIndexChanged += new System.EventHandler(this.cbGradient_SelectedIndexChanged);
//
// label10
//
this.label10.Location = new System.Drawing.Point(161, 24);
this.label10.Name = "label10";
this.label10.Size = new System.Drawing.Size(48, 16);
this.label10.TabIndex = 3;
this.label10.Text = "Gradient";
//
// bBackColor
//
this.bBackColor.Location = new System.Drawing.Point(128, 40);
this.bBackColor.Name = "bBackColor";
this.bBackColor.Size = new System.Drawing.Size(24, 21);
this.bBackColor.TabIndex = 2;
this.bBackColor.Text = "...";
this.bBackColor.Click += new System.EventHandler(this.bColor_Click);
//
// label3
//
this.label3.Location = new System.Drawing.Point(8, 24);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(32, 16);
this.label3.TabIndex = 0;
this.label3.Text = "Color";
//
// groupBox2
//
this.groupBox2.Controls.Add(this.bRepeatExpr);
this.groupBox2.Controls.Add(this.rbNone);
this.groupBox2.Controls.Add(this.cbRepeat);
this.groupBox2.Controls.Add(this.label1);
this.groupBox2.Controls.Add(this.bExternalExpr);
this.groupBox2.Controls.Add(this.bEmbeddedExpr);
this.groupBox2.Controls.Add(this.bMimeExpr);
this.groupBox2.Controls.Add(this.bDatabaseExpr);
this.groupBox2.Controls.Add(this.bEmbedded);
this.groupBox2.Controls.Add(this.bExternal);
this.groupBox2.Controls.Add(this.tbValueExternal);
this.groupBox2.Controls.Add(this.cbValueDatabase);
this.groupBox2.Controls.Add(this.cbMIMEType);
this.groupBox2.Controls.Add(this.cbValueEmbedded);
this.groupBox2.Controls.Add(this.rbDatabase);
this.groupBox2.Controls.Add(this.rbEmbedded);
this.groupBox2.Controls.Add(this.rbExternal);
this.groupBox2.Location = new System.Drawing.Point(16, 109);
this.groupBox2.Name = "groupBox2";
this.groupBox2.Size = new System.Drawing.Size(432, 219);
this.groupBox2.TabIndex = 3;
this.groupBox2.TabStop = false;
this.groupBox2.Text = "Background Image Source";
//
// bRepeatExpr
//
this.bRepeatExpr.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.bRepeatExpr.Location = new System.Drawing.Point(213, 184);
this.bRepeatExpr.Name = "bRepeatExpr";
this.bRepeatExpr.Size = new System.Drawing.Size(24, 21);
this.bRepeatExpr.TabIndex = 16;
this.bRepeatExpr.Tag = "repeat";
this.bRepeatExpr.Text = "fx";
this.bRepeatExpr.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// rbNone
//
this.rbNone.Location = new System.Drawing.Point(6, 25);
this.rbNone.Name = "rbNone";
this.rbNone.Size = new System.Drawing.Size(80, 24);
this.rbNone.TabIndex = 15;
this.rbNone.Text = "None";
this.rbNone.CheckedChanged += new System.EventHandler(this.rbSource_CheckedChanged);
//
// cbRepeat
//
this.cbRepeat.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cbRepeat.Items.AddRange(new object[] {
"Repeat",
"NoRepeat",
"RepeatX",
"RepeatY"});
this.cbRepeat.Location = new System.Drawing.Point(87, 184);
this.cbRepeat.Name = "cbRepeat";
this.cbRepeat.Size = new System.Drawing.Size(120, 21);
this.cbRepeat.TabIndex = 14;
this.cbRepeat.SelectedIndexChanged += new System.EventHandler(this.BackImage_Changed);
this.cbRepeat.TextChanged += new System.EventHandler(this.BackImage_Changed);
//
// label1
//
this.label1.Location = new System.Drawing.Point(22, 184);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(59, 23);
this.label1.TabIndex = 13;
this.label1.Text = "Repeat";
//
// bExternalExpr
//
this.bExternalExpr.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.bExternalExpr.Location = new System.Drawing.Point(376, 55);
this.bExternalExpr.Name = "bExternalExpr";
this.bExternalExpr.Size = new System.Drawing.Size(24, 21);
this.bExternalExpr.TabIndex = 12;
this.bExternalExpr.Tag = "external";
this.bExternalExpr.Text = "fx";
this.bExternalExpr.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.bExternalExpr.Click += new System.EventHandler(this.bExpr_Click);
//
// bEmbeddedExpr
//
this.bEmbeddedExpr.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.bEmbeddedExpr.Location = new System.Drawing.Point(376, 87);
this.bEmbeddedExpr.Name = "bEmbeddedExpr";
this.bEmbeddedExpr.Size = new System.Drawing.Size(24, 21);
this.bEmbeddedExpr.TabIndex = 11;
this.bEmbeddedExpr.Tag = "embedded";
this.bEmbeddedExpr.Text = "fx";
this.bEmbeddedExpr.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.bEmbeddedExpr.Click += new System.EventHandler(this.bExpr_Click);
//
// bMimeExpr
//
this.bMimeExpr.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.bMimeExpr.Location = new System.Drawing.Point(182, 119);
this.bMimeExpr.Name = "bMimeExpr";
this.bMimeExpr.Size = new System.Drawing.Size(24, 21);
this.bMimeExpr.TabIndex = 10;
this.bMimeExpr.Tag = "mime";
this.bMimeExpr.Text = "fx";
this.bMimeExpr.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.bMimeExpr.Click += new System.EventHandler(this.bExpr_Click);
//
// bDatabaseExpr
//
this.bDatabaseExpr.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.bDatabaseExpr.Location = new System.Drawing.Point(376, 151);
this.bDatabaseExpr.Name = "bDatabaseExpr";
this.bDatabaseExpr.Size = new System.Drawing.Size(24, 21);
this.bDatabaseExpr.TabIndex = 9;
this.bDatabaseExpr.Tag = "database";
this.bDatabaseExpr.Text = "fx";
this.bDatabaseExpr.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.bDatabaseExpr.Click += new System.EventHandler(this.bExpr_Click);
//
// bEmbedded
//
this.bEmbedded.Location = new System.Drawing.Point(402, 87);
this.bEmbedded.Name = "bEmbedded";
this.bEmbedded.Size = new System.Drawing.Size(24, 21);
this.bEmbedded.TabIndex = 8;
this.bEmbedded.Text = "...";
this.bEmbedded.Click += new System.EventHandler(this.bEmbedded_Click);
//
// bExternal
//
this.bExternal.Location = new System.Drawing.Point(402, 55);
this.bExternal.Name = "bExternal";
this.bExternal.Size = new System.Drawing.Size(24, 21);
this.bExternal.TabIndex = 7;
this.bExternal.Text = "...";
this.bExternal.Click += new System.EventHandler(this.bExternal_Click);
//
// tbValueExternal
//
this.tbValueExternal.Location = new System.Drawing.Point(86, 55);
this.tbValueExternal.Name = "tbValueExternal";
this.tbValueExternal.Size = new System.Drawing.Size(284, 20);
this.tbValueExternal.TabIndex = 6;
this.tbValueExternal.TextChanged += new System.EventHandler(this.BackImage_Changed);
//
// cbValueDatabase
//
this.cbValueDatabase.Location = new System.Drawing.Point(86, 151);
this.cbValueDatabase.Name = "cbValueDatabase";
this.cbValueDatabase.Size = new System.Drawing.Size(284, 21);
this.cbValueDatabase.TabIndex = 5;
this.cbValueDatabase.SelectedIndexChanged += new System.EventHandler(this.BackImage_Changed);
this.cbValueDatabase.TextChanged += new System.EventHandler(this.BackImage_Changed);
//
// cbMIMEType
//
this.cbMIMEType.Items.AddRange(new object[] {
"image/bmp",
"image/jpeg",
"image/gif",
"image/png",
"image/x-png"});
this.cbMIMEType.Location = new System.Drawing.Point(86, 119);
this.cbMIMEType.Name = "cbMIMEType";
this.cbMIMEType.Size = new System.Drawing.Size(88, 21);
this.cbMIMEType.TabIndex = 4;
this.cbMIMEType.Text = "image/jpeg";
this.cbMIMEType.SelectedIndexChanged += new System.EventHandler(this.BackImage_Changed);
this.cbMIMEType.TextChanged += new System.EventHandler(this.BackImage_Changed);
//
// cbValueEmbedded
//
this.cbValueEmbedded.Location = new System.Drawing.Point(86, 87);
this.cbValueEmbedded.Name = "cbValueEmbedded";
this.cbValueEmbedded.Size = new System.Drawing.Size(284, 21);
this.cbValueEmbedded.TabIndex = 3;
this.cbValueEmbedded.SelectedIndexChanged += new System.EventHandler(this.BackImage_Changed);
this.cbValueEmbedded.TextChanged += new System.EventHandler(this.BackImage_Changed);
//
// rbDatabase
//
this.rbDatabase.Location = new System.Drawing.Point(6, 119);
this.rbDatabase.Name = "rbDatabase";
this.rbDatabase.Size = new System.Drawing.Size(80, 24);
this.rbDatabase.TabIndex = 2;
this.rbDatabase.Text = "Database";
this.rbDatabase.CheckedChanged += new System.EventHandler(this.rbSource_CheckedChanged);
//
// rbEmbedded
//
this.rbEmbedded.Location = new System.Drawing.Point(6, 87);
this.rbEmbedded.Name = "rbEmbedded";
this.rbEmbedded.Size = new System.Drawing.Size(80, 24);
this.rbEmbedded.TabIndex = 1;
this.rbEmbedded.Text = "Embedded";
this.rbEmbedded.CheckedChanged += new System.EventHandler(this.rbSource_CheckedChanged);
//
// rbExternal
//
this.rbExternal.Location = new System.Drawing.Point(6, 55);
this.rbExternal.Name = "rbExternal";
this.rbExternal.Size = new System.Drawing.Size(80, 24);
this.rbExternal.TabIndex = 0;
this.rbExternal.Text = "External";
this.rbExternal.CheckedChanged += new System.EventHandler(this.rbSource_CheckedChanged);
//
// BackgroundCtl
//
this.Controls.Add(this.groupBox2);
this.Controls.Add(this.groupBox1);
this.Name = "BackgroundCtl";
this.Size = new System.Drawing.Size(472, 351);
this.groupBox1.ResumeLayout(false);
this.groupBox2.ResumeLayout(false);
this.groupBox2.PerformLayout();
this.ResumeLayout(false);
}
#endregion
public bool IsValid()
{
return true;
}
public void Apply()
{
// take information in control and apply to all the style nodes
// Only change information that has been marked as modified;
// this way when group is selected it is possible to change just
// the items you want and keep the rest the same.
foreach (XmlNode riNode in this._ReportItems)
ApplyChanges(riNode);
// nothing has changed now
fEndColor = fBackColor = fGradient = fBackImage = false;
}
private void bColor_Click(object sender, System.EventArgs e)
{
ColorDialog cd = new ColorDialog();
cd.AnyColor = true;
cd.FullOpen = true;
cd.CustomColors = RdlDesignerForm.CustomColors;
try
{
if (cd.ShowDialog() != DialogResult.OK)
return;
RdlDesignerForm.CustomColors = cd.CustomColors;
if (sender == this.bEndColor)
cbEndColor.Text = ColorTranslator.ToHtml(cd.Color);
else if (sender == this.bBackColor)
cbBackColor.Text = ColorTranslator.ToHtml(cd.Color);
}
finally
{
cd.Dispose();
}
return;
}
private void cbBackColor_SelectedIndexChanged(object sender, System.EventArgs e)
{
fBackColor = true;
}
private void cbGradient_SelectedIndexChanged(object sender, System.EventArgs e)
{
fGradient = true;
}
private void cbEndColor_SelectedIndexChanged(object sender, System.EventArgs e)
{
fEndColor = true;
}
private void BackImage_Changed(object sender, System.EventArgs e)
{
fBackImage = true;
}
private void rbSource_CheckedChanged(object sender, System.EventArgs e)
{
fBackImage = true;
this.cbValueDatabase.Enabled = this.cbMIMEType.Enabled =
this.bDatabaseExpr.Enabled = this.rbDatabase.Checked;
this.cbValueEmbedded.Enabled = this.bEmbeddedExpr.Enabled =
this.bEmbedded.Enabled = this.rbEmbedded.Checked;
this.tbValueExternal.Enabled = this.bExternalExpr.Enabled =
this.bExternal.Enabled = this.rbExternal.Checked;
}
private void ApplyChanges(XmlNode rNode)
{
if (_names != null)
{
rNode = _Draw.FindCreateNextInHierarchy(rNode, _names);
}
XmlNode xNode = _Draw.GetNamedChildNode(rNode, "Style");
//Added to create a node in case a node doesn't have
// a style node when attempting to save.
if (xNode == null)
{
_Draw.SetElement(rNode, "Style", "");
xNode = _Draw.GetNamedChildNode(rNode, "Style");
}
if (fEndColor)
{ _Draw.SetElement(xNode, "BackgroundGradientEndColor", cbEndColor.Text); }
if (fBackColor)
{ _Draw.SetElement(xNode, "BackgroundColor", cbBackColor.Text); }
if (fGradient)
{ _Draw.SetElement(xNode, "BackgroundGradientType", cbGradient.Text); }
if (fBackImage)
{
_Draw.RemoveElement(xNode, "BackgroundImage");
if (!rbNone.Checked)
{
XmlNode bi = _Draw.CreateElement(xNode, "BackgroundImage", null);
if (rbDatabase.Checked)
{
_Draw.SetElement(bi, "Source", "Database");
_Draw.SetElement(bi, "Value", cbValueDatabase.Text);
_Draw.SetElement(bi, "MIMEType", cbMIMEType.Text);
}
else if (rbExternal.Checked)
{
_Draw.SetElement(bi, "Source", "External");
_Draw.SetElement(bi, "Value", tbValueExternal.Text);
}
else if (rbEmbedded.Checked)
{
_Draw.SetElement(bi, "Source", "Embedded");
_Draw.SetElement(bi, "Value", cbValueEmbedded.Text);
}
_Draw.SetElement(bi, "BackgroundRepeat", cbRepeat.Text);
}
}
}
private void bExternal_Click(object sender, System.EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Bitmap Files (*.bmp)|*.bmp" +
"|JPEG (*.jpg;*.jpeg;*.jpe;*.jfif)|*.jpg;*.jpeg;*.jpe;*.jfif" +
"|GIF (*.gif)|*.gif" +
"|TIFF (*.tif;*.tiff)|*.tif;*.tiff" +
"|PNG (*.png)|*.png" +
"|All Picture Files|*.bmp;*.jpg;*.jpeg;*.jpe;*.jfif;*.gif;*.tif;*.tiff;*.png" +
"|All files (*.*)|*.*";
ofd.FilterIndex = 6;
ofd.CheckFileExists = true;
try
{
if (ofd.ShowDialog(this) == DialogResult.OK)
{
tbValueExternal.Text = ofd.FileName;
}
}
finally
{
ofd.Dispose();
}
}
private void bEmbedded_Click(object sender, System.EventArgs e)
{
DialogEmbeddedImages dlgEI = new DialogEmbeddedImages(this._Draw);
dlgEI.StartPosition = FormStartPosition.CenterParent;
try
{
DialogResult dr = dlgEI.ShowDialog();
if (dr != DialogResult.OK)
return;
// Populate the EmbeddedImage names
cbValueEmbedded.Items.Clear();
cbValueEmbedded.Items.AddRange(_Draw.ReportNames.EmbeddedImageNames);
}
finally
{
dlgEI.Dispose();
}
}
private void bExpr_Click(object sender, System.EventArgs e)
{
Button b = sender as Button;
if (b == null)
return;
Control c = null;
bool bColor=false;
switch (b.Tag as string)
{
case "bcolor":
c = cbBackColor;
bColor = true;
break;
case "bgradient":
c = cbGradient;
break;
case "bendcolor":
c = cbEndColor;
bColor = true;
break;
case "database":
c = cbValueDatabase;
break;
case "embedded":
c = cbValueEmbedded;
break;
case "external":
c = tbValueExternal;
break;
case "repeat":
c = cbRepeat;
break;
case "mime":
c = cbMIMEType;
break;
}
if (c == null)
return;
XmlNode sNode = _ReportItems[0];
DialogExprEditor ee = new DialogExprEditor(_Draw, c.Text, sNode, bColor);
DialogResult dr = ee.ShowDialog();
if (dr == DialogResult.OK)
c.Text = ee.Expression;
return;
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="Timers.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 Akka.Streams.Implementation.Fusing;
using Akka.Streams.Stage;
namespace Akka.Streams.Implementation
{
/// <summary>
/// INTERNAL API
///
/// Various stages for controlling timeouts on IO related streams (although not necessarily).
///
/// The common theme among the processing stages here that
/// - they wait for certain event or events to happen
/// - they have a timer that may fire before these events
/// - if the timer fires before the event happens, these stages all fail the stream
/// - otherwise, these streams do not interfere with the element flow, ordinary completion or failure
/// </summary>
internal static class Timers
{
public static TimeSpan IdleTimeoutCheckInterval(TimeSpan timeout)
=> new TimeSpan(Math.Min(Math.Max(timeout.Ticks/8, 100*TimeSpan.TicksPerMillisecond), timeout.Ticks/2));
}
internal sealed class Initial<T> : SimpleLinearGraphStage<T>
{
#region InitialStageLogic
private sealed class Logic : TimerGraphStageLogic
{
private readonly Initial<T> _stage;
private bool _initialHasPassed;
public Logic(Initial<T> stage) : base(stage.Shape)
{
_stage = stage;
SetHandler(stage.Inlet, onPush: () =>
{
_initialHasPassed = true;
Push(stage.Outlet, Grab(stage.Inlet));
});
SetHandler(stage.Outlet, onPull: () => Pull(stage.Inlet));
}
protected internal override void OnTimer(object timerKey)
{
if (!_initialHasPassed)
FailStage(new TimeoutException($"The first element has not yet passed through in {_stage.Timeout}."));
}
public override void PreStart() => ScheduleOnce("InitialTimeoutTimer", _stage.Timeout);
}
#endregion
public readonly TimeSpan Timeout;
public Initial(TimeSpan timeout)
{
Timeout = timeout;
}
protected override GraphStageLogic CreateLogic(Attributes inheritedAttributes) => new Logic(this);
}
internal sealed class Completion<T> : SimpleLinearGraphStage<T>
{
#region stage logic
private sealed class Logic : TimerGraphStageLogic
{
private readonly Completion<T> _stage;
public Logic(Completion<T> stage) : base(stage.Shape)
{
_stage = stage;
SetHandler(stage.Inlet, onPush: () => Push(stage.Outlet, Grab(stage.Inlet)));
SetHandler(stage.Outlet, onPull: () => Pull(stage.Inlet));
}
protected internal override void OnTimer(object timerKey)
=> FailStage(new TimeoutException($"The stream has not been completed in {_stage.Timeout}."));
public override void PreStart() => ScheduleOnce("CompletionTimeoutTimer", _stage.Timeout);
}
#endregion
public readonly TimeSpan Timeout;
public Completion(TimeSpan timeout)
{
Timeout = timeout;
}
protected override GraphStageLogic CreateLogic(Attributes inheritedAttributes) => new Logic(this);
}
internal sealed class Idle<T> : SimpleLinearGraphStage<T>
{
#region stage logic
private sealed class Logic : TimerGraphStageLogic
{
private readonly Idle<T> _stage;
private DateTime _nextDeadline;
public Logic(Idle<T> stage) : base(stage.Shape)
{
_stage = stage;
_nextDeadline = DateTime.UtcNow + stage.Timeout;
SetHandler(stage.Inlet, onPush: () =>
{
_nextDeadline = DateTime.UtcNow + stage.Timeout;
Push(stage.Outlet, Grab(stage.Inlet));
});
SetHandler(stage.Outlet, onPull: () => Pull(stage.Inlet));
}
protected internal override void OnTimer(object timerKey)
{
if (_nextDeadline <= DateTime.UtcNow)
FailStage(new TimeoutException($"No elements passed in the last {_stage.Timeout}."));
}
public override void PreStart()
=> ScheduleRepeatedly("IdleTimeoutCheckTimer", Timers.IdleTimeoutCheckInterval(_stage.Timeout));
}
#endregion
public readonly TimeSpan Timeout;
public Idle(TimeSpan timeout)
{
Timeout = timeout;
}
protected override GraphStageLogic CreateLogic(Attributes inheritedAttributes) => new Logic(this);
}
internal sealed class IdleTimeoutBidi<TIn, TOut> : GraphStage<BidiShape<TIn, TIn, TOut, TOut>>
{
#region stage logic
private sealed class Logic : TimerGraphStageLogic
{
private readonly IdleTimeoutBidi<TIn, TOut> _stage;
private DateTime _nextDeadline;
public Logic(IdleTimeoutBidi<TIn, TOut> stage) : base(stage.Shape)
{
_stage = stage;
_nextDeadline = DateTime.UtcNow + _stage.Timeout;
SetHandler(_stage.In1, onPush: () =>
{
OnActivity();
Push(_stage.Out1, Grab(_stage.In1));
},
onUpstreamFinish: () => Complete(_stage.Out1));
SetHandler(_stage.In2, onPush: () =>
{
OnActivity();
Push(_stage.Out2, Grab(_stage.In2));
},
onUpstreamFinish: () => Complete(_stage.Out2));
SetHandler(_stage.Out1,
onPull: () => Pull(_stage.In1),
onDownstreamFinish: () => Cancel(_stage.In1));
SetHandler(_stage.Out2,
onPull: () => Pull(_stage.In2),
onDownstreamFinish: () => Cancel(_stage.In2));
}
protected internal override void OnTimer(object timerKey)
{
if (_nextDeadline <= DateTime.UtcNow)
FailStage(new TimeoutException($"No elements passed in the last {_stage.Timeout}."));
}
public override void PreStart()
=> ScheduleRepeatedly("IdleTimeoutBidiCheckTimer", Timers.IdleTimeoutCheckInterval(_stage.Timeout));
private void OnActivity() => _nextDeadline = DateTime.UtcNow + _stage.Timeout;
}
#endregion
public readonly TimeSpan Timeout;
public readonly Inlet<TIn> In1 = new Inlet<TIn>("in1");
public readonly Inlet<TOut> In2 = new Inlet<TOut>("in2");
public readonly Outlet<TIn> Out1 = new Outlet<TIn>("out1");
public readonly Outlet<TOut> Out2 = new Outlet<TOut>("out2");
public IdleTimeoutBidi(TimeSpan timeout)
{
Timeout = timeout;
Shape = new BidiShape<TIn, TIn, TOut, TOut>(In1, Out1, In2, Out2);
}
protected override Attributes InitialAttributes { get; } = Attributes.CreateName("IdleTimeoutBidi");
public override BidiShape<TIn, TIn, TOut, TOut> Shape { get; }
protected override GraphStageLogic CreateLogic(Attributes inheritedAttributes) => new Logic(this);
}
internal sealed class DelayInitial<T> : GraphStage<FlowShape<T, T>>
{
#region stage logic
private sealed class Logic : TimerGraphStageLogic
{
private const string DelayTimer = "DelayTimer";
private readonly DelayInitial<T> _stage;
private bool _isOpen;
public Logic(DelayInitial<T> stage) : base(stage.Shape)
{
_stage = stage;
SetHandler(_stage.In, onPush: () => Push(_stage.Out, Grab(_stage.In)));
SetHandler(_stage.Out, onPull: () =>
{
if (_isOpen)
Pull(_stage.In);
});
}
protected internal override void OnTimer(object timerKey)
{
_isOpen = true;
if (IsAvailable(_stage.Out))
Pull(_stage.In);
}
public override void PreStart()
{
if (_stage.Delay == TimeSpan.Zero)
_isOpen = true;
else
ScheduleOnce(DelayTimer, _stage.Delay);
}
}
#endregion
public readonly TimeSpan Delay;
public readonly Inlet<T> In = new Inlet<T>("DelayInitial.in");
public readonly Outlet<T> Out = new Outlet<T>("DelayInitial.out");
public DelayInitial(TimeSpan delay)
{
Delay = delay;
Shape = new FlowShape<T, T>(In, Out);
}
protected override Attributes InitialAttributes { get; } = Attributes.CreateName("DelayInitial");
public override FlowShape<T, T> Shape { get; }
protected override GraphStageLogic CreateLogic(Attributes inheritedAttributes) => new Logic(this);
}
internal sealed class IdleInject<TIn, TOut> : GraphStage<FlowShape<TIn, TOut>> where TIn : TOut
{
#region stage logic
private sealed class Logic : TimerGraphStageLogic
{
private const string IdleTimer = "IdleInjectTimer";
private readonly IdleInject<TIn, TOut> _stage;
private DateTime _nextDeadline;
public Logic(IdleInject<TIn, TOut> stage) : base(stage.Shape)
{
_stage = stage;
_nextDeadline = DateTime.UtcNow + _stage._timeout;
SetHandler(_stage._in, onPush: () =>
{
_nextDeadline = DateTime.UtcNow + _stage._timeout;
CancelTimer(IdleTimer);
if (IsAvailable(_stage._out))
{
Push(_stage._out, Grab(_stage._in));
Pull(_stage._in);
}
},
onUpstreamFinish: () =>
{
if(!IsAvailable(_stage._in))
CompleteStage();
});
SetHandler(_stage._out, onPull: () =>
{
if (IsAvailable(_stage._in))
{
Push(_stage._out, Grab(_stage._in));
if (IsClosed(_stage._in))
CompleteStage();
else
Pull(_stage._in);
}
else
{
var timeLeft = _nextDeadline - DateTime.UtcNow;
if (timeLeft <= TimeSpan.Zero)
{
_nextDeadline = DateTime.UtcNow + _stage._timeout;
Push(_stage._out, _stage._inject());
}
else
ScheduleOnce(IdleTimer, timeLeft);
}
});
}
protected internal override void OnTimer(object timerKey)
{
if (_nextDeadline <= DateTime.UtcNow && IsAvailable(_stage._out))
{
Push(_stage._out, _stage._inject());
_nextDeadline = DateTime.UtcNow + _stage._timeout;
}
}
// Prefetching to ensure priority of actual upstream elements
public override void PreStart() => Pull(_stage._in);
}
#endregion
private readonly TimeSpan _timeout;
private readonly Func<TOut> _inject;
private readonly Inlet<TIn> _in = new Inlet<TIn>("IdleInject.in");
private readonly Outlet<TOut> _out = new Outlet<TOut>("IdleInject.out");
public IdleInject(TimeSpan timeout, Func<TOut> inject)
{
_timeout = timeout;
_inject = inject;
Shape = new FlowShape<TIn, TOut>(_in, _out);
}
protected override Attributes InitialAttributes { get; } = Attributes.CreateName("IdleInject");
public override FlowShape<TIn, TOut> Shape { get; }
protected override GraphStageLogic CreateLogic(Attributes inheritedAttributes) => new Logic(this);
}
}
| |
/*
* DocuSign REST API
*
* The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign.
*
* OpenAPI spec version: v2
* Contact: devcenter@docusign.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.IdentityModel.Protocols.WSTrust;
using System.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.OpenSsl;
using Org.BouncyCastle.Security;
using RestSharp;
using Newtonsoft.Json.Linq;
namespace DocuSign.eSign.Client
{
/// <summary>
/// API client is mainly responsible for making the HTTP call to the API backend.
/// </summary>
public partial class ApiClient
{
private JsonSerializerSettings serializerSettings = new JsonSerializerSettings
{
ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor
};
/// <summary>
/// Allows for extending request processing for <see cref="ApiClient"/> generated code.
/// </summary>
/// <param name="request">The RestSharp request object</param>
partial void InterceptRequest(IRestRequest request);
/// <summary>
/// Allows for extending response processing for <see cref="ApiClient"/> generated code.
/// </summary>
/// <param name="request">The RestSharp request object</param>
/// <param name="response">The RestSharp response object</param>
partial void InterceptResponse(IRestRequest request, IRestResponse response);
/// <summary>
/// Initializes a new instance of the <see cref="ApiClient" /> class
/// with default configuration and base path (https://www.docusign.net/restapi).
/// </summary>
public ApiClient()
{
Configuration = Configuration.Default;
RestClient = new RestClient("https://www.docusign.net/restapi");
}
/// <summary>
/// Initializes a new instance of the <see cref="ApiClient" /> class
/// with default base path (https://www.docusign.net/restapi).
/// </summary>
/// <param name="config">An instance of Configuration.</param>
public ApiClient(Configuration config = null)
{
if (config == null)
Configuration = Configuration.Default;
else
Configuration = config;
RestClient = new RestClient("https://www.docusign.net/restapi");
}
/// <summary>
/// Initializes a new instance of the <see cref="ApiClient" /> class
/// with default configuration.
/// </summary>
/// <param name="basePath">The base path.</param>
public ApiClient(String basePath = "https://www.docusign.net/restapi")
{
if (String.IsNullOrEmpty(basePath))
throw new ArgumentException("basePath cannot be empty");
RestClient = new RestClient(basePath);
Configuration = Configuration.Default;
Configuration.ApiClient = this;
}
/// <summary>
/// Gets or sets the default API client for making HTTP calls.
/// </summary>
/// <value>The default API client.</value>
[Obsolete("ApiClient.Default is deprecated, please use 'Configuration.Default.ApiClient' instead.")]
public static ApiClient Default;
/// <summary>
/// Gets or sets the Configuration.
/// </summary>
/// <value>An instance of the Configuration.</value>
public Configuration Configuration { get; set; }
/// <summary>
/// Gets or sets the RestClient.
/// </summary>
/// <value>An instance of the RestClient</value>
public RestClient RestClient { get; set; }
// Creates and sets up a RestRequest prior to a call.
private RestRequest PrepareRequest(
String path, RestSharp.Method method, Dictionary<String, String> queryParams, Object postBody,
Dictionary<String, String> headerParams, Dictionary<String, String> formParams,
Dictionary<String, FileParameter> fileParams, Dictionary<String, String> pathParams,
String contentType)
{
var request = new RestRequest(path, method);
// add path parameter, if any
foreach(var param in pathParams)
request.AddParameter(param.Key, param.Value, ParameterType.UrlSegment);
// DocuSign: Add DocuSign tracking headers
request.AddHeader("X-DocuSign-SDK", "C#");
// add header parameter, if any
foreach(var param in headerParams)
request.AddHeader(param.Key, param.Value);
// add query parameter, if any
foreach(var param in queryParams)
request.AddQueryParameter(param.Key, param.Value);
// add form parameter, if any
foreach(var param in formParams)
request.AddParameter(param.Key, param.Value);
// add file parameter, if any
foreach(var param in fileParams)
{
request.AddFile(param.Value.Name, param.Value.Writer, param.Value.FileName, param.Value.ContentLength, param.Value.ContentType);
}
if (postBody != null) // http body (model or byte[]) parameter
{
if (postBody.GetType() == typeof(String))
{
request.AddParameter("application/json", postBody, ParameterType.RequestBody);
}
else if (postBody.GetType() == typeof(byte[]))
{
request.AddParameter(contentType, postBody, ParameterType.RequestBody);
}
}
return request;
}
/// <summary>
/// Makes the HTTP request (Sync).
/// </summary>
/// <param name="path">URL path.</param>
/// <param name="method">HTTP method.</param>
/// <param name="queryParams">Query parameters.</param>
/// <param name="postBody">HTTP body (POST request).</param>
/// <param name="headerParams">Header parameters.</param>
/// <param name="formParams">Form parameters.</param>
/// <param name="fileParams">File parameters.</param>
/// <param name="pathParams">Path parameters.</param>
/// <param name="contentType">Content Type of the request</param>
/// <returns>Object</returns>
public Object CallApi(
String path, RestSharp.Method method, Dictionary<String, String> queryParams, Object postBody,
Dictionary<String, String> headerParams, Dictionary<String, String> formParams,
Dictionary<String, FileParameter> fileParams, Dictionary<String, String> pathParams,
String contentType)
{
var request = PrepareRequest(
path, method, queryParams, postBody, headerParams, formParams, fileParams,
pathParams, contentType);
// set timeout
RestClient.Timeout = Configuration.Timeout;
// set user agent
RestClient.UserAgent = Configuration.UserAgent;
InterceptRequest(request);
var response = RestClient.Execute(request);
InterceptResponse(request, response);
return (Object) response;
}
/// <summary>
/// Makes the asynchronous HTTP request.
/// </summary>
/// <param name="path">URL path.</param>
/// <param name="method">HTTP method.</param>
/// <param name="queryParams">Query parameters.</param>
/// <param name="postBody">HTTP body (POST request).</param>
/// <param name="headerParams">Header parameters.</param>
/// <param name="formParams">Form parameters.</param>
/// <param name="fileParams">File parameters.</param>
/// <param name="pathParams">Path parameters.</param>
/// <param name="contentType">Content type.</param>
/// <returns>The Task instance.</returns>
public async System.Threading.Tasks.Task<Object> CallApiAsync(
String path, RestSharp.Method method, Dictionary<String, String> queryParams, Object postBody,
Dictionary<String, String> headerParams, Dictionary<String, String> formParams,
Dictionary<String, FileParameter> fileParams, Dictionary<String, String> pathParams,
String contentType)
{
var request = PrepareRequest(
path, method, queryParams, postBody, headerParams, formParams, fileParams,
pathParams, contentType);
InterceptRequest(request);
var response = await RestClient.ExecuteTaskAsync(request);
InterceptResponse(request, response);
return (Object)response;
}
/// <summary>
/// Escape string (url-encoded).
/// </summary>
/// <param name="str">String to be escaped.</param>
/// <returns>Escaped string.</returns>
public string EscapeString(string str)
{
return UrlEncode(str);
}
/// <summary>
/// Create FileParameter based on Stream.
/// </summary>
/// <param name="name">Parameter name.</param>
/// <param name="stream">Input stream.</param>
/// <returns>FileParameter.</returns>
public FileParameter ParameterToFile(string name, Stream stream)
{
if (stream is FileStream)
return FileParameter.Create(name, ReadAsBytes(stream), Path.GetFileName(((FileStream)stream).Name));
else
return FileParameter.Create(name, ReadAsBytes(stream), "no_file_name_provided");
}
/// <summary>
/// If parameter is DateTime, output in a formatted string (default ISO 8601), customizable with Configuration.DateTime.
/// If parameter is a list, join the list with ",".
/// Otherwise just return the string.
/// </summary>
/// <param name="obj">The parameter (header, path, query, form).</param>
/// <returns>Formatted string.</returns>
public string ParameterToString(object obj)
{
if (obj is DateTime)
// Return a formatted date string - Can be customized with Configuration.DateTimeFormat
// Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o")
// https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8
// For example: 2009-06-15T13:45:30.0000000
return ((DateTime)obj).ToString (Configuration.DateTimeFormat);
else if (obj is DateTimeOffset)
// Return a formatted date string - Can be customized with Configuration.DateTimeFormat
// Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o")
// https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8
// For example: 2009-06-15T13:45:30.0000000
return ((DateTimeOffset)obj).ToString (Configuration.DateTimeFormat);
else if (obj is IList)
{
var flattenedString = new StringBuilder();
foreach (var param in (IList)obj)
{
if (flattenedString.Length > 0)
flattenedString.Append(",");
flattenedString.Append(param);
}
return flattenedString.ToString();
}
else
return Convert.ToString (obj);
}
/// <summary>
/// Deserialize the JSON string into a proper object.
/// </summary>
/// <param name="response">The HTTP response.</param>
/// <param name="type">Object type.</param>
/// <returns>Object representation of the JSON string.</returns>
public object Deserialize(IRestResponse response, Type type)
{
IList<Parameter> headers = response.Headers;
if (type == typeof(byte[])) // return byte array
{
return response.RawBytes;
}
if (type == typeof(Stream))
{
if (headers != null)
{
var filePath = String.IsNullOrEmpty(Configuration.TempFolderPath)
? Path.GetTempPath()
: Configuration.TempFolderPath;
var regex = new Regex(@"Content-Disposition=.*filename=['""]?([^'""\s]+)['""]?$");
foreach (var header in headers)
{
var match = regex.Match(header.ToString());
if (match.Success)
{
string fileName = filePath + SanitizeFilename(match.Groups[1].Value.Replace("\"", "").Replace("'", ""));
File.WriteAllBytes(fileName, response.RawBytes);
return new FileStream(fileName, FileMode.Open);
}
}
}
var stream = new MemoryStream(response.RawBytes);
return stream;
}
if (type.Name.StartsWith("System.Nullable`1[[System.DateTime")) // return a datetime object
{
return DateTime.Parse(response.Content, null, System.Globalization.DateTimeStyles.RoundtripKind);
}
if (type == typeof(String) || type.Name.StartsWith("System.Nullable")) // return primitive type
{
return ConvertType(response.Content, type);
}
// at this point, it must be a model (json)
try
{
return JsonConvert.DeserializeObject(response.Content, type, serializerSettings);
}
catch (Exception e)
{
throw new ApiException(500, e.Message);
}
}
/// <summary>
/// DocuSign: Deserialize the byte array into a proper object.
/// </summary>
/// <param name="content">Byte Araay (e.g. PDF bytes).</param>
/// <param name="type">Object type.</param>
/// <param name="headers"></param>
/// <returns>Object representation of the JSON string.</returns>
public object Deserialize(byte[] content, Type type, IList<Parameter> headers=null)
{
if (type == typeof(Stream))
{
MemoryStream ms = new MemoryStream(content);
return ms;
}
throw new ApiException(500, "Unhandled response type.");
}
/// <summary>
/// Serialize an input (model) into JSON string
/// </summary>
/// <param name="obj">Object.</param>
/// <returns>JSON string.</returns>
public String Serialize(object obj)
{
try
{
return obj != null ? JsonConvert.SerializeObject(obj) : null;
}
catch (Exception e)
{
throw new ApiException(500, e.Message);
}
}
/// <summary>
/// Select the Content-Type header's value from the given content-type array:
/// if JSON exists in the given array, use it;
/// otherwise use the first one defined in 'consumes'
/// </summary>
/// <param name="contentTypes">The Content-Type array to select from.</param>
/// <returns>The Content-Type header to use.</returns>
public String SelectHeaderContentType(String[] contentTypes)
{
if (contentTypes.Length == 0)
return null;
if (contentTypes.Contains("application/json", StringComparer.OrdinalIgnoreCase))
return "application/json";
return contentTypes[0]; // use the first content type specified in 'consumes'
}
/// <summary>
/// Select the Accept header's value from the given accepts array:
/// if JSON exists in the given array, use it;
/// otherwise use all of them (joining into a string)
/// </summary>
/// <param name="accepts">The accepts array to select from.</param>
/// <returns>The Accept header to use.</returns>
public String SelectHeaderAccept(String[] accepts)
{
if (accepts.Length == 0)
return null;
if (accepts.Contains("application/json", StringComparer.OrdinalIgnoreCase))
return "application/json";
return String.Join(",", accepts);
}
/// <summary>
/// Encode string in base64 format.
/// </summary>
/// <param name="text">String to be encoded.</param>
/// <returns>Encoded string.</returns>
public static string Base64Encode(string text)
{
return System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(text));
}
/// <summary>
/// Dynamically cast the object into target type.
/// Ref: http://stackoverflow.com/questions/4925718/c-dynamic-runtime-cast
/// </summary>
/// <param name="source">Object to be casted</param>
/// <param name="dest">Target type</param>
/// <returns>Casted object</returns>
public static dynamic ConvertType(dynamic source, Type dest)
{
return Convert.ChangeType(source, dest);
}
/// <summary>
/// Convert stream to byte array
/// Credit/Ref: http://stackoverflow.com/a/221941/677735
/// </summary>
/// <param name="input">Input stream to be converted</param>
/// <returns>Byte array</returns>
public static byte[] ReadAsBytes(Stream input)
{
byte[] buffer = new byte[16*1024];
using (MemoryStream ms = new MemoryStream())
{
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
return ms.ToArray();
}
}
/// <summary>
/// URL encode a string
/// Credit/Ref: https://github.com/restsharp/RestSharp/blob/master/RestSharp/Extensions/StringExtensions.cs#L50
/// </summary>
/// <param name="input">String to be URL encoded</param>
/// <returns>Byte array</returns>
public static string UrlEncode(string input)
{
const int maxLength = 32766;
if (input == null)
{
throw new ArgumentNullException("input");
}
if (input.Length <= maxLength)
{
return Uri.EscapeDataString(input);
}
StringBuilder sb = new StringBuilder(input.Length * 2);
int index = 0;
while (index < input.Length)
{
int length = Math.Min(input.Length - index, maxLength);
string subString = input.Substring(index, length);
sb.Append(Uri.EscapeDataString(subString));
index += subString.Length;
}
return sb.ToString();
}
/// <summary>
/// Sanitize filename by removing the path
/// </summary>
/// <param name="filename">Filename</param>
/// <returns>Filename</returns>
public static string SanitizeFilename(string filename)
{
Match match = Regex.Match(filename, @".*[/\\](.*)$");
if (match.Success)
{
return match.Groups[1].Value;
}
else
{
return filename;
}
}
public string GetAuthorizationUri(string clientId, string redirectURI, Boolean isSandbox)
{
return this.GetAuthorizationUri(clientId, redirectURI, isSandbox, null);
}
public string GetAuthorizationUri(string clientId, string redirectURI, Boolean isSandbox, string state)
{
string DocuSignOAuthHost = isSandbox ? "account-d.docusign.com" : "account.docusign.com";
string format = "https://{0}/oauth/auth?response_type=code&scope=all&client_id={1}&redirect_uri={2}";
if (state != null)
{
format += "&state ={3}";
}
return string.Format(format, DocuSignOAuthHost, clientId, redirectURI, state);
}
public string GetOAuthToken(string clientId, string clientSecret, Boolean isSandbox, string accessCode)
{
// The Authentication is completed, so now echange a code returned for
// the access_token and refresh_token.
var webClient = new WebClient();
webClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
// Add the Authorization header with client_id and client_secret as base64
string codeAuth = clientId + ":" + clientSecret;
byte[] codeAuthBytes = Encoding.UTF8.GetBytes(codeAuth);
string codeAuthBase64 = Convert.ToBase64String(codeAuthBytes);
webClient.Headers.Add("Authorization", "Basic " + codeAuthBase64);
// Add the code returned from the authentication site
string tokenGrantAndCode = string.Format("grant_type=authorization_code&code={0}", accessCode);
// Call the token endpoint to exchange the code for an access_token
string DocuSignOAuthHost = isSandbox ? "account-d.docusign.com" : "account.docusign.com";
string tokenEndpoint = string.Format("https://{0}/oauth/token", DocuSignOAuthHost);
string tokenResponse = webClient.UploadString(tokenEndpoint, tokenGrantAndCode);
TokenResponse tokenObj = JsonConvert.DeserializeObject<TokenResponse>(tokenResponse);
// Add the token to this ApiClient
string authHeader = "Bearer " + tokenObj.access_token;
this.Configuration.AddDefaultHeader("Authorization", authHeader);
return tokenObj.access_token;
}
public void ConfigureJwtAuthorizationFlow(string clientId, string userId, string oauthBasePath, string privateKeyFilename, int expiresInHours)
{
JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();
Microsoft.IdentityModel.Tokens.SecurityTokenDescriptor descriptor = new Microsoft.IdentityModel.Tokens.SecurityTokenDescriptor
{
Expires = DateTime.UtcNow.AddHours(expiresInHours),
};
descriptor.Subject = new ClaimsIdentity();
descriptor.Subject.AddClaim(new Claim("scope", "signature"));
descriptor.Subject.AddClaim(new Claim("aud", oauthBasePath));
descriptor.Subject.AddClaim(new Claim("iss", clientId));
if (userId != null)
{
descriptor.Subject.AddClaim(new Claim("sub", userId));
}
if (privateKeyFilename != null)
{
string pemKey = File.ReadAllText(privateKeyFilename);
var rsa = CreateRSAKeyFromPem(pemKey);
Microsoft.IdentityModel.Tokens.RsaSecurityKey rsaKey = new Microsoft.IdentityModel.Tokens.RsaSecurityKey(rsa);
descriptor.SigningCredentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(rsaKey, SecurityAlgorithms.RsaSha256Signature);
}
var token = handler.CreateToken(descriptor);
string jwtToken = handler.WriteToken(token);
Uri baseUrl = this.RestClient.BaseUrl;
this.RestClient.BaseUrl = new Uri(string.Format("https://{0}", oauthBasePath));
string path = "oauth/token";
string contentType = "application/x-www-form-urlencoded";
Dictionary<string, string> formParams = new Dictionary<string, string>();
formParams.Add("grant_type", "urn:ietf:params:oauth:grant-type:jwt-bearer");
formParams.Add("assertion", jwtToken);
Dictionary<string, string> queryParams = new Dictionary<string, string>();
Dictionary<string, string> headerParams = new Dictionary<string, string>();
headerParams.Add("Content-Type", "application/x-www-form-urlencoded");
Dictionary<string, FileParameter> fileParams = new Dictionary<string, FileParameter>();
Dictionary<string, string> pathParams = new Dictionary<string, string>();
object postBody = null;
try
{
var response = CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, contentType);
TokenResponse tokenInfo = JsonConvert.DeserializeObject<TokenResponse>(((RestResponse)response).Content);
var config = Configuration.Default;
config.AddDefaultHeader("Authorization", string.Format("{0} {1}", tokenInfo.token_type, tokenInfo.access_token));
}
catch (Exception ex)
{
}
this.RestClient.BaseUrl = baseUrl;
}
private static RSA CreateRSAKeyFromPem(string key)
{
TextReader reader = new StringReader(key);
PemReader pemReader = new PemReader(reader);
object result = pemReader.ReadObject();
if (result is AsymmetricCipherKeyPair)
{
AsymmetricCipherKeyPair keyPair = (AsymmetricCipherKeyPair)result;
return DotNetUtilities.ToRSA((RsaPrivateCrtKeyParameters)keyPair.Private);
}
else if (result is RsaKeyParameters)
{
RsaKeyParameters keyParameters = (RsaKeyParameters)result;
return DotNetUtilities.ToRSA(keyParameters);
}
throw new Exception("Unepxected PEM type");
}
}
// response object from the OAuth token endpoint. This is used
// to obtain access_tokens for making API calls and refresh_tokens for getting a new
// access token after a token expires.
public class TokenResponse
{
public string access_token { get; set; }
public string token_type { get; set; }
public string refresh_token { get; set; }
public int? expires_in { 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.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
//
//
// Implementation of task continuations, TaskContinuation, and its descendants.
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Security;
using System.Diagnostics;
using System.Runtime.ExceptionServices;
using System.Runtime.CompilerServices;
using System.Threading;
#if FEATURE_COMINTEROP
using System.Runtime.InteropServices.WindowsRuntime;
#endif // FEATURE_COMINTEROP
namespace System.Threading.Tasks
{
// Task type used to implement: Task ContinueWith(Action<Task,...>)
internal sealed class ContinuationTaskFromTask : Task
{
private Task m_antecedent;
public ContinuationTaskFromTask(
Task antecedent, Delegate action, object state, TaskCreationOptions creationOptions, InternalTaskOptions internalOptions) :
base(action, state, Task.InternalCurrentIfAttached(creationOptions), default(CancellationToken), creationOptions, internalOptions, null)
{
Debug.Assert(action is Action<Task> || action is Action<Task, object>,
"Invalid delegate type in ContinuationTaskFromTask");
m_antecedent = antecedent;
}
/// <summary>
/// Evaluates the value selector of the Task which is passed in as an object and stores the result.
/// </summary>
internal override void InnerInvoke()
{
// Get and null out the antecedent. This is crucial to avoid a memory
// leak with long chains of continuations.
var antecedent = m_antecedent;
Debug.Assert(antecedent != null,
"No antecedent was set for the ContinuationTaskFromTask.");
m_antecedent = null;
// Notify the debugger we're completing an asynchronous wait on a task
antecedent.NotifyDebuggerOfWaitCompletionIfNecessary();
// Invoke the delegate
Debug.Assert(m_action != null);
var action = m_action as Action<Task>;
if (action != null)
{
action(antecedent);
return;
}
var actionWithState = m_action as Action<Task, object>;
if (actionWithState != null)
{
actionWithState(antecedent, m_stateObject);
return;
}
Debug.Fail("Invalid m_action in ContinuationTaskFromTask");
}
}
// Task type used to implement: Task<TResult> ContinueWith(Func<Task,...>)
internal sealed class ContinuationResultTaskFromTask<TResult> : Task<TResult>
{
private Task m_antecedent;
public ContinuationResultTaskFromTask(
Task antecedent, Delegate function, object state, TaskCreationOptions creationOptions, InternalTaskOptions internalOptions) :
base(function, state, Task.InternalCurrentIfAttached(creationOptions), default(CancellationToken), creationOptions, internalOptions, null)
{
Debug.Assert(function is Func<Task, TResult> || function is Func<Task, object, TResult>,
"Invalid delegate type in ContinuationResultTaskFromTask");
m_antecedent = antecedent;
}
/// <summary>
/// Evaluates the value selector of the Task which is passed in as an object and stores the result.
/// </summary>
internal override void InnerInvoke()
{
// Get and null out the antecedent. This is crucial to avoid a memory
// leak with long chains of continuations.
var antecedent = m_antecedent;
Debug.Assert(antecedent != null,
"No antecedent was set for the ContinuationResultTaskFromTask.");
m_antecedent = null;
// Notify the debugger we're completing an asynchronous wait on a task
antecedent.NotifyDebuggerOfWaitCompletionIfNecessary();
// Invoke the delegate
Debug.Assert(m_action != null);
var func = m_action as Func<Task, TResult>;
if (func != null)
{
m_result = func(antecedent);
return;
}
var funcWithState = m_action as Func<Task, object, TResult>;
if (funcWithState != null)
{
m_result = funcWithState(antecedent, m_stateObject);
return;
}
Debug.Fail("Invalid m_action in ContinuationResultTaskFromTask");
}
}
// Task type used to implement: Task ContinueWith(Action<Task<TAntecedentResult>,...>)
internal sealed class ContinuationTaskFromResultTask<TAntecedentResult> : Task
{
private Task<TAntecedentResult> m_antecedent;
public ContinuationTaskFromResultTask(
Task<TAntecedentResult> antecedent, Delegate action, object state, TaskCreationOptions creationOptions, InternalTaskOptions internalOptions) :
base(action, state, Task.InternalCurrentIfAttached(creationOptions), default(CancellationToken), creationOptions, internalOptions, null)
{
Debug.Assert(action is Action<Task<TAntecedentResult>> || action is Action<Task<TAntecedentResult>, object>,
"Invalid delegate type in ContinuationTaskFromResultTask");
m_antecedent = antecedent;
}
/// <summary>
/// Evaluates the value selector of the Task which is passed in as an object and stores the result.
/// </summary>
internal override void InnerInvoke()
{
// Get and null out the antecedent. This is crucial to avoid a memory
// leak with long chains of continuations.
var antecedent = m_antecedent;
Debug.Assert(antecedent != null,
"No antecedent was set for the ContinuationTaskFromResultTask.");
m_antecedent = null;
// Notify the debugger we're completing an asynchronous wait on a task
antecedent.NotifyDebuggerOfWaitCompletionIfNecessary();
// Invoke the delegate
Debug.Assert(m_action != null);
var action = m_action as Action<Task<TAntecedentResult>>;
if (action != null)
{
action(antecedent);
return;
}
var actionWithState = m_action as Action<Task<TAntecedentResult>, object>;
if (actionWithState != null)
{
actionWithState(antecedent, m_stateObject);
return;
}
Debug.Fail("Invalid m_action in ContinuationTaskFromResultTask");
}
}
// Task type used to implement: Task<TResult> ContinueWith(Func<Task<TAntecedentResult>,...>)
internal sealed class ContinuationResultTaskFromResultTask<TAntecedentResult, TResult> : Task<TResult>
{
private Task<TAntecedentResult> m_antecedent;
public ContinuationResultTaskFromResultTask(
Task<TAntecedentResult> antecedent, Delegate function, object state, TaskCreationOptions creationOptions, InternalTaskOptions internalOptions) :
base(function, state, Task.InternalCurrentIfAttached(creationOptions), default(CancellationToken), creationOptions, internalOptions, null)
{
Debug.Assert(function is Func<Task<TAntecedentResult>, TResult> || function is Func<Task<TAntecedentResult>, object, TResult>,
"Invalid delegate type in ContinuationResultTaskFromResultTask");
m_antecedent = antecedent;
}
/// <summary>
/// Evaluates the value selector of the Task which is passed in as an object and stores the result.
/// </summary>
internal override void InnerInvoke()
{
// Get and null out the antecedent. This is crucial to avoid a memory
// leak with long chains of continuations.
var antecedent = m_antecedent;
Debug.Assert(antecedent != null,
"No antecedent was set for the ContinuationResultTaskFromResultTask.");
m_antecedent = null;
// Notify the debugger we're completing an asynchronous wait on a task
antecedent.NotifyDebuggerOfWaitCompletionIfNecessary();
// Invoke the delegate
Debug.Assert(m_action != null);
var func = m_action as Func<Task<TAntecedentResult>, TResult>;
if (func != null)
{
m_result = func(antecedent);
return;
}
var funcWithState = m_action as Func<Task<TAntecedentResult>, object, TResult>;
if (funcWithState != null)
{
m_result = funcWithState(antecedent, m_stateObject);
return;
}
Debug.Fail("Invalid m_action in ContinuationResultTaskFromResultTask");
}
}
// For performance reasons, we don't just have a single way of representing
// a continuation object. Rather, we have a hierarchy of types:
// - TaskContinuation: abstract base that provides a virtual Run method
// - StandardTaskContinuation: wraps a task,options,and scheduler, and overrides Run to process the task with that configuration
// - AwaitTaskContinuation: base for continuations created through TaskAwaiter; targets default scheduler by default
// - TaskSchedulerAwaitTaskContinuation: awaiting with a non-default TaskScheduler
// - SynchronizationContextAwaitTaskContinuation: awaiting with a "current" sync ctx
/// <summary>Represents a continuation.</summary>
internal abstract class TaskContinuation
{
/// <summary>Inlines or schedules the continuation.</summary>
/// <param name="completedTask">The antecedent task that has completed.</param>
/// <param name="canInlineContinuationTask">true if inlining is permitted; otherwise, false.</param>
internal abstract void Run(Task completedTask, bool bCanInlineContinuationTask);
/// <summary>Tries to run the task on the current thread, if possible; otherwise, schedules it.</summary>
/// <param name="task">The task to run</param>
/// <param name="needsProtection">
/// true if we need to protect against multiple threads racing to start/cancel the task; otherwise, false.
/// </param>
protected static void InlineIfPossibleOrElseQueue(Task task, bool needsProtection)
{
Debug.Assert(task != null);
Debug.Assert(task.m_taskScheduler != null);
// Set the TASK_STATE_STARTED flag. This only needs to be done
// if the task may be canceled or if someone else has a reference to it
// that may try to execute it.
if (needsProtection)
{
if (!task.MarkStarted())
return; // task has been previously started or canceled. Stop processing.
}
else
{
task.m_stateFlags |= Task.TASK_STATE_STARTED;
}
// Try to inline it but queue if we can't
try
{
if (!task.m_taskScheduler.TryRunInline(task, taskWasPreviouslyQueued: false))
{
task.m_taskScheduler.InternalQueueTask(task);
}
}
catch (Exception e)
{
// Either TryRunInline() or QueueTask() threw an exception. Record the exception, marking the task as Faulted.
// However if it was a ThreadAbortException coming from TryRunInline we need to skip here,
// because it would already have been handled in Task.Execute()
if (!(e is ThreadAbortException &&
(task.m_stateFlags & Task.TASK_STATE_THREAD_WAS_ABORTED) != 0)) // this ensures TAEs from QueueTask will be wrapped in TSE
{
TaskSchedulerException tse = new TaskSchedulerException(e);
task.AddException(tse);
task.Finish(false);
}
// Don't re-throw.
}
}
internal abstract Delegate[] GetDelegateContinuationsForDebugger();
}
/// <summary>Provides the standard implementation of a task continuation.</summary>
internal class StandardTaskContinuation : TaskContinuation
{
/// <summary>The unstarted continuation task.</summary>
internal readonly Task m_task;
/// <summary>The options to use with the continuation task.</summary>
internal readonly TaskContinuationOptions m_options;
/// <summary>The task scheduler with which to run the continuation task.</summary>
private readonly TaskScheduler m_taskScheduler;
/// <summary>Initializes a new continuation.</summary>
/// <param name="task">The task to be activated.</param>
/// <param name="options">The continuation options.</param>
/// <param name="scheduler">The scheduler to use for the continuation.</param>
internal StandardTaskContinuation(Task task, TaskContinuationOptions options, TaskScheduler scheduler)
{
Debug.Assert(task != null, "TaskContinuation ctor: task is null");
Debug.Assert(scheduler != null, "TaskContinuation ctor: scheduler is null");
m_task = task;
m_options = options;
m_taskScheduler = scheduler;
if (AsyncCausalityTracer.LoggingOn)
AsyncCausalityTracer.TraceOperationCreation(CausalityTraceLevel.Required, m_task.Id, "Task.ContinueWith: " + task.m_action.Method.Name, 0);
if (Task.s_asyncDebuggingEnabled)
{
Task.AddToActiveTasks(m_task);
}
}
/// <summary>Invokes the continuation for the target completion task.</summary>
/// <param name="completedTask">The completed task.</param>
/// <param name="bCanInlineContinuationTask">Whether the continuation can be inlined.</param>
internal override void Run(Task completedTask, bool bCanInlineContinuationTask)
{
Debug.Assert(completedTask != null);
Debug.Assert(completedTask.IsCompleted, "ContinuationTask.Run(): completedTask not completed");
// Check if the completion status of the task works with the desired
// activation criteria of the TaskContinuationOptions.
TaskContinuationOptions options = m_options;
bool isRightKind =
completedTask.IsCompletedSuccessfully ?
(options & TaskContinuationOptions.NotOnRanToCompletion) == 0 :
(completedTask.IsCanceled ?
(options & TaskContinuationOptions.NotOnCanceled) == 0 :
(options & TaskContinuationOptions.NotOnFaulted) == 0);
// If the completion status is allowed, run the continuation.
Task continuationTask = m_task;
if (isRightKind)
{
//If the task was cancel before running (e.g a ContinueWhenAll with a cancelled caancelation token)
//we will still flow it to ScheduleAndStart() were it will check the status before running
//We check here to avoid faulty logs that contain a join event to an operation that was already set as completed.
if (!continuationTask.IsCanceled && AsyncCausalityTracer.LoggingOn)
{
// Log now that we are sure that this continuation is being ran
AsyncCausalityTracer.TraceOperationRelation(CausalityTraceLevel.Important, continuationTask.Id, CausalityRelation.AssignDelegate);
}
continuationTask.m_taskScheduler = m_taskScheduler;
// Either run directly or just queue it up for execution, depending
// on whether synchronous or asynchronous execution is wanted.
if (bCanInlineContinuationTask && // inlining is allowed by the caller
(options & TaskContinuationOptions.ExecuteSynchronously) != 0) // synchronous execution was requested by the continuation's creator
{
InlineIfPossibleOrElseQueue(continuationTask, needsProtection: true);
}
else
{
try { continuationTask.ScheduleAndStart(needsProtection: true); }
catch (TaskSchedulerException)
{
// No further action is necessary -- ScheduleAndStart() already transitioned the
// task to faulted. But we want to make sure that no exception is thrown from here.
}
}
}
// Otherwise, the final state of this task does not match the desired
// continuation activation criteria; cancel it to denote this.
else continuationTask.InternalCancel(false);
}
internal override Delegate[] GetDelegateContinuationsForDebugger()
{
if (m_task.m_action == null)
{
return m_task.GetDelegateContinuationsForDebugger();
}
return new Delegate[] { m_task.m_action };
}
}
/// <summary>Task continuation for awaiting with a current synchronization context.</summary>
internal sealed class SynchronizationContextAwaitTaskContinuation : AwaitTaskContinuation
{
/// <summary>SendOrPostCallback delegate to invoke the action.</summary>
private readonly static SendOrPostCallback s_postCallback = state => ((Action)state)(); // can't use InvokeAction as it's SecurityCritical
/// <summary>Cached delegate for PostAction</summary>
private static ContextCallback s_postActionCallback;
/// <summary>The context with which to run the action.</summary>
private readonly SynchronizationContext m_syncContext;
/// <summary>Initializes the SynchronizationContextAwaitTaskContinuation.</summary>
/// <param name="context">The synchronization context with which to invoke the action. Must not be null.</param>
/// <param name="action">The action to invoke. Must not be null.</param>
/// <param name="flowExecutionContext">Whether to capture and restore ExecutionContext.</param>
internal SynchronizationContextAwaitTaskContinuation(
SynchronizationContext context, Action action, bool flowExecutionContext) :
base(action, flowExecutionContext)
{
Debug.Assert(context != null);
m_syncContext = context;
}
/// <summary>Inlines or schedules the continuation.</summary>
/// <param name="ignored">The antecedent task, which is ignored.</param>
/// <param name="canInlineContinuationTask">true if inlining is permitted; otherwise, false.</param>
internal sealed override void Run(Task task, bool canInlineContinuationTask)
{
// If we're allowed to inline, run the action on this thread.
if (canInlineContinuationTask &&
m_syncContext == SynchronizationContext.Current)
{
RunCallback(GetInvokeActionCallback(), m_action, ref Task.t_currentTask);
}
// Otherwise, Post the action back to the SynchronizationContext.
else
{
TplEtwProvider etwLog = TplEtwProvider.Log;
if (etwLog.IsEnabled())
{
m_continuationId = Task.NewId();
etwLog.AwaitTaskContinuationScheduled((task.ExecutingTaskScheduler ?? TaskScheduler.Default).Id, task.Id, m_continuationId);
}
RunCallback(GetPostActionCallback(), this, ref Task.t_currentTask);
}
// Any exceptions will be handled by RunCallback.
}
/// <summary>Calls InvokeOrPostAction(false) on the supplied SynchronizationContextAwaitTaskContinuation.</summary>
/// <param name="state">The SynchronizationContextAwaitTaskContinuation.</param>
private static void PostAction(object state)
{
var c = (SynchronizationContextAwaitTaskContinuation)state;
TplEtwProvider etwLog = TplEtwProvider.Log;
if (etwLog.TasksSetActivityIds && c.m_continuationId != 0)
{
c.m_syncContext.Post(s_postCallback, GetActionLogDelegate(c.m_continuationId, c.m_action));
}
else
{
c.m_syncContext.Post(s_postCallback, c.m_action); // s_postCallback is manually cached, as the compiler won't in a SecurityCritical method
}
}
private static Action GetActionLogDelegate(int continuationId, Action action)
{
return () =>
{
Guid savedActivityId;
Guid activityId = TplEtwProvider.CreateGuidForTaskID(continuationId);
System.Diagnostics.Tracing.EventSource.SetCurrentThreadActivityId(activityId, out savedActivityId);
try { action(); }
finally { System.Diagnostics.Tracing.EventSource.SetCurrentThreadActivityId(savedActivityId); }
};
}
/// <summary>Gets a cached delegate for the PostAction method.</summary>
/// <returns>
/// A delegate for PostAction, which expects a SynchronizationContextAwaitTaskContinuation
/// to be passed as state.
/// </returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static ContextCallback GetPostActionCallback()
{
ContextCallback callback = s_postActionCallback;
if (callback == null) { s_postActionCallback = callback = PostAction; } // lazily initialize SecurityCritical delegate
return callback;
}
}
/// <summary>Task continuation for awaiting with a task scheduler.</summary>
internal sealed class TaskSchedulerAwaitTaskContinuation : AwaitTaskContinuation
{
/// <summary>The scheduler on which to run the action.</summary>
private readonly TaskScheduler m_scheduler;
/// <summary>Initializes the TaskSchedulerAwaitTaskContinuation.</summary>
/// <param name="scheduler">The task scheduler with which to invoke the action. Must not be null.</param>
/// <param name="action">The action to invoke. Must not be null.</param>
/// <param name="flowExecutionContext">Whether to capture and restore ExecutionContext.</param>
internal TaskSchedulerAwaitTaskContinuation(
TaskScheduler scheduler, Action action, bool flowExecutionContext) :
base(action, flowExecutionContext)
{
Debug.Assert(scheduler != null);
m_scheduler = scheduler;
}
/// <summary>Inlines or schedules the continuation.</summary>
/// <param name="ignored">The antecedent task, which is ignored.</param>
/// <param name="canInlineContinuationTask">true if inlining is permitted; otherwise, false.</param>
internal sealed override void Run(Task ignored, bool canInlineContinuationTask)
{
// If we're targeting the default scheduler, we can use the faster path provided by the base class.
if (m_scheduler == TaskScheduler.Default)
{
base.Run(ignored, canInlineContinuationTask);
}
else
{
// We permit inlining if the caller allows us to, and
// either we're on a thread pool thread (in which case we're fine running arbitrary code)
// or we're already on the target scheduler (in which case we'll just ask the scheduler
// whether it's ok to run here). We include the IsThreadPoolThread check here, whereas
// we don't in AwaitTaskContinuation.Run, since here it expands what's allowed as opposed
// to in AwaitTaskContinuation.Run where it restricts what's allowed.
bool inlineIfPossible = canInlineContinuationTask &&
(TaskScheduler.InternalCurrent == m_scheduler || Thread.CurrentThread.IsThreadPoolThread);
// Create the continuation task task. If we're allowed to inline, try to do so.
// The target scheduler may still deny us from executing on this thread, in which case this'll be queued.
var task = CreateTask(state =>
{
try { ((Action)state)(); }
catch (Exception exc) { ThrowAsyncIfNecessary(exc); }
}, m_action, m_scheduler);
if (inlineIfPossible)
{
InlineIfPossibleOrElseQueue(task, needsProtection: false);
}
else
{
// We need to run asynchronously, so just schedule the task.
try { task.ScheduleAndStart(needsProtection: false); }
catch (TaskSchedulerException) { } // No further action is necessary, as ScheduleAndStart already transitioned task to faulted
}
}
}
}
/// <summary>Base task continuation class used for await continuations.</summary>
internal class AwaitTaskContinuation : TaskContinuation, IThreadPoolWorkItem
{
/// <summary>The ExecutionContext with which to run the continuation.</summary>
private readonly ExecutionContext m_capturedContext;
/// <summary>The action to invoke.</summary>
protected readonly Action m_action;
protected int m_continuationId;
/// <summary>Initializes the continuation.</summary>
/// <param name="action">The action to invoke. Must not be null.</param>
/// <param name="flowExecutionContext">Whether to capture and restore ExecutionContext.</param>
internal AwaitTaskContinuation(Action action, bool flowExecutionContext)
{
Debug.Assert(action != null);
m_action = action;
if (flowExecutionContext)
{
m_capturedContext = ExecutionContext.Capture();
}
}
/// <summary>Creates a task to run the action with the specified state on the specified scheduler.</summary>
/// <param name="action">The action to run. Must not be null.</param>
/// <param name="state">The state to pass to the action. Must not be null.</param>
/// <param name="scheduler">The scheduler to target.</param>
/// <returns>The created task.</returns>
protected Task CreateTask(Action<object> action, object state, TaskScheduler scheduler)
{
Debug.Assert(action != null);
Debug.Assert(scheduler != null);
return new Task(
action, state, null, default(CancellationToken),
TaskCreationOptions.None, InternalTaskOptions.QueuedByRuntime, scheduler)
{
CapturedContext = m_capturedContext
};
}
/// <summary>Inlines or schedules the continuation onto the default scheduler.</summary>
/// <param name="ignored">The antecedent task, which is ignored.</param>
/// <param name="canInlineContinuationTask">true if inlining is permitted; otherwise, false.</param>
internal override void Run(Task task, bool canInlineContinuationTask)
{
// For the base AwaitTaskContinuation, we allow inlining if our caller allows it
// and if we're in a "valid location" for it. See the comments on
// IsValidLocationForInlining for more about what's valid. For performance
// reasons we would like to always inline, but we don't in some cases to avoid
// running arbitrary amounts of work in suspected "bad locations", like UI threads.
if (canInlineContinuationTask && IsValidLocationForInlining)
{
RunCallback(GetInvokeActionCallback(), m_action, ref Task.t_currentTask); // any exceptions from m_action will be handled by s_callbackRunAction
}
else
{
TplEtwProvider etwLog = TplEtwProvider.Log;
if (etwLog.IsEnabled())
{
m_continuationId = Task.NewId();
etwLog.AwaitTaskContinuationScheduled((task.ExecutingTaskScheduler ?? TaskScheduler.Default).Id, task.Id, m_continuationId);
}
// We couldn't inline, so now we need to schedule it
ThreadPool.UnsafeQueueCustomWorkItem(this, forceGlobal: false);
}
}
/// <summary>
/// Gets whether the current thread is an appropriate location to inline a continuation's execution.
/// </summary>
/// <remarks>
/// Returns whether SynchronizationContext is null and we're in the default scheduler.
/// If the await had a SynchronizationContext/TaskScheduler where it began and the
/// default/ConfigureAwait(true) was used, then we won't be on this path. If, however,
/// ConfigureAwait(false) was used, or the SynchronizationContext and TaskScheduler were
/// naturally null/Default, then we might end up here. If we do, we need to make sure
/// that we don't execute continuations in a place that isn't set up to handle them, e.g.
/// running arbitrary amounts of code on the UI thread. It would be "correct", but very
/// expensive, to always run the continuations asynchronously, incurring lots of context
/// switches and allocations and locks and the like. As such, we employ the heuristic
/// that if the current thread has a non-null SynchronizationContext or a non-default
/// scheduler, then we better not run arbitrary continuations here.
/// </remarks>
internal static bool IsValidLocationForInlining
{
get
{
// If there's a SynchronizationContext, we'll be conservative and say
// this is a bad location to inline.
var ctx = SynchronizationContext.Current;
if (ctx != null && ctx.GetType() != typeof(SynchronizationContext)) return false;
// Similarly, if there's a non-default TaskScheduler, we'll be conservative
// and say this is a bad location to inline.
var sched = TaskScheduler.InternalCurrent;
return sched == null || sched == TaskScheduler.Default;
}
}
/// <summary>IThreadPoolWorkItem override, which is the entry function for this when the ThreadPool scheduler decides to run it.</summary>
private void ExecuteWorkItemHelper()
{
var etwLog = TplEtwProvider.Log;
Guid savedActivityId = Guid.Empty;
if (etwLog.TasksSetActivityIds && m_continuationId != 0)
{
Guid activityId = TplEtwProvider.CreateGuidForTaskID(m_continuationId);
System.Diagnostics.Tracing.EventSource.SetCurrentThreadActivityId(activityId, out savedActivityId);
}
try
{
// We're not inside of a task, so t_currentTask doesn't need to be specially maintained.
// We're on a thread pool thread with no higher-level callers, so exceptions can just propagate.
// If there's no execution context, just invoke the delegate.
ExecutionContext context = m_capturedContext;
if (context == null)
{
m_action();
}
// If there is an execution context, get the cached delegate and run the action under the context.
else
{
ExecutionContext.RunInternal(context, GetInvokeActionCallback(), m_action);
}
}
finally
{
if (etwLog.TasksSetActivityIds && m_continuationId != 0)
{
System.Diagnostics.Tracing.EventSource.SetCurrentThreadActivityId(savedActivityId);
}
}
}
void IThreadPoolWorkItem.ExecuteWorkItem()
{
// inline the fast path
if (m_capturedContext == null && !TplEtwProvider.Log.IsEnabled())
{
m_action();
}
else
{
ExecuteWorkItemHelper();
}
}
/// <summary>
/// The ThreadPool calls this if a ThreadAbortException is thrown while trying to execute this workitem.
/// </summary>
void IThreadPoolWorkItem.MarkAborted(ThreadAbortException tae) { /* nop */ }
/// <summary>Cached delegate that invokes an Action passed as an object parameter.</summary>
private static ContextCallback s_invokeActionCallback;
/// <summary>Runs an action provided as an object parameter.</summary>
/// <param name="state">The Action to invoke.</param>
private static void InvokeAction(object state) { ((Action)state)(); }
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected static ContextCallback GetInvokeActionCallback()
{
ContextCallback callback = s_invokeActionCallback;
if (callback == null) { s_invokeActionCallback = callback = InvokeAction; } // lazily initialize SecurityCritical delegate
return callback;
}
/// <summary>Runs the callback synchronously with the provided state.</summary>
/// <param name="callback">The callback to run.</param>
/// <param name="state">The state to pass to the callback.</param>
/// <param name="currentTask">A reference to Task.t_currentTask.</param>
protected void RunCallback(ContextCallback callback, object state, ref Task currentTask)
{
Debug.Assert(callback != null);
Debug.Assert(currentTask == Task.t_currentTask);
// Pretend there's no current task, so that no task is seen as a parent
// and TaskScheduler.Current does not reflect false information
var prevCurrentTask = currentTask;
try
{
if (prevCurrentTask != null) currentTask = null;
ExecutionContext context = m_capturedContext;
if (context == null)
{
// If there's no captured context, just run the callback directly.
callback(state);
}
else
{
// Otherwise, use the captured context to do so.
ExecutionContext.RunInternal(context, callback, state);
}
}
catch (Exception exc) // we explicitly do not request handling of dangerous exceptions like AVs
{
ThrowAsyncIfNecessary(exc);
}
finally
{
// Restore the current task information
if (prevCurrentTask != null) currentTask = prevCurrentTask;
}
}
/// <summary>Invokes or schedules the action to be executed.</summary>
/// <param name="action">The action to invoke or queue.</param>
/// <param name="allowInlining">
/// true to allow inlining, or false to force the action to run asynchronously.
/// </param>
/// <param name="currentTask">
/// A reference to the t_currentTask thread static value.
/// This is passed by-ref rather than accessed in the method in order to avoid
/// unnecessary thread-static writes.
/// </param>
/// <remarks>
/// No ExecutionContext work is performed used. This method is only used in the
/// case where a raw Action continuation delegate was stored into the Task, which
/// only happens in Task.SetContinuationForAwait if execution context flow was disabled
/// via using TaskAwaiter.UnsafeOnCompleted or a similar path.
/// </remarks>
internal static void RunOrScheduleAction(Action action, bool allowInlining, ref Task currentTask)
{
Debug.Assert(currentTask == Task.t_currentTask);
// If we're not allowed to run here, schedule the action
if (!allowInlining || !IsValidLocationForInlining)
{
UnsafeScheduleAction(action, currentTask);
return;
}
// Otherwise, run it, making sure that t_currentTask is null'd out appropriately during the execution
Task prevCurrentTask = currentTask;
try
{
if (prevCurrentTask != null) currentTask = null;
action();
}
catch (Exception exception)
{
ThrowAsyncIfNecessary(exception);
}
finally
{
if (prevCurrentTask != null) currentTask = prevCurrentTask;
}
}
/// <summary>Schedules the action to be executed. No ExecutionContext work is performed used.</summary>
/// <param name="action">The action to invoke or queue.</param>
internal static void UnsafeScheduleAction(Action action, Task task)
{
AwaitTaskContinuation atc = new AwaitTaskContinuation(action, flowExecutionContext: false);
var etwLog = TplEtwProvider.Log;
if (etwLog.IsEnabled() && task != null)
{
atc.m_continuationId = Task.NewId();
etwLog.AwaitTaskContinuationScheduled((task.ExecutingTaskScheduler ?? TaskScheduler.Default).Id, task.Id, atc.m_continuationId);
}
ThreadPool.UnsafeQueueCustomWorkItem(atc, forceGlobal: false);
}
/// <summary>Throws the exception asynchronously on the ThreadPool.</summary>
/// <param name="exc">The exception to throw.</param>
protected static void ThrowAsyncIfNecessary(Exception exc)
{
// Awaits should never experience an exception (other than an TAE or ADUE),
// unless a malicious user is explicitly passing a throwing action into the TaskAwaiter.
// We don't want to allow the exception to propagate on this stack, as it'll emerge in random places,
// and we can't fail fast, as that would allow for elevation of privilege.
//
// If unhandled error reporting APIs are available use those, otherwise since this
// would have executed on the thread pool otherwise, let it propagate there.
if (!(exc is ThreadAbortException || exc is AppDomainUnloadedException))
{
#if FEATURE_COMINTEROP
if (!WindowsRuntimeMarshal.ReportUnhandledError(exc))
#endif // FEATURE_COMINTEROP
{
var edi = ExceptionDispatchInfo.Capture(exc);
ThreadPool.QueueUserWorkItem(s => ((ExceptionDispatchInfo)s).Throw(), edi);
}
}
}
internal override Delegate[] GetDelegateContinuationsForDebugger()
{
Debug.Assert(m_action != null);
return new Delegate[] { AsyncMethodBuilderCore.TryGetStateMachineForDebugger(m_action) };
}
}
}
| |
// ****************************************************************
// Copyright 2008, Charlie Poole
// This is free software licensed under the NUnit license. You may
// obtain a copy of the license at http://nunit.org
// ****************************************************************
using System;
using NUnit.Framework;
using NUnit.Util;
using NUnit.TestData;
using NUnit.TestUtilities;
using System.Collections;
namespace NUnit.Core.Tests
{
[TestFixture]
public class TestCaseAttributeTests
{
[TestCase(12, 3, 4)]
[TestCase(12, 2, 6)]
[TestCase(12, 4, 3)]
[TestCase(12, 0, 0, ExpectedException = typeof(System.DivideByZeroException))]
[TestCase(12, 0, 0, ExpectedExceptionName = "System.DivideByZeroException")]
public void IntegerDivisionWithResultPassedToTest(int n, int d, int q)
{
Assert.AreEqual(q, n / d);
}
[TestCase(12, 3, Result = 4)]
[TestCase(12, 2, Result = 6)]
[TestCase(12, 4, Result = 3)]
[TestCase(12, 0, ExpectedException = typeof(System.DivideByZeroException))]
[TestCase(12, 0, ExpectedExceptionName = "System.DivideByZeroException",
TestName = "DivisionByZeroThrowsException")]
public int IntegerDivisionWithResultCheckedByNUnit(int n, int d)
{
return n / d;
}
[TestCase(2, 2, Result=4)]
public double CanConvertIntToDouble(double x, double y)
{
return x + y;
}
[TestCase("2.2", "3.3", Result = 5.5)]
public decimal CanConvertStringToDecimal(decimal x, decimal y)
{
return x + y;
}
[TestCase(2.2, 3.3, Result = 5.5)]
public decimal CanConvertDoubleToDecimal(decimal x, decimal y)
{
return x + y;
}
[TestCase(5, 2, Result = 7)]
public decimal CanConvertIntToDecimal(decimal x, decimal y)
{
return x + y;
}
[TestCase(5, 2, Result = 7)]
public short CanConvertSmallIntsToShort(short x, short y)
{
return (short)(x + y);
}
[TestCase(5, 2, Result = 7)]
public byte CanConvertSmallIntsToByte(byte x, byte y)
{
return (byte)(x + y);
}
[TestCase(5, 2, Result = 7)]
public sbyte CanConvertSmallIntsToSByte(sbyte x, sbyte y)
{
return (sbyte)(x + y);
}
#if CLR_2_0 || CLR_4_0
[TestCase(Result = null)]
public object ExpectedResultCanBeNull()
{
return null;
}
#endif
[Test]
public void ConversionOverflowMakesTestNonRunnable()
{
Test test = (Test)TestBuilder.MakeTestCase(
typeof(TestCaseAttributeFixture), "MethodCausesConversionOverflow").Tests[0];
Assert.AreEqual(RunState.NotRunnable, test.RunState);
}
[TestCase("ABCD\u0019"), Explicit("For display purposes only")]
public void UnicodeCharInStringArgument(string arg)
{
}
[TestCase("12-October-1942")]
public void CanConvertStringToDateTime(DateTime dt)
{
Assert.AreEqual(1942, dt.Year);
}
[TestCase(42, ExpectedException = typeof(System.Exception),
ExpectedMessage = "Test Exception")]
public void CanSpecifyExceptionMessage(int a)
{
throw new System.Exception("Test Exception");
}
[TestCase(42, ExpectedException = typeof(System.Exception),
ExpectedMessage = "Test Exception",
MatchType=MessageMatch.StartsWith)]
public void CanSpecifyExceptionMessageAndMatchType(int a)
{
throw new System.Exception("Test Exception thrown here");
}
#if CLR_2_0 || CLR_4_0
[TestCase(null, null)]
public void CanPassNullAsArgument(object a, string b)
{
Assert.IsNull(a);
Assert.IsNull(b);
}
[TestCase(null)]
public void CanPassNullAsSoleArgument(object a)
{
Assert.IsNull(a);
}
#endif
[TestCase(new object[] { 1, "two", 3.0 })]
[TestCase(new object[] { "zip" })]
public void CanPassObjectArrayAsFirstArgument(object[] a)
{
}
[TestCase(new object[] { "a", "b" })]
public void CanPassArrayAsArgument(object[] array)
{
Assert.AreEqual("a", array[0]);
Assert.AreEqual("b", array[1]);
}
[TestCase("a", "b")]
public void ArgumentsAreCoalescedInObjectArray(object[] array)
{
Assert.AreEqual("a", array[0]);
Assert.AreEqual("b", array[1]);
}
[TestCase(1, "b")]
public void ArgumentsOfDifferentTypeAreCoalescedInObjectArray(object[] array)
{
Assert.AreEqual(1, array[0]);
Assert.AreEqual("b", array[1]);
}
[TestCase("a", "b")]
public void HandlesParamsArrayAsSoleArgument(params string[] array)
{
Assert.AreEqual("a", array[0]);
Assert.AreEqual("b", array[1]);
}
[TestCase("a")]
public void HandlesParamsArrayWithOneItemAsSoleArgument(params string[] array)
{
Assert.AreEqual("a", array[0]);
}
[TestCase("a", "b", "c", "d")]
public void HandlesParamsArrayAsLastArgument(string s1, string s2, params object[] array)
{
Assert.AreEqual("a", s1);
Assert.AreEqual("b", s2);
Assert.AreEqual("c", array[0]);
Assert.AreEqual("d", array[1]);
}
[TestCase("a", "b")]
public void HandlesParamsArrayAsLastArgumentWithNoValues(string s1, string s2, params object[] array)
{
Assert.AreEqual("a", s1);
Assert.AreEqual("b", s2);
Assert.AreEqual(0, array.Length);
}
[TestCase("a", "b", "c")]
public void HandlesParamsArrayWithOneItemAsLastArgument(string s1, string s2, params object[] array)
{
Assert.AreEqual("a", s1);
Assert.AreEqual("b", s2);
Assert.AreEqual("c", array[0]);
}
[Test]
public void CanSpecifyDescription()
{
Test test = (Test)TestBuilder.MakeTestCase(
typeof(TestCaseAttributeFixture), "MethodHasDescriptionSpecified").Tests[0];
Assert.AreEqual("My Description", test.Description);
}
[Test]
public void CanSpecifyTestName()
{
Test test = (Test)TestBuilder.MakeTestCase(
typeof(TestCaseAttributeFixture), "MethodHasTestNameSpecified").Tests[0];
Assert.AreEqual("XYZ", test.TestName.Name);
Assert.AreEqual("NUnit.TestData.TestCaseAttributeFixture.XYZ", test.TestName.FullName);
}
[Test]
public void CanSpecifyCategory()
{
Test test = (Test)TestBuilder.MakeTestCase(
typeof(TestCaseAttributeFixture), "MethodHasSingleCategory").Tests[0];
Assert.AreEqual(new string[] { "XYZ" }, test.Categories);
}
[Test]
public void CanSpecifyMultipleCategories()
{
Test test = (Test)TestBuilder.MakeTestCase(
typeof(TestCaseAttributeFixture), "MethodHasMultipleCategories").Tests[0];
Assert.AreEqual(new string[] { "X", "Y", "Z" }, test.Categories);
}
[Test]
public void CanSpecifyExpectedException()
{
Test test = (Test)TestBuilder.MakeTestCase(
typeof(TestCaseAttributeFixture), "MethodThrowsExpectedException").Tests[0];
TestResult result = test.Run(NullListener.NULL, TestFilter.Empty);
Assert.AreEqual(ResultState.Success, result.ResultState);
}
[Test]
public void CanSpecifyExpectedException_WrongException()
{
Test test = (Test)TestBuilder.MakeTestCase(
typeof(TestCaseAttributeFixture), "MethodThrowsWrongException").Tests[0];
TestResult result = test.Run(NullListener.NULL, TestFilter.Empty);
Assert.AreEqual(ResultState.Failure, result.ResultState);
StringAssert.StartsWith("An unexpected exception type was thrown", result.Message);
}
[Test]
public void CanSpecifyExpectedException_WrongMessage()
{
Test test = (Test)TestBuilder.MakeTestCase(
typeof(TestCaseAttributeFixture), "MethodThrowsExpectedExceptionWithWrongMessage").Tests[0];
TestResult result = test.Run(NullListener.NULL, TestFilter.Empty);
Assert.AreEqual(ResultState.Failure, result.ResultState);
StringAssert.StartsWith("The exception message text was incorrect", result.Message);
}
[Test]
public void CanSpecifyExpectedException_NoneThrown()
{
Test test = (Test)TestBuilder.MakeTestCase(
typeof(TestCaseAttributeFixture), "MethodThrowsNoException").Tests[0];
TestResult result = test.Run(NullListener.NULL, TestFilter.Empty);
Assert.AreEqual(ResultState.Failure, result.ResultState);
Assert.AreEqual("System.ArgumentNullException was expected", result.Message);
}
[Test]
public void IgnoreTakesPrecedenceOverExpectedException()
{
Test test = (Test)TestBuilder.MakeTestCase(
typeof(TestCaseAttributeFixture), "MethodCallsIgnore").Tests[0];
TestResult result = test.Run(NullListener.NULL, TestFilter.Empty);
Assert.AreEqual(ResultState.Ignored, result.ResultState);
Assert.AreEqual("Ignore this", result.Message);
}
[Test]
public void CanIgnoreIndividualTestCases()
{
Test test = TestBuilder.MakeTestCase(
typeof(TestCaseAttributeFixture), "MethodWithIgnoredTestCases");
Test testCase = TestFinder.Find("MethodWithIgnoredTestCases(1)", test, false);
Assert.That(testCase.RunState, Is.EqualTo(RunState.Runnable));
testCase = TestFinder.Find("MethodWithIgnoredTestCases(2)", test, false);
Assert.That(testCase.RunState, Is.EqualTo(RunState.Ignored));
testCase = TestFinder.Find("MethodWithIgnoredTestCases(3)", test, false);
Assert.That(testCase.RunState, Is.EqualTo(RunState.Ignored));
Assert.That(testCase.IgnoreReason, Is.EqualTo("Don't Run Me!"));
}
[Test]
public void CanMarkIndividualTestCasesExplicit()
{
Test test = TestBuilder.MakeTestCase(
typeof(TestCaseAttributeFixture), "MethodWithExplicitTestCases");
Test testCase = TestFinder.Find("MethodWithExplicitTestCases(1)", test, false);
Assert.That(testCase.RunState, Is.EqualTo(RunState.Runnable));
testCase = TestFinder.Find("MethodWithExplicitTestCases(2)", test, false);
Assert.That(testCase.RunState, Is.EqualTo(RunState.Explicit));
testCase = TestFinder.Find("MethodWithExplicitTestCases(3)", test, false);
Assert.That(testCase.RunState, Is.EqualTo(RunState.Explicit));
Assert.That(testCase.IgnoreReason, Is.EqualTo("Connection failing"));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace XSharp.MacroCompiler
{
using Syntax;
using System.Globalization;
using System.Threading;
using static Syntax.TokenAttr;
partial class Lexer
{
struct LexerState
{
internal TokenType LastToken;
internal int Index;
internal bool InDottedIdentifier;
internal bool HasEos;
internal bool InPp;
internal bool InTextBlock;
internal static LexerState Initial => new LexerState() {
LastToken = TokenType.NL,
Index = 0,
InDottedIdentifier = false,
HasEos = true,
InPp = false,
InTextBlock = false,
};
}
// Input source
string _Source;
// Configuration
MacroOptions _options;
// Lexer state
LexerState _s = LexerState.Initial;
// Lexer stats
internal bool HasPreprocessorTokens = false;
internal bool HasPPDefines = false;
internal bool HasPPIncludes = false;
internal bool HasPPMessages = false;
internal bool HasPPRegions = false;
internal bool HasPPIfdefs = false;
internal bool HasPPUDCs = false;
internal bool MustBeProcessed => HasPPMessages || HasPPUDCs || HasPPIncludes || HasPPIfdefs;
// Lexer result
TokenSource _tokenSource = null;
internal Lexer(string source, MacroOptions options)
{
_Source = source;
_options = options;
}
internal bool AllowFourLetterAbbreviations => _options.AllowFourLetterAbbreviations;
internal bool AllowSingleQuotedStrings => _options.AllowSingleQuotedStrings;
internal bool AllowOldStyleComments => _options.AllowOldStyleComments;
internal bool AllowPackedDotOperators =>_options.AllowPackedDotOperators;
internal TokenSource TokenSource => _tokenSource;
bool TryGetKeyword(string text, out TokenType token)
{
var cKwIds = _options.ParseEntities ? coreKwIdsE : _options.ParseStatements ? coreKwIdsS : coreKwIds;
if (cKwIds.TryGetValue(text, out token))
return true;
if (AllowFourLetterAbbreviations)
{
var aKwIds = _options.ParseEntities ? abbrKwIdsE : _options.ParseStatements ? abbrKwIdsS : abbrKwIds;
if (aKwIds.TryGetValue(text, out token))
return true;
}
switch (_options.Dialect)
{
case XSharpDialect.FoxPro:
{
var kwIds = _options.ParseEntities ? foxKwIdsE : _options.ParseStatements ? foxKwIdsS : foxKwIds;
return kwIds.TryGetValue(text, out token);
}
case XSharpDialect.Core:
case XSharpDialect.Vulcan:
{
var kwIds = _options.ParseEntities ? xsKwIdsE : _options.ParseStatements ? xsKwIdsS : xsKwIds;
return kwIds.TryGetValue(text, out token);
}
case XSharpDialect.VO:
default:
{
var kwIds = _options.ParseEntities ? voKwIdsE : _options.ParseStatements ? voKwIdsS : voKwIds;
return kwIds.TryGetValue(text, out token);
}
}
}
IDictionary<string, TokenType> SymIds
{
get
{
return _options.ParseStatements ? symIdsS : symIds;
}
}
char Lb()
{
return _s.Index > 0 ? _Source[_s.Index - 1] : (char)0;
}
char La()
{
return _s.Index < _Source.Length ? _Source[_s.Index] : (char)0;
}
char La(int n)
{
return (_s.Index + n-1) < _Source.Length ? _Source[_s.Index + n-1] : (char)0;
}
bool InRange(char c, char first, char last) => c >= first && c <= last;
bool Eoi()
{
return _s.Index >= _Source.Length;
}
void Consume()
{
_s.Index++;
}
void Consume(int n)
{
_s.Index += n;
}
void Rewind(int pos)
{
_s.Index = pos;
}
bool ExpectDelimited(string s)
{
if (La(0) == s[0])
{
// char 2 etc.
// they may be delimited with spaces
var j = 1;
for (int i = 1; i < s.Length; i++)
{
var c = (char)La(j);
while (c == ' ' || c == '\t')
{
j += 1;
c = (char)La(j);
}
if (c != s[i])
return false;
j += 1;
}
return true;
}
return false;
}
bool Expect(char c)
{
if (La() == c)
{
Consume();
return true;
}
return false;
}
bool Expect(char c1, char c2)
{
if (La() == c1 && La(2) == c2)
{
Consume(2);
return true;
}
return false;
}
bool ExpectEol()
{
bool r = false;
if (La() == '\r')
{
Consume();
r = true;
}
if (La() == '\n')
{
Consume();
r = true;
}
return r;
}
bool ExpectAny(char c1, char c2)
{
var c = La();
if (c == c1 || c == c2)
{
Consume();
return true;
}
return false;
}
bool ExpectAny(char c1, char c2, char c3, char c4)
{
var c = La();
if (c == c1 || c == c2 || c == c3 || c == c4)
{
Consume();
return true;
}
return false;
}
bool ExpectRange(char c1, char c2)
{
if (InRange(La(), c1, c2))
{
Consume();
return true;
}
return false;
}
bool AssertText(string s)
{
int i = 0;
for(i = 0; i < s.Length; i++)
if (char.ToUpper(La(i+1)) != s[i])
return false;
return true;
}
// copied from the Roslyn C# lexer
private static bool IsLetterChar(UnicodeCategory cat)
{
// letter-character:
// A Unicode character of classes Lu, Ll, Lt, Lm, Lo, or Nl
// A Unicode-escape-sequence representing a character of classes Lu, Ll, Lt, Lm, Lo, or Nl
switch (cat)
{
case UnicodeCategory.UppercaseLetter:
case UnicodeCategory.LowercaseLetter:
case UnicodeCategory.TitlecaseLetter:
case UnicodeCategory.ModifierLetter:
case UnicodeCategory.OtherLetter:
case UnicodeCategory.LetterNumber:
return true;
}
return false;
}
// copied from the Roslyn C# lexer
public static bool IsIdentifierPartCharacter(char ch)
{
// identifier-part-character:
// letter-character
// decimal-digit-character
// connecting-character
// combining-character
// formatting-character
if (ch < 'a') // '\u0061'
{
if (ch < 'A') // '\u0041'
{
return ch >= '0' // '\u0030'
&& ch <= '9'; // '\u0039'
}
return ch <= 'Z' // '\u005A'
|| ch == '_'; // '\u005F'
}
if (ch <= 'z') // '\u007A'
{
return true;
}
if (ch <= '\u007F') // max ASCII
{
return false;
}
UnicodeCategory cat = CharUnicodeInfo.GetUnicodeCategory(ch);
return IsLetterChar(cat)
|| cat == UnicodeCategory.DecimalDigitNumber
|| cat == UnicodeCategory.ConnectorPunctuation
|| cat == UnicodeCategory.NonSpacingMark
|| cat == UnicodeCategory.SpacingCombiningMark
|| (ch > 127 && cat == UnicodeCategory.Format);
}
// copied from the Roslyn C# lexer
public static bool IsIdentifierStartCharacter(char ch)
{
// identifier-start-character:
// letter-character
// _ (the underscore character U+005F)
if (ch < 'a') // '\u0061'
{
if (ch < 'A') // '\u0041'
{
return false;
}
return ch <= 'Z' // '\u005A'
|| ch == '_'; // '\u005F'
}
if (ch <= 'z') // '\u007A'
{
return true;
}
if (ch <= '\u007F') // max ASCII
{
return false;
}
return IsLetterChar(CharUnicodeInfo.GetUnicodeCategory(ch));
}
bool ExpectIdStart()
{
var c = La();
if (IsIdentifierStartCharacter(c))
{
Consume();
return true;
}
return false;
}
bool ExpectIdChar()
{
var c = La();
if (IsIdentifierPartCharacter (c))
{
Consume();
return true;
}
return false;
}
bool ExpectLower(string s)
{
if (char.ToLower(La()) == s[0])
{
for(int i=1;i<=s.Length;i++)
{
if (char.ToLower(La(i)) != s[i-1])
return false;
}
Consume(s.Length);
return true;
}
return false;
}
bool Reach(char c)
{
if (!Eoi() && La() != c)
{
Consume();
return false;
}
return true;
}
bool ReachEsc(char c)
{
if (!Eoi() && La() != c)
{
var esc = La() == '\\';
Consume();
if (!Eoi() && esc)
Consume();
return false;
}
return true;
}
bool ReachEol()
{
if (!Eoi())
{
var c = La();
if (c != '\r' && c != '\n')
{
Consume();
return false;
}
}
return true;
}
bool Reach(char c1, char c2)
{
if (!Eoi())
{
if (La() != c1 || La(2) != c2)
{
Consume();
return false;
}
}
return true;
}
internal void Reset()
{
_s = LexerState.Initial;
}
internal IList<Token> AllTokens()
{
if (_tokenSource == null)
{
var source = new TokenSource(_Source);
Token t;
while ((t = NextToken()) != null)
{
t.Source = source;
t.Index = source.Tokens.Count;
source.Tokens.Add(t);
}
Interlocked.CompareExchange(ref _tokenSource, source, null);
}
return _tokenSource.Tokens;
}
internal string GetText(Token t)
{
return _Source.Substring(t.Start, t.Length);
}
internal Token NextToken()
{
if (!Eoi())
{
do
{
int start = _s.Index;
TokenType t = TokenType.UNRECOGNIZED;
TokenType st = TokenType.UNRECOGNIZED;
Channel ch = Channel.Default;
string value = null;
var c = La();
if (c < 128)
{
t = specialTable[c];
Consume();
}
else
{
if (ExpectIdStart())
t = TokenType.ID;
else
Consume();
}
switch (t)
{
case TokenType.LBRKT:
if (_options.AllowBracketStrings)
{
if (_s.LastToken == TokenType.ID || _s.LastToken == TokenType.RPAREN || _s.LastToken == TokenType.RCURLY || _s.LastToken == TokenType.RBRKT || _s.InPp)
{
break;
}
t = TokenType.STRING_CONST;
while (!Reach(']')) ;
if (!Expect(']')) t = TokenType.INCOMPLETE_STRING_CONST;
value = _Source.Substring(start, _s.Index - start);
}
break;
case TokenType.LCURLY:
if (Expect('^'))
{
t = TokenType.DATETIME_CONST;
while (!Reach('}')) ;
if (!Expect('}')) t = TokenType.INCOMPLETE_STRING_CONST;
value = _Source.Substring(start, _s.Index - start);
}
if (_options.Dialect == XSharpDialect.FoxPro )
{
if (ExpectDelimited("{//}") ||
ExpectDelimited("{--}") ||
ExpectDelimited("{..}"))
{
t = TokenType.NULL_DATE;
while (La() != '}')
{
Consume();
}
Consume();
}
}
break;
case TokenType.COLON:
if (Expect(':')) t = TokenType.COLONCOLON;
else if (Expect('=')) t = TokenType.ASSIGN_OP;
break;
case TokenType.PIPE:
if (Expect('|')) t = TokenType.OR;
else if (Expect('=')) t = TokenType.ASSIGN_BITOR;
break;
case TokenType.AMP:
if (Expect('&'))
{
if (AllowOldStyleComments)
{
t = TokenType.SL_COMMENT;
ch = Channel.Hidden;
while (!ReachEol()) ;
break;
}
t = TokenType.AND;
}
else if (Expect('=')) t = TokenType.ASSIGN_BITAND;
break;
case TokenType.ADDROF:
if (Expect('@'))
{
t = TokenType.ID;
goto case TokenType.ID;
}
break;
case TokenType.MINUS:
if (Expect('>')) t = TokenType.ALIAS;
else if (Expect('-')) t = TokenType.DEC;
else if (Expect('=')) t = TokenType.ASSIGN_SUB;
break;
case TokenType.PLUS:
if (Expect('+')) t = TokenType.INC;
else if (Expect('=')) t = TokenType.ASSIGN_ADD;
break;
case TokenType.DIV:
if (Expect('=')) t = TokenType.ASSIGN_DIV;
else if (Expect('/'))
{
t = TokenType.SL_COMMENT;
ch = Channel.Hidden;
if (Expect('/'))
{
t = TokenType.DOC_COMMENT;
ch = Channel.XmlDoc;
}
while (!ReachEol()) ;
}
else if (Expect('*'))
{
t = TokenType.ML_COMMENT;
ch = Channel.Hidden;
while (!Reach('*','/')) ;
Expect('*', '/');
}
break;
case TokenType.MOD:
if (Expect('=')) t = TokenType.ASSIGN_MOD;
break;
case TokenType.EXP:
if (Expect('=')) t = TokenType.ASSIGN_EXP;
break;
case TokenType.LT:
if (Expect('<')) { t = TokenType.LSHIFT; if (Expect('=')) t = TokenType.ASSIGN_LSHIFT; }
else if (Expect('=')) t = TokenType.LTE;
else if (Expect('>')) t = TokenType.NEQ;
break;
case TokenType.GT:
if (Expect('=')) t = TokenType.GTE;
else if (Expect('>', '=')) t = TokenType.ASSIGN_RSHIFT;
break;
case TokenType.TILDE:
if (Expect('=')) t = TokenType.ASSIGN_XOR;
if (Expect('"'))
{
t = TokenType.WS;
ch = Channel.Hidden;
while (!Reach('"')) ;
Expect('"');
}
break;
case TokenType.MULT:
if (_s.LastToken == TokenType.EOS)
{
t = TokenType.SL_COMMENT;
ch = Channel.Hidden;
while (!ReachEol()) ;
}
else if (Expect('=')) t = TokenType.ASSIGN_MUL;
else if (Expect('*')) { t = TokenType.EXP; if (Expect('=')) t = TokenType.ASSIGN_EXP; }
break;
case TokenType.QMARK:
if (Expect('?')) t = TokenType.QQMARK;
break;
case TokenType.EQ:
if (Expect('=')) t = TokenType.EEQ;
else if (_options.ParseStatements && Expect('>')) t = TokenType.UDCSEP;
break;
case TokenType.NOT:
if (Expect('=')) t = TokenType.NEQ;
break;
case TokenType.SEMI:
while (ExpectAny(' ', '\t')) ;
if (Expect('/','/'))
{
t = TokenType.LINE_CONT;
ch = Channel.Hidden;
while (!ReachEol()) ;
}
else if (AllowOldStyleComments && Expect('&', '&'))
{
t = TokenType.LINE_CONT_OLD;
ch = Channel.Hidden;
while (!ReachEol()) ;
}
if (ExpectEol())
{
if (t == TokenType.SEMI) t = TokenType.LINE_CONT;
ch = Channel.Hidden;
}
if (t == TokenType.SEMI && _s.Index > start+1)
{
Rewind(start + 1);
}
break;
case TokenType.DOT:
if (La() >= '0' && La() <= '9') goto case TokenType.REAL_CONST;
if (!_s.InDottedIdentifier || AllowPackedDotOperators)
{
if (La(2) == '.')
{
if (ExpectAny('F', 'f', 'N', 'n')) { Consume(); t = TokenType.FALSE_CONST; }
else if (ExpectAny('T', 't', 'Y', 'y')) { Consume(); t = TokenType.TRUE_CONST; }
else if (Expect('.')) { Consume(); t = TokenType.ELLIPSIS; }
}
else if (La(3) == '.')
{
if (ExpectLower("or")) { Consume(); t = TokenType.LOGIC_OR; }
}
else if (La(4) == '.')
{
if (ExpectLower("and")) { Consume(); t = TokenType.LOGIC_AND; }
else if (ExpectLower("not")) { Consume(); t = TokenType.LOGIC_NOT; }
else if (ExpectLower("xor")) { Consume(); t = TokenType.LOGIC_XOR; }
}
else if (La(5) == '.' && _options.Dialect == XSharpDialect.FoxPro)
{
if (ExpectLower("null")) { Consume(); t = TokenType.NULL; }
}
}
break;
case TokenType.NL:
if (c == '\r') Expect('\n');
break;
case TokenType.WS:
ch = Channel.Hidden;
while (ExpectAny(' ', '\t')) ;
break;
case TokenType.NEQ2:
if (ExpectIdStart())
{
t = TokenType.SYMBOL_CONST;
while (ExpectIdChar()) ;
value = _Source.Substring(start, _s.Index - start);
{
TokenType tt;
if (SymIds.TryGetValue(value, out tt))
{
if (tt >= TokenType.FIRST_NULL && t <= TokenType.LAST_NULL)
{
t = TokenType.NEQ2;
value = null;
Rewind(start + 1);
}
else if (_options.ParseStatements)
{
t = tt;
if (tt >= TokenType.PP_FIRST && t <= TokenType.PP_LAST)
{
_s.InPp = true;
HasPreprocessorTokens = true;
switch (tt)
{
case TokenType.PP_COMMAND:
case TokenType.PP_TRANSLATE:
HasPPUDCs = true;
break;
case TokenType.PP_IFDEF:
case TokenType.PP_IFNDEF:
case TokenType.PP_ELSE:
case TokenType.PP_ENDIF:
HasPPIfdefs = true;
break;
case TokenType.PP_REGION:
case TokenType.PP_ENDREGION:
HasPPRegions = true;
break;
case TokenType.PP_ERROR:
case TokenType.PP_WARNING:
HasPPMessages = true;
break;
case TokenType.PP_INCLUDE:
HasPPIncludes = true;
break;
case TokenType.PP_DEFINE:
case TokenType.PP_UNDEF:
HasPPDefines = true;
break;
case TokenType.PP_LINE:
default:
break;
}
}
else if (tt == TokenType.PRAGMA)
{
ch = Channel.PreProcessor;
while (!ReachEol()) ;
}
}
}
}
}
break;
case TokenType.ID:
if (c == 'c' || c == 'C')
{
if (La() == '"' || La() == '\'') { Consume(); goto case TokenType.CHAR_CONST; }
}
else if (c == 'e' || c == 'E')
{
if (La() == '"') { Consume(); goto case TokenType.ESCAPED_STRING_CONST; } // escaped string
if ((La() == 'i' || La() == 'I') && La(2) == '"') { Consume(2); goto case TokenType.INTERPOLATED_STRING_CONST; } // interpolated escaped string
}
else if (c == 'i' || c == 'I')
{
if (La() == '"') { Consume(); goto case TokenType.INTERPOLATED_STRING_CONST; } // interpolated string
if ((La() == 'e' || La() == 'E') && La(2) == '"') { Consume(2); goto case TokenType.INTERPOLATED_STRING_CONST; } // interpolated escaped string
}
{
while (ExpectIdChar()) ;
bool nokw = _Source[start] == '@';
int idStart = nokw ? start + 2 : start;
value = _Source.Substring(idStart, _s.Index - idStart);
if (!nokw)
{
TokenType tt;
if (TryGetKeyword(value, out tt))
{
t = tt;
if (IsSoftKeyword(tt) || _s.InDottedIdentifier)
{
st = TokenType.ID;
if (_s.LastToken == TokenType.COLON || _s.LastToken == TokenType.DOT)
t = TokenType.ID;
}
}
}
}
break;
case TokenType.SUBSTR:
if (La() == '.' || (La() >= '0' && La() <= '9'))
{
t = TokenType.REAL_CONST;
while (ExpectRange('0', '9') || Expect('_')) ;
if (Lb() == '_') t = TokenType.INVALID_NUMBER;
if (Expect('.')) while (ExpectRange('0', '9') || Expect('_')) ;
if (Lb() == '_') t = TokenType.INVALID_NUMBER;
value = _Source.Substring(start, _s.Index - start).Replace("_", "");
}
break;
case TokenType.INT_CONST:
if (c == '0' && ExpectAny('X','x'))
{
t = TokenType.HEX_CONST;
while (ExpectRange('0', '9') || ExpectRange('A', 'F') || ExpectRange('a', 'f') || Expect('_')) ;
if (Lb() == '_') t = TokenType.INVALID_NUMBER;
ExpectAny('U', 'u', 'L', 'l');
}
else if (c == '0' && ExpectAny('H', 'h'))
{
t = TokenType.BINARY_CONST;
while (ExpectRange('0', '9') || ExpectRange('A', 'F') || ExpectRange('a', 'f') || Expect('_')) ;
if (Lb() == '_') t = TokenType.INVALID_NUMBER;
}
else if (c == '0' && ExpectAny('B', 'b'))
{
while (ExpectRange('0', '1')) ;
ExpectAny('U', 'u');
t = TokenType.BIN_CONST;
}
else
{
while (ExpectRange('0', '9') || Expect('_')) ;
if (Lb() == '_') t = TokenType.INVALID_NUMBER;
c = La();
var c2 = La(2);
// only treat the dot as a trigger to a REAL_CONST when followed by a number or one of the characters
// listed. This allows an expression such as "{||1>2.and.3<4}" to be compiled properly
if (c == '.' && (c2 != 'a' && c2 != 'o' && c2 != 'A' && c2 != 'O'))
{
Consume();
goto case TokenType.REAL_CONST;
}
if (La() == 'E' || La() == 'e') goto case TokenType.REAL_CONST_EXP;
ExpectAny('U', 'u', 'L', 'l');
}
value = _Source.Substring(start, _s.Index - start).Replace("_", "");
break;
case TokenType.REAL_CONST:
if (t != TokenType.INVALID_NUMBER) t = TokenType.REAL_CONST;
if (ExpectRange('0', '9')) while (ExpectRange('0', '9') || Expect('_')) ;
if (Lb() == '_') t = TokenType.INVALID_NUMBER;
if (La() == '.' && InRange(La(2), '0', '9') && (!InRange(La(3), '0', '9') || !InRange(La(4), '0', '9'))) goto case TokenType.DATE_CONST;
if (La() == 'E' || La() == 'e') goto case TokenType.REAL_CONST_EXP;
if (!ExpectAny('S', 's', 'D', 'd'))
ExpectAny('M', 'm');
value = _Source.Substring(start, _s.Index - start).Replace("_", "");
break;
case TokenType.REAL_CONST_EXP:
if (La() == 'E' || La() == 'e')
{
c = La(2);
if (c == '+' || c == '-' || (c >= '0' && c <= '9'))
{
if (t != TokenType.INVALID_NUMBER) t = TokenType.REAL_CONST;
Consume();
if (!(c >= '0' && c <= '9'))
Consume();
if (ExpectRange('0', '9')) while (ExpectRange('0', '9') || Expect('_')) ;
if (Lb() == '_') t = TokenType.INVALID_NUMBER;
ExpectAny('S', 's', 'D', 'd');
}
}
value = _Source.Substring(start, _s.Index - start).Replace("_","");
break;
case TokenType.DATE_CONST:
{
string s = _Source.Substring(start, _s.Index - start);
int z0 = s.IndexOf('.');
if (z0 > 0 && s.Length - z0 > 1 && s.Length - z0 <= 3 && s.Length <= 7)
if (z0 > 0 && z0 <= 4 && s.Length > z0 + 1 && s.Length <= z0+3 && !s.Contains("_"))
{
t = TokenType.DATE_CONST;
Expect('.');
ExpectRange('0', '9');
ExpectRange('0', '9');
}
}
value = _Source.Substring(start, _s.Index - start);
break;
case TokenType.CHAR_CONST:
t = TokenType.CHAR_CONST;
if (La() == '\\' && La(3) == '\'') Consume(3);
else { while (!Reach('\'')) ; if (!Expect('\'')) t = TokenType.INCOMPLETE_STRING_CONST; }
value = _Source.Substring(start, _s.Index - start);
break;
case TokenType.STRING_CONST_SINGLE:
if (!AllowSingleQuotedStrings)
goto case TokenType.CHAR_CONST;
t = TokenType.STRING_CONST;
do {
while (!Reach('\'')) ;
if (!Expect('\'')) t = TokenType.INCOMPLETE_STRING_CONST;
} while (Expect('\''));
value = _Source.Substring(start, _s.Index - start);
break;
case TokenType.STRING_CONST:
do {
while (!Reach('"')) ;
if (!Expect('"')) t = TokenType.INCOMPLETE_STRING_CONST;
} while (Expect('"'));
value = _Source.Substring(start, _s.Index - start);
break;
case TokenType.ESCAPED_STRING_CONST:
t = TokenType.ESCAPED_STRING_CONST;
while (!ReachEsc('"')) ;
if (!Expect('"')) t = TokenType.INCOMPLETE_STRING_CONST;
value = _Source.Substring(start, _s.Index - start);
break;
case TokenType.INTERPOLATED_STRING_CONST:
t = TokenType.INTERPOLATED_STRING_CONST;
while (!ReachEsc('"')) ;
if (!Expect('"')) t = TokenType.INCOMPLETE_STRING_CONST;
value = _Source.Substring(start, _s.Index - start);
break;
}
bool endOfLine = t == TokenType.NL || t == TokenType.SEMI;
bool startOfLine = _s.HasEos;
/* Handle parsing of TEXT...ENDTEXT region (FoxPro) */
if (_options.Dialect == XSharpDialect.FoxPro)
{
if (startOfLine && t == TokenType.TEXT)
{
_s.InTextBlock = true;
}
else if (startOfLine && _s.InTextBlock)
{
if (t != TokenType.ENDTEXT)
{
Rewind(start);
while (!Eoi())
{
while (ExpectAny(' ', '\t')) ;
if (AssertText("ENDTEXT")) break;
while (!ReachEol()) ;
while (ExpectAny('\r', '\n')) ;
}
ch = Channel.Default;
t = TokenType.TEXT_STRING_CONST;
st = TokenType.UNRECOGNIZED;
value = _Source.Substring(start, _s.Index - start);
if (Eoi())
t = TokenType.INCOMPLETE_STRING_CONST;
}
_s.InTextBlock = false;
}
}
/* Update InDottedIdentifier state (handling of positional keyword in ID.ID constructs) */
if (!_s.InDottedIdentifier)
{
// Check if the current token is a valid Identifier (starts with A..Z or _) and is followed by a DOT
// In that case we change the type from Keyword to ID
if (st == TokenType.ID && La() == '.')
{
// Do not convert to ID here - handle at parser!
//if (t != TokenType.SELF && t != TokenType.SUPER)
//{
// t = TokenType.ID;
// st = TokenType.UNRECOGNIZED;
//}
_s.InDottedIdentifier = true;
}
else if (t == TokenType.ID)
{
_s.InDottedIdentifier = true;
}
}
else
{
if (st == TokenType.ID)
{
t = TokenType.ID;
st = TokenType.UNRECOGNIZED;
// keep _state.InDottedIdentifier true
}
else if (t != TokenType.DOT && t != TokenType.ID)
{
_s.InDottedIdentifier = false;
}
}
/* Update HasEos state */
if (endOfLine)
{
if (startOfLine)
{
if (t == TokenType.SEMI)
{
if (_s.LastToken != TokenType.SEMI)
ch = Channel.Hidden;
}
else
{
ch = Channel.Hidden;
}
}
else
{
t = TokenType.EOS;
_s.HasEos = true;
}
}
else if (startOfLine && ch == Channel.Default)
{
_s.HasEos = false;
}
/* Update InPp state (for preprocessor tokens) */
if (_s.InPp)
{
if (ch == Channel.Default)
{
ch = Channel.PreProcessor;
if (t == TokenType.EOS)
_s.InPp = false;
}
}
if (ch == Channel.Default || ch == Channel.PreProcessor)
{
_s.LastToken = t;
return new Token(t, st, start, _s.Index - start, value, ch);
}
} while (!Eoi());
}
if (!_s.HasEos)
{
var ch = _s.InPp ? Channel.PreProcessor : Channel.Default;
_s.HasEos = true;
_s.InPp = false;
return new Token(TokenType.EOS, TokenType.UNRECOGNIZED, _s.Index, 0, null, ch);
}
return null;
}
internal IList<Token> ReclassifyTokens(IList<Token> tokens)
{
// Fix keywords
{
var lastType = TokenType.EOS;
Token last = null;
foreach (var token in tokens)
{
// Some keywords may have been seen as identifier because they were
// originally in the Preprocessor Channel and for example not on a start
// of a line or command
if (token.Channel == Channel.Default)
{
findKeyWord(token, lastType);
}
// Identifier tokens before a DOT are never Keyword but always a type or field/property
if (token.Type == TokenType.DOT)
{
if (last != null && isValidIdentifier(last))
{
last.Type = TokenType.ID;
}
}
last = token;
if (token.Channel == Channel.Default)
{
lastType = token.Type;
}
}
}
return tokens;
bool isValidIdentifier(Token t)
{
if (t == null || t.Text?.Length == 0 || t.Type == TokenType.EOF)
return false;
switch (t.Channel)
{
case Channel.Hidden:
case Channel.XmlDoc:
case Channel.Default:
return false;
case Channel.PreProcessor:
default:
char fc = t.Text?[0] ?? (Char)0;
return fc == '_' || (fc >= 'A' && fc <= 'Z') || (fc >= 'a' && fc <= 'z');
}
}
bool findKeyWord(Token token, TokenType lastToken)
{
if (token.Type == TokenType.ID && token.Channel == Channel.Default)
{
TokenType tt;
if (TryGetKeyword(token.Text, out tt))
{
if (IsSoftKeyword(tt) && (lastToken == TokenType.COLON || lastToken == TokenType.DOT))
{
// do nothing, no new keywords after colon or dot
}
else
{
token.Type = tt;
if (IsSoftKeyword(tt))
token.SubType = TokenType.ID;
}
return true;
}
}
return false;
}
}
}
}
| |
/********************************************************************************************
Copyright (c) Microsoft Corporation
All rights reserved.
Microsoft Public License:
This license governs use of the accompanying software. If you use the software, you
accept this license. If you do not accept the license, do not use the software.
1. Definitions
The terms "reproduce," "reproduction," "derivative works," and "distribution" have the
same meaning here as under U.S. copyright law.
A "contribution" is the original software, or any additions or changes to the software.
A "contributor" is any person that distributes its contribution under this license.
"Licensed patents" are a contributor's patent claims that read directly on its contribution.
2. Grant of Rights
(A) Copyright Grant- Subject to the terms of this license, including the license conditions
and limitations in section 3, each contributor grants you a non-exclusive, worldwide,
royalty-free copyright license to reproduce its contribution, prepare derivative works of
its contribution, and distribute its contribution or any derivative works that you create.
(B) Patent Grant- Subject to the terms of this license, including the license conditions
and limitations in section 3, each contributor grants you a non-exclusive, worldwide,
royalty-free license under its licensed patents to make, have made, use, sell, offer for
sale, import, and/or otherwise dispose of its contribution in the software or derivative
works of the contribution in the software.
3. Conditions and Limitations
(A) No Trademark License- This license does not grant you rights to use any contributors'
name, logo, or trademarks.
(B) If you bring a patent claim against any contributor over patents that you claim are
infringed by the software, your patent license from such contributor to the software ends
automatically.
(C) If you distribute any portion of the software, you must retain all copyright, patent,
trademark, and attribution notices that are present in the software.
(D) If you distribute any portion of the software in source code form, you may do so only
under this license by including a complete copy of this license with your distribution.
If you distribute any portion of the software in compiled or object code form, you may only
do so under a license that complies with this license.
(E) The software is licensed "as-is." You bear the risk of using it. The contributors give
no express warranties, guarantees or conditions. You may have additional consumer rights
under your local laws which this license cannot change. To the extent permitted under your
local laws, the contributors exclude the implied warranties of merchantability, fitness for
a particular purpose and non-infringement.
********************************************************************************************/
using System;
using System.Reflection;
using System.Globalization;
using System.Resources;
using System.Threading;
namespace Microsoft.VisualStudio.Project.Samples.NestedProject
{
/// <summary>
/// This class represent resource storage and management functionality.
/// </summary>
internal sealed class Resources
{
#region Constants
internal const string Application = "Application";
internal const string ApplicationCaption = "ApplicationCaption";
internal const string GeneralCaption = "GeneralCaption";
internal const string AssemblyName = "AssemblyName";
internal const string AssemblyNameDescription = "AssemblyNameDescription";
internal const string OutputType = "OutputType";
internal const string OutputTypeDescription = "OutputTypeDescription";
internal const string DefaultNamespace = "DefaultNamespace";
internal const string DefaultNamespaceDescription = "DefaultNamespaceDescription";
internal const string StartupObject = "StartupObject";
internal const string StartupObjectDescription = "StartupObjectDescription";
internal const string ApplicationIcon = "ApplicationIcon";
internal const string ApplicationIconDescription = "ApplicationIconDescription";
internal const string Project = "Project";
internal const string ProjectFile = "ProjectFile";
internal const string ProjectFileDescription = "ProjectFileDescription";
internal const string ProjectFolder = "ProjectFolder";
internal const string ProjectFolderDescription = "ProjectFolderDescription";
internal const string OutputFile = "OutputFile";
internal const string OutputFileDescription = "OutputFileDescription";
internal const string TargetFrameworkMoniker = "TargetFrameworkMoniker";
internal const string TargetFrameworkMonikerDescription = "TargetFrameworkMonikerDescription";
internal const string NestedProjectFileAssemblyFilter = "NestedProjectFileAssemblyFilter";
//internal const string MsgFailedToLoadTemplateFile = "Failed to add template file to project";
#endregion Constants
#region Fields
private static Resources loader;
private ResourceManager resourceManager;
private static Object internalSyncObjectInstance;
#endregion Fields
#region Constructors
/// <summary>
/// Internal explicitly defined default constructor.
/// </summary>
internal Resources()
{
resourceManager = new System.Resources.ResourceManager("Microsoft.VisualStudio.Project.Samples.NestedProject.Resources",
Assembly.GetExecutingAssembly());
}
#endregion Constructors
#region Properties
/// <summary>
/// Gets the internal sync. object.
/// </summary>
private static Object InternalSyncObject
{
get
{
if(internalSyncObjectInstance == null)
{
Object o = new Object();
Interlocked.CompareExchange(ref internalSyncObjectInstance, o, null);
}
return internalSyncObjectInstance;
}
}
/// <summary>
/// Gets information about a specific culture.
/// </summary>
private static CultureInfo Culture
{
get { return null/*use ResourceManager default, CultureInfo.CurrentUICulture*/; }
}
/// <summary>
/// Gets convenient access to culture-specific resources at runtime.
/// </summary>
public static ResourceManager ResourceManager
{
get
{
return GetLoader().resourceManager;
}
}
#endregion Properties
#region Methods
/// <summary>
/// Provide access to the internal SR loader object.
/// </summary>
/// <returns>Instance of the Resources object.</returns>
private static Resources GetLoader()
{
if(loader == null)
{
lock(InternalSyncObject)
{
if(loader == null)
{
loader = new Resources();
}
}
}
return loader;
}
/// <summary>
/// Provide access to resource string value.
/// </summary>
/// <param name="name">Received string name.</param>
/// <param name="args">Arguments for the String.Format method.</param>
/// <returns>Returns resources string value or null if error occured.</returns>
public static string GetString(string name, params object[] args)
{
Resources resourcesInstance = GetLoader();
if(resourcesInstance == null)
{
return null;
}
string res = resourcesInstance.resourceManager.GetString(name, Resources.Culture);
if(args != null && args.Length > 0)
{
return String.Format(CultureInfo.CurrentCulture, res, args);
}
else
{
return res;
}
}
/// <summary>
/// Provide access to resource string value.
/// </summary>
/// <param name="name">Received string name.</param>
/// <returns>Returns resources string value or null if error occured.</returns>
public static string GetString(string name)
{
Resources resourcesInstance = GetLoader();
if(resourcesInstance == null)
{
return null;
}
return resourcesInstance.resourceManager.GetString(name, Resources.Culture);
}
/// <summary>
/// Provide access to resource object value.
/// </summary>
/// <param name="name">Received object name.</param>
/// <returns>Returns resources object value or null if error occured.</returns>
public static object GetObject(string name)
{
Resources resourcesInstance = GetLoader();
if(resourcesInstance == null)
{
return null;
}
return resourcesInstance.resourceManager.GetObject(name, Resources.Culture);
}
#endregion Methods
}
}
| |
using CorDebugInterop;
using nanoFramework.Tools.Debugger;
using System.Collections;
using System.Diagnostics;
using WireProtocol = nanoFramework.Tools.Debugger.WireProtocol;
namespace nanoFramework.Tools.VisualStudio.Debugger
{
public class CorDebugChain : ICorDebugChain
{
CorDebugThread m_thread;
CorDebugFrame[] m_frames;
public CorDebugChain(CorDebugThread thread, WireProtocol.Commands.Debugging_Thread_Stack.Reply.Call [] calls)
{
m_thread = thread;
ArrayList frames = new ArrayList(calls.Length);
bool lastFrameWasUnmanaged = false;
if (thread.IsVirtualThread)
{
frames.Add(new CorDebugInternalFrame(this, CorDebugInternalFrameType.STUBFRAME_FUNC_EVAL));
}
for (uint i = 0; i < calls.Length; i++)
{
WireProtocol.Commands.Debugging_Thread_Stack.Reply.Call call = calls[i];
WireProtocol.Commands.Debugging_Thread_Stack.Reply.CallEx callEx = call as WireProtocol.Commands.Debugging_Thread_Stack.Reply.CallEx;
if (callEx != null)
{
if ((callEx.m_flags & WireProtocol.Commands.Debugging_Thread_Stack.Reply.c_AppDomainTransition) != 0)
{
//No internal frame is used in the nanoCLR. This is simply to display the AppDomain transition
//in the callstack of Visual Studio.
frames.Add(new CorDebugInternalFrame(this, CorDebugInternalFrameType.STUBFRAME_APPDOMAIN_TRANSITION));
}
if ((callEx.m_flags & WireProtocol.Commands.Debugging_Thread_Stack.Reply.c_PseudoStackFrameForFilter) != 0)
{
//No internal frame is used in the nanoCLR for filters. This is simply to display the transition
//in the callstack of Visual Studio.
frames.Add(new CorDebugInternalFrame(this, CorDebugInternalFrameType.STUBFRAME_M2U));
frames.Add(new CorDebugInternalFrame(this, CorDebugInternalFrameType.STUBFRAME_U2M));
}
if ((callEx.m_flags & WireProtocol.Commands.Debugging_Thread_Stack.Reply.c_MethodKind_Interpreted) != 0)
{
if(lastFrameWasUnmanaged)
{
frames.Add(new CorDebugInternalFrame(this, CorDebugInternalFrameType.STUBFRAME_U2M));
}
lastFrameWasUnmanaged = false;
}
else
{
if(!lastFrameWasUnmanaged)
{
frames.Add(new CorDebugInternalFrame(this, CorDebugInternalFrameType.STUBFRAME_M2U));
}
lastFrameWasUnmanaged = true;
}
}
frames.Add(new CorDebugFrame (this, call, i));
}
m_frames = (CorDebugFrame[])frames.ToArray(typeof(CorDebugFrame));
uint depthCLR = 0;
for(int iFrame = m_frames.Length - 1; iFrame >= 0; iFrame--)
{
m_frames[iFrame].m_depthCLR = depthCLR;
depthCLR++;
}
}
public CorDebugThread Thread
{
[System.Diagnostics.DebuggerHidden]
get { return m_thread; }
}
public Engine Engine
{
get { return m_thread.Engine; }
}
public uint NumFrames
{
[System.Diagnostics.DebuggerHidden]
get {return (uint)m_frames.Length;}
}
public void RefreshFrames ()
{
// The frames need to be different after resuming execution
if (m_frames != null)
{
for (int iFrame = 0; iFrame < m_frames.Length; iFrame++)
{
m_frames[iFrame] = m_frames[iFrame].Clone ();
}
}
}
public CorDebugFrame GetFrameFromDepthCLR (uint depthCLR)
{
int index = m_frames.Length - 1 - (int)depthCLR;
if (Utility.InRange(index, 0, m_frames.Length-1))
return m_frames[index];
return null;
}
public CorDebugFrame GetFrameFromDepthnanoCLR (uint depthnanoCLR)
{
for(uint iFrame = depthnanoCLR; iFrame < m_frames.Length; iFrame++)
{
CorDebugFrame frame = m_frames[iFrame];
if(frame.DepthnanoCLR == depthnanoCLR)
{
return frame;
}
}
return null;
}
public CorDebugFrame ActiveFrame
{
get { return GetFrameFromDepthCLR(0); }
}
#region ICorDebugChain Members
int ICorDebugChain.IsManaged( out int pManaged )
{
pManaged = Boolean.TRUE;
return COM_HResults.S_OK;
}
int ICorDebugChain. GetThread( out ICorDebugThread ppThread )
{
ppThread = m_thread.GetRealCorDebugThread();
return COM_HResults.S_OK;
}
int ICorDebugChain. GetReason( out CorDebugChainReason pReason )
{
pReason = m_thread.IsVirtualThread ? CorDebugChainReason.CHAIN_FUNC_EVAL : CorDebugChainReason.CHAIN_NONE;
return COM_HResults.S_OK;
}
int ICorDebugChain. EnumerateFrames( out ICorDebugFrameEnum ppFrames )
{
//Reverse the order for the enumerator
CorDebugFrame[] frames = new CorDebugFrame[m_frames.Length];
int iFrameSrc = m_frames.Length - 1;
for(int iFrameDst = 0; iFrameDst < m_frames.Length; iFrameDst++)
{
frames[iFrameDst] = m_frames[iFrameSrc];
iFrameSrc--;
}
ppFrames = new CorDebugEnum( frames, typeof( ICorDebugFrame ), typeof( ICorDebugFrameEnum ) );
return COM_HResults.S_OK;
}
int ICorDebugChain. GetCallee( out ICorDebugChain ppChain )
{
ppChain = null;
return COM_HResults.S_OK;
}
int ICorDebugChain. GetCaller( out ICorDebugChain ppChain )
{
ppChain = null;
return COM_HResults.S_OK;
}
int ICorDebugChain. GetNext( out ICorDebugChain ppChain )
{
//Chains are attached from top of the stack to the bottom.
//This corresponds to the last virtual thread stack to the first
CorDebugThread thread = m_thread.PreviousThread;
ppChain = (thread != null) ? thread.Chain : null;
return COM_HResults.S_OK;
}
int ICorDebugChain. GetPrevious( out ICorDebugChain ppChain )
{
CorDebugThread thread = m_thread.NextThread;
ppChain = (thread != null) ? thread.Chain : null;
return COM_HResults.S_OK;
}
int ICorDebugChain. GetContext( out ICorDebugContext ppContext )
{
ppContext = null;
return COM_HResults.S_OK;
}
int ICorDebugChain. GetRegisterSet( out ICorDebugRegisterSet ppRegisters )
{
// CorDebugChain.GetRegisterSet is not implemented
ppRegisters = null;
return COM_HResults.S_OK;
}
int ICorDebugChain. GetActiveFrame( out ICorDebugFrame ppFrame )
{
ppFrame = this.ActiveFrame;
return COM_HResults.S_OK;
}
int ICorDebugChain. GetStackRange( out ulong pStart, out ulong pEnd )
{
ulong u;
Debug.Assert( m_frames[0].m_depthCLR == (m_frames.Length - 1) );
Debug.Assert( m_frames[m_frames.Length - 1].m_depthCLR == 0 );
CorDebugFrame.GetStackRange( this.Thread, 0, out pStart, out u );
CorDebugFrame.GetStackRange( this.Thread, (uint)(m_frames.Length - 1), out u, out pEnd );
return COM_HResults.S_OK;
}
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
namespace Microsoft.Azure.Management.Dns
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// RecordSetsOperations operations.
/// </summary>
internal partial class RecordSetsOperations : IServiceOperations<DnsManagementClient>, IRecordSetsOperations
{
/// <summary>
/// Initializes a new instance of the RecordSetsOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal RecordSetsOperations(DnsManagementClient client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the DnsManagementClient
/// </summary>
public DnsManagementClient Client { get; private set; }
/// <summary>
/// Updates a RecordSet within a DNS zone.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='zoneName'>
/// The name of the zone without a terminating dot.
/// </param>
/// <param name='relativeRecordSetName'>
/// The name of the RecordSet, relative to the name of the zone.
/// </param>
/// <param name='recordType'>
/// The type of DNS record. Possible values include: 'A', 'AAAA', 'CNAME',
/// 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT'
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Update operation.
/// </param>
/// <param name='ifMatch'>
/// The etag of Zone.
/// </param>
/// <param name='ifNoneMatch'>
/// Defines the If-None-Match condition. Set to '*' to force
/// Create-If-Not-Exist. Other values will be ignored.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<RecordSet>> UpdateWithHttpMessagesAsync(string resourceGroupName, string zoneName, string relativeRecordSetName, RecordType recordType, RecordSet parameters, string ifMatch = default(string), string ifNoneMatch = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (zoneName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "zoneName");
}
if (relativeRecordSetName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "relativeRecordSetName");
}
if (parameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "parameters");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("zoneName", zoneName);
tracingParameters.Add("relativeRecordSetName", relativeRecordSetName);
tracingParameters.Add("recordType", recordType);
tracingParameters.Add("parameters", parameters);
tracingParameters.Add("ifMatch", ifMatch);
tracingParameters.Add("ifNoneMatch", ifNoneMatch);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Update", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnszones/{zoneName}/{recordType}/{relativeRecordSetName}").ToString();
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{zoneName}", Uri.EscapeDataString(zoneName));
_url = _url.Replace("{relativeRecordSetName}", relativeRecordSetName);
_url = _url.Replace("{recordType}", Uri.EscapeDataString(SafeJsonConvert.SerializeObject(recordType, this.Client.SerializationSettings).Trim('"')));
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PATCH");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (ifMatch != null)
{
if (_httpRequest.Headers.Contains("If-Match"))
{
_httpRequest.Headers.Remove("If-Match");
}
_httpRequest.Headers.TryAddWithoutValidation("If-Match", ifMatch);
}
if (ifNoneMatch != null)
{
if (_httpRequest.Headers.Contains("If-None-Match"))
{
_httpRequest.Headers.Remove("If-None-Match");
}
_httpRequest.Headers.TryAddWithoutValidation("If-None-Match", ifNoneMatch);
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(parameters != null)
{
_requestContent = SafeJsonConvert.SerializeObject(parameters, this.Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = 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)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<RecordSet>();
_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 = SafeJsonConvert.DeserializeObject<RecordSet>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Creates or Updates a RecordSet within a DNS zone.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='zoneName'>
/// The name of the zone without a terminating dot.
/// </param>
/// <param name='relativeRecordSetName'>
/// The name of the RecordSet, relative to the name of the zone.
/// </param>
/// <param name='recordType'>
/// The type of DNS record. Possible values include: 'A', 'AAAA', 'CNAME',
/// 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT'
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the CreateOrUpdate operation.
/// </param>
/// <param name='ifMatch'>
/// The etag of Recordset.
/// </param>
/// <param name='ifNoneMatch'>
/// Defines the If-None-Match condition. Set to '*' to force
/// Create-If-Not-Exist. Other values will be ignored.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<RecordSet>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string zoneName, string relativeRecordSetName, RecordType recordType, RecordSet parameters, string ifMatch = default(string), string ifNoneMatch = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (zoneName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "zoneName");
}
if (relativeRecordSetName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "relativeRecordSetName");
}
if (parameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "parameters");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("zoneName", zoneName);
tracingParameters.Add("relativeRecordSetName", relativeRecordSetName);
tracingParameters.Add("recordType", recordType);
tracingParameters.Add("parameters", parameters);
tracingParameters.Add("ifMatch", ifMatch);
tracingParameters.Add("ifNoneMatch", ifNoneMatch);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdate", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnszones/{zoneName}/{recordType}/{relativeRecordSetName}").ToString();
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{zoneName}", Uri.EscapeDataString(zoneName));
_url = _url.Replace("{relativeRecordSetName}", relativeRecordSetName);
_url = _url.Replace("{recordType}", Uri.EscapeDataString(SafeJsonConvert.SerializeObject(recordType, this.Client.SerializationSettings).Trim('"')));
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (ifMatch != null)
{
if (_httpRequest.Headers.Contains("If-Match"))
{
_httpRequest.Headers.Remove("If-Match");
}
_httpRequest.Headers.TryAddWithoutValidation("If-Match", ifMatch);
}
if (ifNoneMatch != null)
{
if (_httpRequest.Headers.Contains("If-None-Match"))
{
_httpRequest.Headers.Remove("If-None-Match");
}
_httpRequest.Headers.TryAddWithoutValidation("If-None-Match", ifNoneMatch);
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(parameters != null)
{
_requestContent = SafeJsonConvert.SerializeObject(parameters, this.Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = 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)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 201 && (int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<RecordSet>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<RecordSet>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<RecordSet>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Removes a RecordSet from a DNS zone.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='zoneName'>
/// The name of the zone without a terminating dot.
/// </param>
/// <param name='relativeRecordSetName'>
/// The name of the RecordSet, relative to the name of the zone.
/// </param>
/// <param name='recordType'>
/// The type of DNS record. Possible values include: 'A', 'AAAA', 'CNAME',
/// 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT'
/// </param>
/// <param name='ifMatch'>
/// Defines the If-Match condition. The delete operation will be performed
/// only if the ETag of the zone on the server matches this value.
/// </param>
/// <param name='ifNoneMatch'>
/// Defines the If-None-Match condition. The delete operation will be
/// performed only if the ETag of the zone on the server does not match this
/// value.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string zoneName, string relativeRecordSetName, RecordType recordType, string ifMatch = default(string), string ifNoneMatch = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (zoneName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "zoneName");
}
if (relativeRecordSetName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "relativeRecordSetName");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("zoneName", zoneName);
tracingParameters.Add("relativeRecordSetName", relativeRecordSetName);
tracingParameters.Add("recordType", recordType);
tracingParameters.Add("ifMatch", ifMatch);
tracingParameters.Add("ifNoneMatch", ifNoneMatch);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Delete", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnszones/{zoneName}/{recordType}/{relativeRecordSetName}").ToString();
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{zoneName}", Uri.EscapeDataString(zoneName));
_url = _url.Replace("{relativeRecordSetName}", relativeRecordSetName);
_url = _url.Replace("{recordType}", Uri.EscapeDataString(SafeJsonConvert.SerializeObject(recordType, this.Client.SerializationSettings).Trim('"')));
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("DELETE");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (ifMatch != null)
{
if (_httpRequest.Headers.Contains("If-Match"))
{
_httpRequest.Headers.Remove("If-Match");
}
_httpRequest.Headers.TryAddWithoutValidation("If-Match", ifMatch);
}
if (ifNoneMatch != null)
{
if (_httpRequest.Headers.Contains("If-None-Match"))
{
_httpRequest.Headers.Remove("If-None-Match");
}
_httpRequest.Headers.TryAddWithoutValidation("If-None-Match", ifNoneMatch);
}
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)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 204 && (int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_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)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets a RecordSet.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='zoneName'>
/// The name of the zone without a terminating dot.
/// </param>
/// <param name='relativeRecordSetName'>
/// The name of the RecordSet, relative to the name of the zone.
/// </param>
/// <param name='recordType'>
/// The type of DNS record. Possible values include: 'A', 'AAAA', 'CNAME',
/// 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT'
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<RecordSet>> GetWithHttpMessagesAsync(string resourceGroupName, string zoneName, string relativeRecordSetName, RecordType recordType, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (zoneName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "zoneName");
}
if (relativeRecordSetName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "relativeRecordSetName");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("zoneName", zoneName);
tracingParameters.Add("relativeRecordSetName", relativeRecordSetName);
tracingParameters.Add("recordType", recordType);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnszones/{zoneName}/{recordType}/{relativeRecordSetName}").ToString();
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{zoneName}", Uri.EscapeDataString(zoneName));
_url = _url.Replace("{relativeRecordSetName}", relativeRecordSetName);
_url = _url.Replace("{recordType}", Uri.EscapeDataString(SafeJsonConvert.SerializeObject(recordType, this.Client.SerializationSettings).Trim('"')));
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", 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)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<RecordSet>();
_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 = SafeJsonConvert.DeserializeObject<RecordSet>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Lists the RecordSets of a specified type in a DNS zone.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the zone.
/// </param>
/// <param name='zoneName'>
/// The name of the zone from which to enumerate RecordsSets.
/// </param>
/// <param name='recordType'>
/// The type of record sets to enumerate. Possible values include: 'A',
/// 'AAAA', 'CNAME', 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT'
/// </param>
/// <param name='top'>
/// Query parameters. If null is passed returns the default number of zones.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<RecordSet>>> ListByTypeWithHttpMessagesAsync(string resourceGroupName, string zoneName, RecordType recordType, string top = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (zoneName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "zoneName");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("zoneName", zoneName);
tracingParameters.Add("recordType", recordType);
tracingParameters.Add("top", top);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListByType", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnszones/{zoneName}/{recordType}").ToString();
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{zoneName}", Uri.EscapeDataString(zoneName));
_url = _url.Replace("{recordType}", Uri.EscapeDataString(SafeJsonConvert.SerializeObject(recordType, this.Client.SerializationSettings).Trim('"')));
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (top != null)
{
_queryParameters.Add(string.Format("$top={0}", Uri.EscapeDataString(top)));
}
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", 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)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<RecordSet>>();
_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 = SafeJsonConvert.DeserializeObject<Page<RecordSet>>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Lists all RecordSets in a DNS zone.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the zone.
/// </param>
/// <param name='zoneName'>
/// The name of the zone from which to enumerate RecordSets.
/// </param>
/// <param name='top'>
/// Query parameters. If null is passed returns the default number of zones.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<RecordSet>>> ListAllInResourceGroupWithHttpMessagesAsync(string resourceGroupName, string zoneName, string top = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (zoneName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "zoneName");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("zoneName", zoneName);
tracingParameters.Add("top", top);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListAllInResourceGroup", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnszones/{zoneName}/recordsets").ToString();
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{zoneName}", Uri.EscapeDataString(zoneName));
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (top != null)
{
_queryParameters.Add(string.Format("$top={0}", Uri.EscapeDataString(top)));
}
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", 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)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<RecordSet>>();
_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 = SafeJsonConvert.DeserializeObject<Page<RecordSet>>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Lists the RecordSets of a specified type in a DNS zone.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<RecordSet>>> ListByTypeNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListByTypeNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", 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)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<RecordSet>>();
_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 = SafeJsonConvert.DeserializeObject<Page<RecordSet>>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Lists all RecordSets in a DNS zone.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<RecordSet>>> ListAllInResourceGroupNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListAllInResourceGroupNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", 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)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<RecordSet>>();
_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 = SafeJsonConvert.DeserializeObject<Page<RecordSet>>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
//
// Encog(tm) Core v3.3 - .Net Version
// http://www.heatonresearch.com/encog/
//
// Copyright 2008-2014 Heaton Research, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// For more information on Heaton Research copyrights, licenses
// and trademarks visit:
// http://www.heatonresearch.com/copyright
//
using System;
using System.IO;
using Encog.App.Analyst;
using Encog.App.Analyst.Script.Prop;
using Encog.App.Generate.Generators;
using Encog.App.Generate.Generators.CS;
using Encog.App.Generate.Generators.JS;
using Encog.App.Generate.Generators.Java;
using Encog.App.Generate.Generators.MQL4;
using Encog.App.Generate.Generators.NinjaScript;
using Encog.App.Generate.Program;
using Encog.ML;
using Encog.Neural.Networks;
using Encog.Persist;
namespace Encog.App.Generate
{
/// <summary>
/// Perform Encog code generation. Encog is capable of generating code from
/// several different objects. This code generation will be to the specified
/// target language.
/// </summary>
public class EncogCodeGeneration
{
/**
* The language specific code generator.
*/
private readonly ILanguageSpecificGenerator generator;
/**
* The program that we are generating.
*/
private readonly EncogGenProgram program = new EncogGenProgram();
/// <summary>
/// The target language for the code generation.
/// </summary>
private readonly TargetLanguage targetLanguage;
/**
* Construct the generation object.
*
* @param theTargetLanguage
* The target language.
*/
public EncogCodeGeneration(TargetLanguage theTargetLanguage)
{
targetLanguage = theTargetLanguage;
switch (theTargetLanguage)
{
case TargetLanguage.NoGeneration:
throw new AnalystCodeGenerationError(
"No target language has been specified for code generation.");
case TargetLanguage.Java:
generator = new GenerateEncogJava();
break;
case TargetLanguage.CSharp:
generator = new GenerateCS();
break;
case TargetLanguage.MQL4:
generator = new GenerateMQL4();
break;
case TargetLanguage.NinjaScript:
generator = new GenerateNinjaScript();
break;
case TargetLanguage.JavaScript:
generator = new GenerateEncogJavaScript();
break;
}
}
public bool EmbedData { get; set; }
public TargetLanguage TargetLanguage
{
get { return targetLanguage; }
}
/// <summary>
/// Is the specified method supported for code generation?
/// </summary>
/// <param name="method">The specified method.</param>
/// <returns>True, if the specified method is supported.</returns>
public static bool IsSupported(IMLMethod method)
{
if (method is BasicNetwork)
{
return true;
}
else
{
return false;
}
}
/// <summary>
/// Get the extension fot the specified language.
/// </summary>
/// <param name="lang">The specified language.</param>
/// <returns></returns>
public static string GetExtension(TargetLanguage lang)
{
if (lang == TargetLanguage.Java)
{
return "java";
}
else if (lang == TargetLanguage.JavaScript)
{
return "html";
}
else if (lang == TargetLanguage.CSharp)
{
return "cs";
}
else if (lang == TargetLanguage.MQL4)
{
return "mql4";
}
else if (lang == TargetLanguage.NinjaScript)
{
return "cs";
}
else
{
return "txt";
}
}
/**
* Generate the code from Encog Analyst.
*
* @param analyst
* The Encog Analyst object to use for code generation.
*/
public void Generate(EncogAnalyst analyst)
{
if (targetLanguage == TargetLanguage.MQL4
|| targetLanguage == TargetLanguage.NinjaScript)
{
if (!EmbedData)
{
throw new AnalystCodeGenerationError(
"MQL4 and Ninjascript must be embedded.");
}
}
if (generator is IProgramGenerator)
{
String methodID =
analyst.Script.Properties.GetPropertyString(ScriptProperties.MlConfigMachineLearningFile);
String trainingID = analyst.Script.Properties.GetPropertyString(ScriptProperties.MlConfigTrainingFile);
FileInfo methodFile = analyst.Script.ResolveFilename(methodID);
FileInfo trainingFile = analyst.Script.ResolveFilename(trainingID);
Generate(methodFile, trainingFile);
}
else
{
((ITemplateGenerator) generator).Generate(analyst);
}
}
/**
* Generate from a method and data.
*
* @param method
* The machine learning method to generate from.
* @param data
* The data to use perform generation.
*/
public void Generate(FileInfo method, FileInfo data)
{
EncogProgramNode createNetworkFunction = null;
program.AddComment("Code generated by Encog v"
+ EncogFramework.Instance.Properties[EncogFramework.EncogVersion]);
program.AddComment("Generation Date: " + new DateTime().ToString());
program.AddComment("Generated code may be used freely");
program.AddComment("http://www.heatonresearch.com/encog");
EncogProgramNode mainClass = program.CreateClass("EncogExample");
if (targetLanguage == TargetLanguage.MQL4
|| targetLanguage == TargetLanguage.NinjaScript)
{
throw new AnalystCodeGenerationError(
"MQL4 and Ninjascript can only be generated from Encog Analyst");
}
if (data != null)
{
mainClass.EmbedTraining(data);
if (!(generator is GenerateEncogJavaScript))
{
mainClass.GenerateLoadTraining(data);
}
}
if (method != null)
{
createNetworkFunction = GenerateForMethod(mainClass, method);
}
EncogProgramNode mainFunction = mainClass.CreateMainFunction();
if (createNetworkFunction != null)
{
mainFunction.CreateFunctionCall(createNetworkFunction, "MLMethod",
"method");
}
if (data != null)
{
if (!(generator is GenerateEncogJavaScript))
{
mainFunction.CreateFunctionCall("createTraining", "MLDataSet",
"training");
}
}
mainFunction
.AddComment("Network and/or data is now loaded, you can add code to train, evaluate, etc.");
((IProgramGenerator) generator).Generate(program, EmbedData);
}
/**
* GEnerate from a machine learning method.
*
* @param mainClass
* The main class.
* @param method
* The filename of the method.
* @return The newly created node.
*/
private EncogProgramNode GenerateForMethod(
EncogProgramNode mainClass, FileInfo method)
{
if (EmbedData)
{
var encodable = (IMLEncodable) EncogDirectoryPersistence
.LoadObject(method);
var weights = new double[encodable.EncodedArrayLength()];
encodable.EncodeToArray(weights);
mainClass.CreateArray("WEIGHTS", weights);
}
return mainClass.CreateNetworkFunction("createNetwork", method);
}
/**
* @return the targetLanguage
*/
/**
* Save the contents to a string.
*
* @return The contents.
*/
public String Save()
{
return generator.Contents;
}
/**
* Save the contents to the specified file.
*
* @param file
*/
public void Save(FileInfo file)
{
generator.WriteContents(file);
}
}
}
| |
/*
* Naiad ver. 0.5
* Copyright (c) Microsoft Corporation
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT
* LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR
* A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.
*
* See the Apache Version 2.0 License for specific language governing
* permissions and limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Threading;
using Microsoft.Research.Naiad.Diagnostics;
namespace Microsoft.Research.Naiad.Utilities
{
internal class Win32
{
[DllImport("kernel32.dll")]
internal static extern UInt32 GetLastError();
[DllImport("kernel32.dll", SetLastError = true)]
internal static extern IntPtr GetCurrentThread();
[DllImport("kernel32.dll", SetLastError = true)]
internal static extern UInt32 GetCurrentThreadId();
[DllImport("kernel32.dll", SetLastError = true)]
internal static extern IntPtr SetThreadAffinityMask(IntPtr hThread, IntPtr dwThreadAffinityMask);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
internal static extern int SetThreadIdealProcessor(IntPtr handle, int processor);
[DllImport("kernel32.dll", SetLastError = true)]
internal static extern IntPtr OpenThread(uint DesiredAccess, bool InheritHandle, uint ThreadId);
[DllImport("kernel32.dll", SetLastError = true)]
internal static extern bool CloseHandle(IntPtr Handle);
[DllImport("kernel32.dll", SetLastError = true)]
internal static extern bool QueryThreadCycleTime([In] IntPtr ThreadHandle, [Out] out ulong CycleTime);
[DllImport("kernel32.dll", SetLastError = true)]
internal static extern UInt32 GetCurrentProcessId();
[DllImport("kernel32.dll", SetLastError = true)]
internal static extern IntPtr OpenProcess(uint DesiredAccess, bool InheritHandle, uint ProcessId);
[DllImport("kernel32.dll", SetLastError = true)]
internal static extern bool GetProcessWorkingSetSize([In] IntPtr ProcessHandle, [Out] out ulong MinBytes, [Out] out ulong MaxBytes);
[DllImport("ws2_32.dll", SetLastError = true)]
internal static extern int WSAIoctl([In] IntPtr Socket, UInt32 controlcode,
[In] byte[] inBuf, int cbInBuf,
[In] IntPtr outBuf, int cbOutBuf, // Not used - nust be zero
[Out] out UInt32 pBytesRet,
[In] IntPtr lpOverlapped,
[In] IntPtr lpCompletionRoutine);
/*
WSAAPI
WSAIoctl(
_In_ SOCKET s,
_In_ DWORD dwIoControlCode,
_In_reads_bytes_opt_(cbInBuffer) LPVOID lpvInBuffer,
_In_ DWORD cbInBuffer,
_Out_writes_bytes_to_opt_(cbOutBuffer, *lpcbBytesReturned) LPVOID lpvOutBuffer,
_In_ DWORD cbOutBuffer,
_Out_ LPDWORD lpcbBytesReturned,
_Inout_opt_ LPWSAOVERLAPPED lpOverlapped,
_In_opt_ LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
);
*/
const UInt32 SIO_KEEPALIVE_VALS = 0x98000004;
public static void SetKeepaliveOptions(IntPtr sockHandle)
{
/*
struct tcp_keepalive arg;
DWORD cb;
arg.onoff = 1;
arg.keepalivetime = 10;
arg.keepaliveinterval = 2000;
winStatus = WSAIoctl(s1, SIO_KEEPALIVE_VALS, &arg, sizeof(arg), NULL, 0, &cb, NULL, NULL);
if (winStatus != ERROR_SUCCESS) {
wprintf(L"\nFailed to set SIO_KEEPALIVE_VALS. Error %d", winStatus);
goto bail;
}
*
* http://msdn.microsoft.com/en-us/library/windows/desktop/dd877220(v=vs.85).aspx
* If the onoff member is set to a nonzero value, TCP keep-alive is enabled and the other members in the structure are used.
* The keepalivetime member specifies the timeout, in milliseconds, with no activity until the first keep-alive packet is sent.
* The keepaliveinterval member specifies the interval, in milliseconds, between when successive keep-alive packets are sent
* if no acknowledgement is received.
*
* ie: Keepalive timout is the time from last sent/recvd data packet until a keepalive is sent.
* KAInterval is the time between subsquenet keepalives if no keepalive ack is received
*
*/
byte[] keepalivevals = new byte[12];
int interval = 10;
keepalivevals[0] = 1;
keepalivevals[4] = 10;
keepalivevals[8] = (byte)(interval & 0xff);
keepalivevals[9] = (byte)(interval >> 8);
UInt32 cbRet = 0;
int ret = WSAIoctl(sockHandle, SIO_KEEPALIVE_VALS,
keepalivevals, 12,
IntPtr.Zero, 0,
out cbRet,
IntPtr.Zero, IntPtr.Zero);
if (ret != 0) Console.WriteLine("WSAIoctl returned {0} {1}", ret, cbRet);
}
[DllImport("winmm.dll", EntryPoint="timeBeginPeriod", SetLastError=true)]
internal static extern uint TimeBeginPeriod(uint uMilliseconds);
[DllImport("winmm.dll", EntryPoint="timeEndPeriod", SetLastError=true)]
internal static extern uint TimeEndPeriod(uint uMilliseconds);
}
internal class PinnedThread : IDisposable
{
internal IntPtr processHandle; // handle to the process object
public UInt32 processId; // process id
internal IntPtr OSThreadHandle; // handle to the Windows thread object
public UInt32 OSThreadId; // Windows thread id
public int runtimeThreadId; // .NET thread id
public int cpu;
/// <summary>
/// Gets the current thread cycle count by calling QueryThreadCycleTime
/// </summary>
/// <returns>Number of CPU frontier cycles</returns>
public ulong QueryThreadCycles()
{
ulong cycles = 0;
if (Win32.QueryThreadCycleTime(this.OSThreadHandle, out cycles) == false)
{
Console.Error.WriteLine("QueryThreadCycleTime error {0}", Win32.GetLastError());
}
return cycles;
}
public ulong QueryMaxWorkingSetSize()
{
ulong maxbytes = 0, minbytes = 0;
if (Win32.GetProcessWorkingSetSize(this.processHandle, out minbytes, out maxbytes) == false)
{
Console.Error.WriteLine("GetProcessWorkingSetSize error {0}", Win32.GetLastError());
}
return maxbytes;
}
/// <summary>
/// Affinitizes the current runtime thread to the OS thread and the OS thread to the specified processor
/// </summary>
/// <param name="cpu">Processor number</param>
/// <param name="soft">if true use soft affinity</param>
public PinnedThread(int cpu, bool soft=false)
{
// Tie the runtime thread to the OS thread
Thread.BeginThreadAffinity();
uint ret = Win32.TimeBeginPeriod(1);
if (ret != 0) Console.Error.WriteLine("TimeBeginPeriod returned {0}", ret);
// Get the OS thread handle
this.OSThreadId = Win32.GetCurrentThreadId();
this.OSThreadHandle = Win32.OpenThread(0x001fffff, false, this.OSThreadId); // THREAD_ALL_ACCESS
if (this.OSThreadHandle == IntPtr.Zero || this.OSThreadHandle.ToInt64() == 0)
{
Console.Error.WriteLine("OpenThread error {0}", Win32.GetLastError());
}
if (soft) {
Win32.SetThreadIdealProcessor(Win32.GetCurrentThread(), cpu);
}
else
{
// Tie the OS thread to a processor
IntPtr oldmask;
IntPtr newmask;
if ((oldmask = Win32.SetThreadAffinityMask(Win32.GetCurrentThread(), new IntPtr(1L << cpu))) == IntPtr.Zero)
{
Logging.Error("SetThreadAffinityMask error 0x{0:x} for thread 0x{1:x} (#1)", Win32.GetLastError(), OSThreadId);
}
if ((newmask = Win32.SetThreadAffinityMask(Win32.GetCurrentThread(), new IntPtr(1L << cpu))) == IntPtr.Zero)
{
Logging.Error("SetThreadAffinityMask error 0x{0:x} for thread 0x{1:x} (#2)", Win32.GetLastError(), OSThreadId);
}
//Console.Error.WriteLine("Thread {0:x} affinitized to {1:x} (attempted {2:x}, was {3:x})",
// OSThreadId, newmask.ToInt64(), 1L << cpu, oldmask.ToInt64());
}
this.cpu = cpu;
this.runtimeThreadId = Thread.CurrentThread.ManagedThreadId;
this.processId = Win32.GetCurrentProcessId();
this.processHandle = Win32.OpenProcess(0x1F0FFF, false, this.processId); // PROCESS_ALL_ACCESS
if (this.processHandle == IntPtr.Zero || this.processHandle.ToInt64() == 0)
{
Logging.Error("OpenProcess error {0}", Win32.GetLastError());
}
}
public PinnedThread(ulong affinitymask)
{
// Tie the runtime thread to the OS thread
Thread.BeginThreadAffinity();
uint ret = Win32.TimeBeginPeriod(1);
if (ret != 0) Console.Error.WriteLine("TimeBeginPeriod returned {0}", ret);
// Get the OS thread handle
this.OSThreadId = Win32.GetCurrentThreadId();
this.OSThreadHandle = Win32.OpenThread(0x001fffff, false, this.OSThreadId); // THREAD_ALL_ACCESS
if (this.OSThreadHandle == IntPtr.Zero || this.OSThreadHandle.ToInt64() == 0)
{
Console.Error.WriteLine("OpenThread error {0}", Win32.GetLastError());
}
// Tie the OS thread to a processor
IntPtr oldmask;
IntPtr newmask;
if ((oldmask = Win32.SetThreadAffinityMask(Win32.GetCurrentThread(), new IntPtr((long)affinitymask))) == IntPtr.Zero)
{
Logging.Error("SetThreadAffinityMask error 0x{0:x} for thread 0x{1:x} (#1)", Win32.GetLastError(), OSThreadId);
}
if ((newmask = Win32.SetThreadAffinityMask(Win32.GetCurrentThread(), new IntPtr((long)affinitymask))) == IntPtr.Zero)
{
Logging.Error("SetThreadAffinityMask error 0x{0:x} for thread 0x{1:x} (#2)", Win32.GetLastError(), OSThreadId);
}
this.cpu = -1;
this.runtimeThreadId = Thread.CurrentThread.ManagedThreadId;
this.processId = Win32.GetCurrentProcessId();
this.processHandle = Win32.OpenProcess(0x1F0FFF, false, this.processId); // PROCESS_ALL_ACCESS
if (this.processHandle == IntPtr.Zero || this.processHandle.ToInt64() == 0)
{
Logging.Error("OpenProcess error {0}", Win32.GetLastError());
}
}
public void Dispose()
{
Win32.TimeEndPeriod(1);
if (Win32.CloseHandle(this.OSThreadHandle) == false)
{
Logging.Error("CloseHandle(thread) error {0}", Win32.GetLastError());
}
if (Win32.CloseHandle(this.processHandle) == false)
{
Logging.Error("CloseHandle(process) error {0}", Win32.GetLastError());
}
Thread.EndThreadAffinity();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
namespace System.Linq.Expressions.Tests
{
public static class BinaryOrTests
{
#region Test methods
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckByteOrTest(bool useInterpreter)
{
byte[] array = new byte[] { 0, 1, byte.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyByteOr(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckSByteOrTest(bool useInterpreter)
{
sbyte[] array = new sbyte[] { 0, 1, -1, sbyte.MinValue, sbyte.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifySByteOr(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckUShortOrTest(bool useInterpreter)
{
ushort[] array = new ushort[] { 0, 1, ushort.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyUShortOr(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckShortOrTest(bool useInterpreter)
{
short[] array = new short[] { 0, 1, -1, short.MinValue, short.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyShortOr(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckUIntOrTest(bool useInterpreter)
{
uint[] array = new uint[] { 0, 1, uint.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyUIntOr(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckIntOrTest(bool useInterpreter)
{
int[] array = new int[] { 0, 1, -1, int.MinValue, int.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyIntOr(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckULongOrTest(bool useInterpreter)
{
ulong[] array = new ulong[] { 0, 1, ulong.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyULongOr(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckLongOrTest(bool useInterpreter)
{
long[] array = new long[] { 0, 1, -1, long.MinValue, long.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyLongOr(array[i], array[j], useInterpreter);
}
}
}
#endregion
#region Test verifiers
private static void VerifyByteOr(byte a, byte b, bool useInterpreter)
{
Expression<Func<byte>> e =
Expression.Lambda<Func<byte>>(
Expression.Or(
Expression.Constant(a, typeof(byte)),
Expression.Constant(b, typeof(byte))),
Enumerable.Empty<ParameterExpression>());
Func<byte> f = e.Compile(useInterpreter);
Assert.Equal((byte)(a | b), f());
}
private static void VerifySByteOr(sbyte a, sbyte b, bool useInterpreter)
{
Expression<Func<sbyte>> e =
Expression.Lambda<Func<sbyte>>(
Expression.Or(
Expression.Constant(a, typeof(sbyte)),
Expression.Constant(b, typeof(sbyte))),
Enumerable.Empty<ParameterExpression>());
Func<sbyte> f = e.Compile(useInterpreter);
Assert.Equal((sbyte)(a | b), f());
}
private static void VerifyUShortOr(ushort a, ushort b, bool useInterpreter)
{
Expression<Func<ushort>> e =
Expression.Lambda<Func<ushort>>(
Expression.Or(
Expression.Constant(a, typeof(ushort)),
Expression.Constant(b, typeof(ushort))),
Enumerable.Empty<ParameterExpression>());
Func<ushort> f = e.Compile(useInterpreter);
Assert.Equal((ushort)(a | b), f());
}
private static void VerifyShortOr(short a, short b, bool useInterpreter)
{
Expression<Func<short>> e =
Expression.Lambda<Func<short>>(
Expression.Or(
Expression.Constant(a, typeof(short)),
Expression.Constant(b, typeof(short))),
Enumerable.Empty<ParameterExpression>());
Func<short> f = e.Compile(useInterpreter);
Assert.Equal((short)(a | b), f());
}
private static void VerifyUIntOr(uint a, uint b, bool useInterpreter)
{
Expression<Func<uint>> e =
Expression.Lambda<Func<uint>>(
Expression.Or(
Expression.Constant(a, typeof(uint)),
Expression.Constant(b, typeof(uint))),
Enumerable.Empty<ParameterExpression>());
Func<uint> f = e.Compile(useInterpreter);
Assert.Equal(a | b, f());
}
private static void VerifyIntOr(int a, int b, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.Or(
Expression.Constant(a, typeof(int)),
Expression.Constant(b, typeof(int))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(a | b, f());
}
private static void VerifyULongOr(ulong a, ulong b, bool useInterpreter)
{
Expression<Func<ulong>> e =
Expression.Lambda<Func<ulong>>(
Expression.Or(
Expression.Constant(a, typeof(ulong)),
Expression.Constant(b, typeof(ulong))),
Enumerable.Empty<ParameterExpression>());
Func<ulong> f = e.Compile(useInterpreter);
Assert.Equal(a | b, f());
}
private static void VerifyLongOr(long a, long b, bool useInterpreter)
{
Expression<Func<long>> e =
Expression.Lambda<Func<long>>(
Expression.Or(
Expression.Constant(a, typeof(long)),
Expression.Constant(b, typeof(long))),
Enumerable.Empty<ParameterExpression>());
Func<long> f = e.Compile(useInterpreter);
Assert.Equal(a | b, f());
}
#endregion
[Fact]
public static void CannotReduce()
{
Expression exp = Expression.Or(Expression.Constant(0), Expression.Constant(0));
Assert.False(exp.CanReduce);
Assert.Same(exp, exp.Reduce());
Assert.Throws<ArgumentException>(null, () => exp.ReduceAndCheck());
}
[Fact]
public static void ThrowsOnLeftNull()
{
AssertExtensions.Throws<ArgumentNullException>("left", () => Expression.Or(null, Expression.Constant("")));
}
[Fact]
public static void ThrowsOnRightNull()
{
AssertExtensions.Throws<ArgumentNullException>("right", () => Expression.Or(Expression.Constant(""), null));
}
private static class Unreadable<T>
{
public static T WriteOnly
{
set { }
}
}
[Fact]
public static void ThrowsOnLeftUnreadable()
{
Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly");
AssertExtensions.Throws<ArgumentException>("left", () => Expression.Or(value, Expression.Constant(1)));
}
[Fact]
public static void ThrowsOnRightUnreadable()
{
Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly");
AssertExtensions.Throws<ArgumentException>("right", () => Expression.Or(Expression.Constant(1), value));
}
[Fact]
public static void ToStringTest()
{
BinaryExpression e1 = Expression.Or(Expression.Parameter(typeof(int), "a"), Expression.Parameter(typeof(int), "b"));
Assert.Equal("(a | b)", e1.ToString());
BinaryExpression e2 = Expression.Or(Expression.Parameter(typeof(bool), "a"), Expression.Parameter(typeof(bool), "b"));
Assert.Equal("(a Or b)", e2.ToString());
BinaryExpression e3 = Expression.Or(Expression.Parameter(typeof(bool?), "a"), Expression.Parameter(typeof(bool?), "b"));
Assert.Equal("(a Or b)", e3.ToString());
}
}
}
| |
// Copyright (c) 2017 Jean Ressouche @SouchProd. All rights reserved.
// https://github.com/souchprod/SouchProd.EntityFrameworkCore.Firebird
// This code inherit from the .Net Foundation Entity Core repository (Apache licence)
// and from the Pomelo Foundation Mysql provider repository (MIT licence).
// Licensed under the MIT. See LICENSE in the project root for license information.
using System;
using System.Data;
using System.Data.Common;
using System.Diagnostics;
using System.Text;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Infrastructure.Internal;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.EntityFrameworkCore.Storage.Internal;
using FirebirdSql.Data.FirebirdClient;
namespace Microsoft.EntityFrameworkCore.Internal
{
public class FbOptions : IFirebirdOptions
{
private FbOptionsExtension _relationalOptions;
private readonly Lazy<FbConnectionSettings> _lazyConnectionSettings;
public FbOptions()
{
_lazyConnectionSettings = new Lazy<FbConnectionSettings>(() =>
{
if (_relationalOptions.Connection != null)
return FbConnectionSettings.GetSettings(_relationalOptions.Connection);
return FbConnectionSettings.GetSettings(_relationalOptions.ConnectionString);
});
}
public virtual void Initialize(IDbContextOptions options)
{
_relationalOptions = options.FindExtension<FbOptionsExtension>() ?? new FbOptionsExtension();
}
public virtual void Validate(IDbContextOptions options)
{
if (_relationalOptions.ConnectionString == null && _relationalOptions.Connection == null)
throw new InvalidOperationException(RelationalStrings.NoConnectionOrConnectionString);
}
public virtual FbConnectionSettings ConnectionSettings => _lazyConnectionSettings.Value;
public virtual string GetCreateTable(ISqlGenerationHelper sqlGenerationHelper, string table, string schema)
{
if (_relationalOptions.Connection != null)
return GetCreateTable(_relationalOptions.Connection, sqlGenerationHelper, table, schema);
return GetCreateTable(_relationalOptions.ConnectionString, sqlGenerationHelper, table, schema);
}
private static string GetCreateTable(string connectionString, ISqlGenerationHelper sqlGenerationHelper, string table, string schema)
{
using (var connection = new FbConnection(connectionString))
{
connection.Open();
return ExecuteCreateTable(connection, sqlGenerationHelper, table, schema);
}
}
private static string GetCreateTable(DbConnection connection, ISqlGenerationHelper sqlGenerationHelper, string table, string schema)
{
var opened = false;
if (connection.State == ConnectionState.Closed)
{
connection.Open();
opened = true;
}
try
{
return ExecuteCreateTable(connection, sqlGenerationHelper, table, schema);
}
finally
{
if (opened)
connection.Close();
}
}
private static string ExecuteCreateTable(DbConnection connection, ISqlGenerationHelper sqlGenerationHelper, string table, string schema)
{
Debug.WriteLine("ExecuteCreateTable");
using (var cmd = connection.CreateCommand())
{
cmd.CommandText = $@"select
rf.rdb$field_name as column_name,
case f.rdb$field_type
when 261 then 'BLOB SUB_TYPE ' || F.RDB$FIELD_SUB_TYPE
when 37 then 'VARCHAR(' || (TRUNC(F.RDB$FIELD_LENGTH / CH.RDB$BYTES_PER_CHARACTER)) || ')'
when 35 then 'TIMESTAMP'
when 27 then 'DOUBLE PRECISION'
when 16 then
case f.rdb$field_sub_type
when 0 then 'BIGINT'
when 1 then 'DECIMAL'
when 2 then 'DECIMAL'
end
when 14 then 'CHAR(' || (TRUNC(F.RDB$FIELD_LENGTH / CH.RDB$BYTES_PER_CHARACTER)) || ') '
when 13 then 'TIME'
when 12 then 'DATE'
when 10 then 'FLOAT'
when 9 then 'QUAD'
when 8 then
case f.rdb$field_sub_type
when 0 then 'INTEGER'
when 1 then 'DECIMAL'
when 2 then 'DECIMAL'
end
when 7 then
case f.rdb$field_sub_type
when 0 then 'SMALLINT'
when 1 then 'DECIMAL'
when 2 then 'DECIMAL'
end
end as data_type,
IIF(COALESCE(RF.RDB$NULL_FLAG, 0) = 0, null, 'NOT NULL') as nullable
from rdb$fields f
join rdb$relation_fields rf on rf.rdb$field_source = f.rdb$field_name
left join rdb$character_sets ch on(CH.RDB$CHARACTER_SET_ID = F.RDB$CHARACTER_SET_ID)
where rf.rdb$relation_name = '{sqlGenerationHelper.DelimitIdentifier(table, schema)}'";
Debug.WriteLine("ExecuteCreateTable = > " + cmd.CommandText);
var sb = new StringBuilder();
sb.AppendLine($"CREATE TABLE {sqlGenerationHelper.DelimitIdentifier(table, schema)} (");
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
sb.AppendLine($"{reader.GetFieldValue<string>(0)} {(reader.GetFieldValue<string>(1) + " " +reader.GetFieldValue<string>(2)).Trim()},");
}
}
sb.AppendLine(");");
Debug.WriteLine("ExecuteCreateTable = > List PK");
string GetPrimaryQuery = $@"
select
I.rdb$index_name as Index_Name,
I.rdb$unique_flag as Non_Unique,
I.rdb$relation_name as Columns
from
RDB$INDICES I
where
I.rdb$relation_name = '{sqlGenerationHelper.DelimitIdentifier(table, schema)}'
and I.rdb$index_name like 'PK_%'
group by
Index_Name, Non_Unique, Columns";
cmd.CommandText = GetPrimaryQuery;
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
sb.AppendLine(
$"ALTER TABLE {sqlGenerationHelper.DelimitIdentifier(table, schema)} ADD CONSTRAINT {reader.GetFieldValue<string>(0)} PRIMARY KEY ({reader.GetFieldValue<string>(2)})");
}
}
Debug.WriteLine("ExecuteCreateTable = > List Idx");
string GetIndexesQuery = $@"
select
I.rdb$index_name as Index_Name,
I.rdb$unique_flag as Non_Unique,
I.rdb$relation_name as Columns
from
RDB$INDICES I
where
I.rdb$relation_name = '{sqlGenerationHelper.DelimitIdentifier(table, schema)}'
and I.rdb$index_name not like 'PK_%'
and I.rdb$index_name not like 'FK_%'
group by
Index_Name, Non_Unique, Columns";
cmd.CommandText = GetIndexesQuery;
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
sb.AppendLine(
$"CREATE INDEX {reader.GetFieldValue<string>(0)} ON {sqlGenerationHelper.DelimitIdentifier(table, schema)} ({reader.GetFieldValue<string>(2)})");
}
}
Debug.WriteLine("ExecuteCreateTable = > " + sb.ToString());
return sb.ToString();
// TODO: Triggers
}
return null;
}
}
}
| |
using System;
using NUnit.Framework;
using NServiceKit.Common.Tests.Models;
using NServiceKit.DataAnnotations;
using NServiceKit.OrmLite.Sqlite;
using NServiceKit.Text;
namespace NServiceKit.OrmLite.Tests
{
/// <summary>An ORM lite transaction tests.</summary>
[TestFixture]
public class OrmLiteTransactionTests
: OrmLiteTestBase
{
/// <summary>Transaction commit persists data to the database.</summary>
[Test]
public void Transaction_commit_persists_data_to_the_db()
{
using (var db = Config.OpenDbConnection())
{
db.DropAndCreateTable<ModelWithIdAndName>();
db.Insert(new ModelWithIdAndName(1));
using (var dbTrans = db.OpenTransaction())
{
db.Insert(new ModelWithIdAndName(2));
db.Insert(new ModelWithIdAndName(3));
var rowsInTrans = db.Select<ModelWithIdAndName>();
Assert.That(rowsInTrans, Has.Count.EqualTo(3));
dbTrans.Commit();
}
var rows = db.Select<ModelWithIdAndName>();
Assert.That(rows, Has.Count.EqualTo(3));
}
}
/// <summary>Transaction rollsback if not committed.</summary>
[Test]
public void Transaction_rollsback_if_not_committed()
{
using (var db = Config.OpenDbConnection())
{
db.DropAndCreateTable<ModelWithIdAndName>();
db.Insert(new ModelWithIdAndName(1));
using (var dbTrans = db.OpenTransaction())
{
db.Insert(new ModelWithIdAndName(2));
db.Insert(new ModelWithIdAndName(3));
var rowsInTrans = db.Select<ModelWithIdAndName>();
Assert.That(rowsInTrans, Has.Count.EqualTo(3));
}
var rows = db.Select<ModelWithIdAndName>();
Assert.That(rows, Has.Count.EqualTo(1));
}
}
/// <summary>Transaction rollsback transactions to different tables.</summary>
[Test]
public void Transaction_rollsback_transactions_to_different_tables()
{
using (var db = Config.OpenDbConnection())
{
db.DropAndCreateTable<ModelWithIdAndName>();
db.DropAndCreateTable<ModelWithFieldsOfDifferentTypes>();
db.DropAndCreateTable<ModelWithOnlyStringFields>();
db.Insert(new ModelWithIdAndName(1));
using (var dbTrans = db.OpenTransaction())
{
db.Insert(new ModelWithIdAndName(2));
db.Insert(ModelWithFieldsOfDifferentTypes.Create(3));
db.Insert(ModelWithOnlyStringFields.Create("id3"));
Assert.That(db.Select<ModelWithIdAndName>(), Has.Count.EqualTo(2));
Assert.That(db.Select<ModelWithFieldsOfDifferentTypes>(), Has.Count.EqualTo(1));
Assert.That(db.Select<ModelWithOnlyStringFields>(), Has.Count.EqualTo(1));
}
Assert.That(db.Select<ModelWithIdAndName>(), Has.Count.EqualTo(1));
Assert.That(db.Select<ModelWithFieldsOfDifferentTypes>(), Has.Count.EqualTo(0));
Assert.That(db.Select<ModelWithOnlyStringFields>(), Has.Count.EqualTo(0));
}
}
/// <summary>Transaction commits inserts to different tables.</summary>
[Test]
public void Transaction_commits_inserts_to_different_tables()
{
using (var db = Config.OpenDbConnection())
{
db.DropAndCreateTable<ModelWithIdAndName>();
db.DropAndCreateTable<ModelWithFieldsOfDifferentTypes>();
db.DropAndCreateTable<ModelWithOnlyStringFields>();
db.Insert(new ModelWithIdAndName(1));
using (var dbTrans = db.OpenTransaction())
{
db.Insert(new ModelWithIdAndName(2));
db.Insert(ModelWithFieldsOfDifferentTypes.Create(3));
db.Insert(ModelWithOnlyStringFields.Create("id3"));
Assert.That(db.Select<ModelWithIdAndName>(), Has.Count.EqualTo(2));
Assert.That(db.Select<ModelWithFieldsOfDifferentTypes>(), Has.Count.EqualTo(1));
Assert.That(db.Select<ModelWithOnlyStringFields>(), Has.Count.EqualTo(1));
dbTrans.Commit();
}
Assert.That(db.Select<ModelWithIdAndName>(), Has.Count.EqualTo(2));
Assert.That(db.Select<ModelWithFieldsOfDifferentTypes>(), Has.Count.EqualTo(1));
Assert.That(db.Select<ModelWithOnlyStringFields>(), Has.Count.EqualTo(1));
}
}
/// <summary>my table.</summary>
class MyTable
{
/// <summary>Gets or sets the identifier.</summary>
/// <value>The identifier.</value>
[AutoIncrement]
public int Id { get; set; }
/// <summary>Gets or sets some text field.</summary>
/// <value>some text field.</value>
public String SomeTextField { get; set; }
}
/// <summary>Does sqlite transactions.</summary>
[Test]
public void Does_Sqlite_transactions()
{
var factory = new OrmLiteConnectionFactory(":memory:", true, SqliteDialect.Provider);
// test 1 - no transactions
try
{
using (var conn = factory.OpenDbConnection())
{
conn.CreateTable<MyTable>();
conn.Insert(new MyTable { SomeTextField = "Example" });
var record = conn.GetById<MyTable>(1);
}
"Test 1 Success".Print();
}
catch (Exception e)
{
Assert.Fail("Test 1 Failed: {0}".Fmt(e.Message));
}
// test 2 - all transactions
try
{
using (var conn = factory.OpenDbConnection())
{
conn.CreateTable<MyTable>();
using (var tran = conn.OpenTransaction())
{
conn.Insert(new MyTable { SomeTextField = "Example" });
tran.Commit();
}
using (var tran = conn.OpenTransaction())
{
var record = conn.GetById<MyTable>(1);
}
}
"Test 2 Success".Print();
}
catch (Exception e)
{
Assert.Fail("Test 2 Failed: {0}".Fmt(e.Message));
}
// test 3 - transaction for insert, not for select
try
{
using (var conn = factory.OpenDbConnection())
{
conn.CreateTable<MyTable>();
using (var tran = conn.OpenTransaction())
{
conn.Insert(new MyTable { SomeTextField = "Example" });
tran.Commit();
}
var record = conn.GetById<MyTable>(1);
}
"Test 3 Success".Print();
}
catch (Exception e)
{
Assert.Fail("Test 3 Failed: {0}".Fmt(e.Message));
}
}
}
}
| |
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using IxMilia.BCad.Collections;
using IxMilia.BCad.Display;
using IxMilia.BCad.Entities;
using IxMilia.BCad.Extensions;
using IxMilia.BCad.SnapPoints;
namespace IxMilia.BCad
{
public static class DrawingExtensions
{
/// <summary>
/// Adds an entity to the specified layer.
/// </summary>
/// <param name="layer">The layer to which to add the entity.</param>
/// <param name="entity">The entity to add.</param>
/// <returns>The new drawing with the layer added.</returns>
public static Drawing Add(this Drawing drawing, Layer layer, Entity entity)
{
var updatedLayer = layer.Add(entity);
Debug.Assert(updatedLayer.EntityCount - layer.EntityCount == 1, "Expected to add 1 entity.");
return drawing.Replace(layer, updatedLayer);
}
/// <summary>
/// Adds an entity to the current drawing layer.
/// </summary>
/// <param name="entity">The entity to add.</param>
/// <returns></returns>
public static Drawing AddToCurrentLayer(this Drawing drawing, Entity entity)
{
var newLayer = drawing.CurrentLayer.Add(entity);
var newLayerSet = drawing.Layers.Delete(drawing.CurrentLayer.Name).Insert(newLayer.Name, newLayer);
return drawing.Update(layers: newLayerSet);
}
/// <summary>
/// Replaces the specified entity.
/// </summary>
/// <param name="oldEntity">The entity to be replaced.</param>
/// <param name="newEntity">The replacement entity.</param>
/// <returns>The new drawing with the entity replaced.</returns>
public static Drawing Replace(this Drawing drawing, Entity oldEntity, Entity newEntity)
{
var layer = drawing.ContainingLayer(oldEntity);
if (layer == null)
{
return drawing;
}
return drawing.Replace(layer, oldEntity, newEntity);
}
/// <summary>
/// Replaces the entity in the specified layer.
/// </summary>
/// <param name="layer">The layer containing the entity.</param>
/// <param name="oldEntity">The entity to be replaced.</param>
/// <param name="newEntity">The replacement entity.</param>
/// <returns>The new drawing with the entity replaced.</returns>
public static Drawing Replace(this Drawing drawing, Layer layer, Entity oldEntity, Entity newEntity)
{
var updatedLayer = layer.Replace(oldEntity, newEntity);
Debug.Assert(layer.EntityCount - updatedLayer.EntityCount == 0, "Expected the same number of entities.");
return drawing.Replace(layer, updatedLayer);
}
/// <summary>
/// Removes the entity from the layer.
/// </summary>
/// <param name="layer">The containing layer.</param>
/// <param name="entity">The entity to remove.</param>
/// <returns>The new drawing with the entity removed.</returns>
public static Drawing Remove(this Drawing drawing, Layer layer, Entity entity)
{
var updatedLayer = layer.Remove(entity);
Debug.Assert(layer.EntityCount - updatedLayer.EntityCount == 1, "Expected to remove 1 entity.");
return drawing.Replace(layer, updatedLayer);
}
/// <summary>
/// Removes the entity from the drawing.
/// </summary>
/// <param name="drawing">The drawing.</param>
/// <param name="entity">The entity to remove.</param>
/// <returns>The new drawing with the entity removed.</returns>
public static Drawing Remove(this Drawing drawing, Entity entity)
{
var layer = drawing.ContainingLayer(entity);
if (layer != null)
{
return drawing.Remove(layer, entity);
}
return drawing;
}
/// <summary>
/// Returns the layer that contains the specified entity.
/// </summary>
/// <param name="entity">The entity to find.</param>
/// <returns>The containing layer.</returns>
public static Layer ContainingLayer(this Drawing drawing, Entity entity)
{
foreach (var layer in drawing.GetLayers())
{
if (layer.EntityExists(entity))
return layer;
}
return null;
}
/// <summary>
/// Returns a collection of all entities in the drawing.
/// </summary>
/// <param name="drawing">The drawing.</param>
/// <returns>A collection of all entities in the drawing.</returns>
public static IEnumerable<Entity> GetEntities(this Drawing drawing)
{
return drawing.GetLayers().SelectMany(l => l.GetEntities());
}
/// <summary>
/// Returns the entity specified by the ID.
/// </summary>
/// <param name="id">The ID of the entity.</param>
/// <returns>The appropriate entity, or null.</returns>
public static Entity GetEntityById(this Drawing drawing, uint id)
{
return drawing.GetLayers().Select(l => l.GetEntityById(id)).Where(e => e != null).SingleOrDefault();
}
/// <summary>
/// Returns a renamed drawing.
/// </summary>
/// <param name="drawing">The drawing.</param>
/// <param name="fileName">The new filename.</param>
/// <returns></returns>
public static Drawing Rename(this Drawing drawing, string fileName)
{
var newSettings = drawing.Settings.Update(fileName: fileName);
return drawing.Update(settings: newSettings);
}
/// <summary>
/// Get all transformed snap points for the drawing with the given display transform.
/// </summary>
public static QuadTree<TransformedSnapPoint> GetSnapPoints(this Drawing drawing, Matrix4 displayTransform, double width, double height, CancellationToken cancellationToken = default)
{
// populate the snap points
var transformedQuadTree = new QuadTree<TransformedSnapPoint>(new Rect(0, 0, width, height), t => new Rect(t.ControlPoint.X, t.ControlPoint.Y, 0.0, 0.0));
foreach (var layer in drawing.GetLayers(cancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
foreach (var entity in layer.GetEntities(cancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
foreach (var snapPoint in entity.GetSnapPoints())
{
var projected = displayTransform.Transform(snapPoint.Point);
transformedQuadTree.AddItem(new TransformedSnapPoint(snapPoint.Point, projected, snapPoint.Kind));
}
}
}
// calculate intersections
// TODO: can this be done in a meanintful way in a separate task?
var primitives = drawing.GetEntities().SelectMany(e => e.GetPrimitives()).ToList();
for (int startIndex = 0; startIndex < primitives.Count; startIndex++)
{
cancellationToken.ThrowIfCancellationRequested();
var first = primitives[startIndex];
for (int i = startIndex + 1; i < primitives.Count; i++)
{
cancellationToken.ThrowIfCancellationRequested();
var current = primitives[i];
foreach (var intersection in first.IntersectionPoints(current))
{
cancellationToken.ThrowIfCancellationRequested();
var projected = displayTransform.Transform(intersection);
transformedQuadTree.AddItem(new TransformedSnapPoint(intersection, projected, SnapPointKind.Intersection));
}
}
}
cancellationToken.ThrowIfCancellationRequested();
return transformedQuadTree;
}
/// <summary>
/// Combine the specified entities into a Polyline entities and add to the drawing. The original entities will be removed.
/// </summary>
/// <param name="drawing">The drawing.</param>
/// <param name="entities">The entities to combine.</param>
/// <param name="layerName">The name of the layer to which the final Polylines will be added.</param>
public static Drawing CombineEntitiesIntoPolyline(this Drawing drawing, IEnumerable<Entity> entities, string layerName)
{
foreach (var entity in entities)
{
drawing = drawing.Remove(entity);
}
var primitives = entities.SelectMany(e => e.GetPrimitives());
var polylines = primitives.GetPolylinesFromSegments();
var polyLayer = drawing.Layers.GetValue(layerName);
drawing = drawing.Remove(polyLayer);
foreach (var poly in polylines)
{
polyLayer = polyLayer.Add(poly);
}
return drawing.Add(polyLayer);
}
public static Rect GetExtents(this Drawing drawing, Vector sight)
{
return drawing.GetEntities().SelectMany(e => e.GetPrimitives()).GetExtents(sight);
}
public static ViewPort ShowAllViewPort(this Drawing drawing, Vector sight, Vector up, double viewPortWidth, double viewPortHeight, double viewportBuffer = PrimitiveExtensions.DefaultViewportBuffer)
{
return drawing.GetExtents(sight).ShowAllViewPort(sight, up, viewPortWidth, viewPortHeight, viewportBuffer);
}
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gagvr = Google.Ads.GoogleAds.V10.Resources;
using gax = Google.Api.Gax;
using sys = System;
namespace Google.Ads.GoogleAds.V10.Resources
{
/// <summary>Resource name for the <c>SharedSet</c> resource.</summary>
public sealed partial class SharedSetName : gax::IResourceName, sys::IEquatable<SharedSetName>
{
/// <summary>The possible contents of <see cref="SharedSetName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern <c>customers/{customer_id}/sharedSets/{shared_set_id}</c>.
/// </summary>
CustomerSharedSet = 1,
}
private static gax::PathTemplate s_customerSharedSet = new gax::PathTemplate("customers/{customer_id}/sharedSets/{shared_set_id}");
/// <summary>Creates a <see cref="SharedSetName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="SharedSetName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static SharedSetName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new SharedSetName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="SharedSetName"/> with the pattern <c>customers/{customer_id}/sharedSets/{shared_set_id}</c>
/// .
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="sharedSetId">The <c>SharedSet</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="SharedSetName"/> constructed from the provided ids.</returns>
public static SharedSetName FromCustomerSharedSet(string customerId, string sharedSetId) =>
new SharedSetName(ResourceNameType.CustomerSharedSet, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), sharedSetId: gax::GaxPreconditions.CheckNotNullOrEmpty(sharedSetId, nameof(sharedSetId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="SharedSetName"/> with pattern
/// <c>customers/{customer_id}/sharedSets/{shared_set_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="sharedSetId">The <c>SharedSet</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="SharedSetName"/> with pattern
/// <c>customers/{customer_id}/sharedSets/{shared_set_id}</c>.
/// </returns>
public static string Format(string customerId, string sharedSetId) => FormatCustomerSharedSet(customerId, sharedSetId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="SharedSetName"/> with pattern
/// <c>customers/{customer_id}/sharedSets/{shared_set_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="sharedSetId">The <c>SharedSet</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="SharedSetName"/> with pattern
/// <c>customers/{customer_id}/sharedSets/{shared_set_id}</c>.
/// </returns>
public static string FormatCustomerSharedSet(string customerId, string sharedSetId) =>
s_customerSharedSet.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), gax::GaxPreconditions.CheckNotNullOrEmpty(sharedSetId, nameof(sharedSetId)));
/// <summary>Parses the given resource name string into a new <see cref="SharedSetName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>customers/{customer_id}/sharedSets/{shared_set_id}</c></description></item>
/// </list>
/// </remarks>
/// <param name="sharedSetName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="SharedSetName"/> if successful.</returns>
public static SharedSetName Parse(string sharedSetName) => Parse(sharedSetName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="SharedSetName"/> instance; optionally allowing
/// an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>customers/{customer_id}/sharedSets/{shared_set_id}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="sharedSetName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="SharedSetName"/> if successful.</returns>
public static SharedSetName Parse(string sharedSetName, bool allowUnparsed) =>
TryParse(sharedSetName, allowUnparsed, out SharedSetName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="SharedSetName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>customers/{customer_id}/sharedSets/{shared_set_id}</c></description></item>
/// </list>
/// </remarks>
/// <param name="sharedSetName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="SharedSetName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string sharedSetName, out SharedSetName result) => TryParse(sharedSetName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="SharedSetName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>customers/{customer_id}/sharedSets/{shared_set_id}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="sharedSetName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="SharedSetName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string sharedSetName, bool allowUnparsed, out SharedSetName result)
{
gax::GaxPreconditions.CheckNotNull(sharedSetName, nameof(sharedSetName));
gax::TemplatedResourceName resourceName;
if (s_customerSharedSet.TryParseName(sharedSetName, out resourceName))
{
result = FromCustomerSharedSet(resourceName[0], resourceName[1]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(sharedSetName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private SharedSetName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string customerId = null, string sharedSetId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
CustomerId = customerId;
SharedSetId = sharedSetId;
}
/// <summary>
/// Constructs a new instance of a <see cref="SharedSetName"/> class from the component parts of pattern
/// <c>customers/{customer_id}/sharedSets/{shared_set_id}</c>
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="sharedSetId">The <c>SharedSet</c> ID. Must not be <c>null</c> or empty.</param>
public SharedSetName(string customerId, string sharedSetId) : this(ResourceNameType.CustomerSharedSet, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), sharedSetId: gax::GaxPreconditions.CheckNotNullOrEmpty(sharedSetId, nameof(sharedSetId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CustomerId { get; }
/// <summary>
/// The <c>SharedSet</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string SharedSetId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.CustomerSharedSet: return s_customerSharedSet.Expand(CustomerId, SharedSetId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as SharedSetName);
/// <inheritdoc/>
public bool Equals(SharedSetName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(SharedSetName a, SharedSetName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(SharedSetName a, SharedSetName b) => !(a == b);
}
public partial class SharedSet
{
/// <summary>
/// <see cref="gagvr::SharedSetName"/>-typed view over the <see cref="ResourceName"/> resource name property.
/// </summary>
internal SharedSetName ResourceNameAsSharedSetName
{
get => string.IsNullOrEmpty(ResourceName) ? null : gagvr::SharedSetName.Parse(ResourceName, allowUnparsed: true);
set => ResourceName = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="gagvr::SharedSetName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
internal SharedSetName SharedSetName
{
get => string.IsNullOrEmpty(Name) ? null : gagvr::SharedSetName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
}
| |
/*
* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using CookComputing.XmlRpc;
namespace XenAPI
{
/// <summary>
/// Represents a patch stored on a server
/// First published in XenServer 4.0.
/// </summary>
public partial class Host_patch : XenObject<Host_patch>
{
public Host_patch()
{
}
public Host_patch(string uuid,
string name_label,
string name_description,
string version,
XenRef<Host> host,
bool applied,
DateTime timestamp_applied,
long size,
XenRef<Pool_patch> pool_patch,
Dictionary<string, string> other_config)
{
this.uuid = uuid;
this.name_label = name_label;
this.name_description = name_description;
this.version = version;
this.host = host;
this.applied = applied;
this.timestamp_applied = timestamp_applied;
this.size = size;
this.pool_patch = pool_patch;
this.other_config = other_config;
}
/// <summary>
/// Creates a new Host_patch from a Proxy_Host_patch.
/// </summary>
/// <param name="proxy"></param>
public Host_patch(Proxy_Host_patch proxy)
{
this.UpdateFromProxy(proxy);
}
public override void UpdateFrom(Host_patch update)
{
uuid = update.uuid;
name_label = update.name_label;
name_description = update.name_description;
version = update.version;
host = update.host;
applied = update.applied;
timestamp_applied = update.timestamp_applied;
size = update.size;
pool_patch = update.pool_patch;
other_config = update.other_config;
}
internal void UpdateFromProxy(Proxy_Host_patch proxy)
{
uuid = proxy.uuid == null ? null : (string)proxy.uuid;
name_label = proxy.name_label == null ? null : (string)proxy.name_label;
name_description = proxy.name_description == null ? null : (string)proxy.name_description;
version = proxy.version == null ? null : (string)proxy.version;
host = proxy.host == null ? null : XenRef<Host>.Create(proxy.host);
applied = (bool)proxy.applied;
timestamp_applied = proxy.timestamp_applied;
size = proxy.size == null ? 0 : long.Parse((string)proxy.size);
pool_patch = proxy.pool_patch == null ? null : XenRef<Pool_patch>.Create(proxy.pool_patch);
other_config = proxy.other_config == null ? null : Maps.convert_from_proxy_string_string(proxy.other_config);
}
public Proxy_Host_patch ToProxy()
{
Proxy_Host_patch result_ = new Proxy_Host_patch();
result_.uuid = (uuid != null) ? uuid : "";
result_.name_label = (name_label != null) ? name_label : "";
result_.name_description = (name_description != null) ? name_description : "";
result_.version = (version != null) ? version : "";
result_.host = (host != null) ? host : "";
result_.applied = applied;
result_.timestamp_applied = timestamp_applied;
result_.size = size.ToString();
result_.pool_patch = (pool_patch != null) ? pool_patch : "";
result_.other_config = Maps.convert_to_proxy_string_string(other_config);
return result_;
}
/// <summary>
/// Creates a new Host_patch from a Hashtable.
/// </summary>
/// <param name="table"></param>
public Host_patch(Hashtable table)
{
uuid = Marshalling.ParseString(table, "uuid");
name_label = Marshalling.ParseString(table, "name_label");
name_description = Marshalling.ParseString(table, "name_description");
version = Marshalling.ParseString(table, "version");
host = Marshalling.ParseRef<Host>(table, "host");
applied = Marshalling.ParseBool(table, "applied");
timestamp_applied = Marshalling.ParseDateTime(table, "timestamp_applied");
size = Marshalling.ParseLong(table, "size");
pool_patch = Marshalling.ParseRef<Pool_patch>(table, "pool_patch");
other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config"));
}
public bool DeepEquals(Host_patch other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
return Helper.AreEqual2(this._uuid, other._uuid) &&
Helper.AreEqual2(this._name_label, other._name_label) &&
Helper.AreEqual2(this._name_description, other._name_description) &&
Helper.AreEqual2(this._version, other._version) &&
Helper.AreEqual2(this._host, other._host) &&
Helper.AreEqual2(this._applied, other._applied) &&
Helper.AreEqual2(this._timestamp_applied, other._timestamp_applied) &&
Helper.AreEqual2(this._size, other._size) &&
Helper.AreEqual2(this._pool_patch, other._pool_patch) &&
Helper.AreEqual2(this._other_config, other._other_config);
}
public override string SaveChanges(Session session, string opaqueRef, Host_patch server)
{
if (opaqueRef == null)
{
System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server");
return "";
}
else
{
if (!Helper.AreEqual2(_other_config, server._other_config))
{
Host_patch.set_other_config(session, opaqueRef, _other_config);
}
return null;
}
}
/// <summary>
/// Get a record containing the current state of the given host_patch.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_patch">The opaque_ref of the given host_patch</param>
public static Host_patch get_record(Session session, string _host_patch)
{
return new Host_patch((Proxy_Host_patch)session.proxy.host_patch_get_record(session.uuid, (_host_patch != null) ? _host_patch : "").parse());
}
/// <summary>
/// Get a reference to the host_patch instance with the specified UUID.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_uuid">UUID of object to return</param>
public static XenRef<Host_patch> get_by_uuid(Session session, string _uuid)
{
return XenRef<Host_patch>.Create(session.proxy.host_patch_get_by_uuid(session.uuid, (_uuid != null) ? _uuid : "").parse());
}
/// <summary>
/// Get all the host_patch instances with the given label.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_label">label of object to return</param>
public static List<XenRef<Host_patch>> get_by_name_label(Session session, string _label)
{
return XenRef<Host_patch>.Create(session.proxy.host_patch_get_by_name_label(session.uuid, (_label != null) ? _label : "").parse());
}
/// <summary>
/// Get the uuid field of the given host_patch.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_patch">The opaque_ref of the given host_patch</param>
public static string get_uuid(Session session, string _host_patch)
{
return (string)session.proxy.host_patch_get_uuid(session.uuid, (_host_patch != null) ? _host_patch : "").parse();
}
/// <summary>
/// Get the name/label field of the given host_patch.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_patch">The opaque_ref of the given host_patch</param>
public static string get_name_label(Session session, string _host_patch)
{
return (string)session.proxy.host_patch_get_name_label(session.uuid, (_host_patch != null) ? _host_patch : "").parse();
}
/// <summary>
/// Get the name/description field of the given host_patch.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_patch">The opaque_ref of the given host_patch</param>
public static string get_name_description(Session session, string _host_patch)
{
return (string)session.proxy.host_patch_get_name_description(session.uuid, (_host_patch != null) ? _host_patch : "").parse();
}
/// <summary>
/// Get the version field of the given host_patch.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_patch">The opaque_ref of the given host_patch</param>
public static string get_version(Session session, string _host_patch)
{
return (string)session.proxy.host_patch_get_version(session.uuid, (_host_patch != null) ? _host_patch : "").parse();
}
/// <summary>
/// Get the host field of the given host_patch.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_patch">The opaque_ref of the given host_patch</param>
public static XenRef<Host> get_host(Session session, string _host_patch)
{
return XenRef<Host>.Create(session.proxy.host_patch_get_host(session.uuid, (_host_patch != null) ? _host_patch : "").parse());
}
/// <summary>
/// Get the applied field of the given host_patch.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_patch">The opaque_ref of the given host_patch</param>
public static bool get_applied(Session session, string _host_patch)
{
return (bool)session.proxy.host_patch_get_applied(session.uuid, (_host_patch != null) ? _host_patch : "").parse();
}
/// <summary>
/// Get the timestamp_applied field of the given host_patch.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_patch">The opaque_ref of the given host_patch</param>
public static DateTime get_timestamp_applied(Session session, string _host_patch)
{
return session.proxy.host_patch_get_timestamp_applied(session.uuid, (_host_patch != null) ? _host_patch : "").parse();
}
/// <summary>
/// Get the size field of the given host_patch.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_patch">The opaque_ref of the given host_patch</param>
public static long get_size(Session session, string _host_patch)
{
return long.Parse((string)session.proxy.host_patch_get_size(session.uuid, (_host_patch != null) ? _host_patch : "").parse());
}
/// <summary>
/// Get the pool_patch field of the given host_patch.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_patch">The opaque_ref of the given host_patch</param>
public static XenRef<Pool_patch> get_pool_patch(Session session, string _host_patch)
{
return XenRef<Pool_patch>.Create(session.proxy.host_patch_get_pool_patch(session.uuid, (_host_patch != null) ? _host_patch : "").parse());
}
/// <summary>
/// Get the other_config field of the given host_patch.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_patch">The opaque_ref of the given host_patch</param>
public static Dictionary<string, string> get_other_config(Session session, string _host_patch)
{
return Maps.convert_from_proxy_string_string(session.proxy.host_patch_get_other_config(session.uuid, (_host_patch != null) ? _host_patch : "").parse());
}
/// <summary>
/// Set the other_config field of the given host_patch.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_patch">The opaque_ref of the given host_patch</param>
/// <param name="_other_config">New value to set</param>
public static void set_other_config(Session session, string _host_patch, Dictionary<string, string> _other_config)
{
session.proxy.host_patch_set_other_config(session.uuid, (_host_patch != null) ? _host_patch : "", Maps.convert_to_proxy_string_string(_other_config)).parse();
}
/// <summary>
/// Add the given key-value pair to the other_config field of the given host_patch.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_patch">The opaque_ref of the given host_patch</param>
/// <param name="_key">Key to add</param>
/// <param name="_value">Value to add</param>
public static void add_to_other_config(Session session, string _host_patch, string _key, string _value)
{
session.proxy.host_patch_add_to_other_config(session.uuid, (_host_patch != null) ? _host_patch : "", (_key != null) ? _key : "", (_value != null) ? _value : "").parse();
}
/// <summary>
/// Remove the given key and its corresponding value from the other_config field of the given host_patch. If the key is not in that Map, then do nothing.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_patch">The opaque_ref of the given host_patch</param>
/// <param name="_key">Key to remove</param>
public static void remove_from_other_config(Session session, string _host_patch, string _key)
{
session.proxy.host_patch_remove_from_other_config(session.uuid, (_host_patch != null) ? _host_patch : "", (_key != null) ? _key : "").parse();
}
/// <summary>
/// Destroy the specified host patch, removing it from the disk. This does NOT reverse the patch
/// First published in XenServer 4.0.
/// Deprecated since XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_patch">The opaque_ref of the given host_patch</param>
[Deprecated("XenServer 4.1")]
public static void destroy(Session session, string _host_patch)
{
session.proxy.host_patch_destroy(session.uuid, (_host_patch != null) ? _host_patch : "").parse();
}
/// <summary>
/// Destroy the specified host patch, removing it from the disk. This does NOT reverse the patch
/// First published in XenServer 4.0.
/// Deprecated since XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_patch">The opaque_ref of the given host_patch</param>
[Deprecated("XenServer 4.1")]
public static XenRef<Task> async_destroy(Session session, string _host_patch)
{
return XenRef<Task>.Create(session.proxy.async_host_patch_destroy(session.uuid, (_host_patch != null) ? _host_patch : "").parse());
}
/// <summary>
/// Apply the selected patch and return its output
/// First published in XenServer 4.0.
/// Deprecated since XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_patch">The opaque_ref of the given host_patch</param>
[Deprecated("XenServer 4.1")]
public static string apply(Session session, string _host_patch)
{
return (string)session.proxy.host_patch_apply(session.uuid, (_host_patch != null) ? _host_patch : "").parse();
}
/// <summary>
/// Apply the selected patch and return its output
/// First published in XenServer 4.0.
/// Deprecated since XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_patch">The opaque_ref of the given host_patch</param>
[Deprecated("XenServer 4.1")]
public static XenRef<Task> async_apply(Session session, string _host_patch)
{
return XenRef<Task>.Create(session.proxy.async_host_patch_apply(session.uuid, (_host_patch != null) ? _host_patch : "").parse());
}
/// <summary>
/// Return a list of all the host_patchs known to the system.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
public static List<XenRef<Host_patch>> get_all(Session session)
{
return XenRef<Host_patch>.Create(session.proxy.host_patch_get_all(session.uuid).parse());
}
/// <summary>
/// Get all the host_patch Records at once, in a single XML RPC call
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
public static Dictionary<XenRef<Host_patch>, Host_patch> get_all_records(Session session)
{
return XenRef<Host_patch>.Create<Proxy_Host_patch>(session.proxy.host_patch_get_all_records(session.uuid).parse());
}
/// <summary>
/// Unique identifier/object reference
/// </summary>
public virtual string uuid
{
get { return _uuid; }
set
{
if (!Helper.AreEqual(value, _uuid))
{
_uuid = value;
Changed = true;
NotifyPropertyChanged("uuid");
}
}
}
private string _uuid;
/// <summary>
/// a human-readable name
/// </summary>
public virtual string name_label
{
get { return _name_label; }
set
{
if (!Helper.AreEqual(value, _name_label))
{
_name_label = value;
Changed = true;
NotifyPropertyChanged("name_label");
}
}
}
private string _name_label;
/// <summary>
/// a notes field containing human-readable description
/// </summary>
public virtual string name_description
{
get { return _name_description; }
set
{
if (!Helper.AreEqual(value, _name_description))
{
_name_description = value;
Changed = true;
NotifyPropertyChanged("name_description");
}
}
}
private string _name_description;
/// <summary>
/// Patch version number
/// </summary>
public virtual string version
{
get { return _version; }
set
{
if (!Helper.AreEqual(value, _version))
{
_version = value;
Changed = true;
NotifyPropertyChanged("version");
}
}
}
private string _version;
/// <summary>
/// Host the patch relates to
/// </summary>
public virtual XenRef<Host> host
{
get { return _host; }
set
{
if (!Helper.AreEqual(value, _host))
{
_host = value;
Changed = true;
NotifyPropertyChanged("host");
}
}
}
private XenRef<Host> _host;
/// <summary>
/// True if the patch has been applied
/// </summary>
public virtual bool applied
{
get { return _applied; }
set
{
if (!Helper.AreEqual(value, _applied))
{
_applied = value;
Changed = true;
NotifyPropertyChanged("applied");
}
}
}
private bool _applied;
/// <summary>
/// Time the patch was applied
/// </summary>
public virtual DateTime timestamp_applied
{
get { return _timestamp_applied; }
set
{
if (!Helper.AreEqual(value, _timestamp_applied))
{
_timestamp_applied = value;
Changed = true;
NotifyPropertyChanged("timestamp_applied");
}
}
}
private DateTime _timestamp_applied;
/// <summary>
/// Size of the patch
/// </summary>
public virtual long size
{
get { return _size; }
set
{
if (!Helper.AreEqual(value, _size))
{
_size = value;
Changed = true;
NotifyPropertyChanged("size");
}
}
}
private long _size;
/// <summary>
/// The patch applied
/// First published in XenServer 4.1.
/// </summary>
public virtual XenRef<Pool_patch> pool_patch
{
get { return _pool_patch; }
set
{
if (!Helper.AreEqual(value, _pool_patch))
{
_pool_patch = value;
Changed = true;
NotifyPropertyChanged("pool_patch");
}
}
}
private XenRef<Pool_patch> _pool_patch;
/// <summary>
/// additional configuration
/// First published in XenServer 4.1.
/// </summary>
public virtual Dictionary<string, string> other_config
{
get { return _other_config; }
set
{
if (!Helper.AreEqual(value, _other_config))
{
_other_config = value;
Changed = true;
NotifyPropertyChanged("other_config");
}
}
}
private Dictionary<string, string> _other_config;
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Linq;
namespace dex.net
{
public class EnhancedDexWriter : IDexWriter
{
private Dex _dex;
public Dex dex
{
get { return _dex; }
set {
_dex = value;
_helper._dex = _dex;
}
}
private TypeHelper _helper;
public EnhancedDexWriter() {
_helper = new TypeHelper(GetFieldName, AnnotationToString);
}
#region DexWriter
public string GetName()
{
return "Dex";
}
public string GetExtension ()
{
return ".dex";
}
public void WriteOutMethod (Class dexClass, Method method, TextWriter output, Indentation indent, bool renderOpcodes=false)
{
var jumpTable = BuildJumpTable (method);
foreach (var annotation in method.Annotations) {
AnnotationToString(output, annotation.Values, dexClass, indent);
}
foreach (var annotation in method.ParameterAnnotations) {
AnnotationToString(output, annotation.Values, dexClass, indent);
}
// Initialize a pointer to the first jump target
var targets = jumpTable.Targets.Keys.GetEnumerator();
targets.MoveNext ();
output.Write (indent.ToString());
output.Write (MethodToString(method));
output.WriteLine (" {");
if (renderOpcodes) {
indent++;
var lastTryBlockId = 0;
var activeTryBlocks = new List<TryCatchBlock> ();
TryCatchBlock currentTryBlock = null;
foreach (var opcode in method.GetInstructions()) {
long offset = opcode.OpCodeOffset;
// Print out jump target labels
while (offset == targets.Current) {
output.WriteLine ();
output.WriteLine("{0}:{1}", indent.ToString(), string.Join(", ", jumpTable.GetTargetLabels(targets.Current)));
if (!targets.MoveNext ()) {
break;
}
}
// Test for the end of the current try block
if (currentTryBlock != null && !currentTryBlock.IsInBlock(offset)) {
WriteOutCatchStatements(output, indent, currentTryBlock, jumpTable);
activeTryBlocks.Remove (currentTryBlock);
if (activeTryBlocks.Count > 0) {
currentTryBlock = activeTryBlocks [activeTryBlocks.Count - 1];
} else {
currentTryBlock = null;
}
}
// Should open a new try block?
if (method.TryCatchBlocks != null && method.TryCatchBlocks.Length > lastTryBlockId) {
var tryBlock = method.TryCatchBlocks [lastTryBlockId];
if (tryBlock.IsInBlock (offset)) {
output.Write (indent.ToString ());
output.WriteLine ("try");
activeTryBlocks.Add (tryBlock);
currentTryBlock = tryBlock;
lastTryBlockId++;
indent++;
}
}
if (opcode.Instruction != Instructions.Nop) {
output.Write (indent.ToString ());
output.WriteLine(OpCodeToString(opcode, dexClass, method, jumpTable));
}
}
if (currentTryBlock != null) {
WriteOutCatchStatements (output, indent, currentTryBlock, jumpTable);
}
indent--;
}
output.Write (indent.ToString());
output.WriteLine ("}");
}
private void WriteOutCatchStatements(TextWriter output, Indentation indent, TryCatchBlock currentTryBlock, JumpTable jumpTable)
{
indent--;
foreach (var catchBlock in currentTryBlock.Handlers) {
output.WriteLine (string.Format ("{0}catch({1}) :{2}",
indent.ToString(),
catchBlock.TypeIndex == 0 ? "ALL" : _dex.GetTypeName(catchBlock.TypeIndex),
jumpTable.GetHandlerLabel(catchBlock)));
}
}
public void WriteOutClass (Class dexClass, ClassDisplayOptions options, TextWriter output)
{
WriteOutClassDefinition(output, dexClass, options);
output.WriteLine (" {");
// Display fields
var indent = new Indentation (1);
if ((options & ClassDisplayOptions.Fields) != 0) {
WriteOutFields(output, dexClass, options, indent);
}
if ((options & ClassDisplayOptions.Methods) != 0 && dexClass.HasMethods()) {
foreach (var method in dexClass.GetMethods()) {
WriteOutMethod (dexClass, method, output, indent, (options & ClassDisplayOptions.OpCodes) != 0);
output.WriteLine ();
}
}
output.WriteLine ("}");
}
public List<HightlightInfo> GetCodeHightlight ()
{
var highlight = new List<HightlightInfo> ();
// Annotation
highlight.Add (new HightlightInfo("@.+", 0x81, 0x5B, 0xA4));
// Keywords
highlight.Add (new HightlightInfo("\\b(return-void|return|goto|packed-switch|sparse-switch|filled-new-array/range|new|instance-of|check-cast|const-class|fill-array-data|move-result-object|move-result|move-exception|try|catch|throw|extends|implements)\\b", 158, 28, 78));
// Strings
highlight.Add (new HightlightInfo("(\".*?\")", 58, 92, 120));
// Integers
highlight.Add (new HightlightInfo("\\b(0x[\\da-f]+|\\d+)\\b", 252, 120, 8));
// Labels
highlight.Add (new HightlightInfo("\\s(:.+)\\b", 55, 193, 58));
return highlight;
}
#endregion
class JumpTable
{
internal SortedDictionary<long,ISet<string>> Targets = new SortedDictionary<long,ISet<string>>();
SortedDictionary<long,ISet<string>> Referrers = new SortedDictionary<long,ISet<string>>();
Dictionary<CatchHandler, string> Handlers = new Dictionary<CatchHandler,string>();
string NextTargetLabel (long offset, string labelPrefix, ref int counter)
{
ISet<string> targets;
if (Targets.TryGetValue(offset, out targets)) {
foreach (var target in targets) {
if (target.StartsWith (labelPrefix)) {
return target;
}
}
}
return labelPrefix + counter++;
}
internal string AddTarget(long from, long to, string labelPrefix, ref int counter)
{
var label = NextTargetLabel (to, labelPrefix, ref counter);
ISet<string> target;
if (!Targets.TryGetValue (to, out target)) {
target = new HashSet<string> ();
Targets.Add (to, target);
}
target.Add (label);
ISet<string> referrers;
if (!Referrers.TryGetValue (from, out referrers)) {
referrers = new HashSet<string> ();
Referrers.Add (from, referrers);
}
referrers.Add(label);
return label;
}
internal void AddHandler(CatchHandler handler, string labelPrefix, ref int counter) {
var label = AddTarget(-1, handler.HandlerOffset, labelPrefix, ref counter);
Handlers.Add (handler, label);
}
internal string GetHandlerLabel(CatchHandler handler) {
var label = string.Empty;
Handlers.TryGetValue (handler, out label);
return label;
}
internal string GetReferrerLabel(long offset)
{
ISet<string> labels;
if (!Referrers.TryGetValue (offset, out labels)) {
return string.Empty;
}
return (labels as HashSet<string>).First ();
}
internal IEnumerable<string> GetReferrerLabels(long offset)
{
ISet<string> referrers;
if (Referrers.TryGetValue (offset, out referrers)) {
foreach (var referrer in referrers) {
yield return referrer;
}
}
}
internal IEnumerable<string> GetTargetLabels(long offset) {
ISet<string> targets;
if (Targets.TryGetValue (offset, out targets)) {
foreach (var target in targets) {
yield return target;
}
}
}
}
JumpTable BuildJumpTable(Method method)
{
var jumpTable = new JumpTable ();
int gotoCounter = 0;
int ifCounter = 0;
int switchCounter = 0;
foreach (var opcode in method.GetInstructions()) {
switch (opcode.Instruction) {
case Instructions.Goto:
case Instructions.Goto16:
case Instructions.Goto32:
var gotoOpCode = (dynamic)opcode;
jumpTable.AddTarget(gotoOpCode.OpCodeOffset, gotoOpCode.GetTargetAddress(), "goto_", ref gotoCounter);
break;
case Instructions.PackedSwitch:
case Instructions.SparseSwitch:
dynamic switchOpCode = opcode;
foreach (var switchTarget in switchOpCode.GetTargetAddresses()) {
jumpTable.AddTarget (switchOpCode.OpCodeOffset, switchTarget, "switch_", ref switchCounter);
}
break;
case Instructions.IfEq:
case Instructions.IfNe:
case Instructions.IfLt:
case Instructions.IfGe:
case Instructions.IfGt:
case Instructions.IfLe:
case Instructions.IfEqz:
case Instructions.IfNez:
case Instructions.IfLtz:
case Instructions.IfGez:
case Instructions.IfGtz:
case Instructions.IfLez:
dynamic ifOpCode = opcode;
jumpTable.AddTarget(ifOpCode.OpCodeOffset, ifOpCode.GetTargetAddress(), "if_", ref ifCounter);
break;
}
}
var catchCounter = 0;
if (method.TryCatchBlocks != null) {
foreach (var tryBlock in method.TryCatchBlocks) {
foreach (var catchBlock in tryBlock.Handlers) {
jumpTable.AddHandler (catchBlock, "catch_", ref catchCounter);
}
}
}
return jumpTable;
}
void AnnotationToString(TextWriter output, EncodedAnnotation annotation, Class currentClass, Indentation indent)
{
var attributes = new List<string> ();
foreach (var pair in annotation.GetAnnotations()) {
attributes.Add (string.Format("{0}={1}", pair.GetName(_dex), _helper.EncodedValueToString(pair.Value, currentClass)));
}
output.WriteLine(string.Format ("@{0}({1})", _dex.GetTypeName(annotation.AnnotationType), string.Join(",", attributes)));
}
void WriteOutClassDefinition(TextWriter output, Class dexClass, ClassDisplayOptions options)
{
if ((options & ClassDisplayOptions.ClassAnnotations) != 0) {
var indent = new Indentation ();
foreach (var annotation in dexClass.Annotations) {
AnnotationToString(output, annotation.Values, dexClass, indent);
}
}
if ((options & ClassDisplayOptions.ClassDetails) != 0) {
output.Write (_helper.AccessAndType(dexClass));
}
if ((options & ClassDisplayOptions.ClassName) != 0) {
output.Write (_dex.GetTypeName(dexClass.ClassIndex));
}
if ((options & ClassDisplayOptions.ClassDetails) != 0) {
if (dexClass.SuperClassIndex != Class.NO_INDEX) {
output.Write (" extends ");
output.Write (_dex.GetTypeName (dexClass.SuperClassIndex));
}
if (dexClass.ImplementsInterfaces()) {
output.Write (" implements");
var ifaces = new List<string> ();
foreach (var iface in dexClass.ImplementedInterfaces()) {
ifaces.Add (_dex.GetTypeName(iface));
}
output.Write (string.Join(", ", ifaces));
}
}
}
string MethodToString (Method method)
{
var proto = _dex.GetPrototype (method.PrototypeIndex);
var parameters = new List<string>();
int paramCounter = 0;
foreach (var param in proto.Parameters) {
parameters.Add(string.Format("{0} {1}{2}", _dex.GetTypeName(param), 'a', paramCounter++));
}
return string.Format ("{0} {1} {2} ({3})",
_helper.AccessFlagsToString(((AccessFlag)method.AccessFlags)),
_dex.GetTypeName(proto.ReturnTypeIndex),
method.Name, string.Join(",", parameters));
}
/// <summary>
/// Gets the register name within a method. The layout of a registers is:
/// [v0, v1, ..., vn, this(vn+1)[for instance methods], a0(vn+2), a1(vn+3)] where n is the
/// number of registers defined in a method
/// </summary>
/// <returns>The register name</returns>
/// <param name="index">Index of the register in the register array for a method</param>
string GetRegisterName(uint index, Method method)
{
if (index < method.LocalsCount) {
return string.Format("v{0}", index);
}
if (!method.IsStatic()) {
if (index == method.LocalsCount) {
return "this";
}
// Remove 'this' from the list
index--;
}
return string.Format("a{0}", (index-method.LocalsCount));
}
void WriteOutFields(TextWriter output, Class dexClass, ClassDisplayOptions options, Indentation indent, bool renderAnnotations=true)
{
if ((options & ClassDisplayOptions.Fields) != 0 && dexClass.HasFields()) {
int i=0;
foreach (var field in dexClass.GetFields()) {
// Field Annotations
if (renderAnnotations) {
indent++;
foreach (var annotation in field.Annotations) {
AnnotationToString (output, annotation.Values, dexClass, indent);
}
indent--;
}
// Field modifiers, type and name
if (i < dexClass.StaticFieldsValues.Length) {
output.WriteLine (string.Format ("{4}{0} {1} {2} = {3}",
_helper.AccessFlagsToString (field.AccessFlags),
_dex.GetTypeName (field.TypeIndex),
field.Name,
_helper.EncodedValueToString(dexClass.StaticFieldsValues[i], dexClass),
indent.ToString()));
} else {
output.WriteLine (string.Format ("{3}{0} {1} {2}",
_helper.AccessFlagsToString (field.AccessFlags),
_dex.GetTypeName (field.TypeIndex),
field.Name, indent.ToString()));
}
i++;
}
}
}
string GetFieldName(uint index, Class currentClass, bool isClass=false)
{
var field = _dex.GetField (index);
// Static reference. Return class.field
if (isClass) {
// Remove the package name for fields in the current class
var className = field.ClassIndex == currentClass.ClassIndex ?
currentClass.Name.Substring(currentClass.Name.LastIndexOf('.')+1) :
_dex.GetTypeName(field.ClassIndex);
return className + "." + field.Name;
}
if (field.ClassIndex == currentClass.ClassIndex) {
return "this." + field.Name;
}
return field.Name;
}
string OpCodeToString(OpCode opcode, Class currentClass, Method method, JumpTable jumpTable)
{
switch (opcode.Instruction) {
case Instructions.Const:
case Instructions.Const4:
case Instructions.Const16:
case Instructions.ConstHigh:
case Instructions.ConstWide16:
case Instructions.ConstWide32:
case Instructions.ConstWide:
case Instructions.ConstWideHigh:
dynamic constOpCode = opcode;
return string.Format("{1} = #{2}", constOpCode.Name, GetRegisterName(constOpCode.Destination, method), constOpCode.Value);
case Instructions.Move:
case Instructions.MoveFrom16:
case Instructions.Move16:
case Instructions.MoveWide:
case Instructions.MoveWideFrom16:
case Instructions.MoveWide16:
case Instructions.MoveObject:
case Instructions.MoveObjectFrom16:
case Instructions.MoveObject16:
dynamic moveOpCode = opcode;
return string.Format("{1} = {2}", moveOpCode.Name, GetRegisterName(moveOpCode.To, method), GetRegisterName(moveOpCode.From, method));
case Instructions.MoveResult:
case Instructions.MoveResultWide:
case Instructions.MoveResultObject:
case Instructions.MoveException:
dynamic moveResultOpCode = opcode;
return string.Format("{0} {1}", moveResultOpCode.Name, GetRegisterName(moveResultOpCode.Destination, method));
case Instructions.ConstString:
case Instructions.ConstStringJumbo:
dynamic constStringOpCode = opcode;
return string.Format("{1} = \"{2}\"", constStringOpCode.Name, GetRegisterName(constStringOpCode.Destination, method), _dex.GetString(constStringOpCode.StringIndex).Replace("\n", "\\n"));
case Instructions.ConstClass:
return string.Format("{0} = {1}", GetRegisterName(((ConstClassOpCode)opcode).Destination, method), _dex.GetTypeName(((ConstClassOpCode)opcode).TypeIndex));
case Instructions.CheckCast:
var typeCheckCast = _dex.GetTypeName(((CheckCastOpCode)opcode).TypeIndex);
return string.Format("({1}){0}", GetRegisterName(((CheckCastOpCode)opcode).Destination, method), typeCheckCast);
case Instructions.InstanceOf:
var typeInstanceOf = _dex.GetTypeName(((InstanceOfOpCode)opcode).TypeIndex);
return string.Format("instance-of v{0}, v{1}, {2}", ((InstanceOfOpCode)opcode).Destination, ((InstanceOfOpCode)opcode).Reference, typeInstanceOf);
case Instructions.NewInstance:
var typeNewInstance = _dex.GetTypeName(((NewInstanceOpCode)opcode).TypeIndex);
return string.Format("{0} = new {1}", GetRegisterName(((NewInstanceOpCode)opcode).Destination, method), typeNewInstance);
case Instructions.NewArrayOf:
var newArrayOpCode = (NewArrayOfOpCode)opcode;
var typeNewArrayOfOpCode = _dex.GetTypeName(newArrayOpCode.TypeIndex);
return string.Format("{0} = new {1}", GetRegisterName(newArrayOpCode.Destination, method),
typeNewArrayOfOpCode.Replace("[]", string.Format("[{0}]", GetRegisterName(newArrayOpCode.Size, method))));
case Instructions.FilledNewArrayOf:
var typeFilledNewArrayOf = _dex.GetTypeName(((FilledNewArrayOfOpCode)opcode).TypeIndex);
return string.Format("filled-new-array {0}, {1}", string.Join(",", ((FilledNewArrayOfOpCode)opcode).Values), typeFilledNewArrayOf);
case Instructions.FilledNewArrayRange:
var typeFilledNewArrayRange = _dex.GetTypeName(((FilledNewArrayRangeOpCode)opcode).TypeIndex);
return string.Format("filled-new-array/range {0}, {1}", string.Join(",", ((FilledNewArrayRangeOpCode)opcode).Values), typeFilledNewArrayRange);
case Instructions.ArrayLength:
var arrayLengthOpcode = (ArrayLengthOpCode)opcode;
return string.Format("{0} = {1}.length", GetRegisterName(arrayLengthOpcode.Destination, method), GetRegisterName(arrayLengthOpcode.ArrayReference, method));
case Instructions.InvokeVirtual:
case Instructions.InvokeSuper:
case Instructions.InvokeDirect:
case Instructions.InvokeStatic:
case Instructions.InvokeInterface:
var invokeOpcode = (InvokeOpCode)opcode;
var invokeMethod = _dex.GetMethod (invokeOpcode.MethodIndex);
string invokeObject;
if (invokeMethod.IsStatic () || invokeOpcode.Instruction == Instructions.InvokeStatic) {
invokeObject = _dex.GetTypeName (invokeMethod.ClassIndex);
} else {
invokeObject = GetRegisterName (invokeOpcode.ArgumentRegisters [0], method);
}
string[] registerNames = {};
if (invokeOpcode.ArgumentRegisters.Length > 0) {
var instanceAdjustment = invokeMethod.IsStatic()?0:1;
registerNames = new string[invokeOpcode.ArgumentRegisters.Length - instanceAdjustment];
for (int i=0; i<registerNames.Length; i++) {
registerNames [i] = GetRegisterName (invokeOpcode.ArgumentRegisters[i+instanceAdjustment], method);
}
}
return string.Format("{2}.{3}({1})", ((InvokeOpCode)opcode).Name, string.Join(",", registerNames), invokeObject, invokeMethod.Name);
case Instructions.Sput:
case Instructions.SputWide:
case Instructions.SputObject:
case Instructions.SputBoolean:
case Instructions.SputChar:
case Instructions.SputShort:
case Instructions.SputByte:
var sputOpcode = (StaticOpOpCode)opcode;
return string.Format("{2} = {1}", sputOpcode.Name, GetRegisterName(sputOpcode.Destination, method), GetFieldName(sputOpcode.Index, currentClass, true));
case Instructions.Sget:
case Instructions.SgetWide:
case Instructions.SgetObject:
case Instructions.SgetBoolean:
case Instructions.SgetChar:
case Instructions.SgetShort:
case Instructions.SgetByte:
var sgetOpcode = (StaticOpOpCode)opcode;
return string.Format("{1} = {2}", sgetOpcode.Name, GetRegisterName(sgetOpcode.Destination, method), GetFieldName(sgetOpcode.Index, currentClass, true));
case Instructions.Iput:
case Instructions.IputWide:
case Instructions.IputObject:
case Instructions.IputBoolean:
case Instructions.IputChar:
case Instructions.IputShort:
case Instructions.IputByte:
var iputOpCode = (IinstanceOpOpCode)opcode;
return string.Format("{2} = {1}", iputOpCode.Name, GetRegisterName(iputOpCode.Destination, method), GetFieldName(iputOpCode.Index, currentClass));
case Instructions.Iget:
case Instructions.IgetWide:
case Instructions.IgetObject:
case Instructions.IgetBoolean:
case Instructions.IgetChar:
case Instructions.IgetShort:
case Instructions.IgetByte:
var igetOpCode = (IinstanceOpOpCode)opcode;
return string.Format("{1} = {2}", igetOpCode.Name, GetRegisterName(igetOpCode.Destination, method), GetFieldName(igetOpCode.Index, currentClass));
case Instructions.Aput:
case Instructions.AputWide:
case Instructions.AputObject:
case Instructions.AputBoolean:
case Instructions.AputChar:
case Instructions.AputShort:
case Instructions.AputByte:
var aputOpCode = (ArrayOpOpCode)opcode;
return string.Format("{2}[{3}] = {1}", aputOpCode.Name, GetRegisterName(aputOpCode.Destination, method), GetRegisterName(aputOpCode.Array, method), GetRegisterName(aputOpCode.Index, method));
case Instructions.Aget:
case Instructions.AgetWide:
case Instructions.AgetObject:
case Instructions.AgetBoolean:
case Instructions.AgetChar:
case Instructions.AgetShort:
case Instructions.AgetByte:
var agetOpCode = (ArrayOpOpCode)opcode;
return string.Format("{1} = {2}[{3}]", agetOpCode.Name, GetRegisterName(agetOpCode.Destination, method), GetRegisterName(agetOpCode.Array, method), GetRegisterName(agetOpCode.Index, method));
case Instructions.AddInt:
case Instructions.AddLong:
case Instructions.AddFloat:
case Instructions.AddDouble:
return FormatBinaryOperation((BinaryOpOpCode)opcode, "+", method);
case Instructions.SubInt:
case Instructions.SubLong:
case Instructions.SubFloat:
case Instructions.SubDouble:
return FormatBinaryOperation((BinaryOpOpCode)opcode, "-", method);
case Instructions.MulInt:
case Instructions.MulLong:
case Instructions.MulFloat:
case Instructions.MulDouble:
return FormatBinaryOperation((BinaryOpOpCode)opcode, "*", method);
case Instructions.DivInt:
case Instructions.DivLong:
case Instructions.DivFloat:
case Instructions.DivDouble:
return FormatBinaryOperation((BinaryOpOpCode)opcode, "/", method);
case Instructions.RemInt:
case Instructions.RemLong:
case Instructions.RemFloat:
case Instructions.RemDouble:
return FormatBinaryOperation((BinaryOpOpCode)opcode, "&", method);
case Instructions.AndInt:
case Instructions.AndLong:
return FormatBinaryOperation((BinaryOpOpCode)opcode, "&", method);
case Instructions.OrInt:
case Instructions.OrLong:
return FormatBinaryOperation((BinaryOpOpCode)opcode, "|", method);
case Instructions.XorInt:
case Instructions.XorLong:
return FormatBinaryOperation((BinaryOpOpCode)opcode, "^", method);
case Instructions.ShlInt:
case Instructions.ShlLong:
return FormatBinaryOperation((BinaryOpOpCode)opcode, "<<", method);
case Instructions.ShrInt:
case Instructions.UshrInt:
case Instructions.ShrLong:
case Instructions.UshrLong:
return FormatBinaryOperation((BinaryOpOpCode)opcode, ">>", method);
case Instructions.IfEq:
return FormatIfOperation((IfOpCode)opcode, "=", method, jumpTable);
case Instructions.IfNe:
return FormatIfOperation((IfOpCode)opcode, "!=", method, jumpTable);
case Instructions.IfLt:
return FormatIfOperation((IfOpCode)opcode, "<", method, jumpTable);
case Instructions.IfGe:
return FormatIfOperation((IfOpCode)opcode, ">=", method, jumpTable);
case Instructions.IfGt:
return FormatIfOperation((IfOpCode)opcode, ">", method, jumpTable);
case Instructions.IfLe:
return FormatIfOperation((IfOpCode)opcode, "<=", method, jumpTable);
case Instructions.IfEqz:
return FormatIfzOperation((IfzOpCode)opcode, "=", method, jumpTable);
case Instructions.IfNez:
return FormatIfzOperation((IfzOpCode)opcode, "!=", method, jumpTable);
case Instructions.IfLtz:
return FormatIfzOperation((IfzOpCode)opcode, "<", method, jumpTable);
case Instructions.IfGez:
return FormatIfzOperation((IfzOpCode)opcode, ">=", method, jumpTable);
case Instructions.IfGtz:
return FormatIfzOperation((IfzOpCode)opcode, ">", method, jumpTable);
case Instructions.IfLez:
return FormatIfzOperation((IfzOpCode)opcode, "<=", method, jumpTable);
case Instructions.RsubInt:
case Instructions.RsubIntLit8:
dynamic rsubIntOpCode = opcode;
return string.Format("{0} = #{2} - {1}", GetRegisterName(rsubIntOpCode.Destination, method), GetRegisterName(rsubIntOpCode.Source, method), rsubIntOpCode.Constant);
case Instructions.AddIntLit16:
case Instructions.AddIntLit8:
return FormatBinaryLiteralOperation(opcode, "+", method);
case Instructions.MulIntLit16:
case Instructions.MulIntLit8:
return FormatBinaryLiteralOperation(opcode, "*", method);
case Instructions.DivIntLit16:
case Instructions.DivIntLit8:
return FormatBinaryLiteralOperation(opcode, "/", method);
case Instructions.RemIntLit16:
case Instructions.RemIntLit8:
return FormatBinaryLiteralOperation(opcode, "%", method);
case Instructions.AndIntLit16:
case Instructions.AndIntLit8:
return FormatBinaryLiteralOperation(opcode, "&", method);
case Instructions.OrIntLit16:
case Instructions.OrIntLit8:
return FormatBinaryLiteralOperation(opcode, "|", method);
case Instructions.XorIntLit16:
case Instructions.XorIntLit8:
return FormatBinaryLiteralOperation(opcode, "^", method);
case Instructions.ShlIntLit8:
return FormatBinaryLiteralOperation(opcode, "<<", method);
case Instructions.ShrIntLit8:
return FormatBinaryLiteralOperation(opcode, ">>", method);
case Instructions.UshrIntLit8:
return FormatBinaryLiteralOperation(opcode, ">>", method);
case Instructions.AddInt2Addr:
case Instructions.AddLong2Addr:
case Instructions.AddFloat2Addr:
case Instructions.AddDouble2Addr:
return FormatBinary2AddrOperation((BinaryOp2OpCode)opcode, "+", method);
case Instructions.SubInt2Addr:
case Instructions.SubLong2Addr:
case Instructions.SubFloat2Addr:
case Instructions.SubDouble2Addr:
return FormatBinary2AddrOperation((BinaryOp2OpCode)opcode, "-", method);
case Instructions.MulInt2Addr:
case Instructions.MulLong2Addr:
case Instructions.MulFloat2Addr:
case Instructions.MulDouble2Addr:
return FormatBinary2AddrOperation((BinaryOp2OpCode)opcode, "*", method);
case Instructions.DivInt2Addr:
case Instructions.DivLong2Addr:
case Instructions.DivFloat2Addr:
case Instructions.DivDouble2Addr:
return FormatBinary2AddrOperation((BinaryOp2OpCode)opcode, "/", method);
case Instructions.RemInt2Addr:
case Instructions.RemLong2Addr:
case Instructions.RemFloat2Addr:
case Instructions.RemDouble2Addr:
return FormatBinary2AddrOperation((BinaryOp2OpCode)opcode, "&", method);
case Instructions.AndInt2Addr:
case Instructions.AndLong2Addr:
return FormatBinary2AddrOperation((BinaryOp2OpCode)opcode, "&", method);
case Instructions.OrInt2Addr:
case Instructions.OrLong2Addr:
return FormatBinary2AddrOperation((BinaryOp2OpCode)opcode, "|", method);
case Instructions.XorInt2Addr:
case Instructions.XorLong2Addr:
return FormatBinary2AddrOperation((BinaryOp2OpCode)opcode, "^", method);
case Instructions.ShlInt2Addr:
case Instructions.ShlLong2Addr:
return FormatBinary2AddrOperation((BinaryOp2OpCode)opcode, "<<", method);
case Instructions.ShrInt2Addr:
case Instructions.UshrInt2Addr:
case Instructions.ShrLong2Addr:
case Instructions.UshrLong2Addr:
return FormatBinary2AddrOperation((BinaryOp2OpCode)opcode, ">>", method);
case Instructions.Goto:
case Instructions.Goto16:
case Instructions.Goto32:
dynamic gotoOpCode = opcode;
return string.Format("{0} {1}", gotoOpCode.Name, jumpTable.GetReferrerLabel(gotoOpCode.OpCodeOffset));
case Instructions.PackedSwitch:
var packedSwitchOpCode = (PackedSwitchOpCode)opcode;
return string.Format("{0} {1} - First:{2} - [{3}]", opcode.Name, GetRegisterName(packedSwitchOpCode.Destination,method), packedSwitchOpCode.FirstKey, string.Join(",", jumpTable.GetReferrerLabels(packedSwitchOpCode.OpCodeOffset)));
case Instructions.SparseSwitch:
var sparseSwitchOpCode = (SparseSwitchOpCode)opcode;
return string.Format("{0} {1} - Keys:[{2}] Targets:[{3}]", opcode.Name, GetRegisterName(sparseSwitchOpCode.Destination,method), string.Join(",",sparseSwitchOpCode.Keys), string.Join(",", jumpTable.GetReferrerLabels(sparseSwitchOpCode.OpCodeOffset)));
default:
return opcode.ToString ();
}
}
private string FormatBinaryOperation(BinaryOpOpCode opcode, string operation, Method method)
{
return string.Format("{0} = {1} {3} {2}", GetRegisterName(opcode.Destination, method), GetRegisterName(opcode.First, method), GetRegisterName(opcode.Second, method), operation);
}
private string FormatBinary2AddrOperation(BinaryOp2OpCode opcode, string operation, Method method)
{
return string.Format("{0} = {0} {2} {1}", GetRegisterName(opcode.Destination, method), GetRegisterName(opcode.Source, method), operation);
}
private string FormatBinaryLiteralOperation(dynamic opcode, string operation, Method method)
{
return string.Format("{0} = {1} {3} #{2}", GetRegisterName(opcode.Destination, method), GetRegisterName(opcode.Source, method), opcode.Constant, operation);
}
private string FormatIfOperation(IfOpCode opcode, string comparison, Method method, JumpTable jumpTable)
{
return string.Format("if ({0} {3} {1}) :{2}", GetRegisterName(opcode.First, method), GetRegisterName(opcode.Second, method), jumpTable.GetReferrerLabel(opcode.OpCodeOffset), comparison);
}
private string FormatIfzOperation(IfzOpCode opcode, string comparison, Method method, JumpTable jumpTable)
{
return string.Format("if ({0} {2} 0) :{1}", GetRegisterName(opcode.Destination, method), jumpTable.GetReferrerLabel(opcode.OpCodeOffset), comparison);
}
}
}
| |
#pragma warning disable 109, 114, 219, 429, 168, 162
namespace pony._Function
{
public sealed class Function_Impl_
{
static Function_Impl_()
{
#line 70 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Function.hx"
{
global::pony._Function.Function_Impl_.unusedCount = 0;
#line 73 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Function.hx"
global::pony._Function.Function_Impl_.cslist = new global::pony.Dictionary<object, object>(new global::haxe.lang.Null<int>(1, true));
global::pony._Function.Function_Impl_.list = new global::pony.Dictionary<object, object>(new global::haxe.lang.Null<int>(1, true));
#line 78 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Function.hx"
global::pony._Function.Function_Impl_.counter = -1;
global::pony._Function.Function_Impl_.searchFree = false;
}
}
public static int unusedCount;
public static global::pony.Dictionary<object, object> cslist;
public static global::pony.Dictionary<object, object> list;
public static int counter;
public static bool searchFree;
public static object _new(object f, int count, global::Array args)
{
unchecked
{
#line 82 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Function.hx"
object this1 = default(object);
global::pony._Function.Function_Impl_.counter++;
if (global::pony._Function.Function_Impl_.searchFree)
{
while (true)
{
{
#line 86 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Function.hx"
object __temp_iterator172 = global::pony._Function.Function_Impl_.list.vs.iterator();
#line 86 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Function.hx"
while (((bool) (global::haxe.lang.Runtime.callField(__temp_iterator172, "hasNext", 407283053, default(global::Array))) ))
{
#line 86 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Function.hx"
object e = ((object) (global::haxe.lang.Runtime.callField(__temp_iterator172, "next", 1224901875, default(global::Array))) );
if (( ((int) (global::haxe.lang.Runtime.getField_f(e, "id", 23515, true)) ) != global::pony._Function.Function_Impl_.counter ))
{
break;
}
}
}
#line 90 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Function.hx"
global::pony._Function.Function_Impl_.counter++;
}
}
else
{
#line 92 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Function.hx"
if (( global::pony._Function.Function_Impl_.counter == -1 ))
{
global::pony._Function.Function_Impl_.searchFree = true;
}
}
this1 = new global::haxe.lang.DynamicObject(new global::Array<int>(new int[]{102, 1081380189}), new global::Array<object>(new object[]{f, ( (( args == default(global::Array) )) ? (new global::Array<object>(new object[]{})) : (args) )}), new global::Array<int>(new int[]{23515, 1248019663, 1303220797}), new global::Array<double>(new double[]{((double) (global::pony._Function.Function_Impl_.counter) ), ((double) (count) ), ((double) (0) )}));
#line 82 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Function.hx"
return this1;
}
#line default
}
public static object @from(object f, int argc)
{
unchecked
{
#line 99 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Function.hx"
object h = global::pony._Function.Function_Impl_.buildCSHash(f);
bool __temp_stmt372 = default(bool);
#line 100 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Function.hx"
{
#line 100 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Function.hx"
global::pony.Dictionary<object, object> _this = global::pony._Function.Function_Impl_.cslist;
#line 100 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Function.hx"
__temp_stmt372 = ( global::pony.Tools.superIndexOf<object>(_this.ks, h, new global::haxe.lang.Null<int>(_this.maxDepth, true)) != -1 );
}
#line 100 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Function.hx"
if (__temp_stmt372)
{
return global::pony._Function.Function_Impl_.cslist.@get(h);
}
else
{
#line 103 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Function.hx"
global::pony._Function.Function_Impl_.unusedCount++;
object o = global::pony._Function.Function_Impl_._new(f, argc, default(global::Array));
global::pony._Function.Function_Impl_.cslist.@set(h, o);
return o;
}
}
#line default
}
public static object buildCSHash(object f)
{
unchecked
{
#line 122 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Function.hx"
if (( f is global::haxe.lang.Closure ))
{
{
#line 123 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Function.hx"
object __temp_odecl373 = global::haxe.lang.Runtime.getField(f, "obj", 5541879, true);
#line 123 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Function.hx"
string __temp_odecl374 = global::haxe.lang.Runtime.toString(global::haxe.lang.Runtime.getField(f, "field", 9671866, true));
#line 123 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Function.hx"
return new global::haxe.lang.DynamicObject(new global::Array<int>(new int[]{110, 111}), new global::Array<object>(new object[]{__temp_odecl374, __temp_odecl373}), new global::Array<int>(new int[]{}), new global::Array<double>(new double[]{}));
}
}
else
{
#line 125 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Function.hx"
string key = global::Std.@string(f);
global::System.Type t = f.GetType();
global::System.Reflection.FieldInfo[] a = t.GetFields();
global::Array data = new global::Array<object>(new object[]{});
{
#line 129 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Function.hx"
int _g1 = 0;
#line 129 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Function.hx"
int _g = ( a as global::System.Array ).Length;
#line 129 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Function.hx"
while (( _g1 < _g ))
{
#line 129 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Function.hx"
int i = _g1++;
global::haxe.lang.Runtime.callField(data, "push", 1247875546, new global::Array<object>(new object[]{global::Reflect.field(f, a[i].Name)}));
}
}
#line 132 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Function.hx"
return new global::haxe.lang.DynamicObject(new global::Array<int>(new int[]{110, 111}), new global::Array<object>(new object[]{key, ((object) (data) )}), new global::Array<int>(new int[]{}), new global::Array<double>(new double[]{}));
}
}
#line default
}
public static object from0<R>(global::haxe.lang.Function f)
{
unchecked
{
#line 138 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Function.hx"
return global::pony._Function.Function_Impl_.@from(f, 0);
}
#line default
}
public static object from1<R>(global::haxe.lang.Function f)
{
unchecked
{
#line 141 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Function.hx"
return global::pony._Function.Function_Impl_.@from(f, 1);
}
#line default
}
public static object from2<R>(global::haxe.lang.Function f)
{
unchecked
{
#line 144 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Function.hx"
return global::pony._Function.Function_Impl_.@from(f, 2);
}
#line default
}
public static object from3<R>(global::haxe.lang.Function f)
{
unchecked
{
#line 147 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Function.hx"
return global::pony._Function.Function_Impl_.@from(f, 3);
}
#line default
}
public static object from4<R>(global::haxe.lang.Function f)
{
unchecked
{
#line 150 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Function.hx"
return global::pony._Function.Function_Impl_.@from(f, 4);
}
#line default
}
public static object from5<R>(global::haxe.lang.Function f)
{
unchecked
{
#line 153 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Function.hx"
return global::pony._Function.Function_Impl_.@from(f, 5);
}
#line default
}
public static object from6<R>(global::haxe.lang.Function f)
{
unchecked
{
#line 156 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Function.hx"
return global::pony._Function.Function_Impl_.@from(f, 6);
}
#line default
}
public static object from7<R>(global::haxe.lang.Function f)
{
unchecked
{
#line 159 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Function.hx"
return global::pony._Function.Function_Impl_.@from(f, 7);
}
#line default
}
public static object call(object this1, global::Array args)
{
unchecked
{
#line 162 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Function.hx"
if (( args == default(global::Array) ))
{
#line 162 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Function.hx"
args = new global::Array<object>(new object[]{});
}
return global::Reflect.callMethod(default(object), global::haxe.lang.Runtime.getField(this1, "f", 102, true), ((global::Array) (global::haxe.lang.Runtime.callField(((global::Array) (global::haxe.lang.Runtime.getField(this1, "args", 1081380189, true)) ), "concat", 1204816148, new global::Array<object>(new object[]{args}))) ));
}
#line default
}
public static int _get_id(object this1)
{
unchecked
{
#line 166 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Function.hx"
return ((int) (global::haxe.lang.Runtime.getField_f(this1, "id", 23515, true)) );
}
#line default
}
public static int _get_count(object this1)
{
unchecked
{
#line 167 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Function.hx"
return ((int) (global::haxe.lang.Runtime.getField_f(this1, "count", 1248019663, true)) );
}
#line default
}
public static void _setArgs(object this1, global::Array args)
{
unchecked
{
#line 170 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Function.hx"
{
#line 170 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Function.hx"
object __temp_dynop173 = this1;
#line 170 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Function.hx"
global::haxe.lang.Runtime.setField_f(__temp_dynop173, "count", 1248019663, ((double) (( ((int) (global::haxe.lang.Runtime.getField_f(__temp_dynop173, "count", 1248019663, true)) ) - ((int) (global::haxe.lang.Runtime.getField_f(args, "length", 520590566, true)) ) )) ));
}
global::haxe.lang.Runtime.setField(this1, "args", 1081380189, ((global::Array) (global::haxe.lang.Runtime.callField(((global::Array) (global::haxe.lang.Runtime.getField(this1, "args", 1081380189, true)) ), "concat", 1204816148, new global::Array<object>(new object[]{args}))) ));
}
#line default
}
public static void _use(object this1)
{
unchecked
{
#line 174 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Function.hx"
{
#line 174 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Function.hx"
object __temp_getvar174 = this1;
#line 174 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Function.hx"
int __temp_ret175 = ((int) (global::haxe.lang.Runtime.getField_f(__temp_getvar174, "used", 1303220797, true)) );
#line 174 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Function.hx"
global::haxe.lang.Runtime.setField_f(__temp_getvar174, "used", 1303220797, ((double) (( __temp_ret175 + 1 )) ));
#line 174 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Function.hx"
int __temp_expr375 = __temp_ret175;
}
}
#line default
}
public static void unuse(object this1)
{
unchecked
{
#line 177 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Function.hx"
{
#line 177 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Function.hx"
object __temp_getvar176 = this1;
#line 177 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Function.hx"
int __temp_ret177 = ((int) (global::haxe.lang.Runtime.getField_f(__temp_getvar176, "used", 1303220797, true)) );
#line 177 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Function.hx"
global::haxe.lang.Runtime.setField_f(__temp_getvar176, "used", 1303220797, ((double) (( __temp_ret177 - 1 )) ));
#line 177 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Function.hx"
int __temp_expr376 = __temp_ret177;
}
if (( global::haxe.lang.Runtime.compare(((int) (global::haxe.lang.Runtime.getField_f(this1, "used", 1303220797, true)) ), 0) <= 0 ))
{
#line 180 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Function.hx"
if (( global::haxe.lang.Runtime.getField(this1, "f", 102, true) is global::haxe.lang.Closure ))
{
global::pony._Function.Function_Impl_.cslist.@remove(global::pony._Function.Function_Impl_.buildCSHash(global::haxe.lang.Runtime.getField(this1, "f", 102, true)));
}
else
{
#line 183 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Function.hx"
global::pony._Function.Function_Impl_.list.@remove(global::pony._Function.Function_Impl_.buildCSHash(global::haxe.lang.Runtime.getField(this1, "f", 102, true)));
}
#line 187 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Function.hx"
this1 = default(object);
global::pony._Function.Function_Impl_.unusedCount--;
}
}
#line default
}
public static int _get_used(object this1)
{
unchecked
{
#line 192 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Function.hx"
return ((int) (global::haxe.lang.Runtime.getField_f(this1, "used", 1303220797, true)) );
}
#line default
}
}
}
| |
//=============================================================================
// System : Sandcastle Help File Builder
// File : AboutDlg.cs
// Author : Eric Woodruff (Eric@EWoodruff.us)
// Updated : 09/30/2006
// Note : Copyright 2006, Eric Woodruff, All rights reserved
// Compiler: Microsoft Visual C#
//
// This form is used to display application version information.
//
// 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.0.0.0 08/02/2006 EFW Created the code
//=============================================================================
using System;
using System.Collections;
using System.ComponentModel;
using System.Configuration;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Reflection;
using System.Windows.Forms;
using SandcastleBuilder.Gui.Properties;
using SandcastleBuilder.Utils;
namespace SandcastleBuilder.Gui
{
/// <summary>
/// This form is used to display application version information.
/// </summary>
public class AboutDlg : System.Windows.Forms.Form
{
private System.Windows.Forms.ColumnHeader ColumnHeader1;
private System.Windows.Forms.ColumnHeader ColumnHeader2;
private System.Windows.Forms.Label Label1;
private System.Windows.Forms.Label lblName;
private System.Windows.Forms.Label lblDescription;
private System.Windows.Forms.Button btnSysInfo;
private System.Windows.Forms.Button btnOK;
private System.Windows.Forms.ListView lvComponents;
private System.Windows.Forms.LinkLabel lnkHelp;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.PictureBox pictureBox1;
private System.Windows.Forms.ToolTip toolTip1;
private SandcastleBuilder.Utils.Controls.StatusBarTextProvider sbMessage;
private LinkLabel lnkEWoodruffUrl;
private LinkLabel lnkProjectUrl;
private Label lblCopyright;
private System.Windows.Forms.Label lblVersion;
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.lnkHelp = new System.Windows.Forms.LinkLabel();
this.ColumnHeader1 = new System.Windows.Forms.ColumnHeader();
this.btnSysInfo = new System.Windows.Forms.Button();
this.btnOK = new System.Windows.Forms.Button();
this.lvComponents = new System.Windows.Forms.ListView();
this.ColumnHeader2 = new System.Windows.Forms.ColumnHeader();
this.Label1 = new System.Windows.Forms.Label();
this.lblName = new System.Windows.Forms.Label();
this.lblDescription = new System.Windows.Forms.Label();
this.lblVersion = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.pictureBox1 = new System.Windows.Forms.PictureBox();
this.toolTip1 = new System.Windows.Forms.ToolTip(this.components);
this.lnkEWoodruffUrl = new System.Windows.Forms.LinkLabel();
this.lnkProjectUrl = new System.Windows.Forms.LinkLabel();
this.sbMessage = new SandcastleBuilder.Utils.Controls.StatusBarTextProvider(this.components);
this.lblCopyright = new System.Windows.Forms.Label();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
this.SuspendLayout();
//
// lnkHelp
//
this.lnkHelp.Location = new System.Drawing.Point(493, 321);
this.lnkHelp.Name = "lnkHelp";
this.lnkHelp.Size = new System.Drawing.Size(281, 18);
this.sbMessage.SetStatusBarText(this.lnkHelp, "Send e-mail to the help desk");
this.lnkHelp.TabIndex = 7;
this.lnkHelp.TabStop = true;
this.lnkHelp.Text = "Eric@EWoodruff.us";
this.toolTip1.SetToolTip(this.lnkHelp, "Send e-mail requesting help");
this.lnkHelp.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.Link_LinkClicked);
//
// ColumnHeader1
//
this.ColumnHeader1.Text = "Name";
this.ColumnHeader1.Width = 250;
//
// btnSysInfo
//
this.btnSysInfo.Location = new System.Drawing.Point(544, 385);
this.btnSysInfo.Name = "btnSysInfo";
this.btnSysInfo.Size = new System.Drawing.Size(112, 32);
this.sbMessage.SetStatusBarText(this.btnSysInfo, "System Info: View system information for the PC on which the application is runni" +
"ng");
this.btnSysInfo.TabIndex = 10;
this.btnSysInfo.Text = "System Info...";
this.toolTip1.SetToolTip(this.btnSysInfo, "Display system information");
this.btnSysInfo.Click += new System.EventHandler(this.btnSysInfo_Click);
//
// btnOK
//
this.btnOK.DialogResult = System.Windows.Forms.DialogResult.OK;
this.btnOK.Location = new System.Drawing.Point(664, 385);
this.btnOK.Name = "btnOK";
this.btnOK.Size = new System.Drawing.Size(112, 32);
this.sbMessage.SetStatusBarText(this.btnOK, "OK: Close this dialog box");
this.btnOK.TabIndex = 11;
this.btnOK.Text = "OK";
this.toolTip1.SetToolTip(this.btnOK, "Close this dialog box");
//
// lvComponents
//
this.lvComponents.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.ColumnHeader1,
this.ColumnHeader2});
this.lvComponents.FullRowSelect = true;
this.lvComponents.GridLines = true;
this.lvComponents.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.Nonclickable;
this.lvComponents.Location = new System.Drawing.Point(336, 128);
this.lvComponents.MultiSelect = false;
this.lvComponents.Name = "lvComponents";
this.lvComponents.Size = new System.Drawing.Size(438, 160);
this.sbMessage.SetStatusBarText(this.lvComponents, "Component name and version information");
this.lvComponents.TabIndex = 4;
this.lvComponents.UseCompatibleStateImageBehavior = false;
this.lvComponents.View = System.Windows.Forms.View.Details;
//
// ColumnHeader2
//
this.ColumnHeader2.Text = "Version";
this.ColumnHeader2.Width = 150;
//
// Label1
//
this.Label1.Location = new System.Drawing.Point(336, 104);
this.Label1.Name = "Label1";
this.Label1.Size = new System.Drawing.Size(160, 19);
this.Label1.TabIndex = 3;
this.Label1.Text = "Product Components";
//
// lblName
//
this.lblName.Font = new System.Drawing.Font("Microsoft Sans Serif", 7.8F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lblName.Location = new System.Drawing.Point(336, 8);
this.lblName.Name = "lblName";
this.lblName.Size = new System.Drawing.Size(440, 19);
this.lblName.TabIndex = 0;
this.lblName.Text = "<Application Name>";
//
// lblDescription
//
this.lblDescription.Location = new System.Drawing.Point(336, 56);
this.lblDescription.Name = "lblDescription";
this.lblDescription.Size = new System.Drawing.Size(440, 46);
this.lblDescription.TabIndex = 2;
this.lblDescription.Text = "<Description>";
//
// lblVersion
//
this.lblVersion.Font = new System.Drawing.Font("Microsoft Sans Serif", 7.8F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lblVersion.Location = new System.Drawing.Point(336, 32);
this.lblVersion.Name = "lblVersion";
this.lblVersion.Size = new System.Drawing.Size(440, 19);
this.lblVersion.TabIndex = 1;
this.lblVersion.Text = "<Version>";
//
// label2
//
this.label2.Location = new System.Drawing.Point(336, 321);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(160, 19);
this.label2.TabIndex = 6;
this.label2.Text = "For help send e-mail to";
//
// pictureBox1
//
this.pictureBox1.BackColor = System.Drawing.Color.Tan;
this.pictureBox1.Image = global::SandcastleBuilder.Gui.Properties.Resources.Sandcastle;
this.pictureBox1.Location = new System.Drawing.Point(8, 8);
this.pictureBox1.Name = "pictureBox1";
this.pictureBox1.Size = new System.Drawing.Size(312, 409);
this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom;
this.pictureBox1.TabIndex = 12;
this.pictureBox1.TabStop = false;
//
// lnkEWoodruffUrl
//
this.lnkEWoodruffUrl.Location = new System.Drawing.Point(336, 339);
this.lnkEWoodruffUrl.Name = "lnkEWoodruffUrl";
this.lnkEWoodruffUrl.Size = new System.Drawing.Size(438, 18);
this.sbMessage.SetStatusBarText(this.lnkEWoodruffUrl, "Open a browser to view www.EWoodruff.us");
this.lnkEWoodruffUrl.TabIndex = 8;
this.lnkEWoodruffUrl.TabStop = true;
this.lnkEWoodruffUrl.Text = "http://www.EWoodruff.us";
this.toolTip1.SetToolTip(this.lnkEWoodruffUrl, "View www.EWoodruff.us");
this.lnkEWoodruffUrl.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.Link_LinkClicked);
//
// lnkProjectUrl
//
this.lnkProjectUrl.Location = new System.Drawing.Point(336, 357);
this.lnkProjectUrl.Name = "lnkProjectUrl";
this.lnkProjectUrl.Size = new System.Drawing.Size(438, 18);
this.sbMessage.SetStatusBarText(this.lnkProjectUrl, "View the project website on CodePlex");
this.lnkProjectUrl.TabIndex = 9;
this.lnkProjectUrl.TabStop = true;
this.lnkProjectUrl.Text = "http://SHFB.CodePlex.com";
this.toolTip1.SetToolTip(this.lnkProjectUrl, "View project website");
this.lnkProjectUrl.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.Link_LinkClicked);
//
// lblCopyright
//
this.lblCopyright.Location = new System.Drawing.Point(336, 291);
this.lblCopyright.Name = "lblCopyright";
this.lblCopyright.Size = new System.Drawing.Size(440, 19);
this.lblCopyright.TabIndex = 5;
this.lblCopyright.Text = "<Copyright>";
//
// AboutDlg
//
this.AcceptButton = this.btnOK;
this.CancelButton = this.btnOK;
this.ClientSize = new System.Drawing.Size(786, 429);
this.Controls.Add(this.lblCopyright);
this.Controls.Add(this.lnkProjectUrl);
this.Controls.Add(this.lnkEWoodruffUrl);
this.Controls.Add(this.lnkHelp);
this.Controls.Add(this.pictureBox1);
this.Controls.Add(this.btnSysInfo);
this.Controls.Add(this.btnOK);
this.Controls.Add(this.lvComponents);
this.Controls.Add(this.Label1);
this.Controls.Add(this.lblName);
this.Controls.Add(this.lblDescription);
this.Controls.Add(this.lblVersion);
this.Controls.Add(this.label2);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "AboutDlg";
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "About";
this.Load += new System.EventHandler(this.AboutDlg_Load);
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
this.ResumeLayout(false);
}
#endregion
private System.ComponentModel.IContainer components;
/// <summary>
/// Constructor
/// </summary>
public AboutDlg()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
}
/// <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 )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
/// <summary>
/// Load the controls on the forms with data
/// </summary>
/// <param name="sender">The sender of the event</param>
/// <param name="e">The event arguments</param>
private void AboutDlg_Load(object sender, System.EventArgs e)
{
// Get assembly information not available from the application object
Assembly asm = Assembly.GetExecutingAssembly();
AssemblyDescriptionAttribute aDescr = (AssemblyDescriptionAttribute)
AssemblyDescriptionAttribute.GetCustomAttribute(asm,
typeof(AssemblyDescriptionAttribute));
AssemblyCopyrightAttribute aCopyright = (AssemblyCopyrightAttribute)
AssemblyCopyrightAttribute.GetCustomAttribute(asm,
typeof(AssemblyCopyrightAttribute));
// Set the labels
this.Text = "About " + Application.ProductName;
lblName.Text = Application.ProductName;
lblVersion.Text = "Version: " + Application.ProductVersion;
lblDescription.Text = aDescr.Description;
lblCopyright.Text = aCopyright.Copyright;
lnkHelp.Text = Settings.Default.AuthorEMailAddress;
lnkEWoodruffUrl.Text = Settings.Default.EWoodruffURL;
lnkProjectUrl.Text = Settings.Default.ProjectURL;
// Display components used by this assembly sorted by name
AssemblyName[] anComponents = asm.GetReferencedAssemblies();
foreach(AssemblyName an in anComponents)
{
ListViewItem lvi = lvComponents.Items.Add(an.Name);
lvi.SubItems.Add(an.Version.ToString());
}
lvComponents.Sorting = SortOrder.Ascending;
lvComponents.Sort();
// Set the e-mail and URL links
lnkHelp.Links[0].LinkData = "mailto:" + lnkHelp.Text +
"?Subject=" + Application.ProductName;
lnkEWoodruffUrl.Links[0].LinkData = lnkEWoodruffUrl.Text;
lnkProjectUrl.Links[0].LinkData = lnkProjectUrl.Text;
}
/// <summary>
/// View system information using <b>MSInfo32.exe</b>
/// </summary>
/// <param name="sender">The sender of the event</param>
/// <param name="e">The event arguments</param>
private void btnSysInfo_Click(object sender, System.EventArgs e)
{
try
{
System.Diagnostics.Process.Start("MSInfo32.exe");
}
catch(Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.ToString());
MessageBox.Show("Unable to launch system information " +
"viewer. Reason: " + ex.Message, Constants.AppName,
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
/// <summary>
/// Open the target of the clicked link
/// </summary>
/// <param name="sender">The sender of the event</param>
/// <param name="e">The event arguments</param>
private void Link_LinkClicked(object sender,
System.Windows.Forms.LinkLabelLinkClickedEventArgs e)
{
try
{
// Launch the e-mail URL, this will fail if user does not
// have an association for e-mail URLs.
System.Diagnostics.Process.Start((string)e.Link.LinkData);
}
catch(Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.ToString());
MessageBox.Show("Unable to launch link target. " +
"Reason: " + ex.Message, Constants.AppName,
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
#if WINRT && !UNITY_EDITOR
using Windows.Networking;
using Windows.Networking.Connectivity;
#else
using System.Net;
using System.Net.Sockets;
using System.Net.NetworkInformation;
#endif
namespace LiteNetLib
{
#if WINRT && !UNITY_EDITOR
public enum ConsoleColor
{
Gray,
Yellow,
Cyan,
DarkCyan,
DarkGreen,
Blue,
DarkRed,
Red,
Green,
DarkYellow
}
#endif
/// <summary>
/// Address type that you want to receive from NetUtils.GetLocalIp method
/// </summary>
[Flags]
public enum LocalAddrType
{
IPv4 = 1,
IPv6 = 2,
All = 3
}
/// <summary>
/// Some specific network utilities
/// </summary>
public static class NetUtils
{
/// <summary>
/// Request time from NTP server and calls callback (if success)
/// </summary>
/// <param name="ntpServerAddress">NTP Server address</param>
/// <param name="port">port</param>
/// <param name="onRequestComplete">callback (called from other thread!)</param>
public static void RequestTimeFromNTP(string ntpServerAddress, int port, Action<DateTime?> onRequestComplete)
{
NetSocket socket = null;
var ntpEndPoint = new NetEndPoint(ntpServerAddress, port);
NetManager.OnMessageReceived onReceive = (data, length, code, point) =>
{
if (!point.Equals(ntpEndPoint) || length < 48)
{
return;
}
socket.Close();
ulong intPart = (ulong)data[40] << 24 | (ulong)data[41] << 16 | (ulong)data[42] << 8 | (ulong)data[43];
ulong fractPart = (ulong)data[44] << 24 | (ulong)data[45] << 16 | (ulong)data[46] << 8 | (ulong)data[47];
var milliseconds = (intPart * 1000) + ((fractPart * 1000) / 0x100000000L);
onRequestComplete(new DateTime(1900, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds((long) milliseconds));
};
//Create and start socket
socket = new NetSocket(onReceive);
socket.Bind(0, false);
//Send request
int errorCode = 0;
var sendData = new byte[48];
sendData[0] = 0x1B;
var sendCount = socket.SendTo(sendData, 0, sendData.Length, ntpEndPoint, ref errorCode);
if (errorCode != 0 || sendCount != sendData.Length)
{
onRequestComplete(null);
}
}
/// <summary>
/// Get all local ip addresses
/// </summary>
/// <param name="addrType">type of address (IPv4, IPv6 or both)</param>
/// <returns>List with all local ip adresses</returns>
public static List<string> GetLocalIpList(LocalAddrType addrType)
{
List<string> targetList = new List<string>();
GetLocalIpList(targetList, addrType);
return targetList;
}
/// <summary>
/// Get all local ip addresses (non alloc version)
/// </summary>
/// <param name="targetList">result list</param>
/// <param name="addrType">type of address (IPv4, IPv6 or both)</param>
public static void GetLocalIpList(List<string> targetList, LocalAddrType addrType)
{
bool ipv4 = (addrType & LocalAddrType.IPv4) == LocalAddrType.IPv4;
bool ipv6 = (addrType & LocalAddrType.IPv6) == LocalAddrType.IPv6;
#if WINRT && !UNITY_EDITOR
foreach (HostName localHostName in NetworkInformation.GetHostNames())
{
if (localHostName.IPInformation != null &&
((ipv4 && localHostName.Type == HostNameType.Ipv4) ||
(ipv6 && localHostName.Type == HostNameType.Ipv6)))
{
targetList.Add(localHostName.ToString());
}
}
#else
try
{
foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())
{
//Skip loopback and disabled network interfaces
if (ni.NetworkInterfaceType == NetworkInterfaceType.Loopback ||
ni.OperationalStatus != OperationalStatus.Up)
continue;
var ipProps = ni.GetIPProperties();
//Skip address without gateway
if (ipProps.GatewayAddresses.Count == 0)
continue;
foreach (UnicastIPAddressInformation ip in ipProps.UnicastAddresses)
{
var address = ip.Address;
if ((ipv4 && address.AddressFamily == AddressFamily.InterNetwork) ||
(ipv6 && address.AddressFamily == AddressFamily.InterNetworkV6))
targetList.Add(address.ToString());
}
}
}
catch
{
//ignored
}
//Fallback mode (unity android)
if (targetList.Count == 0)
{
#if NETCORE
var hostTask = Dns.GetHostEntryAsync(Dns.GetHostName());
hostTask.Wait();
var host = hostTask.Result;
#else
var host = Dns.GetHostEntry(Dns.GetHostName());
#endif
foreach (IPAddress ip in host.AddressList)
{
if((ipv4 && ip.AddressFamily == AddressFamily.InterNetwork) ||
(ipv6 && ip.AddressFamily == AddressFamily.InterNetworkV6))
targetList.Add(ip.ToString());
}
}
#endif
if (targetList.Count == 0)
{
if(ipv4)
targetList.Add("127.0.0.1");
if(ipv6)
targetList.Add("::1");
}
}
private static readonly List<string> IpList = new List<string>();
/// <summary>
/// Get first detected local ip address
/// </summary>
/// <param name="addrType">type of address (IPv4, IPv6 or both)</param>
/// <returns>IP address if available. Else - string.Empty</returns>
public static string GetLocalIp(LocalAddrType addrType)
{
lock (IpList)
{
IpList.Clear();
GetLocalIpList(IpList, addrType);
return IpList.Count == 0 ? string.Empty : IpList[0];
}
}
// ===========================================
// Internal and debug log related stuff
// ===========================================
internal static void PrintInterfaceInfos()
{
#if !WINRT || UNITY_EDITOR
DebugWriteForce(ConsoleColor.Green, "IPv6Support: {0}", NetSocket.IPv6Support);
try
{
foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())
{
foreach (UnicastIPAddressInformation ip in ni.GetIPProperties().UnicastAddresses)
{
if (ip.Address.AddressFamily == AddressFamily.InterNetwork ||
ip.Address.AddressFamily == AddressFamily.InterNetworkV6)
{
DebugWriteForce(
ConsoleColor.Green,
"Interface: {0}, Type: {1}, Ip: {2}, OpStatus: {3}",
ni.Name,
ni.NetworkInterfaceType.ToString(),
ip.Address.ToString(),
ni.OperationalStatus.ToString());
}
}
}
}
catch (Exception e)
{
DebugWriteForce(ConsoleColor.Red, "Error while getting interface infos: {0}", e.ToString());
}
#endif
}
internal static int RelativeSequenceNumber(int number, int expected)
{
return (number - expected + NetConstants.MaxSequence + NetConstants.HalfMaxSequence) % NetConstants.MaxSequence - NetConstants.HalfMaxSequence;
}
private static readonly object DebugLogLock = new object();
private static void DebugWriteLogic(ConsoleColor color, string str, params object[] args)
{
lock (DebugLogLock)
{
if (NetDebug.Logger == null)
{
#if UNITY
UnityEngine.Debug.LogFormat(str, args);
#elif WINRT
Debug.WriteLine(str, args);
#else
Console.ForegroundColor = color;
Console.WriteLine(str, args);
Console.ForegroundColor = ConsoleColor.Gray;
#endif
}
else
{
NetDebug.Logger.WriteNet(color, str, args);
}
}
}
[Conditional("DEBUG_MESSAGES")]
internal static void DebugWrite(string str, params object[] args)
{
DebugWriteLogic(ConsoleColor.DarkGreen, str, args);
}
[Conditional("DEBUG_MESSAGES")]
internal static void DebugWrite(ConsoleColor color, string str, params object[] args)
{
DebugWriteLogic(color, str, args);
}
[Conditional("DEBUG_MESSAGES"), Conditional("DEBUG")]
internal static void DebugWriteForce(ConsoleColor color, string str, params object[] args)
{
DebugWriteLogic(color, str, args);
}
[Conditional("DEBUG_MESSAGES"), Conditional("DEBUG")]
internal static void DebugWriteError(string str, params object[] args)
{
DebugWriteLogic(ConsoleColor.Red, str, args);
}
}
}
| |
//! \file Huffman.cs
//! \date Wed May 18 22:19:23 2016
//! \brief Google WEBP Huffman compression implementaion.
/*
Copyright (c) 2010, Google Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* 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 Google 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.
*/
//
// C# port by morkt (C) 2016
//
namespace GameRes.Formats.Google
{
static class Huffman
{
public const int CodesPerMetaCode = 5;
public const int PackedBits = 6;
public const int PackedTableSize = 1 << PackedBits;
public const int DefaultCodeLength = 8;
public const int MaxAllowedCodeLength = 15;
public const int NumLiteralCodes = 256;
public const int NumLengthCodes = 24;
public const int NumDistanceCodes = 40;
public const int CodeLengthCodes = 19;
public const int MinBits = 2; // min number of Huffman bits
public const int MaxBits = 9; // max number of Huffman bits
public const int TableBits = 8;
public const int TableMask = (1 << TableBits) - 1;
public const int LengthsTableBits = 7;
public const int LengthsTableMask = (1 << LengthsTableBits) - 1;
static uint GetNextKey (uint key, int len)
{
uint step = 1u << (len - 1);
while (0 != (key & step))
step >>= 1;
return (key & (step - 1)) + step;
}
public static int BuildTable (HuffmanCode[] root_table, int index, int root_bits, int[] code_lengths, int code_lengths_size)
{
int table = index; // next available space in table
int total_size = 1 << root_bits; // total size root table + 2nd level table
int len; // current code length
int symbol; // symbol index in original or sorted table
// number of codes of each length:
int[] count = new int[MaxAllowedCodeLength + 1];
// offsets in sorted table for each length:
int[] offset = new int[MaxAllowedCodeLength + 1];
// Build histogram of code lengths.
for (symbol = 0; symbol < code_lengths_size; ++symbol)
{
if (code_lengths[symbol] > MaxAllowedCodeLength)
return 0;
++count[code_lengths[symbol]];
}
// Error, all code lengths are zeros.
if (count[0] == code_lengths_size)
return 0;
// Generate offsets into sorted symbol table by code length.
offset[1] = 0;
for (len = 1; len < MaxAllowedCodeLength; ++len)
{
if (count[len] > (1 << len))
return 0;
offset[len + 1] = offset[len] + count[len];
}
var sorted = new int[code_lengths_size];
// Sort symbols by length, by symbol order within each length.
for (symbol = 0; symbol < code_lengths_size; ++symbol)
{
int symbol_code_length = code_lengths[symbol];
if (code_lengths[symbol] > 0)
sorted[offset[symbol_code_length]++] = symbol;
}
// Special case code with only one value.
if (offset[MaxAllowedCodeLength] == 1)
{
HuffmanCode code;
code.bits = 0;
code.value = (ushort)sorted[0];
ReplicateValue (root_table, table, 1, total_size, code);
return total_size;
}
int step; // step size to replicate values in current table
uint low = uint.MaxValue; // low bits for current root entry
uint mask = (uint)total_size - 1; // mask for low bits
uint key = 0; // reversed prefix code
int num_nodes = 1; // number of Huffman tree nodes
int num_open = 1; // number of open branches in current tree level
int table_bits = root_bits; // key length of current table
int table_size = 1 << table_bits; // size of current table
symbol = 0;
// Fill in root table.
for (len = 1, step = 2; len <= root_bits; ++len, step <<= 1)
{
num_open <<= 1;
num_nodes += num_open;
num_open -= count[len];
if (num_open < 0)
return 0;
for (; count[len] > 0; --count[len])
{
HuffmanCode code;
code.bits = (byte)len;
code.value = (ushort)sorted[symbol++];
ReplicateValue (root_table, table + (int)key, step, table_size, code);
key = GetNextKey (key, len);
}
}
// Fill in 2nd level tables and add pointers to root table.
for (len = root_bits + 1, step = 2; len <= MaxAllowedCodeLength; ++len, step <<= 1)
{
num_open <<= 1;
num_nodes += num_open;
num_open -= count[len];
if (num_open < 0)
return 0;
for (; count[len] > 0; --count[len])
{
HuffmanCode code;
if ((key & mask) != low)
{
table += table_size;
table_bits = NextTableBitSize (count, len, root_bits);
table_size = 1 << table_bits;
total_size += table_size;
low = key & mask;
root_table[index+low].bits = (byte)(table_bits + root_bits);
root_table[index+low].value = (ushort)(table - index - low);
}
code.bits = (byte)(len - root_bits);
code.value = (ushort)sorted[symbol++];
ReplicateValue (root_table, table + (int)(key >> root_bits), step, table_size, code);
key = GetNextKey (key, len);
}
}
// Check if tree is full.
if (num_nodes != 2 * offset[MaxAllowedCodeLength] - 1)
return 0;
return total_size;
}
static void ReplicateValue (HuffmanCode[] table, int offset, int step, int end, HuffmanCode code)
{
do
{
end -= step;
table[offset+end] = code;
}
while (end > 0);
}
static int NextTableBitSize (int[] count, int len, int root_bits)
{
int left = 1 << (len - root_bits);
while (len < MaxAllowedCodeLength)
{
left -= count[len];
if (left <= 0) break;
++len;
left <<= 1;
}
return len - root_bits;
}
}
internal struct HuffmanCode
{
public byte bits; // number of bits used for this symbol
public ushort value; // symbol value or table offset
}
internal struct HuffmanCode32
{
public int bits; // number of bits used for this symbol,
// or an impossible value if not a literal code.
public uint value; // 32b packed ARGB value if literal,
// or non-literal symbol otherwise
}
internal class HTreeGroup
{
HuffmanCode[] tables;
int[] htrees = new int[Huffman.CodesPerMetaCode];
public bool is_trivial_literal; // True, if huffman trees for Red, Blue & Alpha
// Symbols are trivial (have a single code).
public uint literal_arb; // If is_trivial_literal is true, this is the
// ARGB value of the pixel, with Green channel
// being set to zero.
public bool is_trivial_code; // true if is_trivial_literal with only one code
public bool use_packed_table; // use packed table below for short literal code
// table mapping input bits to a packed values, or escape case to literal code
public HuffmanCode32[] packed_table = new HuffmanCode32[Huffman.PackedTableSize];
public HuffmanCode[] Tables { get { return tables; } }
public void SetMeta (int meta, int base_index)
{
htrees[meta] = base_index;
}
public int GetMeta (int meta)
{
return htrees[meta];
}
public HuffmanCode GetCode (int meta, int index)
{
return tables[htrees[meta] + index];
}
public void SetCode (int meta, int index, HuffmanCode code)
{
tables[htrees[meta] + index] = code;
}
public static HTreeGroup[] New (int num_htree_groups, int table_size)
{
var tables = new HuffmanCode[num_htree_groups * table_size];
var htree_groups = new HTreeGroup[num_htree_groups];
for (int i = 0; i < num_htree_groups; ++i)
{
htree_groups[i] = new HTreeGroup();
htree_groups[i].tables = tables;
}
return htree_groups;
}
}
}
| |
//
// MonoSQLiteStorageEngine.cs
//
// Author:
// Zachary Gramana <zack@xamarin.com>
//
// Copyright (c) 2014 Xamarin Inc
// Copyright (c) 2014 .NET Foundation
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//
// Copyright (c) 2014 Couchbase, 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 Couchbase.Lite.Storage;
using Sharpen;
using System.Collections.Generic;
using System.Data.Common;
using System.IO;
using Couchbase.Lite.Util;
using System;
using System.Data;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Threading;
using System.Runtime.InteropServices;
using SQLitePCL;
namespace Couchbase.Lite.Storage
{
internal sealed class MonoSQLiteStorageEngine : ISQLiteStorageEngine, IDisposable
{
private const String Tag = "MonoSQLiteStorageEngine";
static readonly IsolationLevel DefaultIsolationLevel = IsolationLevel.ReadCommitted;
private SQLiteConnection Connection;
private SQLitePCL.SQLiteConnection currentTransaction;
private Boolean shouldCommit;
#region implemented abstract members of SQLiteStorageEngine
public override bool Open (String path)
{
var connectionString = new SqliteConnectionStringBuilder
{
DataSource = path,
Version = 3,
SyncMode = SynchronizationModes.Full
};
var result = true;
try {
shouldCommit = false;
Connection = new SqliteConnection (connectionString.ToString ());
Connection.Open();
} catch (Exception ex) {
Log.E(Tag, "Error opening the Sqlite connection using connection String: {0}".Fmt(connectionString.ToString()), ex);
result = false;
}
return result;
}
public override Int32 GetVersion()
{
var command = Connection.CreateCommand();
command.CommandText = "PRAGMA user_version;";
var result = -1;
try {
var commandResult = command.ExecuteScalar();
if (commandResult is Int32) {
result = (Int32)commandResult;
}
} catch (Exception e) {
Log.E(Tag, "Error getting user version", e);
} finally {
command.Dispose();
}
return result;
}
public override void SetVersion(Int32 version)
{
var command = Connection.CreateCommand();
command.CommandText = "PRAGMA user_version = @";
command.Parameters[0].Value = version;
try {
command.ExecuteNonQuery();
} catch (Exception e) {
Log.E(Tag, "Error getting user version", e);
} finally {
command.Dispose();
}
return;
}
public override bool IsOpen
{
get {
return Connection.State == ConnectionState.Open;
}
}
public override void BeginTransaction ()
{
BeginTransaction(DefaultIsolationLevel);
}
int transactionCount = 0;
public override void BeginTransaction (IsolationLevel isolationLevel)
{
// NOTE.ZJG: Seems like we should really be using TO SAVEPOINT
// but this is how Android SqliteDatabase does it,
// so I'm matching that for now.
Interlocked.Increment(ref transactionCount);
currentTransaction = Connection.BeginTransaction(isolationLevel);
}
public override void EndTransaction ()
{
if (Connection.State != ConnectionState.Open)
throw new InvalidOperationException("Database is not open.");
if (Interlocked.Decrement(ref transactionCount) > 0)
return;
if (currentTransaction == null) {
if (shouldCommit)
throw new InvalidOperationException ("Transaction missing.");
return;
}
if (shouldCommit) {
currentTransaction.Commit();
shouldCommit = false;
} else {
currentTransaction.Rollback();
}
currentTransaction.Dispose();
currentTransaction = null;
}
public override void SetTransactionSuccessful ()
{
shouldCommit = true;
}
public override void ExecSQL (String sql, params Object[] paramArgs)
{
var command = BuildCommand (sql, paramArgs);
try {
command.ExecuteNonQuery();
} catch (Exception e) {
Log.E(Tag, "Error executing sql'{0}'".Fmt(sql), e);
} finally {
command.Dispose();
}
}
public override Cursor RawQuery (String sql, params Object[] paramArgs)
{
return RawQuery(sql, CommandBehavior.Default, paramArgs);
}
public override Cursor RawQuery (String sql, CommandBehavior behavior, params Object[] paramArgs)
{
var command = BuildCommand (sql, paramArgs);
Cursor cursor = null;
try {
Log.V(Tag, "RawQuery sql: {0}".Fmt(sql));
var reader = command.ExecuteReader(behavior);
cursor = new Cursor(reader);
} catch (Exception e) {
Log.E(Tag, "Error executing raw query '{0}'".Fmt(sql), e);
throw;
} finally {
command.Dispose();
}
return cursor;
}
public override long Insert (String table, String nullColumnHack, ContentValues values)
{
return InsertWithOnConflict(table, null, values, ConflictResolutionStrategy.None);
}
public override long InsertWithOnConflict (String table, String nullColumnHack, ContentValues initialValues, ConflictResolutionStrategy conflictResolutionStrategy)
{
if (!String.IsNullOrWhiteSpace(nullColumnHack)) {
var e = new InvalidOperationException("{0} does not support the 'nullColumnHack'.".Fmt(Tag));
Log.E(Tag, "Unsupported use of nullColumnHack", e);
throw e;
}
var command = GetInsertCommand(table, initialValues, conflictResolutionStrategy);
var lastInsertedId = -1L;
try {
command.ExecuteNonQuery();
// Get the new row's id.
// TODO.ZJG: This query should ultimately be replaced with a call to sqlite3_last_insert_rowid.
var lastInsertedIndexCommand = new SqliteCommand("select last_insert_rowid()", Connection, currentTransaction);
lastInsertedId = (Int64)lastInsertedIndexCommand.ExecuteScalar();
lastInsertedIndexCommand.Dispose();
if (lastInsertedId == -1L) {
Log.E(Tag, "Error inserting " + initialValues + " using " + command.CommandText);
} else {
Log.V(Tag, "Inserting row " + lastInsertedId + " from " + initialValues + " using " + command.CommandText);
}
} catch (Exception ex) {
Log.E(Tag, "Error inserting into table " + table, ex);
} finally {
command.Dispose();
}
return lastInsertedId;
}
public override int Update (String table, ContentValues values, String whereClause, params String[] whereArgs)
{
Debug.Assert(!table.IsEmpty());
Debug.Assert(values != null);
var builder = new SqliteCommandBuilder();
builder.SetAllValues = false;
var command = GetUpdateCommand(table, values, whereClause, whereArgs);
var resultCount = -1;
try {
resultCount = (Int32)command.ExecuteNonQuery ();
} catch (Exception ex) {
Log.E(Tag, "Error updating table " + table, ex);
}
return resultCount;
}
public override int Delete (String table, String whereClause, params String[] whereArgs)
{
Debug.Assert(!table.IsEmpty());
var command = GetDeleteCommand(table, whereClause, whereArgs);
var resultCount = -1;
try {
resultCount = command.ExecuteNonQuery ();
} catch (Exception ex) {
Log.E(Tag, "Error deleting from table " + table, ex);
} finally {
command.Dispose();
}
return resultCount;
}
public override void Close ()
{
Connection.Close();
}
#endregion
#region Non-public Members
SqliteCommand BuildCommand (string sql, object[] paramArgs)
{
var command = Connection.CreateCommand ();
command.CommandText = sql.ReplacePositionalParams ();
if (currentTransaction != null)
command.Transaction = currentTransaction;
if (paramArgs != null && paramArgs.Length > 0)
command.Parameters.AddRange (paramArgs.ToSqliteParameters ());
return command;
}
/// <summary>
/// Avoids the additional database trip that using SqliteCommandBuilder requires.
/// </summary>
/// <returns>The update command.</returns>
/// <param name="table">Table.</param>
/// <param name="values">Values.</param>
/// <param name="whereClause">Where clause.</param>
/// <param name="whereArgs">Where arguments.</param>
SqliteCommand GetUpdateCommand (string table, ContentValues values, string whereClause, string[] whereArgs)
{
var builder = new StringBuilder("UPDATE ");
builder.Append(table);
builder.Append(" SET ");
// Append our content column names and create our SQL parameters.
var valueSet = values.ValueSet();
var valueSetLength = valueSet.Count();
var whereArgsLength = (whereArgs != null ? whereArgs.Length : 0);
var sqlParams = new List<SqliteParameter>(valueSetLength + whereArgsLength);
foreach(var column in valueSet)
{
if (sqlParams.Count > 0) {
builder.Append(",");
}
builder.AppendFormat( "{0} = @{0}", column.Key);
sqlParams.Add(new SqliteParameter(column.Key, column.Value));
}
if (!whereClause.IsEmpty()) {
builder.Append(" WHERE ");
builder.Append(whereClause.ReplacePositionalParams());
}
if (whereArgsLength > 0)
sqlParams.AddRange(whereArgs.ToSqliteParameters());
var sql = builder.ToString();
var command = new SqliteCommand(sql, Connection, currentTransaction);
command.Parameters.Clear();
command.Parameters.AddRange(sqlParams.ToArray());
return command;
}
/// <summary>
/// Avoids the additional database trip that using SqliteCommandBuilder requires.
/// </summary>
/// <returns>The insert command.</returns>
/// <param name="table">Table.</param>
/// <param name="values">Values.</param>
/// <param name="conflictResolutionStrategy">Conflict resolution strategy.</param>
SqliteCommand GetInsertCommand (String table, ContentValues values, ConflictResolutionStrategy conflictResolutionStrategy)
{
var builder = new StringBuilder("INSERT");
if (conflictResolutionStrategy != ConflictResolutionStrategy.None) {
builder.Append(" OR ");
builder.Append(conflictResolutionStrategy);
}
builder.Append(" INTO ");
builder.Append(table);
builder.Append(" (");
// Append our content column names and create our SQL parameters.
var valueSet = values.ValueSet();
var sqlParams = new SqliteParameter[valueSet.LongCount()];
var valueBuilder = new StringBuilder();
var index = 0L;
foreach(var column in valueSet)
{
if (index > 0) {
builder.Append(",");
valueBuilder.Append(",");
}
builder.AppendFormat( "{0}", column.Key);
valueBuilder.AppendFormat("@{0}", column.Key);
sqlParams[index++] = new SqliteParameter(column.Key, column.Value);
}
builder.Append(") VALUES (");
builder.Append(valueBuilder);
builder.Append(")");
var sql = builder.ToString();
var command = new SqliteCommand(sql, Connection, currentTransaction);
command.Parameters.Clear();
command.Parameters.AddRange(sqlParams);
return command;
}
/// <summary>
/// Avoids the additional database trip that using SqliteCommandBuilder requires.
/// </summary>
/// <returns>The delete command.</returns>
/// <param name="table">Table.</param>
/// <param name="whereClause">Where clause.</param>
/// <param name="whereArgs">Where arguments.</param>
SqliteCommand GetDeleteCommand (string table, string whereClause, string[] whereArgs)
{
var builder = new StringBuilder("DELETE FROM ");
builder.Append(table);
if (!whereClause.IsEmpty()) {
builder.Append(" WHERE ");
builder.Append(whereClause.ReplacePositionalParams());
}
var command = new SqliteCommand(builder.ToString(), Connection, currentTransaction);
command.Parameters.Clear();
command.Parameters.AddRange(whereArgs.ToSqliteParameters());
return command;
}
#endregion
#region IDisposable implementation
public void Dispose ()
{
if (Connection != null && Connection.State != ConnectionState.Closed)
Connection.Close();
}
#endregion
}
}
| |
#region S# License
/******************************************************************************************
NOTICE!!! This program and source code is owned and licensed by
StockSharp, LLC, www.stocksharp.com
Viewing or use of this code requires your acceptance of the license
agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE
Removal of this comment is a violation of the license agreement.
Project: StockSharp.Oanda.Native.Oanda
File: OandaStreamingClient.cs
Created: 2015, 11, 11, 2:32 PM
Copyright 2010 by StockSharp, LLC
*******************************************************************************************/
#endregion S# License
namespace StockSharp.Oanda.Native
{
using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Security;
using Ecng.Collections;
using Ecng.Common;
using Ecng.Web;
using Newtonsoft.Json;
using StockSharp.Oanda.Native.Communications;
using StockSharp.Oanda.Native.DataTypes;
class OandaStreamingClient : Disposable
{
private class StreamingWorker<TData, TResponse>
{
private enum States
{
Starting,
Started,
Stopping,
Stopped,
}
private readonly OandaStreamingClient _parent;
private readonly string _methodName;
private readonly Action<QueryString, TData[]> _fillQuery;
private readonly Action<TResponse> _newLine;
private readonly CachedSynchronizedSet<TData> _data = new CachedSynchronizedSet<TData>();
private int _dataVersion;
private States _currState = States.Stopped;
private WebResponse _response;
public StreamingWorker(OandaStreamingClient parent, string methodName, Action<QueryString, TData[]> fillQuery, Action<TResponse> newLine)
{
if (parent == null)
throw new ArgumentNullException(nameof(parent));
if (methodName.IsEmpty())
throw new ArgumentNullException(nameof(methodName));
if (fillQuery == null)
throw new ArgumentNullException(nameof(fillQuery));
if (newLine == null)
throw new ArgumentNullException(nameof(newLine));
_parent = parent;
_methodName = methodName;
_fillQuery = fillQuery;
_newLine = newLine;
}
public void Add(TData data)
{
lock (_data.SyncRoot)
{
if (!_data.TryAdd(data))
return;
_dataVersion++;
switch (_currState)
{
case States.Starting:
return;
case States.Started:
//_currState = States.Starting;
_response.Close();
return;
case States.Stopping:
_currState = States.Starting;
return;
case States.Stopped:
_currState = States.Starting;
break;
default:
throw new ArgumentOutOfRangeException();
}
}
ThreadingHelper.Thread(() =>
{
var errorCount = 0;
const int maxErrorCount = 10;
while (!_parent.IsDisposed)
{
var dataVersion = 0;
try
{
var url = new Url(_parent._streamingUrl + "/v1/" + _methodName);
TData[] cachedData;
lock (_data.SyncRoot)
{
switch (_currState)
{
case States.Starting:
lock (_data.SyncRoot)
{
cachedData = _data.Cache;
dataVersion = _dataVersion;
}
break;
case States.Started:
case States.Stopped:
throw new InvalidOperationException();
case States.Stopping:
_currState = States.Stopped;
return;
default:
throw new ArgumentOutOfRangeException();
}
}
_fillQuery(url.QueryString, cachedData);
var request = WebRequest.Create(url);
// for non-sandbox requests
if (_parent._token != null)
request.Headers.Add("Authorization", "Bearer " + _parent._token.To<string>());
request.Headers.Add("X-Accept-Datetime-Format", "UNIX");
using (var response = request.GetResponse())
{
lock (_data.SyncRoot)
{
switch (_currState)
{
case States.Starting:
// new items may be added or removed
if (dataVersion < _dataVersion)
continue;
_currState = States.Started;
_response = response;
break;
case States.Started:
case States.Stopped:
throw new InvalidOperationException();
case States.Stopping:
continue;
default:
throw new ArgumentOutOfRangeException();
}
}
using (var reader = new StreamReader(response.GetResponseStream()))
{
string line;
var lineErrorCount = 0;
const int maxLineErrorCount = 100;
while (!_parent.IsDisposed && (line = reader.ReadLine()) != null)
{
try
{
_newLine(JsonConvert.DeserializeObject<TResponse>(line));
lineErrorCount = 0;
}
catch (Exception ex)
{
_parent.NewError.SafeInvoke(ex);
if (++lineErrorCount >= maxLineErrorCount)
{
//this.AddErrorLog("Max error {0} limit reached.", maxLineErrorCount);
break;
}
}
}
}
}
}
catch (Exception ex)
{
bool needLog;
lock (_data.SyncRoot)
{
needLog = dataVersion == _dataVersion;
_currState = _data.Count > 0 ? States.Starting : States.Stopping;
_response = null;
}
if (needLog)
{
_parent.NewError.SafeInvoke(ex);
if (++errorCount >= maxErrorCount)
{
//this.AddErrorLog("Max error {0} limit reached.", maxErrorCount);
break;
}
}
else
errorCount = 0;
}
finally
{
lock (_data.SyncRoot)
_response = null;
}
}
})
.Name("Oanda " + _methodName)
.Launch();
}
public void Remove(TData data)
{
lock (_data.SyncRoot)
{
if (!_data.Remove(data))
return;
_dataVersion++;
switch (_currState)
{
case States.Starting:
if (_data.Count == 0)
_currState = States.Stopping;
break;
case States.Started:
//if (_data.Count == 0)
// _currState = States.Stopping;
_response.Close();
break;
case States.Stopping:
return;
case States.Stopped:
throw new InvalidOperationException();
default:
throw new ArgumentOutOfRangeException();
}
}
}
public void Stop()
{
lock (_data.SyncRoot)
{
_data.Clear();
_dataVersion++;
switch (_currState)
{
case States.Starting:
_currState = States.Stopping;
break;
case States.Started:
//_currState = States.Stopping;
_response.Close();
break;
case States.Stopping:
case States.Stopped:
return;
default:
throw new ArgumentOutOfRangeException();
}
}
}
}
private readonly string _streamingUrl;
private readonly StreamingWorker<string, StreamingPriceResponse> _pricesWorker;
private readonly StreamingWorker<int, StreamingEventResponse> _eventsWorker;
private readonly SecureString _token;
public OandaStreamingClient(OandaServers server, SecureString token, Func<string, int> getAccountId)
{
if (getAccountId == null)
throw new ArgumentNullException(nameof(getAccountId));
switch (server)
{
case OandaServers.Sandbox:
if (token != null)
throw new ArgumentException("token");
_streamingUrl = "http://stream-sandbox.oanda.com";
break;
case OandaServers.Practice:
if (token == null)
throw new ArgumentNullException(nameof(token));
_streamingUrl = "https://stream-fxpractice.oanda.com";
break;
case OandaServers.Real:
if (token == null)
throw new ArgumentNullException(nameof(token));
_streamingUrl = "https://stream-fxtrade.oanda.com";
break;
default:
throw new ArgumentOutOfRangeException(nameof(server));
}
_token = token;
_pricesWorker = new StreamingWorker<string, StreamingPriceResponse>(this, "prices",
(qs, instruments) =>
qs
.Append("accountId", getAccountId(null))
.Append("instruments", instruments.Join(",")),
price =>
{
if (price.Tick == null)
return;
NewPrice.SafeInvoke(price.Tick);
});
_eventsWorker = new StreamingWorker<int, StreamingEventResponse>(this, "events",
(qs, accounts) =>
qs.Append("accountIds", accounts.Select(a => a.To<string>()).Join(",")),
price =>
{
if (price.Transaction == null)
return;
NewTransaction.SafeInvoke(price.Transaction);
});
}
public event Action<Exception> NewError;
public event Action<Price> NewPrice;
public event Action<Transaction> NewTransaction;
public void SubscribePricesStreaming(int accountId, string instrument)
{
_pricesWorker.Add(instrument);
}
public void UnSubscribePricesStreaming(string instrument)
{
_pricesWorker.Remove(instrument);
}
public void SubscribeEventsStreaming(int accountId)
{
_eventsWorker.Add(accountId);
}
public void UnSubscribeEventsStreaming(int accountId)
{
_eventsWorker.Remove(accountId);
}
protected override void DisposeManaged()
{
_eventsWorker.Stop();
_pricesWorker.Stop();
base.DisposeManaged();
}
}
}
| |
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 OfficeDevPnP.PartnerPack.ScheduledJob
{
/// <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 (Exception) // was: 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
}
| |
//-----------------------------------------------------------------------------
// Filename: IPSocket.cs
//
// Description: Converts special charatcers in XML to their safe equivalent.
//
// History:
// 22 jun 2005 Aaron Clauson Created.
//
// License:
// This software is licensed under the BSD License http://www.opensource.org/licenses/bsd-license.php
//
// Copyright (c) 2006 Aaron Clauson (aaron@sipsorcery.com), SIP Sorcery PTY LTD, Hobart, Australia (www.sipsorcery.com)
// 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 SIP Sorcery PTY LTD.
// 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.Text.RegularExpressions;
#if UNITTEST
using NUnit.Framework;
#endif
namespace SIPSorcery.Sys
{
public class IPSocket
{
/// <summary>
/// Returns an IPv4 end point from a socket address in 10.0.0.1:5060 format.
/// </summary>>
public static IPEndPoint GetIPEndPoint(string IPSocket)
{
if(IPSocket == null || IPSocket.Trim().Length == 0)
{
throw new ApplicationException("IPSocket cannot parse an IPEndPoint from an empty string.");
}
try
{
int colonIndex = IPSocket.IndexOf(":");
if(colonIndex != -1)
{
string ipAddress = IPSocket.Substring(0, colonIndex).Trim();
int port = Convert.ToInt32(IPSocket.Substring(colonIndex+1).Trim());
IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse(ipAddress), port);
return endPoint;
}
else
{
return new IPEndPoint(IPAddress.Parse(IPSocket.Trim()), 0);
}
}
catch(Exception excp)
{
throw new ApplicationException(excp.Message + "(" + IPSocket + ")");
}
}
public static string GetSocketString(IPEndPoint endPoint)
{
if(endPoint != null)
{
return endPoint.Address.ToString() + ":" + endPoint.Port;
}
else
{
return null;
}
}
public static void ParseSocketString(string socket, out string host, out int port)
{
try
{
host = null;
port = 0;
if(socket == null || socket.Trim().Length == 0)
{
return;
}
else
{
int colonIndex = socket.IndexOf(":");
if(colonIndex == -1)
{
host = socket.Trim();
}
else
{
host = socket.Substring(0, colonIndex).Trim();
try
{
port = Int32.Parse(socket.Substring(colonIndex+1).Trim());
}
catch{}
}
}
}
catch(Exception excp)
{
throw new ApplicationException("Exception ParseSocketString (" + socket + "). " + excp.Message);
}
}
public static IPEndPoint ParseSocketString(string socket)
{
string ipAddress;
int port;
ParseSocketString(socket, out ipAddress, out port);
return new IPEndPoint(IPAddress.Parse(ipAddress), port);
}
public static string ParseHostFromSocket(string socket)
{
string host = socket;
if (socket != null && socket.Trim().Length > 0 && socket.IndexOf(':') != -1)
{
host = socket.Substring(0, socket.LastIndexOf(':')).Trim();
}
return host;
}
public static int ParsePortFromSocket(string socket)
{
int port = 0;
if (socket != null && socket.Trim().Length > 0 && socket.IndexOf(':') != -1)
{
int colonIndex = socket.LastIndexOf(':');
port = Convert.ToInt32(socket.Substring(colonIndex + 1).Trim());
}
return port;
}
public static bool IsIPSocket(string socket)
{
if(socket == null || socket.Trim().Length == 0)
{
return false;
}
else
{
#if SILVERLIGHT
return Regex.Match(socket, @"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}(:\d{1,5})$").Success;
#else
return Regex.Match(socket, @"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}(:\d{1,5})$", RegexOptions.Compiled).Success;
#endif
}
}
public static bool IsIPAddress(string socket) {
if (socket == null || socket.Trim().Length == 0) {
return false;
}
else {
#if SILVERLIGHT
return Regex.Match(socket, @"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$").Success;
#else
return Regex.Match(socket, @"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$", RegexOptions.Compiled).Success;
#endif
}
}
/// <summary>
/// Checks the Contact SIP URI host and if it is recognised as a private address it is replaced with the socket
/// the SIP message was received on.
///
/// Private address space blocks RFC 1597.
/// 10.0.0.0 - 10.255.255.255
/// 172.16.0.0 - 172.31.255.255
/// 192.168.0.0 - 192.168.255.255
///
/// </summary>
public static bool IsPrivateAddress(string host)
{
if (host != null && host.Trim().Length > 0)
{
if (host.StartsWith("127.0.0.1") ||
host.StartsWith("10.") ||
Regex.Match(host, @"^172\.1[6-9]\.").Success ||
Regex.Match(host, @"^172\.2\d\.").Success ||
host.StartsWith("172.30.") ||
host.StartsWith("172.31.") ||
host.StartsWith("192.168."))
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
#region Unit testing.
#if UNITTEST
[TestFixture]
public class IPSocketUnitTest
{
[Test]
public void SampleTest()
{
Console.WriteLine(System.Reflection.MethodBase.GetCurrentMethod().Name);
Assert.IsTrue(true, "True was false.");
}
[Test]
public void ParsePortFromSocketTest()
{
Console.WriteLine(System.Reflection.MethodBase.GetCurrentMethod().Name);
int port = IPSocket.ParsePortFromSocket("localhost:5060");
Console.WriteLine("port=" + port);
Assert.IsTrue(port == 5060, "The port was not parsed correctly.");
}
[Test]
public void ParseHostFromSocketTest()
{
Console.WriteLine(System.Reflection.MethodBase.GetCurrentMethod().Name);
string host = IPSocket.ParseHostFromSocket("localhost:5060");
Console.WriteLine("host=" + host);
Assert.IsTrue(host == "localhost", "The host was not parsed correctly.");
}
[Test]
public void Test172IPRangeIsPrivate()
{
Console.WriteLine("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);
Assert.IsFalse(IPSocket.IsPrivateAddress("172.15.1.1"), "Public IP address was mistakenly identified as private.");
Assert.IsTrue(IPSocket.IsPrivateAddress("172.16.1.1"), "Private IP address was not correctly identified.");
Console.WriteLine("-----------------------------------------");
}
}
#endif
#endregion
}
}
| |
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// Copyright (c) 2008 - 2015 Jb Evain
// Copyright (c) 2008 - 2011 Novell, Inc.
//
// Licensed under the MIT/X11 license.
//
using System.Text;
using Mono.Collections.Generic;
namespace Mono.Cecil {
// HACK - Reflexil - Partial for legacy classes
public sealed partial class PropertyDefinition : PropertyReference, IMemberDefinition, IConstantProvider {
bool? has_this;
ushort attributes;
Collection<CustomAttribute> custom_attributes;
internal MethodDefinition get_method;
internal MethodDefinition set_method;
internal Collection<MethodDefinition> other_methods;
object constant = Mixin.NotResolved;
public PropertyAttributes Attributes {
get { return (PropertyAttributes) attributes; }
set { attributes = (ushort) value; }
}
public bool HasThis {
get {
if (has_this.HasValue)
return has_this.Value;
if (GetMethod != null)
return get_method.HasThis;
if (SetMethod != null)
return set_method.HasThis;
return false;
}
set { has_this = value; }
}
public bool HasCustomAttributes {
get {
if (custom_attributes != null)
return custom_attributes.Count > 0;
return this.GetHasCustomAttributes (Module);
}
}
public Collection<CustomAttribute> CustomAttributes {
get { return custom_attributes ?? (this.GetCustomAttributes (ref custom_attributes, Module)); }
}
public MethodDefinition GetMethod {
get {
if (get_method != null)
return get_method;
InitializeMethods ();
return get_method;
}
set { get_method = value; }
}
public MethodDefinition SetMethod {
get {
if (set_method != null)
return set_method;
InitializeMethods ();
return set_method;
}
set { set_method = value; }
}
public bool HasOtherMethods {
get {
if (other_methods != null)
return other_methods.Count > 0;
InitializeMethods ();
return !other_methods.IsNullOrEmpty ();
}
}
public Collection<MethodDefinition> OtherMethods {
get {
if (other_methods != null)
return other_methods;
InitializeMethods ();
if (other_methods != null)
return other_methods;
return other_methods = new Collection<MethodDefinition> ();
}
}
public bool HasParameters {
get {
InitializeMethods ();
if (get_method != null)
return get_method.HasParameters;
if (set_method != null)
return set_method.HasParameters && set_method.Parameters.Count > 1;
return false;
}
}
public override Collection<ParameterDefinition> Parameters {
get {
InitializeMethods ();
if (get_method != null)
return MirrorParameters (get_method, 0);
if (set_method != null)
return MirrorParameters (set_method, 1);
return new Collection<ParameterDefinition> ();
}
}
static Collection<ParameterDefinition> MirrorParameters (MethodDefinition method, int bound)
{
var parameters = new Collection<ParameterDefinition> ();
if (!method.HasParameters)
return parameters;
var original_parameters = method.Parameters;
var end = original_parameters.Count - bound;
for (int i = 0; i < end; i++)
parameters.Add (original_parameters [i]);
return parameters;
}
public bool HasConstant {
get {
this.ResolveConstant (ref constant, Module);
return constant != Mixin.NoValue;
}
set { if (!value) constant = Mixin.NoValue; }
}
public object Constant {
get { return HasConstant ? constant : null; }
set { constant = value; }
}
#region PropertyAttributes
public bool IsSpecialName {
get { return attributes.GetAttributes ((ushort) PropertyAttributes.SpecialName); }
set { attributes = attributes.SetAttributes ((ushort) PropertyAttributes.SpecialName, value); }
}
public bool IsRuntimeSpecialName {
get { return attributes.GetAttributes ((ushort) PropertyAttributes.RTSpecialName); }
set { attributes = attributes.SetAttributes ((ushort) PropertyAttributes.RTSpecialName, value); }
}
public bool HasDefault {
get { return attributes.GetAttributes ((ushort) PropertyAttributes.HasDefault); }
set { attributes = attributes.SetAttributes ((ushort) PropertyAttributes.HasDefault, value); }
}
#endregion
public new TypeDefinition DeclaringType {
get { return (TypeDefinition) base.DeclaringType; }
set { base.DeclaringType = value; }
}
public override bool IsDefinition {
get { return true; }
}
public override string FullName {
get {
var builder = new StringBuilder ();
builder.Append (PropertyType.ToString ());
builder.Append (' ');
builder.Append (MemberFullName ());
builder.Append ('(');
if (HasParameters) {
var parameters = Parameters;
for (int i = 0; i < parameters.Count; i++) {
if (i > 0)
builder.Append (',');
builder.Append (parameters [i].ParameterType.FullName);
}
}
builder.Append (')');
return builder.ToString ();
}
}
public PropertyDefinition (string name, PropertyAttributes attributes, TypeReference propertyType)
: base (name, propertyType)
{
this.attributes = (ushort) attributes;
this.token = new MetadataToken (TokenType.Property);
}
void InitializeMethods ()
{
var module = this.Module;
if (module == null)
return;
lock (module.SyncRoot) {
if (get_method != null || set_method != null)
return;
if (!module.HasImage ())
return;
module.Read (this, (property, reader) => reader.ReadMethods (property));
}
}
public override PropertyDefinition Resolve ()
{
return this;
}
}
}
| |
// 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.Diagnostics;
using System.Net.Security;
using System.Runtime.InteropServices;
using System.Security.Authentication;
using System.Security.Cryptography;
using Microsoft.Win32.SafeHandles;
internal static partial class Interop
{
internal static partial class Ssl
{
internal delegate int SslCtxSetVerifyCallback(int preverify_ok, IntPtr x509_ctx);
[DllImport(Libraries.CryptoNative)]
internal static extern void EnsureLibSslInitialized();
[DllImport(Libraries.CryptoNative)]
internal static extern IntPtr SslV2_3Method();
[DllImport(Libraries.CryptoNative)]
internal static extern IntPtr SslV3Method();
[DllImport(Libraries.CryptoNative)]
internal static extern IntPtr TlsV1Method();
[DllImport(Libraries.CryptoNative)]
internal static extern IntPtr TlsV1_1Method();
[DllImport(Libraries.CryptoNative)]
internal static extern IntPtr TlsV1_2Method();
[DllImport(Libraries.CryptoNative)]
internal static extern void SetProtocolOptions(SafeSslContextHandle ctx, SslProtocols protocols);
[DllImport(Libraries.CryptoNative)]
internal static extern SafeSslHandle SslCreate(SafeSslContextHandle ctx);
[DllImport(Libraries.CryptoNative)]
internal static extern SslErrorCode SslGetError(SafeSslHandle ssl, int ret);
[DllImport(Libraries.CryptoNative)]
internal static extern void SslDestroy(IntPtr ssl);
[DllImport(Libraries.CryptoNative)]
internal static extern void SslSetConnectState(SafeSslHandle ssl);
[DllImport(Libraries.CryptoNative)]
internal static extern void SslSetAcceptState(SafeSslHandle ssl);
[DllImport(Libraries.CryptoNative)]
private static extern IntPtr SslGetVersion(SafeSslHandle ssl);
internal static string GetProtocolVersion(SafeSslHandle ssl)
{
return Marshal.PtrToStringAnsi(SslGetVersion(ssl));
}
[DllImport(Libraries.CryptoNative)]
internal static extern bool GetSslConnectionInfo(
SafeSslHandle ssl,
out int dataCipherAlg,
out int keyExchangeAlg,
out int dataHashAlg,
out int dataKeySize,
out int hashKeySize);
[DllImport(Libraries.CryptoNative)]
internal static unsafe extern int SslWrite(SafeSslHandle ssl, byte* buf, int num);
[DllImport(Libraries.CryptoNative)]
internal static extern int SslRead(SafeSslHandle ssl, byte[] buf, int num);
[DllImport(Libraries.CryptoNative)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool IsSslRenegotiatePending(SafeSslHandle ssl);
[DllImport(Libraries.CryptoNative)]
internal static extern int SslShutdown(SafeSslHandle ssl);
[DllImport(Libraries.CryptoNative)]
internal static extern void SslSetBio(SafeSslHandle ssl, SafeBioHandle rbio, SafeBioHandle wbio);
[DllImport(Libraries.CryptoNative)]
internal static extern int SslDoHandshake(SafeSslHandle ssl);
[DllImport(Libraries.CryptoNative)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool IsSslStateOK(SafeSslHandle ssl);
// NOTE: this is just an (unsafe) overload to the BioWrite method from Interop.Bio.cs.
[DllImport(Libraries.CryptoNative)]
internal static unsafe extern int BioWrite(SafeBioHandle b, byte* data, int len);
[DllImport(Libraries.CryptoNative)]
internal static extern SafeX509Handle SslGetPeerCertificate(SafeSslHandle ssl);
[DllImport(Libraries.CryptoNative)]
internal static extern SafeSharedX509StackHandle SslGetPeerCertChain(SafeSslHandle ssl);
[DllImport(Libraries.CryptoNative)]
internal static extern int SslCtxUseCertificate(SafeSslContextHandle ctx, SafeX509Handle certPtr);
[DllImport(Libraries.CryptoNative)]
internal static extern int SslCtxUsePrivateKey(SafeSslContextHandle ctx, SafeEvpPKeyHandle keyPtr);
[DllImport(Libraries.CryptoNative)]
internal static extern int SslCtxCheckPrivateKey(SafeSslContextHandle ctx);
[DllImport(Libraries.CryptoNative)]
internal static extern void SslCtxSetQuietShutdown(SafeSslContextHandle ctx);
[DllImport(Libraries.CryptoNative, EntryPoint = "SslGetClientCAList")]
private static extern SafeSharedX509NameStackHandle SslGetClientCAList_private(SafeSslHandle ssl);
internal static SafeSharedX509NameStackHandle SslGetClientCAList(SafeSslHandle ssl)
{
Crypto.CheckValidOpenSslHandle(ssl);
SafeSharedX509NameStackHandle handle = SslGetClientCAList_private(ssl);
if (!handle.IsInvalid)
{
handle.SetParent(ssl);
}
return handle;
}
[DllImport(Libraries.CryptoNative)]
internal static extern void SslCtxSetVerify(SafeSslContextHandle ctx, SslCtxSetVerifyCallback callback);
[DllImport(Libraries.CryptoNative)]
internal static extern void SetEncryptionPolicy(SafeSslContextHandle ctx, EncryptionPolicy policy);
[DllImport(Libraries.CryptoNative)]
internal static extern void SslCtxSetClientCAList(SafeSslContextHandle ctx, SafeX509NameStackHandle x509NameStackPtr);
[DllImport(Libraries.CryptoNative)]
internal static extern void GetStreamSizes(out int header, out int trailer, out int maximumMessage);
internal static class SslMethods
{
internal static readonly IntPtr TLSv1_method = TlsV1Method();
internal static readonly IntPtr TLSv1_1_method = TlsV1_1Method();
internal static readonly IntPtr TLSv1_2_method = TlsV1_2Method();
internal static readonly IntPtr SSLv3_method = SslV3Method();
internal static readonly IntPtr SSLv23_method = SslV2_3Method();
}
internal enum SslErrorCode
{
SSL_ERROR_NONE = 0,
SSL_ERROR_SSL = 1,
SSL_ERROR_WANT_READ = 2,
SSL_ERROR_WANT_WRITE = 3,
SSL_ERROR_SYSCALL = 5,
SSL_ERROR_ZERO_RETURN = 6,
// NOTE: this SslErrorCode value doesn't exist in OpenSSL, but
// we use it to distinguish when a renegotiation is pending.
// Choosing an arbitrarily large value that shouldn't conflict
// with any actual OpenSSL error codes
SSL_ERROR_RENEGOTIATE = 29304
}
}
}
namespace Microsoft.Win32.SafeHandles
{
internal sealed class SafeSslHandle : SafeHandle
{
private SafeBioHandle _readBio;
private SafeBioHandle _writeBio;
private bool _isServer;
public bool IsServer
{
get { return _isServer; }
}
public SafeBioHandle InputBio
{
get
{
return _readBio;
}
}
public SafeBioHandle OutputBio
{
get
{
return _writeBio;
}
}
public static SafeSslHandle Create(SafeSslContextHandle context, bool isServer)
{
SafeBioHandle readBio = Interop.Crypto.CreateMemoryBio();
if (readBio.IsInvalid)
{
return new SafeSslHandle();
}
SafeBioHandle writeBio = Interop.Crypto.CreateMemoryBio();
if (writeBio.IsInvalid)
{
readBio.Dispose();
return new SafeSslHandle();
}
SafeSslHandle handle = Interop.Ssl.SslCreate(context);
if (handle.IsInvalid)
{
readBio.Dispose();
writeBio.Dispose();
return handle;
}
handle._isServer = isServer;
// After SSL_set_bio, the BIO handles are owned by SSL pointer
// and are automatically freed by SSL_free. To prevent a double
// free, we need to keep the ref counts bumped up till SSL_free
bool gotRef = false;
readBio.DangerousAddRef(ref gotRef);
try
{
bool ignore = false;
writeBio.DangerousAddRef(ref ignore);
}
catch
{
if (gotRef)
{
readBio.DangerousRelease();
}
throw;
}
Interop.Ssl.SslSetBio(handle, readBio, writeBio);
handle._readBio = readBio;
handle._writeBio = writeBio;
if (isServer)
{
Interop.Ssl.SslSetAcceptState(handle);
}
else
{
Interop.Ssl.SslSetConnectState(handle);
}
return handle;
}
public override bool IsInvalid
{
get { return handle == IntPtr.Zero; }
}
protected override bool ReleaseHandle()
{
Interop.Ssl.SslDestroy(handle);
if (_readBio != null)
{
_readBio.SetHandleAsInvalid(); // BIO got freed in SslDestroy
}
if (_writeBio != null)
{
_writeBio.SetHandleAsInvalid(); // BIO got freed in SslDestroy
}
return true;
}
private SafeSslHandle() : base(IntPtr.Zero, true)
{
}
}
}
| |
using System;
using System.Collections.Specialized;
using System.Linq;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using Elasticsearch.Net;
using Nest;
using Tests.Framework.Configuration;
using Tests.Framework.Integration;
using Tests.Framework.ManagedElasticsearch.Process;
using Tests.Framework.Versions;
#if !DOTNETCORE
using XplatManualResetEvent = System.Threading.ManualResetEvent;
#endif
namespace Tests.Framework.ManagedElasticsearch.Nodes
{
public class ElasticsearchNode : IDisposable
{
private readonly object _lock = new object();
private CompositeDisposable _composite;
private int? ProcessId { get; set; }
private readonly NodeConfiguration _config;
public ElasticsearchVersion Version => _config.ElasticsearchVersion;
public NodeFileSystem FileSystem { get; }
public bool Started { get; private set; }
public int Port { get; private set; }
private bool RunningOnCI { get; }
public ElasticsearchNode(NodeConfiguration config)
{
this._config = config;
this.FileSystem = config.FileSystem;
this.RunningOnCI = !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("TEAMCITY_VERSION"));
this.Port = config.DesiredPort;
if (this._config.RunIntegrationTests && !this._config.TestAgainstAlreadyRunningElasticsearch) return;
}
private readonly object _lockGetClient = new object { };
private IElasticClient _client;
public IElasticClient Client
{
get
{
if (!this.Started && TestClient.Configuration.RunIntegrationTests)
throw new Exception("can not request a client from an ElasticsearchNode if that node hasn't started yet");
if (this._client != null) return this._client;
lock (_lockGetClient)
{
if (this._client != null) return this._client;
var port = this.Started ? this.Port : 9200;
this._client = TestClient.GetClient(ComposeSettings, port, forceSsl: this._config.EnableSsl);
return this.Client;
}
}
}
public void Start(string[] settings)
{
if (!this._config.RunIntegrationTests || this.Started) return;
lock (_lock)
{
if (!this._config.RunIntegrationTests || this.Started) return;
this.FreeResources();
if (UseAlreadyRunningInstance())
{
this.Started = true;
return;
}
var timeout = TimeSpan.FromMinutes(1);
var handle = new XplatManualResetEvent(false);
var booted = false;
var process = new ObservableProcess(this.FileSystem.Binary, settings);
this._composite = new CompositeDisposable(process);
Console.WriteLine($"Starting: {process.Binary} {process.Arguments}");
try
{
var subscription = Observable.Using(() => process, p => p.Start())
.Select(c => new ElasticsearchConsoleOut(this._config.ElasticsearchVersion, c.Error, c.Data))
.Subscribe(s => this.HandleConsoleMessage(s, handle), e => throw e, () => handle.Set());
this._composite.Add(subscription);
if (!handle.WaitOne(timeout, true))
throw new Exception($"Could not start elasticsearch within {timeout}");
booted = true;
}
finally
{
if (!booted) this.FreeResources();
}
}
}
private bool UseAlreadyRunningInstance()
{
var client = this.GetPrivateClient(null, false, this.Port);
return this._config.TestAgainstAlreadyRunningElasticsearch && client.RootNodeInfo().IsValid;
}
private void HandleConsoleMessage(ElasticsearchConsoleOut consoleOut, XplatManualResetEvent handle)
{
//no need to snoop for metadata if we already started
if (!this._config.RunIntegrationTests || this.Started) return;
//if we are running on CI and not started dump elasticsearch stdout/err
//before the started notification to help debug failures to start
if (this.RunningOnCI && !this.Started)
{
if (consoleOut.Error) Console.Error.WriteLine(consoleOut.Data);
else Console.WriteLine(consoleOut.Data);
}
if (consoleOut.Error && !this.Started && !string.IsNullOrWhiteSpace(consoleOut.Data)) throw new Exception(consoleOut.Data);
string version;
int? pid;
int port;
if (this.ProcessId == null && consoleOut.TryParseNodeInfo(out version, out pid))
{
var startedVersion = ElasticsearchVersion.GetOrAdd(version);
this.ProcessId = pid;
if (this.Version != startedVersion)
throw new Exception($"Booted elasticsearch is version {startedVersion} but the test config dictates {this.Version}");
}
else if (consoleOut.TryGetPortNumber(out port))
this.Port = port;
else if (consoleOut.TryGetStartedConfirmation())
{
this.Started = true;
handle.Set();
}
}
private ConnectionSettings ClusterSettings(ConnectionSettings s, Func<ConnectionSettings, ConnectionSettings> settings) =>
AddClusterSpecificConnectionSettings(AppendClusterNameToHttpHeaders(settings(s)));
private IElasticClient GetPrivateClient(Func<ConnectionSettings, ConnectionSettings> settings, bool forceInMemory, int port)
{
settings = settings ?? (s => s);
var client = forceInMemory
? TestClient.GetInMemoryClient(s => ClusterSettings(s, settings), port)
: TestClient.GetClient(s => ClusterSettings(s, settings), port, forceSsl: this._config.EnableSsl);
return client;
}
private ConnectionSettings ComposeSettings(ConnectionSettings s) =>
AddClusterSpecificConnectionSettings(AppendClusterNameToHttpHeaders(s));
private ConnectionSettings AddClusterSpecificConnectionSettings(ConnectionSettings settings) =>
this._config.ClusterConnectionSettings(settings);
private ConnectionSettings AppendClusterNameToHttpHeaders(ConnectionSettings settings)
{
IConnectionConfigurationValues values = settings;
var headers = values.Headers ?? new NameValueCollection();
headers.Add("ClusterName", this._config.ClusterName);
return settings;
}
private void FreeResources()
{
var hasStarted = this.Started;
this.Started = false;
this._composite?.Dispose();
var esProcess = this.ProcessId == null
? null
: System.Diagnostics.Process.GetProcesses().FirstOrDefault(p => p.Id == this.ProcessId.Value);
if (esProcess != null)
{
Console.WriteLine($"Killing elasticsearch PID {this.ProcessId}");
esProcess.Kill();
esProcess.WaitForExit(5000);
esProcess.Close();
}
if (!this._config.RunIntegrationTests || !hasStarted) return;
Console.WriteLine($"Stopping... node has started and ran integrations: {this._config.RunIntegrationTests}");
Console.WriteLine($"Node started on port: {this.Port} using PID: {this.ProcessId}");
}
public void Stop()
{
lock (_lock) this.FreeResources();
}
public void Dispose() => this.Stop();
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Runtime.Intrinsics;
namespace System.Runtime.Intrinsics.X86
{
/// <summary>
/// This class provides access to Intel SSE4.2 hardware instructions via intrinsics
/// </summary>
[CLSCompliant(false)]
public abstract class Sse42 : Sse41
{
internal Sse42() { }
public new static bool IsSupported { get { return false; } }
/// <summary>
/// int _mm_cmpistra (__m128i a, __m128i b, const int imm8)
/// PCMPISTRI xmm, xmm/m128, imm8
/// int _mm_cmpistrc (__m128i a, __m128i b, const int imm8)
/// PCMPISTRI xmm, xmm/m128, imm8
/// int _mm_cmpistro (__m128i a, __m128i b, const int imm8)
/// PCMPISTRI xmm, xmm/m128, imm8
/// int _mm_cmpistrs (__m128i a, __m128i b, const int imm8)
/// PCMPISTRI xmm, xmm/m128, imm8
/// int _mm_cmpistrz (__m128i a, __m128i b, const int imm8)
/// PCMPISTRI xmm, xmm/m128, imm8
/// </summary>
public static bool CompareImplicitLength(Vector128<sbyte> left, Vector128<sbyte> right, ResultsFlag flag, StringComparisonMode mode) { throw new PlatformNotSupportedException(); }
/// <summary>
/// int _mm_cmpistra (__m128i a, __m128i b, const int imm8)
/// PCMPISTRI xmm, xmm/m128, imm8
/// int _mm_cmpistrc (__m128i a, __m128i b, const int imm8)
/// PCMPISTRI xmm, xmm/m128, imm8
/// int _mm_cmpistro (__m128i a, __m128i b, const int imm8)
/// PCMPISTRI xmm, xmm/m128, imm8
/// int _mm_cmpistrs (__m128i a, __m128i b, const int imm8)
/// PCMPISTRI xmm, xmm/m128, imm8
/// int _mm_cmpistrz (__m128i a, __m128i b, const int imm8)
/// PCMPISTRI xmm, xmm/m128, imm8
/// </summary>
public static bool CompareImplicitLength(Vector128<byte> left, Vector128<byte> right, ResultsFlag flag, StringComparisonMode mode) { throw new PlatformNotSupportedException(); }
/// <summary>
/// int _mm_cmpistra (__m128i a, __m128i b, const int imm8)
/// PCMPISTRI xmm, xmm/m128, imm8
/// int _mm_cmpistrc (__m128i a, __m128i b, const int imm8)
/// PCMPISTRI xmm, xmm/m128, imm8
/// int _mm_cmpistro (__m128i a, __m128i b, const int imm8)
/// PCMPISTRI xmm, xmm/m128, imm8
/// int _mm_cmpistrs (__m128i a, __m128i b, const int imm8)
/// PCMPISTRI xmm, xmm/m128, imm8
/// int _mm_cmpistrz (__m128i a, __m128i b, const int imm8)
/// PCMPISTRI xmm, xmm/m128, imm8
/// </summary>
public static bool CompareImplicitLength(Vector128<short> left, Vector128<short> right, ResultsFlag flag, StringComparisonMode mode) { throw new PlatformNotSupportedException(); }
/// <summary>
/// int _mm_cmpistra (__m128i a, __m128i b, const int imm8)
/// PCMPISTRI xmm, xmm/m128, imm8
/// int _mm_cmpistrc (__m128i a, __m128i b, const int imm8)
/// PCMPISTRI xmm, xmm/m128, imm8
/// int _mm_cmpistro (__m128i a, __m128i b, const int imm8)
/// PCMPISTRI xmm, xmm/m128, imm8
/// int _mm_cmpistrs (__m128i a, __m128i b, const int imm8)
/// PCMPISTRI xmm, xmm/m128, imm8
/// int _mm_cmpistrz (__m128i a, __m128i b, const int imm8)
/// PCMPISTRI xmm, xmm/m128, imm8
/// </summary>
public static bool CompareImplicitLength(Vector128<ushort> left, Vector128<ushort> right, ResultsFlag flag, StringComparisonMode mode) { throw new PlatformNotSupportedException(); }
/// <summary>
/// int _mm_cmpestra (__m128i a, int la, __m128i b, int lb, const int imm8)
/// PCMPESTRI xmm, xmm/m128, imm8
/// int _mm_cmpestrc (__m128i a, int la, __m128i b, int lb, const int imm8)
/// PCMPESTRI xmm, xmm/m128, imm8
/// int _mm_cmpestro (__m128i a, int la, __m128i b, int lb, const int imm8)
/// PCMPESTRI xmm, xmm/m128, imm8
/// int _mm_cmpestrs (__m128i a, int la, __m128i b, int lb, const int imm8)
/// PCMPESTRI xmm, xmm/m128, imm8
/// int _mm_cmpestrz (__m128i a, int la, __m128i b, int lb, const int imm8)
/// PCMPESTRI xmm, xmm/m128, imm8
/// </summary>
public static bool CompareExplicitLength(Vector128<sbyte> left, byte leftLength, Vector128<sbyte> right, byte rightLength, ResultsFlag flag, StringComparisonMode mode) { throw new PlatformNotSupportedException(); }
/// <summary>
/// int _mm_cmpestra (__m128i a, int la, __m128i b, int lb, const int imm8)
/// PCMPESTRI xmm, xmm/m128, imm8
/// int _mm_cmpestrc (__m128i a, int la, __m128i b, int lb, const int imm8)
/// PCMPESTRI xmm, xmm/m128, imm8
/// int _mm_cmpestro (__m128i a, int la, __m128i b, int lb, const int imm8)
/// PCMPESTRI xmm, xmm/m128, imm8
/// int _mm_cmpestrs (__m128i a, int la, __m128i b, int lb, const int imm8)
/// PCMPESTRI xmm, xmm/m128, imm8
/// int _mm_cmpestrz (__m128i a, int la, __m128i b, int lb, const int imm8)
/// PCMPESTRI xmm, xmm/m128, imm8
/// </summary>
public static bool CompareExplicitLength(Vector128<byte> left, byte leftLength, Vector128<byte> right, byte rightLength, ResultsFlag flag, StringComparisonMode mode) { throw new PlatformNotSupportedException(); }
/// <summary>
/// int _mm_cmpestra (__m128i a, int la, __m128i b, int lb, const int imm8)
/// PCMPESTRI xmm, xmm/m128, imm8
/// int _mm_cmpestrc (__m128i a, int la, __m128i b, int lb, const int imm8)
/// PCMPESTRI xmm, xmm/m128, imm8
/// int _mm_cmpestro (__m128i a, int la, __m128i b, int lb, const int imm8)
/// PCMPESTRI xmm, xmm/m128, imm8
/// int _mm_cmpestrs (__m128i a, int la, __m128i b, int lb, const int imm8)
/// PCMPESTRI xmm, xmm/m128, imm8
/// int _mm_cmpestrz (__m128i a, int la, __m128i b, int lb, const int imm8)
/// PCMPESTRI xmm, xmm/m128, imm8
/// </summary>
public static bool CompareExplicitLength(Vector128<short> left, byte leftLength, Vector128<short> right, byte rightLength, ResultsFlag flag, StringComparisonMode mode) { throw new PlatformNotSupportedException(); }
/// <summary>
/// int _mm_cmpestra (__m128i a, int la, __m128i b, int lb, const int imm8)
/// PCMPESTRI xmm, xmm/m128, imm8
/// int _mm_cmpestrc (__m128i a, int la, __m128i b, int lb, const int imm8)
/// PCMPESTRI xmm, xmm/m128, imm8
/// int _mm_cmpestro (__m128i a, int la, __m128i b, int lb, const int imm8)
/// PCMPESTRI xmm, xmm/m128, imm8
/// int _mm_cmpestrs (__m128i a, int la, __m128i b, int lb, const int imm8)
/// PCMPESTRI xmm, xmm/m128, imm8
/// int _mm_cmpestrz (__m128i a, int la, __m128i b, int lb, const int imm8)
/// PCMPESTRI xmm, xmm/m128, imm8
/// </summary>
public static bool CompareExplicitLength(Vector128<ushort> left, byte leftLength, Vector128<ushort> right, byte rightLength, ResultsFlag flag, StringComparisonMode mode) { throw new PlatformNotSupportedException(); }
/// <summary>
/// int _mm_cmpistri (__m128i a, __m128i b, const int imm8)
/// PCMPISTRI xmm, xmm/m128, imm8
/// </summary>
public static int CompareImplicitLengthIndex(Vector128<sbyte> left, Vector128<sbyte> right, StringComparisonMode mode) { throw new PlatformNotSupportedException(); }
/// <summary>
/// int _mm_cmpistri (__m128i a, __m128i b, const int imm8)
/// PCMPISTRI xmm, xmm/m128, imm8
/// </summary>
public static int CompareImplicitLengthIndex(Vector128<byte> left, Vector128<byte> right, StringComparisonMode mode) { throw new PlatformNotSupportedException(); }
/// <summary>
/// int _mm_cmpistri (__m128i a, __m128i b, const int imm8)
/// PCMPISTRI xmm, xmm/m128, imm8
/// </summary>
public static int CompareImplicitLengthIndex(Vector128<short> left, Vector128<short> right, StringComparisonMode mode) { throw new PlatformNotSupportedException(); }
/// <summary>
/// int _mm_cmpistri (__m128i a, __m128i b, const int imm8)
/// PCMPISTRI xmm, xmm/m128, imm8
/// </summary>
public static int CompareImplicitLengthIndex(Vector128<ushort> left, Vector128<ushort> right, StringComparisonMode mode) { throw new PlatformNotSupportedException(); }
/// <summary>
/// int _mm_cmpestri (__m128i a, int la, __m128i b, int lb, const int imm8)
/// PCMPESTRI xmm, xmm/m128, imm8
/// </summary>
public static int CompareExplicitLengthIndex(Vector128<sbyte> left, byte leftLength, Vector128<sbyte> right, byte rightLength, StringComparisonMode mode) { throw new PlatformNotSupportedException(); }
/// <summary>
/// int _mm_cmpestri (__m128i a, int la, __m128i b, int lb, const int imm8)
/// PCMPESTRI xmm, xmm/m128, imm8
/// </summary>
public static int CompareExplicitLengthIndex(Vector128<byte> left, byte leftLength, Vector128<byte> right, byte rightLength, StringComparisonMode mode) { throw new PlatformNotSupportedException(); }
/// <summary>
/// int _mm_cmpestri (__m128i a, int la, __m128i b, int lb, const int imm8)
/// PCMPESTRI xmm, xmm/m128, imm8
/// </summary>
public static int CompareExplicitLengthIndex(Vector128<short> left, byte leftLength, Vector128<short> right, byte rightLength, StringComparisonMode mode) { throw new PlatformNotSupportedException(); }
/// <summary>
/// int _mm_cmpestri (__m128i a, int la, __m128i b, int lb, const int imm8)
/// PCMPESTRI xmm, xmm/m128, imm8
/// </summary>
public static int CompareExplicitLengthIndex(Vector128<ushort> left, byte leftLength, Vector128<ushort> right, byte rightLength, StringComparisonMode mode) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_cmpistrm (__m128i a, __m128i b, const int imm8)
/// PCMPISTRM xmm, xmm/m128, imm8
/// </summary>
public static Vector128<ushort> CompareImplicitLengthBitMask(Vector128<sbyte> left, Vector128<sbyte> right, StringComparisonMode mode) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_cmpistrm (__m128i a, __m128i b, const int imm8)
/// PCMPISTRM xmm, xmm/m128, imm8
/// </summary>
public static Vector128<ushort> CompareImplicitLengthBitMask(Vector128<byte> left, Vector128<byte> right, StringComparisonMode mode) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_cmpistrm (__m128i a, __m128i b, const int imm8)
/// PCMPISTRM xmm, xmm/m128, imm8
/// </summary>
public static Vector128<byte> CompareImplicitLengthBitMask(Vector128<short> left, Vector128<short> right, StringComparisonMode mode) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_cmpistrm (__m128i a, __m128i b, const int imm8)
/// PCMPISTRM xmm, xmm/m128, imm8
/// </summary>
public static Vector128<byte> CompareImplicitLengthBitMask(Vector128<ushort> left, Vector128<ushort> right, StringComparisonMode mode) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_cmpistrm (__m128i a, __m128i b, const int imm8)
/// PCMPISTRM xmm, xmm/m128, imm8
/// </summary>
public static Vector128<byte> CompareImplicitLengthUnitMask(Vector128<sbyte> left, Vector128<sbyte> right, StringComparisonMode mode) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_cmpistrm (__m128i a, __m128i b, const int imm8)
/// PCMPISTRM xmm, xmm/m128, imm8
/// </summary>
public static Vector128<byte> CompareImplicitLengthUnitMask(Vector128<byte> left, Vector128<byte> right, StringComparisonMode mode) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_cmpistrm (__m128i a, __m128i b, const int imm8)
/// PCMPISTRM xmm, xmm/m128, imm8
/// </summary>
public static Vector128<ushort> CompareImplicitLengthUnitMask(Vector128<short> left, Vector128<short> right, StringComparisonMode mode) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_cmpistrm (__m128i a, __m128i b, const int imm8)
/// PCMPISTRM xmm, xmm/m128, imm8
/// </summary>
public static Vector128<ushort> CompareImplicitLengthUnitMask(Vector128<ushort> left, Vector128<ushort> right, StringComparisonMode mode) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_cmpestrm (__m128i a, int la, __m128i b, int lb, const int imm8)
/// PCMPESTRM xmm, xmm/m128, imm8
/// </summary>
public static Vector128<ushort> CompareExplicitLengthBitMask(Vector128<sbyte> left, byte leftLength, Vector128<sbyte> right, byte rightLength, StringComparisonMode mode) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_cmpestrm (__m128i a, int la, __m128i b, int lb, const int imm8)
/// PCMPESTRM xmm, xmm/m128, imm8
/// </summary>
public static Vector128<ushort> CompareExplicitLengthBitMask(Vector128<byte> left, byte leftLength, Vector128<byte> right, byte rightLength, StringComparisonMode mode) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_cmpestrm (__m128i a, int la, __m128i b, int lb, const int imm8)
/// PCMPESTRM xmm, xmm/m128, imm8
/// </summary>
public static Vector128<byte> CompareExplicitLengthBitMask(Vector128<short> left, byte leftLength, Vector128<short> right, byte rightLength, StringComparisonMode mode) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_cmpestrm (__m128i a, int la, __m128i b, int lb, const int imm8)
/// PCMPESTRM xmm, xmm/m128, imm8
/// </summary>
public static Vector128<byte> CompareExplicitLengthBitMask(Vector128<ushort> left, byte leftLength, Vector128<ushort> right, byte rightLength, StringComparisonMode mode) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_cmpestrm (__m128i a, int la, __m128i b, int lb, const int imm8)
/// PCMPESTRM xmm, xmm/m128, imm8
/// </summary>
public static Vector128<byte> CompareExplicitLengthUnitMask(Vector128<sbyte> left, byte leftLength, Vector128<sbyte> right, byte rightLength, StringComparisonMode mode) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_cmpestrm (__m128i a, int la, __m128i b, int lb, const int imm8)
/// PCMPESTRM xmm, xmm/m128, imm8
/// </summary>
public static Vector128<byte> CompareExplicitLengthUnitMask(Vector128<byte> left, byte leftLength, Vector128<byte> right, byte rightLength, StringComparisonMode mode) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_cmpestrm (__m128i a, int la, __m128i b, int lb, const int imm8)
/// PCMPESTRM xmm, xmm/m128, imm8
/// </summary>
public static Vector128<ushort> CompareExplicitLengthUnitMask(Vector128<short> left, byte leftLength, Vector128<short> right, byte rightLength, StringComparisonMode mode) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_cmpestrm (__m128i a, int la, __m128i b, int lb, const int imm8)
/// PCMPESTRM xmm, xmm/m128, imm8
/// </summary>
public static Vector128<ushort> CompareExplicitLengthUnitMask(Vector128<ushort> left, byte leftLength, Vector128<ushort> right, byte rightLength, StringComparisonMode mode) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_cmpgt_epi64 (__m128i a, __m128i b)
/// PCMPGTQ xmm, xmm/m128
/// </summary>
public static Vector128<long> CompareGreaterThan(Vector128<long> left, Vector128<long> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// unsigned int _mm_crc32_u8 (unsigned int crc, unsigned char v)
/// CRC32 reg, reg/m8
/// </summary>
public static uint Crc32(uint crc, byte data) { throw new PlatformNotSupportedException(); }
/// <summary>
/// unsigned int _mm_crc32_u16 (unsigned int crc, unsigned short v)
/// CRC32 reg, reg/m16
/// </summary>
public static uint Crc32(uint crc, ushort data) { throw new PlatformNotSupportedException(); }
/// <summary>
/// unsigned int _mm_crc32_u32 (unsigned int crc, unsigned int v)
/// CRC32 reg, reg/m32
/// </summary>
public static uint Crc32(uint crc, uint data) { throw new PlatformNotSupportedException(); }
/// <summary>
/// unsigned __int64 _mm_crc32_u64 (unsigned __int64 crc, unsigned __int64 v)
/// CRC32 reg, reg/m64
/// </summary>
public static ulong Crc32(ulong crc, ulong data) { throw new PlatformNotSupportedException(); }
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
namespace UnityEditor.XCodeEditor
{
public class PBXFileReference : PBXObject
{
protected const string PATH_KEY = "path";
protected const string NAME_KEY = "name";
protected const string SOURCETREE_KEY = "sourceTree";
protected const string EXPLICIT_FILE_TYPE_KEY = "explicitFileType";
protected const string LASTKNOWN_FILE_TYPE_KEY = "lastKnownFileType";
protected const string ENCODING_KEY = "fileEncoding";
public string buildPhase;
public readonly Dictionary<TreeEnum, string> trees = new Dictionary<TreeEnum, string> {
{ TreeEnum.ABSOLUTE, "<absolute>" },
{ TreeEnum.GROUP, "<group>" },
{ TreeEnum.BUILT_PRODUCTS_DIR, "BUILT_PRODUCTS_DIR" },
{ TreeEnum.DEVELOPER_DIR, "DEVELOPER_DIR" },
{ TreeEnum.SDKROOT, "SDKROOT" },
{ TreeEnum.SOURCE_ROOT, "SOURCE_ROOT" }
};
public static readonly Dictionary<string, string> typeNames = new Dictionary<string, string> {
{ ".a", "archive.ar" },
{ ".app", "wrapper.application" },
{ ".s", "sourcecode.asm" },
{ ".c", "sourcecode.c.c" },
{ ".cpp", "sourcecode.cpp.cpp" },
{ ".framework", "wrapper.framework" },
{ ".h", "sourcecode.c.h" },
{ ".icns", "image.icns" },
{ ".m", "sourcecode.c.objc" },
{ ".mm", "sourcecode.cpp.objcpp" },
{ ".nib", "wrapper.nib" },
{ ".plist", "text.plist.xml" },
{ ".png", "image.png" },
{ ".rtf", "text.rtf" },
{ ".tiff", "image.tiff" },
{ ".txt", "text" },
{ ".xcodeproj", "wrapper.pb-project" },
{ ".xib", "file.xib" },
{ ".strings", "text.plist.strings" },
{ ".bundle", "wrapper.plug-in" },
{ ".dylib", "compiled.mach-o.dylib" }
};
public static readonly Dictionary<string, string> typePhases = new Dictionary<string, string> {
{ ".a", "PBXFrameworksBuildPhase" },
{ ".app", null },
{ ".s", "PBXSourcesBuildPhase" },
{ ".c", "PBXSourcesBuildPhase" },
{ ".cpp", "PBXSourcesBuildPhase" },
{ ".framework", "PBXFrameworksBuildPhase" },
{ ".h", null },
{ ".icns", "PBXResourcesBuildPhase" },
{ ".m", "PBXSourcesBuildPhase" },
{ ".mm", "PBXSourcesBuildPhase" },
{ ".nib", "PBXResourcesBuildPhase" },
{ ".plist", "PBXResourcesBuildPhase" },
{ ".png", "PBXResourcesBuildPhase" },
{ ".rtf", "PBXResourcesBuildPhase" },
{ ".tiff", "PBXResourcesBuildPhase" },
{ ".txt", "PBXResourcesBuildPhase" },
{ ".xcodeproj", null },
{ ".xib", "PBXResourcesBuildPhase" },
{ ".strings", "PBXResourcesBuildPhase" },
{ ".bundle", "PBXResourcesBuildPhase" },
{ ".dylib", "PBXFrameworksBuildPhase" }
};
public PBXFileReference( string guid, PBXDictionary dictionary ) : base( guid, dictionary )
{
}
public PBXFileReference( string filePath, TreeEnum tree = TreeEnum.SOURCE_ROOT ) : base()
{
this.Add( PATH_KEY, filePath );
this.Add( NAME_KEY, System.IO.Path.GetFileName( filePath ) );
this.Add( SOURCETREE_KEY, (string)( System.IO.Path.IsPathRooted( filePath ) ? trees[TreeEnum.ABSOLUTE] : trees[tree] ) );
this.GuessFileType();
}
public string name {
get {
if( !ContainsKey( NAME_KEY ) ) {
return null;
}
return (string)_data[NAME_KEY];
}
}
private void GuessFileType()
{
this.Remove( EXPLICIT_FILE_TYPE_KEY );
this.Remove( LASTKNOWN_FILE_TYPE_KEY );
string extension = System.IO.Path.GetExtension( (string)_data[ PATH_KEY ] );
if( !PBXFileReference.typeNames.ContainsKey( extension ) ){
Debug.LogWarning( "Unknown file extension: " + extension + "\nPlease add extension and Xcode type to PBXFileReference.types" );
return;
}
this.Add( LASTKNOWN_FILE_TYPE_KEY, PBXFileReference.typeNames[ extension ] );
this.buildPhase = PBXFileReference.typePhases[ extension ];
}
private void SetFileType( string fileType )
{
this.Remove( EXPLICIT_FILE_TYPE_KEY );
this.Remove( LASTKNOWN_FILE_TYPE_KEY );
this.Add( EXPLICIT_FILE_TYPE_KEY, fileType );
}
// class PBXFileReference(PBXType):
// def __init__(self, d=None):
// PBXType.__init__(self, d)
// self.build_phase = None
//
// types = {
// '.a':('archive.ar', 'PBXFrameworksBuildPhase'),
// '.app': ('wrapper.application', None),
// '.s': ('sourcecode.asm', 'PBXSourcesBuildPhase'),
// '.c': ('sourcecode.c.c', 'PBXSourcesBuildPhase'),
// '.cpp': ('sourcecode.cpp.cpp', 'PBXSourcesBuildPhase'),
// '.framework': ('wrapper.framework','PBXFrameworksBuildPhase'),
// '.h': ('sourcecode.c.h', None),
// '.icns': ('image.icns','PBXResourcesBuildPhase'),
// '.m': ('sourcecode.c.objc', 'PBXSourcesBuildPhase'),
// '.mm': ('sourcecode.cpp.objcpp', 'PBXSourcesBuildPhase'),
// '.nib': ('wrapper.nib', 'PBXResourcesBuildPhase'),
// '.plist': ('text.plist.xml', 'PBXResourcesBuildPhase'),
// '.png': ('image.png', 'PBXResourcesBuildPhase'),
// '.rtf': ('text.rtf', 'PBXResourcesBuildPhase'),
// '.tiff': ('image.tiff', 'PBXResourcesBuildPhase'),
// '.txt': ('text', 'PBXResourcesBuildPhase'),
// '.xcodeproj': ('wrapper.pb-project', None),
// '.xib': ('file.xib', 'PBXResourcesBuildPhase'),
// '.strings': ('text.plist.strings', 'PBXResourcesBuildPhase'),
// '.bundle': ('wrapper.plug-in', 'PBXResourcesBuildPhase'),
// '.dylib': ('compiled.mach-o.dylib', 'PBXFrameworksBuildPhase')
// }
//
// trees = [
// '<absolute>',
// '<group>',
// 'BUILT_PRODUCTS_DIR',
// 'DEVELOPER_DIR',
// 'SDKROOT',
// 'SOURCE_ROOT',
// ]
//
// def guess_file_type(self):
// self.remove('explicitFileType')
// self.remove('lastKnownFileType')
// ext = os.path.splitext(self.get('name', ''))[1]
//
// f_type, build_phase = PBXFileReference.types.get(ext, ('?', None))
//
// self['lastKnownFileType'] = f_type
// self.build_phase = build_phase
//
// if f_type == '?':
// print 'unknown file extension: %s' % ext
// print 'please add extension and Xcode type to PBXFileReference.types'
//
// return f_type
//
// def set_file_type(self, ft):
// self.remove('explicitFileType')
// self.remove('lastKnownFileType')
//
// self['explicitFileType'] = ft
//
// @classmethod
// def Create(cls, os_path, tree='SOURCE_ROOT'):
// if tree not in cls.trees:
// print 'Not a valid sourceTree type: %s' % tree
// return None
//
// fr = cls()
// fr.id = cls.GenerateId()
// fr['path'] = os_path
// fr['name'] = os.path.split(os_path)[1]
// fr['sourceTree'] = '<absolute>' if os.path.isabs(os_path) else tree
// fr.guess_file_type()
//
// return fr
}
public enum TreeEnum {
ABSOLUTE,
GROUP,
BUILT_PRODUCTS_DIR,
DEVELOPER_DIR,
SDKROOT,
SOURCE_ROOT
}
}
| |
// 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.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Telemetry
{
internal class CompilationErrorDetailDiscoverer
{
/// <summary>
/// name does not exist in context
/// </summary>
private const string CS0103 = "CS0103";
/// <summary>
/// type or namespace could not be found
/// </summary>
private const string CS0246 = "CS0246";
/// <summary>
/// wrong number of type args
/// </summary>
private const string CS0305 = "CS0305";
/// <summary>
/// The non-generic type 'A' cannot be used with type arguments
/// </summary>
private const string CS0308 = "CS0308";
/// <summary>
/// An attempt was made to use a non-attribute class in an attribute block. All the attribute types need to be inherited from System.Attribute
/// </summary>
private const string CS0616 = "CS0616";
/// <summary>
/// type does not contain a definition of method or extension method
/// </summary>
private const string CS1061 = "CS1061";
/// <summary>
/// The type of one argument in a method does not match the type that was passed when the class was instantiated. This error typically appears along with CS1502
/// Likely to occur when a type / member exists in a new framework but its specific overload is missing.
/// </summary>
private const string CS1503 = "CS1503";
/// <summary>
/// cannot find implementation of query pattern
/// </summary>
private const string CS1935 = "CS1935";
/// <summary>
/// Used to record generic argument types the semantic model doesn't know about
/// </summary>
private const string UnknownGenericArgumentTypeName = "Unknown";
/// <summary>
/// Used to record symbol names for error scenarios where GetSymbolInfo/GetTypeInfo returns no symbol.
/// </summary>
private const string UnknownSymbolName = "Unknown";
public async Task<List<CompilationErrorDetails>> GetCompilationErrorDetails(Document document, SyntaxNode bodyOpt, CancellationToken cancellationToken)
{
try
{
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
ImmutableArray<Diagnostic> diagnostics;
// If we have the SyntaxNode bodyOpt,
// then we can use its fullSpan property to process a subset of the document.
if (bodyOpt == null)
{
diagnostics = semanticModel.GetDiagnostics(cancellationToken: cancellationToken);
}
else
{
diagnostics = semanticModel.GetDiagnostics(bodyOpt.FullSpan, cancellationToken: cancellationToken);
}
if (diagnostics.Length == 0)
{
return null;
}
var syntaxFacts = document.Project.LanguageServices.GetService<ISyntaxFactsService>();
List<CompilationErrorDetails> ret = new List<CompilationErrorDetails>();
foreach (var diagnostic in diagnostics)
{
if (diagnostic.Severity != DiagnosticSeverity.Error || diagnostic.IsWarningAsError)
{
continue;
}
if (!IsTrackedCompilationError(diagnostic))
{
continue;
}
string errorDetailsFilename = diagnostic.Location.GetLineSpan().Path;
string errorDetailsUnresolvedMemberName = null;
string errorDetailsMethodName = null;
string errorDetailsLeftExpressionDocId = null;
string[] errorDetailsGenericArguments = null;
string[] errorDetailsArgumentTypes = null;
string[] errorDetailsLeftExpressionBaseTypeDocIds = null;
TextSpan span = diagnostic.Location.SourceSpan;
var node = root.FindNode(span);
if (node == null)
{
continue;
}
// If the expression binds, this could just be an extension method so we will continue and not
// log, as it's not actually an error.
if (ExpressionBinds(node, semanticModel, cancellationToken, checkForExtensionMethods: true))
{
continue;
}
// This is used to get unresolved member names. It will not alway find a member name, but has been tested to do so
// in the cases where the error code needs it.
syntaxFacts.GetNameAndArityOfSimpleName(node, out var name, out var arity);
errorDetailsUnresolvedMemberName = name;
// Here we reuse the unresolved member name field for attribute classes that can't be resolved as
// actually being attributes. Could factor this into a separate field for readability later.
AttributeSyntax attributeSyntax = node as AttributeSyntax;
if (attributeSyntax != null)
{
errorDetailsUnresolvedMemberName = semanticModel.GetTypeInfo(attributeSyntax, cancellationToken).Type.GetDocumentationCommentId();
}
GenericNameSyntax genericNameSyntax = node as GenericNameSyntax;
if (genericNameSyntax != null)
{
List<string> genericArgumentDocIds = new List<string>();
foreach (var genericArgument in genericNameSyntax.TypeArgumentList.Arguments)
{
var semanticInfo = semanticModel.GetTypeInfo(genericArgument, cancellationToken);
if (semanticInfo.Type != null)
{
genericArgumentDocIds.Add(GetDocId(semanticInfo.Type));
}
else
{
genericArgumentDocIds.Add(UnknownGenericArgumentTypeName);
}
}
errorDetailsGenericArguments = genericArgumentDocIds.ToArray();
}
ArgumentSyntax argumentSyntax = node as ArgumentSyntax;
if (argumentSyntax != null)
{
var argumentListSyntax = argumentSyntax.GetAncestor<BaseArgumentListSyntax>().Arguments;
var invocationExpression = argumentSyntax.GetAncestor<InvocationExpressionSyntax>();
errorDetailsArgumentTypes = (from argument in argumentListSyntax
select GetDocId(semanticModel.GetTypeInfo(argument.Expression, cancellationToken).Type)).ToArray();
if (invocationExpression != null)
{
var memberAccessExpression = invocationExpression.Expression as ExpressionSyntax;
var symbolInfo = semanticModel.GetSymbolInfo(memberAccessExpression, cancellationToken);
if (symbolInfo.CandidateSymbols.Length > 0)
{
// In this case, there is argument mismatch of some sort.
// Here we are getting the method name of any candidate symbols, then
// getting the docid of the type where the argument mismatch happened and storing this in LeftExpressionDocId.
errorDetailsMethodName = symbolInfo.CandidateSymbols.First().Name;
errorDetailsLeftExpressionDocId = GetDocId(symbolInfo.CandidateSymbols.First().ContainingType);
}
}
}
if (syntaxFacts.IsSimpleMemberAccessExpression(node.Parent))
{
var expression = node.Parent;
var leftExpression = syntaxFacts.GetExpressionOfMemberAccessExpression(expression);
if (leftExpression != null)
{
var semanticInfo = semanticModel.GetTypeInfo(leftExpression, cancellationToken);
var leftExpressionType = semanticInfo.Type;
if (leftExpressionType != null)
{
errorDetailsLeftExpressionDocId = GetDocId(leftExpressionType);
IEnumerable<string> baseTypeDocids = leftExpressionType.GetBaseTypes().Select(t => GetDocId(t));
errorDetailsLeftExpressionBaseTypeDocIds = baseTypeDocids.ToArray();
}
}
}
ret.Add(new CompilationErrorDetails(diagnostic.Id, errorDetailsFilename, errorDetailsMethodName, errorDetailsUnresolvedMemberName,
errorDetailsLeftExpressionDocId, errorDetailsLeftExpressionBaseTypeDocIds, errorDetailsGenericArguments, errorDetailsArgumentTypes));
}
return ret;
}
catch (Exception e)
{
List<CompilationErrorDetails> ret = new List<CompilationErrorDetails>();
ret.Add(new CompilationErrorDetails("EXCEPTION", e.Message, e.StackTrace, null, null, null, null, null));
return ret;
}
}
private string GetDocId(ISymbol symbol)
{
if (symbol == null)
{
return UnknownSymbolName;
}
if (symbol is INamedTypeSymbol)
{
var typeSymbol = (INamedTypeSymbol)symbol;
if (typeSymbol.IsGenericType && typeSymbol.OriginalDefinition != null)
{
return typeSymbol.OriginalDefinition.GetDocumentationCommentId();
}
}
else if (symbol is IMethodSymbol)
{
var methodSymbol = (IMethodSymbol)symbol;
if (methodSymbol.IsGenericMethod && methodSymbol.OriginalDefinition != null)
{
return methodSymbol.OriginalDefinition.GetDocumentationCommentId();
}
}
return symbol.GetDocumentationCommentId();
}
private bool IsTrackedCompilationError(Diagnostic diagnostic)
{
return diagnostic.Id == CS0103 ||
diagnostic.Id == CS0246 ||
diagnostic.Id == CS0305 ||
diagnostic.Id == CS0308 ||
diagnostic.Id == CS0616 ||
diagnostic.Id == CS1061 ||
diagnostic.Id == CS1503 ||
diagnostic.Id == CS1935;
}
private bool ExpressionBinds(SyntaxNode expression, SemanticModel semanticModel, CancellationToken cancellationToken, bool checkForExtensionMethods = false)
{
// See if the name binds to something other then the error type. If it does, there's nothing further we need to do.
// For extension methods, however, we will continue to search if there exists any better matched method.
cancellationToken.ThrowIfCancellationRequested();
var symbolInfo = semanticModel.GetSymbolInfo(expression, cancellationToken);
if (symbolInfo.CandidateReason == CandidateReason.OverloadResolutionFailure && !checkForExtensionMethods)
{
return true;
}
return symbolInfo.Symbol != null;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using JoinRpg.DataModel;
using Microsoft.AspNet.Identity;
namespace JoinRpg.Dal.Impl
{
public class MyUserStore :
IUserPasswordStore<User, int>,
IUserLockoutStore<User, int>,
IUserTwoFactorStore<User, int>,
IUserEmailStore<User, int>,
IUserLoginStore<User, int>,
IUserRoleStore<User, int>
{
private readonly MyDbContext _ctx;
public MyUserStore(MyDbContext ctx)
{
_ctx = ctx;
}
public void Dispose()
{
_ctx?.Dispose();
}
public Task CreateAsync(User user)
{
if (user == null)
{
throw new ArgumentNullException(nameof(user));
}
user.Auth = user.Auth ?? new UserAuthDetails() {RegisterDate = DateTime.Now};
if (!_ctx.Set<User>().Any())
{
user.Auth.EmailConfirmed = true;
user.Auth.IsAdmin = true;
}
_ctx.UserSet.Add(user);
return _ctx.SaveChangesAsync();
}
public Task UpdateAsync(User user)
{
if (user == null)
{
throw new ArgumentNullException(nameof(user));
}
_ctx.UserSet.Attach(user);
return _ctx.SaveChangesAsync();
}
public Task DeleteAsync(User user)
{
if (user == null)
{
throw new ArgumentNullException(nameof(user));
}
_ctx.UserSet.Remove(user);
return _ctx.SaveChangesAsync();
}
public async Task<User> FindByIdAsync(int userId)
{
return await _ctx.UserSet.FindAsync(userId);
}
public async Task<User> FindByNameAsync(string userName)
{
return await _ctx.UserSet.SingleOrDefaultAsync(user => user.Email == userName);
}
public Task SetPasswordHashAsync(User user, string passwordHash)
{
if (user == null)
{
throw new ArgumentNullException(nameof(user));
}
user.PasswordHash = passwordHash;
if (user.Allrpg != null)
{
//First time we change password, we should never ask allrpg.info for password
user.Allrpg.PreventAllrpgPassword = true;
}
return SaveUserIfRequired(user);
}
private Task SaveUserIfRequired(User user)
{
var entry = _ctx.Entry(user);
if (entry.State != EntityState.Detached)
{
return _ctx.SaveChangesAsync();
}
else
{
return Task.FromResult(0); //Will save anything on CreateUser()
}
}
public Task<string> GetPasswordHashAsync(User user)
{
return Task.FromResult(user.PasswordHash);
}
public Task<bool> HasPasswordAsync(User user)
{
return Task.FromResult(user.PasswordHash != null);
}
public Task<DateTimeOffset> GetLockoutEndDateAsync(User user)
{
throw new NotImplementedException();
}
public Task SetLockoutEndDateAsync(User user, DateTimeOffset lockoutEnd)
{
throw new NotImplementedException();
}
public Task<int> IncrementAccessFailedCountAsync(User user)
{
throw new NotImplementedException();
}
public Task ResetAccessFailedCountAsync(User user)
{
return Task.FromResult<object>(null);
}
public Task<int> GetAccessFailedCountAsync(User user)
{
return Task.FromResult(0);
}
public Task<bool> GetLockoutEnabledAsync(User user)
{
return Task.FromResult(false);
}
public Task SetLockoutEnabledAsync(User user, bool enabled)
{
throw new NotImplementedException();
}
public Task SetTwoFactorEnabledAsync(User user, bool enabled)
{
throw new NotImplementedException();
}
public Task<bool> GetTwoFactorEnabledAsync(User user)
{
return Task.FromResult(false);
}
public Task SetEmailAsync(User user, string email)
{
user.Email = email;
return Task.FromResult<object>(null);
}
public Task<string> GetEmailAsync(User user)
{
return Task.FromResult(user.Email);
}
public Task<bool> GetEmailConfirmedAsync(User user)
{
return Task.FromResult(user.Auth?.EmailConfirmed ?? false);
}
public Task SetEmailConfirmedAsync(User user, bool confirmed)
{
user.Auth = user.Auth ?? new UserAuthDetails() { RegisterDate = DateTime.Now };
user.Auth.EmailConfirmed = confirmed;
return Task.FromResult(0);
}
public Task<User> FindByEmailAsync(string email)
{
return _ctx.UserSet.SingleOrDefaultAsync(user => user.Email == email);
}
public Task AddLoginAsync(User user, UserLoginInfo login)
{
user.ExternalLogins.Add(new UserExternalLogin() {Key = login.ProviderKey, Provider = login.LoginProvider});
return _ctx.SaveChangesAsync();
}
public Task RemoveLoginAsync(User user, UserLoginInfo login)
{
var el =
user.ExternalLogins.First(
externalLogin => externalLogin.Key == login.ProviderKey && externalLogin.Provider == login.LoginProvider);
_ctx.Set<UserExternalLogin>().Remove(el);
return Task.FromResult(0);
}
public async Task<IList<UserLoginInfo>> GetLoginsAsync(User user)
{
var result =
await
_ctx.Set<UserExternalLogin>()
.Where(uel => uel.UserId == user.UserId)
.ToListAsync();
return result.Select(uel => new UserLoginInfo(uel.Provider, uel.Key)).ToList();
}
public async Task<User> FindAsync(UserLoginInfo login)
{
var uel =
await _ctx.Set<UserExternalLogin>()
.SingleOrDefaultAsync(u => u.Key == login.ProviderKey && u.Provider == login.LoginProvider);
return uel?.User;
}
#region Implementation of IUserRoleStore<User,in int>
public Task AddToRoleAsync(User user, string roleName)
{
//This is not managed via UserManager
throw new NotSupportedException();
}
public Task RemoveFromRoleAsync(User user, string roleName)
{
//This is not managed via UserManager
throw new NotSupportedException();
}
public Task<IList<string>> GetRolesAsync(User user)
{
List<string> list;
if (user.Auth?.IsAdmin ?? false)
{
list = new List<string>() { Security.AdminRoleName };
}
else
{
list = new List<string>();
}
return Task.FromResult((IList<string>) list);
}
public async Task<bool> IsInRoleAsync(User user, string roleName)
{
var roles = await GetRolesAsync(user);
return roles.Contains(roleName);
}
#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.
//
// An AppDomainManager gives a hosting application the chance to
// participate in the creation and control the settings of new AppDomains.
//
namespace System {
using System.Collections;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Security;
using System.Security.Permissions;
using System.Security.Policy;
using System.Threading;
#if FEATURE_CLICKONCE
using System.Runtime.Hosting;
#endif
using System.Runtime.Versioning;
using System.Runtime.InteropServices;
using System.Diagnostics.Contracts;
#if FEATURE_APPDOMAINMANAGER_INITOPTIONS
[Flags]
[System.Runtime.InteropServices.ComVisible(true)]
public enum AppDomainManagerInitializationOptions {
None = 0x0000,
RegisterWithHost = 0x0001
}
#endif // FEATURE_APPDOMAINMANAGER_INITOPTIONS
[System.Security.SecurityCritical] // auto-generated_required
[System.Runtime.InteropServices.ComVisible(true)]
#if !FEATURE_CORECLR
[SecurityPermissionAttribute(SecurityAction.InheritanceDemand, Flags = SecurityPermissionFlag.Infrastructure)]
#endif
#if FEATURE_REMOTING
public class AppDomainManager : MarshalByRefObject {
#else // FEATURE_REMOTING
public class AppDomainManager {
#endif // FEATURE_REMOTING
public AppDomainManager () {}
#if FEATURE_REMOTING
[System.Security.SecurityCritical] // auto-generated
public virtual AppDomain CreateDomain (string friendlyName,
Evidence securityInfo,
AppDomainSetup appDomainInfo) {
return CreateDomainHelper(friendlyName, securityInfo, appDomainInfo);
}
[System.Security.SecurityCritical] // auto-generated_required
[SecurityPermissionAttribute(SecurityAction.Demand, ControlAppDomain = true)]
protected static AppDomain CreateDomainHelper (string friendlyName,
Evidence securityInfo,
AppDomainSetup appDomainInfo) {
if (friendlyName == null)
throw new ArgumentNullException(Environment.GetResourceString("ArgumentNull_String"));
Contract.EndContractBlock();
// If evidence is provided, we check to make sure that is allowed.
if (securityInfo != null) {
new SecurityPermission(SecurityPermissionFlag.ControlEvidence).Demand();
// Check the evidence to ensure that if it expects a sandboxed domain, it actually gets one.
AppDomain.CheckDomainCreationEvidence(appDomainInfo, securityInfo);
}
if (appDomainInfo == null) {
appDomainInfo = new AppDomainSetup();
}
// If there was no specified AppDomainManager for the new domain, default it to being the same
// as the current domain's AppDomainManager.
if (appDomainInfo.AppDomainManagerAssembly == null || appDomainInfo.AppDomainManagerType == null) {
string inheritedDomainManagerAssembly;
string inheritedDomainManagerType;
AppDomain.CurrentDomain.GetAppDomainManagerType(out inheritedDomainManagerAssembly,
out inheritedDomainManagerType);
if (appDomainInfo.AppDomainManagerAssembly == null) {
appDomainInfo.AppDomainManagerAssembly = inheritedDomainManagerAssembly;
}
if (appDomainInfo.AppDomainManagerType == null) {
appDomainInfo.AppDomainManagerType = inheritedDomainManagerType;
}
}
// If there was no specified TargetFrameworkName for the new domain, default it to the current domain's.
if (appDomainInfo.TargetFrameworkName == null)
appDomainInfo.TargetFrameworkName = AppDomain.CurrentDomain.GetTargetFrameworkName();
return AppDomain.nCreateDomain(friendlyName,
appDomainInfo,
securityInfo,
securityInfo == null ? AppDomain.CurrentDomain.InternalEvidence : null,
AppDomain.CurrentDomain.GetSecurityDescriptor());
}
#endif // FEATURE_REMOTING
[System.Security.SecurityCritical]
public virtual void InitializeNewDomain (AppDomainSetup appDomainInfo) {
// By default, InitializeNewDomain does nothing. AppDomain.CreateAppDomainManager relies on this fact.
}
#if FEATURE_APPDOMAINMANAGER_INITOPTIONS
private AppDomainManagerInitializationOptions m_flags = AppDomainManagerInitializationOptions.None;
public AppDomainManagerInitializationOptions InitializationFlags {
get {
return m_flags;
}
set {
m_flags = value;
}
}
#endif // FEATURE_APPDOMAINMANAGER_INITOPTIONS
#if FEATURE_CLICKONCE
private ApplicationActivator m_appActivator = null;
public virtual ApplicationActivator ApplicationActivator {
get {
if (m_appActivator == null)
m_appActivator = new ApplicationActivator();
return m_appActivator;
}
}
#endif //#if FEATURE_CLICKONCE
#if FEATURE_CAS_POLICY
public virtual HostSecurityManager HostSecurityManager {
get {
return null;
}
}
public virtual HostExecutionContextManager HostExecutionContextManager {
get {
// By default, the AppDomainManager returns the HostExecutionContextManager.
return HostExecutionContextManager.GetInternalHostExecutionContextManager();
}
}
#endif // FEATURE_CAS_POLICY
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
private static extern void GetEntryAssembly(ObjectHandleOnStack retAssembly);
private Assembly m_entryAssembly = null;
public virtual Assembly EntryAssembly {
[System.Security.SecurityCritical] // auto-generated
get {
// The default AppDomainManager sets the EntryAssembly depending on whether the
// AppDomain is a manifest application domain or not. In the first case, we parse
// the application manifest to find out the entry point assembly and return that assembly.
// In the second case, we maintain the old behavior by calling GetEntryAssembly().
if (m_entryAssembly == null)
{
#if FEATURE_CLICKONCE
AppDomain domain = AppDomain.CurrentDomain;
if (domain.IsDefaultAppDomain() && domain.ActivationContext != null) {
ManifestRunner runner = new ManifestRunner(domain, domain.ActivationContext);
m_entryAssembly = runner.EntryAssembly;
} else
#endif //#if FEATURE_CLICKONCE
{
RuntimeAssembly entryAssembly = null;
GetEntryAssembly(JitHelpers.GetObjectHandleOnStack(ref entryAssembly));
m_entryAssembly = entryAssembly;
}
}
return m_entryAssembly;
}
}
internal static AppDomainManager CurrentAppDomainManager {
[System.Security.SecurityCritical] // auto-generated
get {
return AppDomain.CurrentDomain.DomainManager;
}
}
public virtual bool CheckSecuritySettings (SecurityState state)
{
return false;
}
#if FEATURE_APPDOMAINMANAGER_INITOPTIONS
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern bool HasHost();
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SecurityCritical]
[SuppressUnmanagedCodeSecurity]
private static extern void RegisterWithHost(IntPtr appDomainManager);
internal void RegisterWithHost() {
if (HasHost()) {
IntPtr punkAppDomainManager = IntPtr.Zero;
RuntimeHelpers.PrepareConstrainedRegions();
try {
punkAppDomainManager = Marshal.GetIUnknownForObject(this);
RegisterWithHost(punkAppDomainManager);
}
finally {
if (!punkAppDomainManager.IsNull()) {
Marshal.Release(punkAppDomainManager);
}
}
}
}
#endif // FEATURE_APPDOMAINMANAGER_INITOPTIONS
}
}
| |
// 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.IO;
namespace System.Net.NetworkInformation
{
/// <summary>
/// Implements a NetworkInterface on Linux.
/// </summary>
internal class LinuxNetworkInterface : UnixNetworkInterface
{
private readonly OperationalStatus _operationalStatus;
private readonly bool? _supportsMulticast;
private readonly long? _speed;
private readonly LinuxIPInterfaceProperties _ipProperties;
internal LinuxNetworkInterface(string name, int index) : base(name)
{
_index = index;
_operationalStatus = GetOperationalStatus(name);
_supportsMulticast = GetSupportsMulticast(name);
_speed = GetSpeed(name);
_ipProperties = new LinuxIPInterfaceProperties(this);
}
public static unsafe NetworkInterface[] GetLinuxNetworkInterfaces()
{
Dictionary<string, LinuxNetworkInterface> interfacesByName = new Dictionary<string, LinuxNetworkInterface>();
List<Exception> exceptions = null;
const int MaxTries = 3;
for (int attempt = 0; attempt < MaxTries; attempt++)
{
// Because these callbacks are executed in a reverse-PInvoke, we do not want any exceptions
// to propagate out, because they will not be catchable. Instead, we track all the exceptions
// that are thrown in these callbacks, and aggregate them at the end.
int result = Interop.Sys.EnumerateInterfaceAddresses(
(name, ipAddr, maskAddr) =>
{
try
{
LinuxNetworkInterface lni = GetOrCreate(interfacesByName, name, ipAddr->InterfaceIndex);
lni.ProcessIpv4Address(ipAddr, maskAddr);
}
catch (Exception e)
{
if (exceptions == null)
{
exceptions = new List<Exception>();
}
exceptions.Add(e);
}
},
(name, ipAddr, scopeId) =>
{
try
{
LinuxNetworkInterface lni = GetOrCreate(interfacesByName, name, ipAddr->InterfaceIndex);
lni.ProcessIpv6Address(ipAddr, *scopeId);
}
catch (Exception e)
{
if (exceptions == null)
{
exceptions = new List<Exception>();
}
exceptions.Add(e);
}
},
(name, llAddr) =>
{
try
{
LinuxNetworkInterface lni = GetOrCreate(interfacesByName, name, llAddr->InterfaceIndex);
lni.ProcessLinkLayerAddress(llAddr);
}
catch (Exception e)
{
if (exceptions == null)
{
exceptions = new List<Exception>();
}
exceptions.Add(e);
}
});
if (exceptions != null)
{
throw new NetworkInformationException(SR.net_PInvokeError, new AggregateException(exceptions));
}
else if (result == 0)
{
var results = new LinuxNetworkInterface[interfacesByName.Count];
int i = 0;
foreach (KeyValuePair<string, LinuxNetworkInterface> item in interfacesByName)
{
results[i++] = item.Value;
}
return results;
}
else
{
interfacesByName.Clear();
}
}
throw new NetworkInformationException(SR.net_PInvokeError);
}
/// <summary>
/// Gets or creates a LinuxNetworkInterface, based on whether it already exists in the given Dictionary.
/// If created, it is added to the Dictionary.
/// </summary>
/// <param name="interfaces">The Dictionary of existing interfaces.</param>
/// <param name="name">The name of the interface.</param>
/// <param name="index">Interafce index of the interface.</param>
/// <returns>The cached or new LinuxNetworkInterface with the given name.</returns>
private static LinuxNetworkInterface GetOrCreate(Dictionary<string, LinuxNetworkInterface> interfaces, string name, int index)
{
LinuxNetworkInterface lni;
if (!interfaces.TryGetValue(name, out lni))
{
lni = new LinuxNetworkInterface(name, index);
interfaces.Add(name, lni);
}
return lni;
}
public override bool SupportsMulticast
{
get
{
if (_supportsMulticast.HasValue)
{
return _supportsMulticast.Value;
}
else
{
throw new PlatformNotSupportedException(SR.net_InformationUnavailableOnPlatform);
}
}
}
private static bool? GetSupportsMulticast(string name)
{
// /sys/class/net/<interface_name>/flags
string path = Path.Combine(NetworkFiles.SysClassNetFolder, name, NetworkFiles.FlagsFileName);
if (File.Exists(path))
{
try
{
Interop.LinuxNetDeviceFlags flags = (Interop.LinuxNetDeviceFlags)StringParsingHelpers.ParseRawHexFileAsInt(path);
return (flags & Interop.LinuxNetDeviceFlags.IFF_MULTICAST) == Interop.LinuxNetDeviceFlags.IFF_MULTICAST;
}
catch (Exception) // Ignore any problems accessing or parsing the file.
{
}
}
return null;
}
public override IPInterfaceProperties GetIPProperties()
{
return _ipProperties;
}
public override IPInterfaceStatistics GetIPStatistics()
{
return new LinuxIPInterfaceStatistics(_name);
}
public override IPv4InterfaceStatistics GetIPv4Statistics()
{
return new LinuxIPv4InterfaceStatistics(_name);
}
public override OperationalStatus OperationalStatus { get { return _operationalStatus; } }
public override long Speed
{
get
{
if (_speed.HasValue)
{
return _speed.Value;
}
else
{
throw new PlatformNotSupportedException(SR.net_InformationUnavailableOnPlatform);
}
}
}
public override bool IsReceiveOnly { get { throw new PlatformNotSupportedException(SR.net_InformationUnavailableOnPlatform); } }
private static long? GetSpeed(string name)
{
try
{
string path = Path.Combine(NetworkFiles.SysClassNetFolder, name, NetworkFiles.SpeedFileName);
long megabitsPerSecond = StringParsingHelpers.ParseRawLongFile(path);
return megabitsPerSecond == -1
? megabitsPerSecond
: megabitsPerSecond * 1_000_000; // Value must be returned in bits per second, not megabits.
}
catch (Exception) // Ignore any problems accessing or parsing the file.
{
return null;
}
}
private static OperationalStatus GetOperationalStatus(string name)
{
// /sys/class/net/<name>/operstate
string path = Path.Combine(NetworkFiles.SysClassNetFolder, name, NetworkFiles.OperstateFileName);
if (File.Exists(path))
{
try
{
string state = File.ReadAllText(path).Trim();
return MapState(state);
}
catch (Exception) // Ignore any problems accessing or parsing the file.
{
}
}
return OperationalStatus.Unknown;
}
// Maps values from /sys/class/net/<interface>/operstate to OperationalStatus values.
private static OperationalStatus MapState(string state)
{
//
// http://users.sosdg.org/~qiyong/lxr/source/Documentation/networking/operstates.txt?a=um#L41
//
switch (state)
{
case "unknown":
return OperationalStatus.Unknown;
case "notpresent":
return OperationalStatus.NotPresent;
case "down":
return OperationalStatus.Down;
case "lowerlayerdown":
return OperationalStatus.LowerLayerDown;
case "testing":
return OperationalStatus.Testing;
case "dormant":
return OperationalStatus.Dormant;
case "up":
return OperationalStatus.Up;
default:
return OperationalStatus.Unknown;
}
}
}
}
| |
//
// Copyright (c) 2003-2006 Jaroslaw Kowalski <jaak@jkowalski.net>
// Copyright (c) 2006-2014 Piotr Fusik <piotr@fusik.info>
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
using Sooda.ObjectMapper.FieldHandlers;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Xml.Serialization;
namespace Sooda.Schema
{
/// <summary>
/// Stores database table schema information
/// </summary>
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://www.sooda.org/schemas/SoodaSchema.xsd")]
[Serializable]
public class ClassInfo : IFieldContainer
{
[XmlAttribute("datasource")]
public string DataSourceName;
[XmlElement("description")]
public string Description;
[System.Xml.Serialization.XmlElementAttribute("table")]
public List<TableInfo> LocalTables;
[System.Xml.Serialization.XmlElementAttribute("collectionOneToMany")]
public CollectionOnetoManyInfo[] Collections1toN;
[System.Xml.Serialization.XmlElementAttribute("collectionManyToMany")]
public CollectionManyToManyInfo[] CollectionsNtoN;
[XmlIgnore]
[NonSerialized]
public List<CollectionBaseInfo> UnifiedCollections = new List<CollectionBaseInfo>();
[XmlIgnore]
[NonSerialized]
public List<CollectionBaseInfo> LocalCollections = new List<CollectionBaseInfo>();
[System.Xml.Serialization.XmlElementAttribute("const")]
public ConstantInfo[] Constants;
private string _name = null;
[System.Xml.Serialization.XmlAnyAttribute()]
[NonSerialized]
public System.Xml.XmlAttribute[] Extensions;
[System.Xml.Serialization.XmlAttributeAttribute("defaultPrecommitValue")]
public string DefaultPrecommitValue;
[System.Xml.Serialization.XmlAttributeAttribute("name")]
public string Name
{
get
{
return _name;
}
set
{
_name = value;
}
}
[System.Xml.Serialization.XmlAttributeAttribute("extBaseClassName")]
public string ExtBaseClassName;
private string[] _orderedFieldNames;
[System.Xml.Serialization.XmlAttributeAttribute("cached")]
[System.ComponentModel.DefaultValueAttribute(false)]
public bool Cached = false;
[System.Xml.Serialization.XmlAttributeAttribute("cacheCollections")]
[System.ComponentModel.DefaultValueAttribute(false)]
public bool CacheCollections = false;
[System.Xml.Serialization.XmlAttributeAttribute("cardinality")]
[System.ComponentModel.DefaultValueAttribute(ClassCardinality.Medium)]
public ClassCardinality Cardinality = ClassCardinality.Medium;
[System.Xml.Serialization.XmlAttributeAttribute("triggers")]
[System.ComponentModel.DefaultValueAttribute(true)]
public bool Triggers = true;
[System.Xml.Serialization.XmlAttributeAttribute("readOnly")]
[System.ComponentModel.DefaultValueAttribute(false)]
public bool ReadOnly = false;
[System.Xml.Serialization.XmlAttributeAttribute("label")]
public string LabelField = null;
[System.Xml.Serialization.XmlAttributeAttribute("subclassSelectorField")]
public string SubclassSelectorFieldName = null;
[System.Xml.Serialization.XmlAttributeAttribute("subclassSelectorValue")]
public string SubclassSelectorStringValue = null;
[System.Xml.Serialization.XmlAttributeAttribute("inheritFrom")]
public string InheritFrom = null;
[System.Xml.Serialization.XmlAttributeAttribute("keygen")]
public string KeyGenName;
[System.Xml.Serialization.XmlAttributeAttribute("ignorePartial")]
[System.ComponentModel.DefaultValueAttribute(false)]
public bool IgnorePartial = false;
// array of FieldInfo's that point to this class
[XmlIgnore()]
[NonSerialized]
public List<FieldInfo> OuterReferences;
[XmlIgnore()]
[NonSerialized]
public FieldInfo SubclassSelectorField;
[XmlIgnore()]
[NonSerialized]
public object SubclassSelectorValue;
[System.Xml.Serialization.XmlAttributeAttribute("disableTypeCache")]
[System.ComponentModel.DefaultValueAttribute(false)]
public bool DisableTypeCache = false;
public CollectionOnetoManyInfo FindCollectionOneToMany(string collectionName)
{
if (Collections1toN != null)
{
foreach (CollectionOnetoManyInfo i in Collections1toN)
{
if (collectionName == i.Name)
return i;
}
}
if (InheritsFromClass != null)
return InheritsFromClass.FindCollectionOneToMany(collectionName);
return null;
}
public CollectionManyToManyInfo FindCollectionManyToMany(string collectionName)
{
if (CollectionsNtoN != null)
{
foreach (CollectionManyToManyInfo i in CollectionsNtoN)
{
if (collectionName == i.Name)
return i;
}
}
if (InheritsFromClass != null)
return InheritsFromClass.FindCollectionManyToMany(collectionName);
return null;
}
public int ContainsCollection(string collectionName)
{
if (FindCollectionOneToMany(collectionName) != null)
return 1;
if (FindCollectionManyToMany(collectionName) != null)
return 2;
return 0;
}
FieldInfo[] _primaryKeyFields = null;
public FieldInfo[] GetPrimaryKeyFields()
{
return _primaryKeyFields;
}
public FieldInfo GetFirstPrimaryKeyField()
{
return _primaryKeyFields[0];
}
[NonSerialized]
private SchemaInfo parentSchema;
[NonSerialized]
[XmlIgnore]
public List<FieldInfo> LocalFields;
[NonSerialized]
[XmlIgnore]
public List<FieldInfo> UnifiedFields;
[NonSerialized]
[XmlIgnore]
public List<TableInfo> DatabaseTables;
[NonSerialized]
[XmlIgnore]
public ClassInfo InheritsFromClass;
[NonSerialized]
[XmlIgnore]
public List<TableInfo> UnifiedTables;
public List<ClassInfo> GetSubclassesForSchema(SchemaInfo schema)
{
return schema.GetSubclasses(this);
}
internal void ResolveInheritance(SchemaInfo schema)
{
if (InheritFrom != null)
{
InheritsFromClass = schema.FindClassByName(InheritFrom);
}
else
{
InheritsFromClass = null;
}
}
internal void FlattenTables()
{
// Console.WriteLine(">>> FlattenTables for {0}", Name);
if (LocalTables == null)
LocalTables = new List<TableInfo>();
if (InheritsFromClass != null)
{
if (InheritsFromClass.UnifiedTables == null || InheritsFromClass.UnifiedTables.Count == 0)
{
InheritsFromClass.FlattenTables();
}
UnifiedTables = new List<TableInfo>();
foreach (TableInfo ti in InheritsFromClass.UnifiedTables)
{
UnifiedTables.Add(ti.Clone(this));
}
foreach (TableInfo ti in LocalTables)
{
UnifiedTables.Add(ti);
}
}
else
{
UnifiedTables = LocalTables;
}
int ordinalInClass = 0;
foreach (TableInfo t in UnifiedTables)
{
// Console.WriteLine("Setting OrdinalInClass for {0}.{1} to {2}", Name, t.DBTableName, ordinalInClass);
t.OrdinalInClass = ordinalInClass++;
t.NameToken = this.Name + "#" + t.OrdinalInClass;
t.Rehash();
t.OwnerClass = this;
t.Resolve(this.Name, false);
}
if (UnifiedTables.Count > 30)
{
throw new SoodaSchemaException("Class " + Name + " is invalid, because it's based on more than 30 tables");
}
// Console.WriteLine("<<< End of FlattenTables for {0}", Name);
}
internal void Resolve(SchemaInfo schema)
{
if (parentSchema == null)
parentSchema = schema;
OuterReferences = new List<FieldInfo>();
// local fields - a sum of all tables local to the class
LocalFields = new List<FieldInfo>();
int localOrdinal = 0;
int count = 0;
foreach (TableInfo table in LocalTables)
{
foreach (FieldInfo fi in table.Fields)
{
// add all fields from the root table + all non-key fields
// from other tables
if (table.OrdinalInClass == 0 || !fi.IsPrimaryKey)
{
// Console.WriteLine("Adding local field {0} to class {1}", fi.Name, Name);
LocalFields.Add(fi);
fi.ClassLocalOrdinal = localOrdinal++;
}
}
count++;
}
if (SubclassSelectorFieldName == null && InheritsFromClass != null)
{
for (ClassInfo ci = this; ci != null; ci = ci.InheritsFromClass)
{
if (ci.SubclassSelectorFieldName != null)
{
SubclassSelectorFieldName = ci.SubclassSelectorFieldName;
break;
}
}
}
UnifiedCollections = new List<CollectionBaseInfo>();
LocalCollections = new List<CollectionBaseInfo>();
for (ClassInfo ci = this; ci != null; ci = ci.InheritsFromClass)
{
if (ci.Collections1toN != null)
{
foreach (CollectionOnetoManyInfo c in ci.Collections1toN)
{
UnifiedCollections.Add(c);
if (ci == this)
LocalCollections.Add(c);
}
}
if (ci.CollectionsNtoN != null)
{
foreach (CollectionManyToManyInfo c in ci.CollectionsNtoN)
{
UnifiedCollections.Add(c);
if (ci == this)
LocalCollections.Add(c);
}
}
}
// all inherited fields + local fields
UnifiedFields = new List<FieldInfo>();
int unifiedOrdinal = 0;
foreach (TableInfo ti in UnifiedTables)
{
foreach (FieldInfo fi in ti.Fields)
{
if (ti.OrdinalInClass == 0 || !fi.IsPrimaryKey)
{
UnifiedFields.Add(fi);
fi.ClassUnifiedOrdinal = unifiedOrdinal++;
}
}
}
_orderedFieldNames = new string[UnifiedFields.Count];
for (int i = 0; i < UnifiedFields.Count; ++i)
{
_orderedFieldNames[i] = UnifiedFields[i].Name;
}
if (SubclassSelectorFieldName != null)
{
SubclassSelectorField = FindFieldByName(SubclassSelectorFieldName);
if (SubclassSelectorField == null)
throw new SoodaSchemaException("subclassSelectorField points to invalid field name " + SubclassSelectorFieldName + " in " + Name);
}
else if (InheritFrom != null)
{
throw new SoodaSchemaException(String.Format("Must use subclassSelectorFieldName when defining inherited class '{0}'", this.Name));
}
if (SubclassSelectorStringValue != null)
{
// TODO - allow other types based on the field type
//
if (SubclassSelectorField == null)
throw new SoodaSchemaException("subclassSelectorField is invalid");
switch (SubclassSelectorField.DataType)
{
case FieldDataType.Integer:
SubclassSelectorValue = Convert.ToInt32(SubclassSelectorStringValue);
break;
case FieldDataType.String:
SubclassSelectorValue = SubclassSelectorStringValue;
break;
default:
throw new SoodaSchemaException("Field data type not supported for subclassSelectorValue: " + SubclassSelectorField.DataType);
}
}
List<FieldInfo> pkFields = new List<FieldInfo>();
foreach (FieldInfo fi in UnifiedFields)
{
if (fi.IsPrimaryKey)
pkFields.Add(fi);
}
_primaryKeyFields = pkFields.ToArray();
}
internal Array MergeArray(Array oldArray, Array merge)
{
int oldSize = oldArray.Length;
int mergeSize = merge.Length;
int newSize = oldSize + mergeSize;
System.Type elementType = oldArray.GetType().GetElementType();
System.Array newArray = System.Array.CreateInstance(elementType, newSize);
System.Array.Copy(oldArray, 0, newArray, 0, oldSize);
System.Array.Copy(merge, 0, newArray, oldSize, mergeSize);
return newArray;
}
internal void Merge(ClassInfo merge)
{
Hashtable mergeNames = new Hashtable();
foreach (TableInfo mti in this.LocalTables)
mergeNames.Add(mti.DBTableName, mti);
foreach (TableInfo ti in merge.LocalTables)
{
if (mergeNames.ContainsKey(ti.DBTableName))
((TableInfo)mergeNames[ti.DBTableName]).Merge(ti);
else
LocalTables.Add(ti);
}
mergeNames.Clear();
if (this.Collections1toN != null)
{
foreach (CollectionOnetoManyInfo ci in Collections1toN)
mergeNames.Add(ci.Name, ci);
}
if (this.Collections1toN == null)
this.Collections1toN = merge.Collections1toN;
else
{
if (merge.Collections1toN != null)
{
foreach (CollectionOnetoManyInfo mci in merge.Collections1toN)
if (mergeNames.ContainsKey(mci.Name))
throw new SoodaSchemaException(String.Format("Duplicate collection 1:N '{0}' found!", mci.Name));
this.Collections1toN = (CollectionOnetoManyInfo[])MergeArray(this.Collections1toN, merge.Collections1toN);
}
}
mergeNames.Clear();
if (this.CollectionsNtoN != null)
{
foreach (CollectionManyToManyInfo ci in CollectionsNtoN)
mergeNames.Add(ci.Name, ci);
}
if (this.CollectionsNtoN == null)
this.CollectionsNtoN = merge.CollectionsNtoN;
else
{
if (merge.CollectionsNtoN != null)
{
foreach (CollectionManyToManyInfo mci in merge.CollectionsNtoN)
if (mergeNames.ContainsKey(mci.Name))
throw new SoodaSchemaException(String.Format("Duplicate collection N:N '{0}' found!", mci.Name));
this.CollectionsNtoN = (CollectionManyToManyInfo[])MergeArray(this.CollectionsNtoN, merge.CollectionsNtoN);
}
}
mergeNames.Clear();
if (this.Constants != null)
{
foreach (ConstantInfo ci in Constants)
mergeNames.Add(ci.Name, ci);
}
if (this.Constants == null)
this.Constants = merge.Constants;
else
{
if (merge.Constants != null)
{
foreach (ConstantInfo mci in merge.Constants)
if (mergeNames.ContainsKey(mci.Name))
throw new SoodaSchemaException(String.Format("Duplicate constant name '{0}' found!", mci.Name));
this.Constants = (ConstantInfo[])MergeArray(this.Constants, merge.Constants);
}
}
}
internal void MergeTables()
{
DatabaseTables = new List<TableInfo>();
Dictionary<string, TableInfo> mergedTables = new Dictionary<string, TableInfo>();
foreach (TableInfo table in UnifiedTables)
{
TableInfo mt;
if (!mergedTables.TryGetValue(table.DBTableName, out mt))
{
mt = new TableInfo();
mt.DBTableName = table.DBTableName;
mt.TableUsageType = table.TableUsageType;
mt.OrdinalInClass = -1;
mt.Rehash();
mergedTables[table.DBTableName] = mt;
DatabaseTables.Add(mt);
}
foreach (FieldInfo fi in table.Fields)
{
if (mt.ContainsField(fi.Name))
{
if (!fi.IsPrimaryKey)
throw new SoodaSchemaException("Duplicate field found for one table!");
continue;
}
mt.Fields.Add(fi);
}
mt.Rehash();
}
}
internal void ResolveCollections(SchemaInfo schema)
{
if (CollectionsNtoN != null)
{
foreach (CollectionManyToManyInfo cinfo in CollectionsNtoN)
{
cinfo.Resolve(schema);
}
}
if (Collections1toN != null)
{
foreach (CollectionOnetoManyInfo cinfo in Collections1toN)
{
ClassInfo ci = schema.FindClassByName(cinfo.ClassName);
if (ci == null)
throw new SoodaSchemaException("Collection " + Name + "." + cinfo.Name + " cannot find class " + cinfo.ClassName);
FieldInfo fi = ci.FindFieldByName(cinfo.ForeignFieldName);
if (fi == null)
throw new SoodaSchemaException("Collection " + Name + "." + cinfo.Name + " cannot find field " + cinfo.ClassName + "." + cinfo.ForeignFieldName);
schema.AddBackRefCollection(fi, cinfo.Name);
cinfo.ForeignField2 = fi;
cinfo.Class = ci;
}
}
}
internal void ResolveReferences(SchemaInfo schema)
{
// logger.Debug("ResolveReferences({0})", this.Name);
foreach (FieldInfo fi in UnifiedFields)
{
// logger.Debug("unifiedField: {0}", fi.Name);
fi.ResolveReferences(schema);
}
foreach (FieldInfo fi in LocalFields)
{
fi.ParentClass = this;
// logger.Debug("localField: {0}", fi.Name);
if (fi.ReferencedClass != null)
{
// logger.Debug("Is a reference to {0} with ondelete = {1}", fi.ReferencedClass.Name, fi.DeleteAction);
fi.ReferencedClass.OuterReferences.Add(fi);
}
}
}
internal void ResolvePrecommitValues()
{
foreach (FieldInfo fi in UnifiedFields)
{
string pcv = fi.PrecommitValue;
if (pcv == null && fi.ReferencedClass != null)
pcv = fi.ReferencedClass.DefaultPrecommitValue;
if (pcv == null)
{
fi.PrecommitTypedValue = Schema.GetDefaultPrecommitValueForDataType(fi.DataType);
}
else
{
fi.PrecommitTypedValue = FieldHandlerFactory.GetFieldHandler(fi.DataType).RawDeserialize(pcv);
}
}
}
public DataSourceInfo GetDataSource()
{
return parentSchema.GetDataSourceInfo(DataSourceName);
}
[XmlIgnore()]
public SchemaInfo Schema
{
get
{
return parentSchema;
}
set
{
parentSchema = value;
}
}
public List<FieldInfo> GetAllFields()
{
return UnifiedFields;
}
public string[] OrderedFieldNames
{
get { return _orderedFieldNames; }
}
public FieldInfo FindFieldByName(string fieldName)
{
foreach (TableInfo ti in UnifiedTables)
{
FieldInfo fi = ti.FindFieldByName(fieldName);
if (fi != null)
return fi;
}
return null;
}
public FieldInfo FindFieldByDBName(string fieldName)
{
foreach (TableInfo ti in UnifiedTables)
{
FieldInfo fi = ti.FindFieldByDBName(fieldName);
if (fi != null)
return fi;
}
return null;
}
public bool ContainsField(string fieldName)
{
return FindFieldByName(fieldName) != null;
}
public ClassInfo GetRootClass()
{
if (InheritsFromClass != null)
return InheritsFromClass.GetRootClass();
else
return this;
}
public bool IsAbstractClass()
{
return SubclassSelectorFieldName != null && SubclassSelectorValue == null;
}
public string GetLabel()
{
if (LabelField != null)
return LabelField;
if (InheritsFromClass != null)
return InheritsFromClass.GetLabel();
return null;
}
public string GetSafeDataSourceName()
{
return DataSourceName ?? "default";
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Class: SerializationInfo
**
**
** Purpose: The structure for holding all of the data needed
** for object serialization and deserialization.
**
**
===========================================================*/
namespace System.Runtime.Serialization
{
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.Remoting;
#if FEATURE_REMOTING
using System.Runtime.Remoting.Proxies;
#endif
using System.Globalization;
using System.Diagnostics.Contracts;
using System.Security;
#if FEATURE_CORECLR
using System.Runtime.CompilerServices;
#endif
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class SerializationInfo
{
private const int defaultSize = 4;
private const string s_mscorlibAssemblySimpleName = "mscorlib";
private const string s_mscorlibFileName = s_mscorlibAssemblySimpleName + ".dll";
// Even though we have a dictionary, we're still keeping all the arrays around for back-compat.
// Otherwise we may run into potentially breaking behaviors like GetEnumerator() not returning entries in the same order they were added.
internal String[] m_members;
internal Object[] m_data;
internal Type[] m_types;
private Dictionary<string, int> m_nameToIndex;
internal int m_currMember;
internal IFormatterConverter m_converter;
private String m_fullTypeName;
private String m_assemName;
private Type objectType;
private bool isFullTypeNameSetExplicit;
private bool isAssemblyNameSetExplicit;
#if FEATURE_SERIALIZATION
private bool requireSameTokenInPartialTrust;
#endif
[CLSCompliant(false)]
public SerializationInfo(Type type, IFormatterConverter converter)
#if FEATURE_SERIALIZATION
: this(type, converter, false)
{
}
[CLSCompliant(false)]
public SerializationInfo(Type type, IFormatterConverter converter, bool requireSameTokenInPartialTrust)
#endif
{
if ((object)type == null)
{
throw new ArgumentNullException("type");
}
if (converter == null)
{
throw new ArgumentNullException("converter");
}
Contract.EndContractBlock();
objectType = type;
m_fullTypeName = type.FullName;
m_assemName = type.Module.Assembly.FullName;
m_members = new String[defaultSize];
m_data = new Object[defaultSize];
m_types = new Type[defaultSize];
m_nameToIndex = new Dictionary<string, int>();
m_converter = converter;
#if FEATURE_SERIALIZATION
this.requireSameTokenInPartialTrust = requireSameTokenInPartialTrust;
#endif
}
public String FullTypeName
{
get
{
return m_fullTypeName;
}
set
{
if (null == value)
{
throw new ArgumentNullException("value");
}
Contract.EndContractBlock();
m_fullTypeName = value;
isFullTypeNameSetExplicit = true;
}
}
public String AssemblyName
{
get
{
return m_assemName;
}
#if FEATURE_SERIALIZATION
[SecuritySafeCritical]
#endif
set
{
if (null == value)
{
throw new ArgumentNullException("value");
}
Contract.EndContractBlock();
#if FEATURE_SERIALIZATION
if (this.requireSameTokenInPartialTrust)
{
DemandForUnsafeAssemblyNameAssignments(this.m_assemName, value);
}
#endif
m_assemName = value;
isAssemblyNameSetExplicit = true;
}
}
#if FEATURE_SERIALIZATION
[SecuritySafeCritical]
#endif
public void SetType(Type type)
{
if ((object)type == null)
{
throw new ArgumentNullException("type");
}
Contract.EndContractBlock();
#if FEATURE_SERIALIZATION
if (this.requireSameTokenInPartialTrust)
{
DemandForUnsafeAssemblyNameAssignments(this.ObjectType.Assembly.FullName, type.Assembly.FullName);
}
#endif
if (!Object.ReferenceEquals(objectType, type))
{
objectType = type;
m_fullTypeName = type.FullName;
m_assemName = type.Module.Assembly.FullName;
isFullTypeNameSetExplicit = false;
isAssemblyNameSetExplicit = false;
}
}
private static bool Compare(byte[] a, byte[] b)
{
// if either or both assemblies do not have public key token, we should demand, hence, returning false will force a demand
if (a == null || b == null || a.Length == 0 || b.Length == 0 || a.Length != b.Length)
{
return false;
}
else
{
for (int i = 0; i < a.Length; i++)
{
if (a[i] != b[i]) return false;
}
return true;
}
}
[SecuritySafeCritical]
internal static void DemandForUnsafeAssemblyNameAssignments(string originalAssemblyName, string newAssemblyName)
{
if (!IsAssemblyNameAssignmentSafe(originalAssemblyName, newAssemblyName))
{
CodeAccessPermission.Demand(PermissionType.SecuritySerialization);
}
}
internal static bool IsAssemblyNameAssignmentSafe(string originalAssemblyName, string newAssemblyName)
{
if (originalAssemblyName == newAssemblyName)
{
return true;
}
AssemblyName originalAssembly = new AssemblyName(originalAssemblyName);
AssemblyName newAssembly = new AssemblyName(newAssemblyName);
// mscorlib will get loaded by the runtime regardless of its string casing or its public key token,
// so setting the assembly name to mscorlib must always be protected by a demand
if (string.Equals(newAssembly.Name, s_mscorlibAssemblySimpleName, StringComparison.OrdinalIgnoreCase) ||
string.Equals(newAssembly.Name, s_mscorlibFileName, StringComparison.OrdinalIgnoreCase))
{
return false;
}
return Compare(originalAssembly.GetPublicKeyToken(), newAssembly.GetPublicKeyToken());
}
public int MemberCount
{
get
{
return m_currMember;
}
}
public Type ObjectType
{
get
{
return objectType;
}
}
public bool IsFullTypeNameSetExplicit
{
get
{
return isFullTypeNameSetExplicit;
}
}
public bool IsAssemblyNameSetExplicit
{
get
{
return isAssemblyNameSetExplicit;
}
}
public SerializationInfoEnumerator GetEnumerator()
{
return new SerializationInfoEnumerator(m_members, m_data, m_types, m_currMember);
}
private void ExpandArrays()
{
int newSize;
Contract.Assert(m_members.Length == m_currMember, "[SerializationInfo.ExpandArrays]m_members.Length == m_currMember");
newSize = (m_currMember * 2);
//
// In the pathological case, we may wrap
//
if (newSize < m_currMember)
{
if (Int32.MaxValue > m_currMember)
{
newSize = Int32.MaxValue;
}
}
//
// Allocate more space and copy the data
//
String[] newMembers = new String[newSize];
Object[] newData = new Object[newSize];
Type[] newTypes = new Type[newSize];
Array.Copy(m_members, newMembers, m_currMember);
Array.Copy(m_data, newData, m_currMember);
Array.Copy(m_types, newTypes, m_currMember);
//
// Assign the new arrys back to the member vars.
//
m_members = newMembers;
m_data = newData;
m_types = newTypes;
}
public void AddValue(String name, Object value, Type type)
{
if (null == name)
{
throw new ArgumentNullException("name");
}
if ((object)type == null)
{
throw new ArgumentNullException("type");
}
Contract.EndContractBlock();
AddValueInternal(name, value, type);
}
public void AddValue(String name, Object value)
{
if (null == value)
{
AddValue(name, value, typeof(Object));
}
else
{
AddValue(name, value, value.GetType());
}
}
public void AddValue(String name, bool value)
{
AddValue(name, (Object)value, typeof(bool));
}
public void AddValue(String name, char value)
{
AddValue(name, (Object)value, typeof(char));
}
[CLSCompliant(false)]
public void AddValue(String name, sbyte value)
{
AddValue(name, (Object)value, typeof(sbyte));
}
public void AddValue(String name, byte value)
{
AddValue(name, (Object)value, typeof(byte));
}
public void AddValue(String name, short value)
{
AddValue(name, (Object)value, typeof(short));
}
[CLSCompliant(false)]
public void AddValue(String name, ushort value)
{
AddValue(name, (Object)value, typeof(ushort));
}
public void AddValue(String name, int value)
{
AddValue(name, (Object)value, typeof(int));
}
[CLSCompliant(false)]
public void AddValue(String name, uint value)
{
AddValue(name, (Object)value, typeof(uint));
}
public void AddValue(String name, long value)
{
AddValue(name, (Object)value, typeof(long));
}
[CLSCompliant(false)]
public void AddValue(String name, ulong value)
{
AddValue(name, (Object)value, typeof(ulong));
}
public void AddValue(String name, float value)
{
AddValue(name, (Object)value, typeof(float));
}
public void AddValue(String name, double value)
{
AddValue(name, (Object)value, typeof(double));
}
public void AddValue(String name, decimal value)
{
AddValue(name, (Object)value, typeof(decimal));
}
public void AddValue(String name, DateTime value)
{
AddValue(name, (Object)value, typeof(DateTime));
}
internal void AddValueInternal(String name, Object value, Type type)
{
if (m_nameToIndex.ContainsKey(name))
{
BCLDebug.Trace("SER", "[SerializationInfo.AddValue]Tried to add ", name, " twice to the SI.");
throw new SerializationException(Environment.GetResourceString("Serialization_SameNameTwice"));
}
m_nameToIndex.Add(name, m_currMember);
//
// If we need to expand the arrays, do so.
//
if (m_currMember >= m_members.Length)
{
ExpandArrays();
}
//
// Add the data and then advance the counter.
//
m_members[m_currMember] = name;
m_data[m_currMember] = value;
m_types[m_currMember] = type;
m_currMember++;
}
/*=================================UpdateValue==================================
**Action: Finds the value if it exists in the current data. If it does, we replace
** the values, if not, we append it to the end. This is useful to the
** ObjectManager when it's performing fixups, but shouldn't be used by
** clients. Exposing out this functionality would allow children to overwrite
** their parent's values.
**Returns: void
**Arguments: name -- the name of the data to be updated.
** value -- the new value.
** type -- the type of the data being added.
**Exceptions: None. All error checking is done with asserts.
==============================================================================*/
internal void UpdateValue(String name, Object value, Type type)
{
Contract.Assert(null != name, "[SerializationInfo.UpdateValue]name!=null");
Contract.Assert(null != value, "[SerializationInfo.UpdateValue]value!=null");
Contract.Assert(null != (object)type, "[SerializationInfo.UpdateValue]type!=null");
int index = FindElement(name);
if (index < 0)
{
AddValueInternal(name, value, type);
}
else
{
m_data[index] = value;
m_types[index] = type;
}
}
private int FindElement(String name)
{
if (null == name)
{
throw new ArgumentNullException("name");
}
Contract.EndContractBlock();
BCLDebug.Trace("SER", "[SerializationInfo.FindElement]Looking for ", name, " CurrMember is: ", m_currMember);
int index;
if (m_nameToIndex.TryGetValue(name, out index))
{
return index;
}
return -1;
}
/*==================================GetElement==================================
**Action: Use FindElement to get the location of a particular member and then return
** the value of the element at that location. The type of the member is
** returned in the foundType field.
**Returns: The value of the element at the position associated with name.
**Arguments: name -- the name of the element to find.
** foundType -- the type of the element associated with the given name.
**Exceptions: None. FindElement does null checking and throws for elements not
** found.
==============================================================================*/
private Object GetElement(String name, out Type foundType)
{
int index = FindElement(name);
if (index == -1)
{
throw new SerializationException(Environment.GetResourceString("Serialization_NotFound", name));
}
Contract.Assert(index < m_data.Length, "[SerializationInfo.GetElement]index<m_data.Length");
Contract.Assert(index < m_types.Length, "[SerializationInfo.GetElement]index<m_types.Length");
foundType = m_types[index];
Contract.Assert((object)foundType != null, "[SerializationInfo.GetElement]foundType!=null");
return m_data[index];
}
[System.Runtime.InteropServices.ComVisible(true)]
//
private Object GetElementNoThrow(String name, out Type foundType)
{
int index = FindElement(name);
if (index == -1)
{
foundType = null;
return null;
}
Contract.Assert(index < m_data.Length, "[SerializationInfo.GetElement]index<m_data.Length");
Contract.Assert(index < m_types.Length, "[SerializationInfo.GetElement]index<m_types.Length");
foundType = m_types[index];
Contract.Assert((object)foundType != null, "[SerializationInfo.GetElement]foundType!=null");
return m_data[index];
}
//
// The user should call one of these getters to get the data back in the
// form requested.
//
[System.Security.SecuritySafeCritical] // auto-generated
public Object GetValue(String name, Type type)
{
if ((object)type == null)
{
throw new ArgumentNullException("type");
}
Contract.EndContractBlock();
RuntimeType rt = type as RuntimeType;
if (rt == null)
throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"));
Type foundType;
Object value;
value = GetElement(name, out foundType);
#if FEATURE_REMOTING
if (RemotingServices.IsTransparentProxy(value))
{
RealProxy proxy = RemotingServices.GetRealProxy(value);
if (RemotingServices.ProxyCheckCast(proxy, rt))
return value;
}
else
#endif
if (Object.ReferenceEquals(foundType, type) || type.IsAssignableFrom(foundType) || value == null)
{
return value;
}
Contract.Assert(m_converter != null, "[SerializationInfo.GetValue]m_converter!=null");
return m_converter.Convert(value, type);
}
[System.Security.SecuritySafeCritical] // auto-generated
[System.Runtime.InteropServices.ComVisible(true)]
//
internal Object GetValueNoThrow(String name, Type type)
{
Type foundType;
Object value;
Contract.Assert((object)type != null, "[SerializationInfo.GetValue]type ==null");
Contract.Assert(type is RuntimeType, "[SerializationInfo.GetValue]type is not a runtime type");
value = GetElementNoThrow(name, out foundType);
if (value == null)
return null;
#if FEATURE_REMOTING
if (RemotingServices.IsTransparentProxy(value))
{
RealProxy proxy = RemotingServices.GetRealProxy(value);
if (RemotingServices.ProxyCheckCast(proxy, (RuntimeType)type))
return value;
}
else
#endif
if (Object.ReferenceEquals(foundType, type) || type.IsAssignableFrom(foundType) || value == null)
{
return value;
}
Contract.Assert(m_converter != null, "[SerializationInfo.GetValue]m_converter!=null");
return m_converter.Convert(value, type);
}
public bool GetBoolean(String name)
{
Type foundType;
Object value;
value = GetElement(name, out foundType);
if (Object.ReferenceEquals(foundType, typeof(bool)))
{
return (bool)value;
}
return m_converter.ToBoolean(value);
}
public char GetChar(String name)
{
Type foundType;
Object value;
value = GetElement(name, out foundType);
if (Object.ReferenceEquals(foundType, typeof(char)))
{
return (char)value;
}
return m_converter.ToChar(value);
}
[CLSCompliant(false)]
public sbyte GetSByte(String name)
{
Type foundType;
Object value;
value = GetElement(name, out foundType);
if (Object.ReferenceEquals(foundType, typeof(sbyte)))
{
return (sbyte)value;
}
return m_converter.ToSByte(value);
}
public byte GetByte(String name)
{
Type foundType;
Object value;
value = GetElement(name, out foundType);
if (Object.ReferenceEquals(foundType, typeof(byte)))
{
return (byte)value;
}
return m_converter.ToByte(value);
}
public short GetInt16(String name)
{
Type foundType;
Object value;
value = GetElement(name, out foundType);
if (Object.ReferenceEquals(foundType, typeof(short)))
{
return (short)value;
}
return m_converter.ToInt16(value);
}
[CLSCompliant(false)]
public ushort GetUInt16(String name)
{
Type foundType;
Object value;
value = GetElement(name, out foundType);
if (Object.ReferenceEquals(foundType, typeof(ushort)))
{
return (ushort)value;
}
return m_converter.ToUInt16(value);
}
public int GetInt32(String name)
{
Type foundType;
Object value;
value = GetElement(name, out foundType);
if (Object.ReferenceEquals(foundType, typeof(int)))
{
return (int)value;
}
return m_converter.ToInt32(value);
}
[CLSCompliant(false)]
public uint GetUInt32(String name)
{
Type foundType;
Object value;
value = GetElement(name, out foundType);
if (Object.ReferenceEquals(foundType, typeof(uint)))
{
return (uint)value;
}
return m_converter.ToUInt32(value);
}
public long GetInt64(String name)
{
Type foundType;
Object value;
value = GetElement(name, out foundType);
if (Object.ReferenceEquals(foundType, typeof(long)))
{
return (long)value;
}
return m_converter.ToInt64(value);
}
[CLSCompliant(false)]
public ulong GetUInt64(String name)
{
Type foundType;
Object value;
value = GetElement(name, out foundType);
if (Object.ReferenceEquals(foundType, typeof(ulong)))
{
return (ulong)value;
}
return m_converter.ToUInt64(value);
}
public float GetSingle(String name)
{
Type foundType;
Object value;
value = GetElement(name, out foundType);
if (Object.ReferenceEquals(foundType, typeof(float)))
{
return (float)value;
}
return m_converter.ToSingle(value);
}
public double GetDouble(String name)
{
Type foundType;
Object value;
value = GetElement(name, out foundType);
if (Object.ReferenceEquals(foundType, typeof(double)))
{
return (double)value;
}
return m_converter.ToDouble(value);
}
public decimal GetDecimal(String name)
{
Type foundType;
Object value;
value = GetElement(name, out foundType);
if (Object.ReferenceEquals(foundType, typeof(decimal)))
{
return (decimal)value;
}
return m_converter.ToDecimal(value);
}
public DateTime GetDateTime(String name)
{
Type foundType;
Object value;
value = GetElement(name, out foundType);
if (Object.ReferenceEquals(foundType, typeof(DateTime)))
{
return (DateTime)value;
}
return m_converter.ToDateTime(value);
}
public String GetString(String name)
{
Type foundType;
Object value;
value = GetElement(name, out foundType);
if (Object.ReferenceEquals(foundType, typeof(String)) || value == null)
{
return (String)value;
}
return m_converter.ToString(value);
}
internal string[] MemberNames
{
get
{
return m_members;
}
}
internal object[] MemberValues
{
get
{
return m_data;
}
}
}
}
| |
// 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;
namespace System
{
// The class designed as to keep working set of Uri class as minimal.
// The idea is to stay with static helper methods and strings
internal class DomainNameHelper
{
private DomainNameHelper()
{
}
internal const string Localhost = "localhost";
internal const string Loopback = "loopback";
internal static string ParseCanonicalName(string str, int start, int end, ref bool loopback)
{
string res = null;
for (int i = end - 1; i >= start; --i)
{
if (str[i] >= 'A' && str[i] <= 'Z')
{
res = str.Substring(start, end - start).ToLowerInvariant();
break;
}
if (str[i] == ':')
end = i;
}
if (res == null)
{
res = str.Substring(start, end - start);
}
if (res == Localhost || res == Loopback)
{
loopback = true;
return Localhost;
}
return res;
}
//
// IsValid
//
// Determines whether a string is a valid domain name
//
// subdomain -> <label> | <label> "." <subdomain>
//
// Inputs:
// - name as Name to test
// - starting position
// - ending position
//
// Outputs:
// The end position of a valid domain name string, the canonical flag if found so
//
// Returns:
// bool
//
// Remarks: Optimized for speed as a most comon case,
// MUST NOT be used unless all input indexes are are verified and trusted.
//
internal unsafe static bool IsValid(char* name, ushort pos, ref int returnedEnd, ref bool notCanonical, bool notImplicitFile)
{
char* curPos = name + pos;
char* newPos = curPos;
char* end = name + returnedEnd;
for (; newPos < end; ++newPos)
{
char ch = *newPos;
if (ch > 0x7f) return false; // not ascii
if (ch == '/' || ch == '\\' || (notImplicitFile && (ch == ':' || ch == '?' || ch == '#')))
{
end = newPos;
break;
}
}
if (end == curPos)
{
return false;
}
do
{
// Determines whether a string is a valid domain name label. In keeping
// with RFC 1123, section 2.1, the requirement that the first character
// of a label be alphabetic is dropped. Therefore, Domain names are
// formed as:
//
// <label> -> <alphanum> [<alphanum> | <hyphen> | <underscore>] * 62
//find the dot or hit the end
newPos = curPos;
while (newPos < end)
{
if (*newPos == '.') break;
++newPos;
}
//check the label start/range
if (curPos == newPos || newPos - curPos > 63 || !IsASCIILetterOrDigit(*curPos++, ref notCanonical))
{
return false;
}
//check the label content
while (curPos < newPos)
{
if (!IsValidDomainLabelCharacter(*curPos++, ref notCanonical))
{
return false;
}
}
++curPos;
} while (curPos < end);
returnedEnd = (ushort)(end - name);
return true;
}
//
// Checks if the domain name is valid according to iri
// There are pretty much no restrictions and we effectively return the end of the
// domain name.
//
internal unsafe static bool IsValidByIri(char* name, ushort pos, ref int returnedEnd, ref bool notCanonical, bool notImplicitFile)
{
char* curPos = name + pos;
char* newPos = curPos;
char* end = name + returnedEnd;
int count = 0; // count number of octets in a label;
for (; newPos < end; ++newPos)
{
char ch = *newPos;
if (ch == '/' || ch == '\\' || (notImplicitFile && (ch == ':' || ch == '?' || ch == '#')))
{
end = newPos;
break;
}
}
if (end == curPos)
{
return false;
}
do
{
// Determines whether a string is a valid domain name label. In keeping
// with RFC 1123, section 2.1, the requirement that the first character
// of a label be alphabetic is dropped. Therefore, Domain names are
// formed as:
//
// <label> -> <alphanum> [<alphanum> | <hyphen> | <underscore>] * 62
//find the dot or hit the end
newPos = curPos;
count = 0;
bool labelHasUnicode = false; // if label has unicode we need to add 4 to label count for xn--
while (newPos < end)
{
if ((*newPos == '.') ||
(*newPos == '\u3002') || //IDEOGRAPHIC FULL STOP
(*newPos == '\uFF0E') || //FULLWIDTH FULL STOP
(*newPos == '\uFF61')) //HALFWIDTH IDEOGRAPHIC FULL STOP
break;
count++;
if (*newPos > 0xFF)
count++; // counts for two octets
if (*newPos >= 0xA0)
labelHasUnicode = true;
++newPos;
}
//check the label start/range
if (curPos == newPos || (labelHasUnicode ? count + 4 : count) > 63 || ((*curPos++ < 0xA0) && !IsASCIILetterOrDigit(*(curPos - 1), ref notCanonical)))
{
return false;
}
//check the label content
while (curPos < newPos)
{
if ((*curPos++ < 0xA0) && !IsValidDomainLabelCharacter(*(curPos - 1), ref notCanonical))
{
return false;
}
}
++curPos;
} while (curPos < end);
returnedEnd = (ushort)(end - name);
return true;
}
internal static string IdnEquivalent(string hostname)
{
bool allAscii = true;
bool atLeastOneValidIdn = false;
unsafe
{
fixed (char* host = hostname)
{
return IdnEquivalent(host, 0, hostname.Length, ref allAscii, ref atLeastOneValidIdn);
}
}
}
//
// Will convert a host name into its idn equivalent + tell you if it had a valid idn label
//
internal unsafe static string IdnEquivalent(char* hostname, int start, int end, ref bool allAscii, ref bool atLeastOneValidIdn)
{
string bidiStrippedHost = null;
string idnEquivalent = IdnEquivalent(hostname, start, end, ref allAscii, ref bidiStrippedHost);
if (idnEquivalent != null)
{
string strippedHost = (allAscii ? idnEquivalent : bidiStrippedHost);
fixed (char* strippedHostPtr = strippedHost)
{
int length = strippedHost.Length;
int newPos = 0;
int curPos = 0;
bool foundAce = false;
bool checkedAce = false;
bool foundDot = false;
do
{
foundAce = false;
checkedAce = false;
foundDot = false;
//find the dot or hit the end
newPos = curPos;
while (newPos < length)
{
char c = strippedHostPtr[newPos];
if (!checkedAce)
{
checkedAce = true;
if ((newPos + 3 < length) && IsIdnAce(strippedHostPtr, newPos))
{
newPos += 4;
foundAce = true;
continue;
}
}
if ((c == '.') || (c == '\u3002') || //IDEOGRAPHIC FULL STOP
(c == '\uFF0E') || //FULLWIDTH FULL STOP
(c == '\uFF61')) //HALFWIDTH IDEOGRAPHIC FULL STOP
{
foundDot = true;
break;
}
++newPos;
}
if (foundAce)
{
// check ace validity
try
{
IdnMapping map = new IdnMapping();
map.GetUnicode(new string(strippedHostPtr, curPos, newPos - curPos));
atLeastOneValidIdn = true;
break;
}
catch (ArgumentException)
{
// not valid ace so treat it as a normal ascii label
}
}
curPos = newPos + (foundDot ? 1 : 0);
} while (curPos < length);
}
}
else
{
atLeastOneValidIdn = false;
}
return idnEquivalent;
}
//
// Will convert a host name into its idn equivalent
//
internal unsafe static string IdnEquivalent(char* hostname, int start, int end, ref bool allAscii, ref string bidiStrippedHost)
{
string idn = null;
if (end <= start)
return idn;
// indexes are validated
int newPos = start;
allAscii = true;
while (newPos < end)
{
// check if only ascii chars
// special case since idnmapping will not lowercase if only ascii present
if (hostname[newPos] > '\x7F')
{
allAscii = false;
break;
}
++newPos;
}
if (allAscii)
{
// just lowercase for ascii
string unescapedHostname = new string(hostname, start, end - start);
return ((unescapedHostname != null) ? unescapedHostname.ToLowerInvariant() : null);
}
else
{
IdnMapping map = new IdnMapping();
string asciiForm;
bidiStrippedHost = Uri.StripBidiControlCharacter(hostname, start, end - start);
try
{
asciiForm = map.GetAscii(bidiStrippedHost);
}
catch (ArgumentException)
{
throw new UriFormatException(SR.net_uri_BadUnicodeHostForIdn);
}
return asciiForm;
}
}
private unsafe static bool IsIdnAce(string input, int index)
{
if ((input[index] == 'x') &&
(input[index + 1] == 'n') &&
(input[index + 2] == '-') &&
(input[index + 3] == '-'))
return true;
else
return false;
}
private unsafe static bool IsIdnAce(char* input, int index)
{
if ((input[index] == 'x') &&
(input[index + 1] == 'n') &&
(input[index + 2] == '-') &&
(input[index + 3] == '-'))
return true;
else
return false;
}
//
// Will convert a host name into its unicode equivalent expanding any existing idn names present
//
internal unsafe static string UnicodeEquivalent(string idnHost, char* hostname, int start, int end)
{
IdnMapping map = new IdnMapping();
// Test comon scenario first for perf
// try to get unicode equivalent
try
{
return map.GetUnicode(idnHost);
}
catch (ArgumentException)
{
}
// Here because something threw in GetUnicode above
// Need to now check individual labels of they had an ace label that was not valid Idn name
// or if there is a label with invalid Idn char.
bool dummy = true;
return UnicodeEquivalent(hostname, start, end, ref dummy, ref dummy);
}
internal unsafe static string UnicodeEquivalent(char* hostname, int start, int end, ref bool allAscii, ref bool atLeastOneValidIdn)
{
IdnMapping map = new IdnMapping();
// hostname already validated
allAscii = true;
atLeastOneValidIdn = false;
string idn = null;
if (end <= start)
return idn;
string unescapedHostname = Uri.StripBidiControlCharacter(hostname, start, (end - start));
string unicodeEqvlHost = null;
int curPos = 0;
int newPos = 0;
int length = unescapedHostname.Length;
bool asciiLabel = true;
bool foundAce = false;
bool checkedAce = false;
bool foundDot = false;
// We run a loop where for every label
// a) if label is ascii and no ace then we lowercase it
// b) if label is ascii and ace and not valid idn then just lowercase it
// c) if label is ascii and ace and is valid idn then get its unicode eqvl
// d) if label is unicode then clean it by running it through idnmapping
do
{
asciiLabel = true;
foundAce = false;
checkedAce = false;
foundDot = false;
//find the dot or hit the end
newPos = curPos;
while (newPos < length)
{
char c = unescapedHostname[newPos];
if (!checkedAce)
{
checkedAce = true;
if ((newPos + 3 < length) && (c == 'x') && IsIdnAce(unescapedHostname, newPos))
foundAce = true;
}
if (asciiLabel && (c > '\x7F'))
{
asciiLabel = false;
allAscii = false;
}
if ((c == '.') || (c == '\u3002') || //IDEOGRAPHIC FULL STOP
(c == '\uFF0E') || //FULLWIDTH FULL STOP
(c == '\uFF61')) //HALFWIDTH IDEOGRAPHIC FULL STOP
{
foundDot = true;
break;
}
++newPos;
}
if (!asciiLabel)
{
string asciiForm = unescapedHostname.Substring(curPos, newPos - curPos);
try
{
asciiForm = map.GetAscii(asciiForm);
}
catch (ArgumentException)
{
throw new UriFormatException(SR.net_uri_BadUnicodeHostForIdn);
}
unicodeEqvlHost += map.GetUnicode(asciiForm);
if (foundDot)
unicodeEqvlHost += ".";
}
else
{
bool aceValid = false;
if (foundAce)
{
// check ace validity
try
{
unicodeEqvlHost += map.GetUnicode(unescapedHostname.Substring(curPos, newPos - curPos));
if (foundDot)
unicodeEqvlHost += ".";
aceValid = true;
atLeastOneValidIdn = true;
}
catch (ArgumentException)
{
// not valid ace so treat it as a normal ascii label
}
}
if (!aceValid)
{
// for invalid aces we just lowercase the label
unicodeEqvlHost += unescapedHostname.Substring(curPos, newPos - curPos).ToLowerInvariant();
if (foundDot)
unicodeEqvlHost += ".";
}
}
curPos = newPos + (foundDot ? 1 : 0);
} while (curPos < length);
return unicodeEqvlHost;
}
//
// Determines whether a character is a letter or digit according to the
// DNS specification [RFC 1035]. We use our own variant of IsLetterOrDigit
// because the base version returns false positives for non-ANSI characters
//
private static bool IsASCIILetterOrDigit(char character, ref bool notCanonical)
{
if ((character >= 'a' && character <= 'z') || (character >= '0' && character <= '9'))
return true;
if (character >= 'A' && character <= 'Z')
{
notCanonical = true;
return true;
}
return false;
}
//
// Takes into account the additional legal domain name characters '-' and '_'
// Note that '_' char is formally invalid but is historically in use, especially on corpnets
//
private static bool IsValidDomainLabelCharacter(char character, ref bool notCanonical)
{
if ((character >= 'a' && character <= 'z') || (character >= '0' && character <= '9') || (character == '-') || (character == '_'))
return true;
if (character >= 'A' && character <= 'Z')
{
notCanonical = true;
return true;
}
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.Diagnostics;
using System.Threading.Tasks;
using System.Threading.Tasks.Sources;
namespace System.Runtime.CompilerServices
{
/// <summary>Provides an awaiter for a <see cref="ValueTask"/>.</summary>
public readonly struct ValueTaskAwaiter : ICriticalNotifyCompletion
#if CORECLR
, IValueTaskAwaiter
#endif
{
/// <summary>Shim used to invoke an <see cref="Action"/> passed as the state argument to a <see cref="Action{Object}"/>.</summary>
internal static readonly Action<object> s_invokeActionDelegate = state =>
{
if (!(state is Action action))
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.state);
return;
}
action();
};
/// <summary>The value being awaited.</summary>
private readonly ValueTask _value;
/// <summary>Initializes the awaiter.</summary>
/// <param name="value">The value to be awaited.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal ValueTaskAwaiter(ValueTask value) => _value = value;
/// <summary>Gets whether the <see cref="ValueTask"/> has completed.</summary>
public bool IsCompleted
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => _value.IsCompleted;
}
/// <summary>Gets the result of the ValueTask.</summary>
[StackTraceHidden]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void GetResult() => _value.ThrowIfCompletedUnsuccessfully();
/// <summary>Schedules the continuation action for this ValueTask.</summary>
public void OnCompleted(Action continuation)
{
if (_value.ObjectIsTask)
{
_value.UnsafeGetTask().GetAwaiter().OnCompleted(continuation);
}
else if (_value._obj != null)
{
_value.UnsafeGetValueTaskSource().OnCompleted(s_invokeActionDelegate, continuation, _value._token, ValueTaskSourceOnCompletedFlags.UseSchedulingContext | ValueTaskSourceOnCompletedFlags.FlowExecutionContext);
}
else
{
ValueTask.CompletedTask.GetAwaiter().OnCompleted(continuation);
}
}
/// <summary>Schedules the continuation action for this ValueTask.</summary>
public void UnsafeOnCompleted(Action continuation)
{
if (_value.ObjectIsTask)
{
_value.UnsafeGetTask().GetAwaiter().UnsafeOnCompleted(continuation);
}
else if (_value._obj != null)
{
_value.UnsafeGetValueTaskSource().OnCompleted(s_invokeActionDelegate, continuation, _value._token, ValueTaskSourceOnCompletedFlags.UseSchedulingContext);
}
else
{
ValueTask.CompletedTask.GetAwaiter().UnsafeOnCompleted(continuation);
}
}
#if CORECLR
void IValueTaskAwaiter.AwaitUnsafeOnCompleted(IAsyncStateMachineBox box)
{
if (_value.ObjectIsTask)
{
TaskAwaiter.UnsafeOnCompletedInternal(_value.UnsafeGetTask(), box, continueOnCapturedContext: true);
}
else if (_value._obj != null)
{
_value.UnsafeGetValueTaskSource().OnCompleted(s_invokeAsyncStateMachineBox, box, _value._token, ValueTaskSourceOnCompletedFlags.UseSchedulingContext);
}
else
{
TaskAwaiter.UnsafeOnCompletedInternal(Task.CompletedTask, box, continueOnCapturedContext: true);
}
}
/// <summary>Shim used to invoke <see cref="ITaskCompletionAction.Invoke"/> of the supplied <see cref="IAsyncStateMachineBox"/>.</summary>
internal static readonly Action<object> s_invokeAsyncStateMachineBox = state =>
{
if (!(state is IAsyncStateMachineBox box))
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.state);
return;
}
box.MoveNext();
};
#endif
}
/// <summary>Provides an awaiter for a <see cref="ValueTask{TResult}"/>.</summary>
public readonly struct ValueTaskAwaiter<TResult> : ICriticalNotifyCompletion
#if CORECLR
, IValueTaskAwaiter
#endif
{
/// <summary>The value being awaited.</summary>
private readonly ValueTask<TResult> _value;
/// <summary>Initializes the awaiter.</summary>
/// <param name="value">The value to be awaited.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal ValueTaskAwaiter(ValueTask<TResult> value) => _value = value;
/// <summary>Gets whether the <see cref="ValueTask{TResult}"/> has completed.</summary>
public bool IsCompleted
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => _value.IsCompleted;
}
/// <summary>Gets the result of the ValueTask.</summary>
[StackTraceHidden]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public TResult GetResult() => _value.Result;
/// <summary>Schedules the continuation action for this ValueTask.</summary>
public void OnCompleted(Action continuation)
{
if (_value.ObjectIsTask)
{
_value.UnsafeGetTask().GetAwaiter().OnCompleted(continuation);
}
else if (_value._obj != null)
{
_value.UnsafeGetValueTaskSource().OnCompleted(ValueTaskAwaiter.s_invokeActionDelegate, continuation, _value._token, ValueTaskSourceOnCompletedFlags.UseSchedulingContext | ValueTaskSourceOnCompletedFlags.FlowExecutionContext);
}
else
{
ValueTask.CompletedTask.GetAwaiter().OnCompleted(continuation);
}
}
/// <summary>Schedules the continuation action for this ValueTask.</summary>
public void UnsafeOnCompleted(Action continuation)
{
if (_value.ObjectIsTask)
{
_value.UnsafeGetTask().GetAwaiter().UnsafeOnCompleted(continuation);
}
else if (_value._obj != null)
{
_value.UnsafeGetValueTaskSource().OnCompleted(ValueTaskAwaiter.s_invokeActionDelegate, continuation, _value._token, ValueTaskSourceOnCompletedFlags.UseSchedulingContext);
}
else
{
ValueTask.CompletedTask.GetAwaiter().UnsafeOnCompleted(continuation);
}
}
#if CORECLR
void IValueTaskAwaiter.AwaitUnsafeOnCompleted(IAsyncStateMachineBox box)
{
if (_value.ObjectIsTask)
{
TaskAwaiter.UnsafeOnCompletedInternal(_value.UnsafeGetTask(), box, continueOnCapturedContext: true);
}
else if (_value._obj != null)
{
_value.UnsafeGetValueTaskSource().OnCompleted(ValueTaskAwaiter.s_invokeAsyncStateMachineBox, box, _value._token, ValueTaskSourceOnCompletedFlags.UseSchedulingContext);
}
else
{
TaskAwaiter.UnsafeOnCompletedInternal(Task.CompletedTask, box, continueOnCapturedContext: true);
}
}
#endif
}
#if CORECLR
/// <summary>Internal interface used to enable optimizations from <see cref="AsyncTaskMethodBuilder"/> on <see cref="ValueTask"/>.</summary>>
internal interface IValueTaskAwaiter
{
/// <summary>Invoked to set <see cref="ITaskCompletionAction.Invoke"/> of the <paramref name="box"/> as the awaiter's continuation.</summary>
/// <param name="box">The box object.</param>
void AwaitUnsafeOnCompleted(IAsyncStateMachineBox box);
}
#endif
}
| |
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
public abstract class ChunkedComponentSystem<T, TSystem> : IComponentSystem<T>
where T : ChunkedComponent<T, TSystem>
where TSystem : ChunkedComponentSystem<T, TSystem>, new()
{
protected static readonly ushort CHUNK_SIZE = 16; //NOTE: override in child systems constr
public readonly Dictionary<Point, List<T>> chunks_ = new Dictionary<Point, List<T>>();
protected static Color debugColor = Color.White;
public void DrawDebug()
{
foreach (KeyValuePair<Point, List<T>> chunk in chunks_)
{
var pos = chunk.Key;
var comp = chunk.Value;
//draw region square
var regionRect = new Rectangle(pos.X*CHUNK_SIZE, pos.Y*CHUNK_SIZE, CHUNK_SIZE, CHUNK_SIZE);
Dbg.AddDebugRect(regionRect, debugColor, Randy.NextFloat(0.25f));
Dbg.AddDebugText(comp.Count.ToString(), regionRect.Location.ToVector2(), debugColor);
for (var index = 0; index < comp.Count; index++)
{
T component = comp[index];
//DebugHelper.AddDebugText(index.ToString(), component.entity.Position, debugColor);
}
}
}
protected Point GetChunkKeyForPos(Vector2 position)
{
return new Point((position.X/CHUNK_SIZE).Settle(), (position.Y/CHUNK_SIZE).Settle());
}
protected List<T> GetChunkEntityList(Point key)
{
if (chunks_.TryGetValue(key, out List<T> ol))
return ol;
return null;
}
protected List<T> GetChunkEntityListForPos(Vector2 position)
{
return GetChunkEntityList(GetChunkKeyForPos(position));
}
public List<Point> GetChunksInRect(RectF rect)
{
// assemble list of unique chunks in rect
List<Point> chunksInRect = new List<Point>();
for (float rx = rect.X; rx < rect.Right + CHUNK_SIZE; rx += CHUNK_SIZE - 0.1f) //TODO FIXME
for (float ry = rect.Y; ry < rect.Bottom + CHUNK_SIZE; ry += CHUNK_SIZE - 0.1f)
{
Point p = GetChunkKeyForPos(new Vector2(rx, ry));
if (!chunksInRect.Contains(p))
chunksInRect.Add(p);
}
return chunksInRect;
}
public List<T> GetComponentsInRect(RectF rect)
{
List<Point> chunksToCheck = GetChunksInRect(rect);
List<T> retList = new List<T>();
foreach (Point chunkPos in chunksToCheck)
if (chunks_.ContainsKey(chunkPos) && chunks_[chunkPos] != null)//TODO use out value
foreach (T component in chunks_[chunkPos])
if(rect.Contains(component.entity.Position))
retList.Add(component);
return retList;
}
public List<T> GetAllComponents()
{
List<T> retList = new List<T>();
foreach (KeyValuePair<Point, List<T>> pair in chunks_) //loop all chunks and add to list
{
retList.AddRange(pair.Value);
}
return retList;
}
internal void UpdateComponentChunk(T component)
{
Point newKey = GetChunkKeyForPos(component.entity.Position);
// if we didn't change chunk, do nothing
if (newKey == component.currentChunkPos_)
return;
//Debug.WriteLine($"changing obj from {currentChunkPos_} to {newChunkPos}");
RemoveFromCurrentChunk(component);
// add to new chunk if it doesn't exist
if (!chunks_.ContainsKey(newKey))
{
//Debug.WriteLine($"creating new chunk for item at: {currentChunkPos_}");
chunks_[newKey] = new List<T>(); // creates new if doesn't exist
}
chunks_[newKey].Add(component); // adds obj to chunk at new position
// store current chunk
component.currentChunkPos_ = newKey;
}
internal void RemoveFromCurrentChunk(T component)
{
Point currentKey = component.currentChunkPos_;
// cleaning up previous chunk stuff
if (chunks_.ContainsKey(currentKey)) //if chunk at previous position exists
{
if (chunks_[currentKey] != null) //if list is ok
{
chunks_[currentKey].Remove(component); // remove from previous chunk
if (chunks_[currentKey].Count == 0) //clean up if empty
{
//Debug.WriteLine($"deleting chunk with no items: {currentChunkPos_}");
chunks_.Remove(currentKey);
}
}
}
}
public void OnComponentCtor(T component)
{
UpdateComponentChunk(component);
}
public void OnComponentFinalize(T component)
{
RemoveFromCurrentChunk(component);
}
}
public abstract class ChunkedComponent<T, TSystem> : ManagedComponent<T, TSystem>
where T : ChunkedComponent<T, TSystem>
where TSystem : ChunkedComponentSystem<T, TSystem>, new()
{
static ChunkedComponent()
{
Dbg.onBeforeDebugDrawing += Systems.Default.DrawDebug;
}
internal Point currentChunkPos_ = new Point(Int32.MaxValue, Int32.MaxValue);
protected void UpdateChunk()
{
System.UpdateComponentChunk((T)this);
}
public override void EntityChanged()
{
base.EntityChanged();
UpdateChunk();
}
protected ChunkedComponent(Entity entity, byte system = 0) : base(entity, system){}
}
//TODO REMOVE THIS CLASS, rename above one
//public abstract class ManagedChunkedComponent<T> : Component
//{
// protected static ushort CHUNK_SIZE = 10;
//
// protected static readonly Dictionary<Point, List<ManagedChunkedComponent<T>>> chunks_ =
// new Dictionary<Point, List<ManagedChunkedComponent<T>>>();
//
// static ManagedChunkedComponent()
// {
// Dbg.onBeforeDebugDrawing += DrawDebug;
// }
//
// protected static List<ManagedChunkedComponent<T>> GetChunkEntityList(Point key)
// {
// if (chunks_.TryGetValue(key, out List<ManagedChunkedComponent<T>> ol))
// return ol;
// return null;
// }
//
// protected static List<ManagedChunkedComponent<T>> GetChunkEntityListForPos(Vector2 position)
// {
// return GetChunkEntityList(GetChunkKeyForPos(position));
// }
//
// protected static Point GetChunkKeyForPos(Vector2 position)
// {
// return new Point((position.X/CHUNK_SIZE).Settle(), (position.Y/CHUNK_SIZE).Settle());
// }
// public static List<Point> GetChunksInRect(RectF rect)
// {
// // assemble list of unique chunks in rect
// List<Point> chunksInRect = new List<Point>();
//
// for (float rx = rect.X; rx < rect.Right + CHUNK_SIZE; rx += CHUNK_SIZE - 0.1f) //TODO FIXME
// for (float ry = rect.Y; ry < rect.Bottom + CHUNK_SIZE; ry += CHUNK_SIZE - 0.1f)
// {
// Point p = GetChunkKeyForPos(new Vector2(rx, ry));
// if (!chunksInRect.Contains(p))
// chunksInRect.Add(p);
// }
// return chunksInRect;
// }
//
// public static List<ManagedChunkedComponent<T>> GetComponentsInRect(RectF rect)
// {
// List<Point> chunksToCheck = GetChunksInRect(rect);
// List<ManagedChunkedComponent<T>> retList = new List<ManagedChunkedComponent<T>>();
// foreach (Point chunkPos in chunksToCheck)
// {
// if (chunks_.ContainsKey(chunkPos) && chunks_[chunkPos] != null)
// foreach (ManagedChunkedComponent<T> component in chunks_[chunkPos])
// if(rect.Contains(component.entity.Position))
// retList.Add(component);
//
// }
// return retList;
// }
//
// public static List<ManagedChunkedComponent<T>> GetAllComponents()
// {
// List<ManagedChunkedComponent<T>> retList = new List<ManagedChunkedComponent<T>>();
// foreach (KeyValuePair<Point, List<ManagedChunkedComponent<T>>> pair in chunks_)
// {
// retList.AddRange(pair.Value);
// }
// return retList;
// }
//
//
// protected ManagedChunkedComponent(Entity entity) : base(entity)
// {
// UpdateChunk();
// }
//
// private Point currentChunkPos_ = new Point(Int32.MaxValue, Int32.MaxValue);
// protected void UpdateChunk()
// {
// Point newChunkPos = GetChunkKeyForPos(entity.Position);
//
// // if we didn't change chunk, do nothing
// if (newChunkPos == currentChunkPos_)
// return;
//
// //Debug.WriteLine($"changing obj from {currentChunkPos_} to {newChunkPos}");
//
// TryRemoveFromCurrentChunk();
//
// // add to new chunk
// if (!chunks_.ContainsKey(newChunkPos))
// {
// //Debug.WriteLine($"creating new chunk for item at: {currentChunkPos_}");
// chunks_[newChunkPos] = new List<ManagedChunkedComponent<T>>(); // creates new if doesn't exist
// }
//
// chunks_[newChunkPos].Add(this); // adds obj to chunk at new position
//
// // store current chunk
// currentChunkPos_ = newChunkPos;
// }
//
// protected void TryRemoveFromCurrentChunk()
// {
// // cleaning up previous chunk stuff
// if (chunks_.ContainsKey(currentChunkPos_)) //if chunk at previous position exists
// {
// if (chunks_[currentChunkPos_] != null) //if list is ok
// {
// chunks_[currentChunkPos_].Remove(this); // remove from previous chunk
//
// if (chunks_[currentChunkPos_].Count == 0) //clean up if empty
// {
// //Debug.WriteLine($"deleting chunk with no items: {currentChunkPos_}");
// chunks_.Remove(currentChunkPos_);
// }
// }
// }
// }
//
// public override void EntityChanged()
// {
// base.EntityChanged();
// UpdateChunk();
// }
//
// public override void FinalizeComponent()
// {
// TryRemoveFromCurrentChunk();
// base.FinalizeComponent();
// }
//
//
// //debug
// protected static Color debugColor = Color.White;
// private static void DrawDebug()
// {
// foreach (KeyValuePair<Point, List<ManagedChunkedComponent<T>>> chunk in chunks_)
// {
// var pos = chunk.Key;
// var comp = chunk.Value;
//
// //draw region square
// var regionRect = new Rectangle(pos.X*CHUNK_SIZE, pos.Y*CHUNK_SIZE, CHUNK_SIZE, CHUNK_SIZE);
// Dbg.AddDebugRect(regionRect, debugColor, Randy.NextFloat(0.25f));
//
// Dbg.AddDebugText(comp.Count.ToString(), regionRect.Location.ToVector2(), debugColor);
//
// for (var index = 0; index < comp.Count; index++)
// {
// ManagedChunkedComponent<T> component = comp[index];
// //DebugHelper.AddDebugText(index.ToString(), component.entity.Position, debugColor);
// }
// }
// }
//}
| |
using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using Frapid.ApplicationState.Cache;
using Frapid.ApplicationState.CacheFactory;
using Frapid.Framework.Extensions;
using Frapid.i18n;
using Frapid.Reports.Engine.Model;
namespace Frapid.Reports.Helpers
{
public static class ExpressionHelper
{
public static string ParseDataSource(string expression, List<DataSource> dataSources)
{
if (string.IsNullOrWhiteSpace(expression))
{
return null;
}
if (dataSources == null)
{
return null;
}
foreach (var match in Regex.Matches(expression, "{.*?}"))
{
string word = match.ToString();
if (word.StartsWith("{DataSource", StringComparison.OrdinalIgnoreCase))
{
int index = word.Split('.').First().Replace("{DataSource[", "").Replace("]", "").To<int>();
string column = word.Split('.').Last().Replace("}", "");
var dataSource = dataSources.FirstOrDefault(x => x.Index.Equals(index));
if (dataSource?.Data?.Rows.Count > 0)
{
if (dataSource.Data.Columns.Contains(column))
{
string value = FormattingHelper.GetFormattedValue(dataSource.Data.Rows[0][column]);
expression = expression.Replace(word, value);
}
}
else
{
expression = expression.Replace(word, string.Empty);
}
}
}
return expression;
}
private static string GetDictionaryValue(string tenant, string key)
{
string globalLoginId = HttpContext.Current.User.Identity.Name;
if (!string.IsNullOrWhiteSpace(globalLoginId))
{
string cacheKey = tenant + "/dictionary/" + globalLoginId;
var cache = new DefaultCacheFactory();
var dictionary = cache.Get<Dictionary<string, object>>(cacheKey);
if (dictionary != null && dictionary.ContainsKey(key))
{
var value = dictionary?[key];
if (value != null)
{
return value.ToString();
}
}
}
return string.Empty;
}
private static string GetLogo()
{
return AppUsers.GetCurrent().Logo.Or("/Static/images/logo-sm.png");
}
public static string GetCurrentDomainName()
{
if (HttpContext.Current == null)
{
return string.Empty;
}
string url = HttpContext.Current.Request.Url.Scheme + "://" + HttpContext.Current.Request.Url.Host;
if (HttpContext.Current.Request.Url.Port != 80)
{
url += ":" + HttpContext.Current.Request.Url.Port.ToString(CultureInfo.InvariantCulture);
}
return url;
}
public static string ParseExpression(string tenant, string expression, List<DataSource> dataSources, ParameterInfo info)
{
if (string.IsNullOrWhiteSpace(expression))
{
return string.Empty;
}
string logo = GetLogo();
if (!string.IsNullOrWhiteSpace(logo))
{
//Or else logo will not be exported into excel.
expression = expression.Replace("{LogoPath}", GetCurrentDomainName() + VirtualPathUtility.ToAbsolute(logo));
}
expression = expression.Replace("{PrintDate}", DateTime.Now.ToString(CultureManager.GetCurrentUiCulture()));
foreach (var match in Regex.Matches(expression, "{.*?}"))
{
string word = match.ToString();
if (word.StartsWith("{Meta.", StringComparison.OrdinalIgnoreCase))
{
string sessionKey = RemoveBraces(word);
sessionKey = sessionKey.Replace("Meta.", "");
sessionKey = sessionKey.Trim();
string value = GetDictionaryValue(tenant, sessionKey);
expression = expression.Replace(word, value);
}
else if (word.StartsWith("{Query.", StringComparison.OrdinalIgnoreCase))
{
string res = RemoveBraces(word);
var resource = res.Split('.');
string key = resource[1];
var parameter = info.Parameters.FirstOrDefault(x => x.Name.ToLower().Equals(key.ToLower()));
if (parameter != null)
{
string value = FormattingHelper.GetFormattedValue(parameter.Value);
var datasourceParameter = info.DataSourceParameters.FirstOrDefault(x => x.Name.Replace("@", "").ToLower().Equals(parameter.Name.ToLower()));
if (datasourceParameter != null)
{
string type = datasourceParameter.Type;
value = DataSourceParameterHelper.CastValue(value, type).ToString();
}
expression = expression.Replace(word, value);
}
}
else if (word.StartsWith("{i18n.", StringComparison.OrdinalIgnoreCase))
{
string res = RemoveBraces(word);
var resource = res.Split('.');
string key = resource[1];
expression = expression.Replace(word, LocalizationHelper.Localize(key, false));
}
else if (word.StartsWith("{DataSource", StringComparison.OrdinalIgnoreCase) && word.ToLower(CultureInfo.InvariantCulture).Contains("runningtotalfieldvalue"))
{
if (dataSources == null)
{
return null;
}
string res = RemoveBraces(word);
var resource = res.Split('.');
int dataSourceIndex = resource[0].ToLower(CultureInfo.InvariantCulture)
.Replace("datasource", "")
.Replace("[", "")
.Replace("]", "").To<int>();
int index = resource[1].ToLower(CultureInfo.InvariantCulture)
.Replace("runningtotalfieldvalue", "")
.Replace("[", "")
.Replace("]", "").To<int>();
if (dataSourceIndex >= 0 && index >= 0)
{
var dataSource = dataSources.FirstOrDefault(x => x.Index.Equals(dataSourceIndex));
if (dataSource?.Data != null)
{
expression = expression.Replace(word,
GetSum(dataSource.Data, index)
.ToString(CultureInfo.InvariantCulture));
}
}
}
//else if (word.StartsWith("{Barcode", StringComparison.OrdinalIgnoreCase))
//{
//string res = RemoveBraces(word).Replace("Barcode(", "").Replace(")", "");
//string barCodeValue = res;
// if (res.StartsWith("DataSource"))
// {
// barCodeValue = ParseDataSource("{" + res + "}", dataTableCollection);
// }
// string barCodeFormat = ConfigurationHelper.GetReportParameter("BarCodeFormat");
// string barCodeDisplayValue = ConfigurationHelper.GetReportParameter("BarCodeDisplayValue");
// string barCodeFontSize = ConfigurationHelper.GetReportParameter("BarCodeFontSize");
// string barCodeWidth = ConfigurationHelper.GetReportParameter("BarCodeWidth");
// string barCodeHeight = ConfigurationHelper.GetReportParameter("BarCodeHeight");
// string barCodeQuite = ConfigurationHelper.GetReportParameter("BarCodeQuite");
// string barCodeFont = ConfigurationHelper.GetReportParameter("BarCodeFont");
// string barCodeTextAlign = ConfigurationHelper.GetReportParameter("BarCodeTextAlign");
// string barCodeBackgroundColor = ConfigurationHelper.GetReportParameter("BarCodeBackgroundColor");
// string barCodeLineColor = ConfigurationHelper.GetReportParameter("BarCodeLineColor");
// string imageSource =
// "<img class='reportEngineBarCode' data-barcodevalue='{0}' alt='{0}' value='{0}' data-barcodeformat='{1}' data-barcodedisplayvalue='{2}' data-barcodefontsize='{3}' data-barcodewidth='{4}' data-barcodeheight='{5}' data-barcodefont='{6}' data-barcodetextalign='{7}' data-barcodebackgroundcolor='{8}' data-barcodelinecolor='{9}' data-barcodequite={10} />";
// imageSource = string.Format(CultureInfo.InvariantCulture, imageSource, barCodeValue,
// barCodeFormat, barCodeDisplayValue, barCodeFontSize, barCodeWidth, barCodeHeight,
// barCodeFont, barCodeTextAlign, barCodeBackgroundColor, barCodeLineColor, barCodeQuite);
// expression = expression.Replace(word, imageSource).ToString(CultureInfo.InvariantCulture);
//}
//else if (word.StartsWith("{QRCode", StringComparison.OrdinalIgnoreCase))
//{
// string res = RemoveBraces(word).Replace("QRCode(", "").Replace(")", "");
// string qrCodeValue = res;
// if (res.StartsWith("DataSource"))
// {
// qrCodeValue = ParseDataSource("{" + res + "}", dataTableCollection);
// }
// string qrCodeRender = ConfigurationHelper.GetReportParameter("QRCodeRender");
// string qrCodeBackgroundColor = ConfigurationHelper.GetReportParameter("QRCodeBackgroundColor");
// string qrCodeForegroundColor = ConfigurationHelper.GetReportParameter("QRCodeForegroundColor");
// string qrCodeWidth = ConfigurationHelper.GetReportParameter("QRCodeWidth");
// string qrCodeHeight = ConfigurationHelper.GetReportParameter("QRCodeHeight");
// string qrCodeTypeNumber = ConfigurationHelper.GetReportParameter("QRCodeTypeNumber");
// string qrCodeDiv =
// "<div class='reportEngineQRCode' data-qrcodevalue={0} data-qrcoderender='{1}' data-qrcodebackgroundcolor='{2}' data-qrcodeforegroundcolor='{3}' data-qrcodewidth='{4}' data-qrcodeheight='{5}' data-qrcodetypenumber='{6}'></div>";
// qrCodeDiv = string.Format(CultureInfo.InvariantCulture, qrCodeDiv, qrCodeValue, qrCodeRender,
// qrCodeBackgroundColor, qrCodeForegroundColor, qrCodeWidth, qrCodeHeight, qrCodeTypeNumber);
// expression = expression.Replace(word, qrCodeDiv).ToString(CultureInfo.InvariantCulture);
//
//}
}
return expression;
}
public static string RemoveBraces(string expression)
{
if (string.IsNullOrWhiteSpace(expression))
{
return string.Empty;
}
return expression.Replace("{", "").Replace("}", "");
}
public static decimal GetSum(DataTable table, int index)
{
if (table != null && table.Rows.Count > 0)
{
string expression = "SUM(" + table.Columns[index].ColumnName + ")";
return table.Compute(expression, "").To<decimal>();
}
return 0;
}
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Data.dll
// Description: The data access libraries for the DotSpatial project.
//
// ********************************************************************************************************
//
// The Original Code is DotSpatial
//
// The Initial Developer of this Original Code is Ted Dunsford. Created in January, 2008.
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
//
// ********************************************************************************************************
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using GeoAPI.Geometries;
namespace DotSpatial.Data
{
/// <summary>
/// A shapefile class that handles the special case where the data type is point
/// </summary>
public class PointShapefile : Shapefile
{
/// <summary>
/// Creates a new instance of a PointShapefile for in-ram handling only.
/// </summary>
public PointShapefile()
: base(FeatureType.Point)
{
Attributes = new AttributeTable();
Header = new ShapefileHeader { FileLength = 100, ShapeType = ShapeType.Point };
}
/// <summary>
/// Creates a new instance of a PointShapefile that is loaded from the supplied fileName.
/// </summary>
/// <param name="fileName">The string fileName of the polygon shapefile to load</param>
public PointShapefile(string fileName)
: this()
{
Open(fileName, null);
}
/// <summary>
/// Opens a shapefile
/// </summary>
/// <param name="fileName">The string fileName of the point shapefile to load</param>
/// <param name="progressHandler">Any valid implementation of the DotSpatial.Data.IProgressHandler</param>
public void Open(string fileName, IProgressHandler progressHandler)
{
if (!File.Exists(fileName)) return;
Filename = fileName;
IndexMode = true;
Header = new ShapefileHeader(Filename);
switch (Header.ShapeType)
{
case ShapeType.PointM:
CoordinateType = CoordinateType.M;
break;
case ShapeType.PointZ:
CoordinateType = CoordinateType.Z;
break;
default:
CoordinateType = CoordinateType.Regular;
break;
}
Extent = Header.ToExtent();
Name = Path.GetFileNameWithoutExtension(fileName);
Attributes.Open(Filename);
FillPoints(Filename, progressHandler);
ReadProjection();
}
/// <summary>
/// Obtains a typed list of ShapefilePoint structures with double values associated with the various coordinates.
/// </summary>
/// <param name="fileName">A string fileName</param>
/// <param name="progressHandler">Progress handler</param>
private void FillPoints(string fileName, IProgressHandler progressHandler)
{
// Check to ensure the fileName is not null
if (fileName == null)
{
throw new NullReferenceException(DataStrings.ArgumentNull_S.Replace("%S", "fileName"));
}
if (File.Exists(fileName) == false)
{
throw new FileNotFoundException(DataStrings.FileNotFound_S.Replace("%S", fileName));
}
// Get the basic header information.
var header = Header;
// Check to ensure that the fileName is the correct shape type
if (header.ShapeType != ShapeType.Point && header.ShapeType != ShapeType.PointM && header.ShapeType != ShapeType.PointZ)
{
throw new ApplicationException(DataStrings.FileNotPoints_S.Replace("%S", fileName));
}
if (new FileInfo(fileName).Length == 100)
{
// the file is empty so we are done reading
return;
}
// Reading the headers gives us an easier way to track the number of shapes and their overall length etc.
List<ShapeHeader> shapeHeaders = ReadIndexFile(fileName);
var numShapes = shapeHeaders.Count;
double[] m = null;
double[] z = null;
var vert = new double[2 * numShapes]; // X,Y
if (header.ShapeType == ShapeType.PointM || header.ShapeType == ShapeType.PointZ)
{
m = new double[numShapes];
}
if (header.ShapeType == ShapeType.PointZ)
{
z = new double[numShapes];
}
var progressMeter = new ProgressMeter(progressHandler, "Reading from " + Path.GetFileName(fileName))
{
StepPercent = 5
};
using (var reader = new FileStream(fileName, FileMode.Open, FileAccess.Read))
{
for (var shp = 0; shp < numShapes; shp++)
{
progressMeter.CurrentPercent = (int)(shp * 100.0 / numShapes);
reader.Seek(shapeHeaders[shp].ByteOffset, SeekOrigin.Begin);
var recordNumber = reader.ReadInt32(Endian.BigEndian);
Debug.Assert(recordNumber == shp + 1);
var contentLen = reader.ReadInt32(Endian.BigEndian);
Debug.Assert(contentLen == shapeHeaders[shp].ContentLength);
var shapeType = (ShapeType)reader.ReadInt32();
if (shapeType == ShapeType.NullShape)
{
if (m != null)
{
m[shp] = double.MinValue;
}
goto fin;
}
// Read X
var ind = 4;
vert[shp * 2] = reader.ReadDouble();
ind += 8;
// Read Y
vert[shp * 2 + 1] = reader.ReadDouble();
ind += 8;
// Read Z
if (z != null)
{
z[shp] = reader.ReadDouble();
ind += 8;
}
// Read M
if (m != null)
{
if (shapeHeaders[shp].ByteLength <= ind)
{
m[shp] = double.MinValue;
}
else
{
m[shp] = reader.ReadDouble();
ind += 8;
}
}
fin:
var shape = new ShapeRange(FeatureType.Point)
{
RecordNumber = recordNumber,
StartIndex = shp,
ContentLength = shapeHeaders[shp].ContentLength,
NumPoints = 1,
NumParts = 1
};
ShapeIndices.Add(shape);
var part = new PartRange(vert, shp, 0, FeatureType.Point) { NumVertices = 1 };
shape.Parts.Add(part);
shape.Extent = new Extent(new[] { vert[shp * 2], vert[shp * 2 + 1], vert[shp * 2], vert[shp * 2 + 1] });
}
}
Vertex = vert;
M = m;
Z = z;
progressMeter.Reset();
}
/// <inheritdoc />
public override IFeature GetFeature(int index)
{
IFeature f;
if (!IndexMode)
{
f = Features[index];
}
else
{
f = GetPoint(index);
f.DataRow = AttributesPopulated ? DataTable.Rows[index] : Attributes.SupplyPageOfData(index, 1).Rows[0];
}
return f;
}
/// <summary>
/// Saves the shapefile to a different fileName, but still as a shapefile. This method does not support saving to
/// any other file format.
/// </summary>
/// <param name="fileName">The string fileName to save as</param>
/// <param name="overwrite">A boolean that is true if the file should be overwritten</param>
public override void SaveAs(string fileName, bool overwrite)
{
EnsureValidFileToSave(fileName, overwrite);
Filename = fileName;
// Set Header.ShapeType before setting extent.
// wordSize is the length of the byte representation in 16 bit words of a single shape, including header.
int wordSize = 14; // 3 int(2) and 2 double(4)
if (CoordinateType == CoordinateType.Regular)
{
Header.ShapeType = ShapeType.Point;
}
if (CoordinateType == CoordinateType.M)
{
Header.ShapeType = ShapeType.PointM;
wordSize = 18; // 3 int(2), 3 double(4)
}
if (CoordinateType == CoordinateType.Z)
{
Header.ShapeType = ShapeType.PointZ;
wordSize = 22; // 3 int(2), 4 double (4)
}
InvalidateEnvelope();
Header.SetExtent(Extent);
if (IndexMode)
{
Header.ShxLength = ShapeIndices.Count * 4 + 50;
Header.FileLength = ShapeIndices.Count * wordSize + 50;
}
else
{
Header.ShxLength = Features.Count * 4 + 50;
Header.FileLength = Features.Count * wordSize + 50;
}
Header.SaveAs(Filename);
var shpStream = new FileStream(Filename, FileMode.Append, FileAccess.Write, FileShare.None, 1000000);
var shxStream = new FileStream(Header.ShxFilename, FileMode.Append, FileAccess.Write, FileShare.None, 1000000);
// Special slightly faster writing for index mode
if (IndexMode)
{
for (int shp = 0; shp < ShapeIndices.Count; shp++)
{
shpStream.WriteBe(shp + 1);
shpStream.WriteBe(wordSize - 4); // shape word size without 4 shapeHeader words.
shxStream.WriteBe(50 + shp * wordSize);
shxStream.WriteBe(wordSize - 4);
shpStream.WriteLe((int)Header.ShapeType);
shpStream.WriteLe(Vertex[shp * 2]);
shpStream.WriteLe(Vertex[shp * 2 + 1]);
if (Z != null) shpStream.WriteLe(Z[shp]);
if (M != null) shpStream.WriteLe(M[shp]);
}
}
else
{
int fid = 0;
foreach (IFeature f in Features)
{
Coordinate c = f.Geometry.Coordinates[0];
shpStream.WriteBe(fid + 1);
shpStream.WriteBe(wordSize - 4);
shxStream.WriteBe(50 + fid * wordSize);
shxStream.WriteBe(wordSize - 4);
shpStream.WriteLe((int)Header.ShapeType);
if (Header.ShapeType == ShapeType.NullShape)
{
continue;
}
shpStream.WriteLe(c.X);
shpStream.WriteLe(c.Y);
if (Header.ShapeType == ShapeType.PointZ)
{
shpStream.WriteLe(c.Z);
}
if (Header.ShapeType == ShapeType.PointM || Header.ShapeType == ShapeType.PointZ)
{
shpStream.WriteLe(c.M);
}
fid++;
}
}
shpStream.Close();
shxStream.Close();
UpdateAttributes();
SaveProjection();
}
}
}
| |
/*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using ReaderException = com.google.zxing.ReaderException;
using BitMatrix = com.google.zxing.common.BitMatrix;
namespace com.google.zxing.qrcode.decoder
{
/// <author> Sean Owen
/// </author>
/// <author>www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source
/// </author>
sealed class BitMatrixParser
{
//UPGRADE_NOTE: Final was removed from the declaration of 'bitMatrix '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
private BitMatrix bitMatrix;
private Version parsedVersion;
private FormatInformation parsedFormatInfo;
/// <param name="bitMatrix">{@link BitMatrix} to parse
/// </param>
/// <throws> ReaderException if dimension is not >= 21 and 1 mod 4 </throws>
internal BitMatrixParser(BitMatrix bitMatrix)
{
int dimension = bitMatrix.Dimension;
if (dimension < 21 || (dimension & 0x03) != 1)
{
throw ReaderException.Instance;
}
this.bitMatrix = bitMatrix;
}
/// <summary> <p>Reads format information from one of its two locations within the QR Code.</p>
///
/// </summary>
/// <returns> {@link FormatInformation} encapsulating the QR Code's format info
/// </returns>
/// <throws> ReaderException if both format information locations cannot be parsed as </throws>
/// <summary> the valid encoding of format information
/// </summary>
internal FormatInformation readFormatInformation()
{
if (parsedFormatInfo != null)
{
return parsedFormatInfo;
}
// Read top-left format info bits
int formatInfoBits = 0;
for (int i = 0; i < 6; i++)
{
formatInfoBits = copyBit(i, 8, formatInfoBits);
}
// .. and skip a bit in the timing pattern ...
formatInfoBits = copyBit(7, 8, formatInfoBits);
formatInfoBits = copyBit(8, 8, formatInfoBits);
formatInfoBits = copyBit(8, 7, formatInfoBits);
// .. and skip a bit in the timing pattern ...
for (int j = 5; j >= 0; j--)
{
formatInfoBits = copyBit(8, j, formatInfoBits);
}
parsedFormatInfo = FormatInformation.decodeFormatInformation(formatInfoBits);
if (parsedFormatInfo != null)
{
return parsedFormatInfo;
}
// Hmm, failed. Try the top-right/bottom-left pattern
int dimension = bitMatrix.Dimension;
formatInfoBits = 0;
int iMin = dimension - 8;
for (int i = dimension - 1; i >= iMin; i--)
{
formatInfoBits = copyBit(i, 8, formatInfoBits);
}
for (int j = dimension - 7; j < dimension; j++)
{
formatInfoBits = copyBit(8, j, formatInfoBits);
}
parsedFormatInfo = FormatInformation.decodeFormatInformation(formatInfoBits);
if (parsedFormatInfo != null)
{
return parsedFormatInfo;
}
throw ReaderException.Instance;
}
/// <summary> <p>Reads version information from one of its two locations within the QR Code.</p>
///
/// </summary>
/// <returns> {@link Version} encapsulating the QR Code's version
/// </returns>
/// <throws> ReaderException if both version information locations cannot be parsed as </throws>
/// <summary> the valid encoding of version information
/// </summary>
internal Version readVersion()
{
if (parsedVersion != null)
{
return parsedVersion;
}
int dimension = bitMatrix.Dimension;
int provisionalVersion = (dimension - 17) >> 2;
if (provisionalVersion <= 6)
{
return Version.getVersionForNumber(provisionalVersion);
}
// Read top-right version info: 3 wide by 6 tall
int versionBits = 0;
int ijMin = dimension - 11;
for (int j = 5; j >= 0; j--)
{
for (int i = dimension - 9; i >= ijMin; i--)
{
versionBits = copyBit(i, j, versionBits);
}
}
parsedVersion = Version.decodeVersionInformation(versionBits);
if (parsedVersion != null && parsedVersion.DimensionForVersion == dimension)
{
return parsedVersion;
}
// Hmm, failed. Try bottom left: 6 wide by 3 tall
versionBits = 0;
for (int i = 5; i >= 0; i--)
{
for (int j = dimension - 9; j >= ijMin; j--)
{
versionBits = copyBit(i, j, versionBits);
}
}
parsedVersion = Version.decodeVersionInformation(versionBits);
if (parsedVersion != null && parsedVersion.DimensionForVersion == dimension)
{
return parsedVersion;
}
throw ReaderException.Instance;
}
private int copyBit(int i, int j, int versionBits)
{
return bitMatrix.get_Renamed(i, j)?(versionBits << 1) | 0x1:versionBits << 1;
}
/// <summary> <p>Reads the bits in the {@link BitMatrix} representing the finder pattern in the
/// correct order in order to reconstitute the codewords bytes contained within the
/// QR Code.</p>
///
/// </summary>
/// <returns> bytes encoded within the QR Code
/// </returns>
/// <throws> ReaderException if the exact number of bytes expected is not read </throws>
internal sbyte[] readCodewords()
{
FormatInformation formatInfo = readFormatInformation();
Version version = readVersion();
// Get the data mask for the format used in this QR Code. This will exclude
// some bits from reading as we wind through the bit matrix.
DataMask dataMask = DataMask.forReference((int) formatInfo.DataMask);
int dimension = bitMatrix.Dimension;
dataMask.unmaskBitMatrix(bitMatrix, dimension);
BitMatrix functionPattern = version.buildFunctionPattern();
bool readingUp = true;
sbyte[] result = new sbyte[version.TotalCodewords];
int resultOffset = 0;
int currentByte = 0;
int bitsRead = 0;
// Read columns in pairs, from right to left
for (int j = dimension - 1; j > 0; j -= 2)
{
if (j == 6)
{
// Skip whole column with vertical alignment pattern;
// saves time and makes the other code proceed more cleanly
j--;
}
// Read alternatingly from bottom to top then top to bottom
for (int count = 0; count < dimension; count++)
{
int i = readingUp?dimension - 1 - count:count;
for (int col = 0; col < 2; col++)
{
// Ignore bits covered by the function pattern
if (!functionPattern.get_Renamed(j - col, i))
{
// Read a bit
bitsRead++;
currentByte <<= 1;
if (bitMatrix.get_Renamed(j - col, i))
{
currentByte |= 1;
}
// If we've made a whole byte, save it off
if (bitsRead == 8)
{
result[resultOffset++] = (sbyte) currentByte;
bitsRead = 0;
currentByte = 0;
}
}
}
}
readingUp ^= true; // readingUp = !readingUp; // switch directions
}
if (resultOffset != version.TotalCodewords)
{
throw ReaderException.Instance;
}
return result;
}
}
}
| |
// 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.Diagnostics;
using System.Net.Security;
using System.Runtime.InteropServices;
using System.Security.Authentication;
using System.Security.Authentication.ExtendedProtection;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using Microsoft.Win32.SafeHandles;
internal static partial class Interop
{
internal static partial class OpenSsl
{
private static Ssl.SslCtxSetVerifyCallback s_verifyClientCertificate = VerifyClientCertificate;
#region internal methods
internal static SafeChannelBindingHandle QueryChannelBinding(SafeSslHandle context, ChannelBindingKind bindingType)
{
SafeChannelBindingHandle bindingHandle;
switch (bindingType)
{
case ChannelBindingKind.Endpoint:
bindingHandle = new SafeChannelBindingHandle(bindingType);
QueryEndPointChannelBinding(context, bindingHandle);
break;
case ChannelBindingKind.Unique:
bindingHandle = new SafeChannelBindingHandle(bindingType);
QueryUniqueChannelBinding(context, bindingHandle);
break;
default:
// Keeping parity with windows, we should return null in this case.
bindingHandle = null;
break;
}
return bindingHandle;
}
internal static SafeSslHandle AllocateSslContext(SslProtocols protocols, SafeX509Handle certHandle, SafeEvpPKeyHandle certKeyHandle, EncryptionPolicy policy, bool isServer, bool remoteCertRequired)
{
SafeSslHandle context = null;
IntPtr method = GetSslMethod(protocols);
using (SafeSslContextHandle innerContext = Ssl.SslCtxCreate(method))
{
if (innerContext.IsInvalid)
{
throw CreateSslException(SR.net_allocate_ssl_context_failed);
}
Ssl.SetProtocolOptions(innerContext, protocols);
Ssl.SslCtxSetQuietShutdown(innerContext);
Ssl.SetEncryptionPolicy(innerContext, policy);
if (certHandle != null && certKeyHandle != null)
{
SetSslCertificate(innerContext, certHandle, certKeyHandle);
}
if (remoteCertRequired)
{
Debug.Assert(isServer, "isServer flag should be true");
Ssl.SslCtxSetVerify(innerContext,
s_verifyClientCertificate);
//update the client CA list
UpdateCAListFromRootStore(innerContext);
}
context = SafeSslHandle.Create(innerContext, isServer);
Debug.Assert(context != null, "Expected non-null return value from SafeSslHandle.Create");
if (context.IsInvalid)
{
context.Dispose();
throw CreateSslException(SR.net_allocate_ssl_context_failed);
}
}
return context;
}
internal static bool DoSslHandshake(SafeSslHandle context, byte[] recvBuf, int recvOffset, int recvCount, out byte[] sendBuf, out int sendCount)
{
sendBuf = null;
sendCount = 0;
if ((recvBuf != null) && (recvCount > 0))
{
BioWrite(context.InputBio, recvBuf, recvOffset, recvCount);
}
Ssl.SslErrorCode error;
int retVal = Ssl.SslDoHandshake(context);
if (retVal != 1)
{
error = GetSslError(context, retVal);
if ((retVal != -1) || (error != Ssl.SslErrorCode.SSL_ERROR_WANT_READ))
{
throw CreateSslException(context, SR.net_ssl_handshake_failed_error, retVal);
}
}
sendCount = Crypto.BioCtrlPending(context.OutputBio);
if (sendCount > 0)
{
sendBuf = new byte[sendCount];
try
{
sendCount = BioRead(context.OutputBio, sendBuf, sendCount);
}
finally
{
if (sendCount <= 0)
{
sendBuf = null;
sendCount = 0;
}
}
}
bool stateOk = Ssl.IsSslStateOK(context);
if (stateOk)
{
context.MarkHandshakeCompleted();
}
return stateOk;
}
internal static int Encrypt(SafeSslHandle context, byte[] buffer, int offset, int count, out Ssl.SslErrorCode errorCode)
{
Debug.Assert(buffer != null);
Debug.Assert(offset >= 0);
Debug.Assert(count >= 0);
Debug.Assert(buffer.Length >= offset + count);
errorCode = Ssl.SslErrorCode.SSL_ERROR_NONE;
int retVal;
unsafe
{
fixed (byte* fixedBuffer = buffer)
{
retVal = Ssl.SslWrite(context, fixedBuffer + offset, count);
}
}
if (retVal != count)
{
errorCode = GetSslError(context, retVal);
retVal = 0;
switch (errorCode)
{
// indicate end-of-file
case Ssl.SslErrorCode.SSL_ERROR_ZERO_RETURN:
case Ssl.SslErrorCode.SSL_ERROR_WANT_READ:
break;
default:
throw CreateSslException(SR.net_ssl_encrypt_failed, errorCode);
}
}
else
{
int capacityNeeded = Crypto.BioCtrlPending(context.OutputBio);
Debug.Assert(buffer.Length >= capacityNeeded, "Input buffer of size " + buffer.Length +
" bytes is insufficient since encryption needs " + capacityNeeded + " bytes.");
retVal = BioRead(context.OutputBio, buffer, capacityNeeded);
}
return retVal;
}
internal static int Decrypt(SafeSslHandle context, byte[] outBuffer, int count, out Ssl.SslErrorCode errorCode)
{
errorCode = Ssl.SslErrorCode.SSL_ERROR_NONE;
int retVal = BioWrite(context.InputBio, outBuffer, 0, count);
if (retVal == count)
{
retVal = Ssl.SslRead(context, outBuffer, retVal);
if (retVal > 0)
{
count = retVal;
}
}
if (retVal != count)
{
errorCode = GetSslError(context, retVal);
retVal = 0;
switch (errorCode)
{
// indicate end-of-file
case Ssl.SslErrorCode.SSL_ERROR_ZERO_RETURN:
break;
case Ssl.SslErrorCode.SSL_ERROR_WANT_READ:
// update error code to renegotiate if renegotiate is pending, otherwise make it SSL_ERROR_WANT_READ
errorCode = Ssl.IsSslRenegotiatePending(context) ?
Ssl.SslErrorCode.SSL_ERROR_RENEGOTIATE :
Ssl.SslErrorCode.SSL_ERROR_WANT_READ;
break;
default:
throw CreateSslException(SR.net_ssl_decrypt_failed, errorCode);
}
}
return retVal;
}
internal static SafeX509Handle GetPeerCertificate(SafeSslHandle context)
{
return Ssl.SslGetPeerCertificate(context);
}
internal static SafeSharedX509StackHandle GetPeerCertificateChain(SafeSslHandle context)
{
return Ssl.SslGetPeerCertChain(context);
}
#endregion
#region private methods
private static void QueryEndPointChannelBinding(SafeSslHandle context, SafeChannelBindingHandle bindingHandle)
{
using (SafeX509Handle certSafeHandle = GetPeerCertificate(context))
{
if (certSafeHandle == null || certSafeHandle.IsInvalid)
{
throw CreateSslException(SR.net_ssl_invalid_certificate);
}
bool gotReference = false;
try
{
certSafeHandle.DangerousAddRef(ref gotReference);
using (X509Certificate2 cert = new X509Certificate2(certSafeHandle.DangerousGetHandle()))
using (HashAlgorithm hashAlgo = GetHashForChannelBinding(cert))
{
byte[] bindingHash = hashAlgo.ComputeHash(cert.RawData);
bindingHandle.SetCertHash(bindingHash);
}
}
finally
{
if (gotReference)
{
certSafeHandle.DangerousRelease();
}
}
}
}
private static void QueryUniqueChannelBinding(SafeSslHandle context, SafeChannelBindingHandle bindingHandle)
{
bool sessionReused = Ssl.SslSessionReused(context);
int certHashLength = context.IsServer ^ sessionReused ?
Ssl.SslGetPeerFinished(context, bindingHandle.CertHashPtr, bindingHandle.Length) :
Ssl.SslGetFinished(context, bindingHandle.CertHashPtr, bindingHandle.Length);
if (0 == certHashLength)
{
throw CreateSslException(SR.net_ssl_get_channel_binding_token_failed);
}
bindingHandle.SetCertHashLength(certHashLength);
}
private static IntPtr GetSslMethod(SslProtocols protocols)
{
Debug.Assert(protocols != SslProtocols.None, "All protocols are disabled");
bool ssl2 = (protocols & SslProtocols.Ssl2) == SslProtocols.Ssl2;
bool ssl3 = (protocols & SslProtocols.Ssl3) == SslProtocols.Ssl3;
bool tls10 = (protocols & SslProtocols.Tls) == SslProtocols.Tls;
bool tls11 = (protocols & SslProtocols.Tls11) == SslProtocols.Tls11;
bool tls12 = (protocols & SslProtocols.Tls12) == SslProtocols.Tls12;
IntPtr method = Ssl.SslMethods.SSLv23_method; // default
string methodName = "SSLv23_method";
if (!ssl2)
{
if (!ssl3)
{
if (!tls11 && !tls12)
{
method = Ssl.SslMethods.TLSv1_method;
methodName = "TLSv1_method";
}
else if (!tls10 && !tls12)
{
method = Ssl.SslMethods.TLSv1_1_method;
methodName = "TLSv1_1_method";
}
else if (!tls10 && !tls11)
{
method = Ssl.SslMethods.TLSv1_2_method;
methodName = "TLSv1_2_method";
}
}
else if (!tls10 && !tls11 && !tls12)
{
method = Ssl.SslMethods.SSLv3_method;
methodName = "SSLv3_method";
}
}
if (IntPtr.Zero == method)
{
throw new SslException(SR.Format(SR.net_get_ssl_method_failed, methodName));
}
return method;
}
private static int VerifyClientCertificate(int preverify_ok, IntPtr x509_ctx_ptr)
{
using (SafeX509StoreCtxHandle storeHandle = new SafeX509StoreCtxHandle(x509_ctx_ptr, false))
{
using (var chain = new X509Chain())
{
chain.ChainPolicy.RevocationMode = X509RevocationMode.Online;
chain.ChainPolicy.RevocationFlag = X509RevocationFlag.ExcludeRoot;
using (SafeX509StackHandle chainStack = Crypto.X509StoreCtxGetChain(storeHandle))
{
if (chainStack.IsInvalid)
{
Debug.Fail("Invalid chain stack handle");
return 0;
}
IntPtr certPtr = Crypto.GetX509StackField(chainStack, 0);
if (IntPtr.Zero == certPtr)
{
return 0;
}
using (X509Certificate2 cert = new X509Certificate2(certPtr))
{
return chain.Build(cert) ? 1 : 0;
}
}
}
}
}
private static void UpdateCAListFromRootStore(SafeSslContextHandle context)
{
using (SafeX509NameStackHandle nameStack = Crypto.NewX509NameStack())
{
//maintaining the HashSet of Certificate's issuer name to keep track of duplicates
HashSet<string> issuerNameHashSet = new HashSet<string>();
//Enumerate Certificates from LocalMachine and CurrentUser root store
AddX509Names(nameStack, StoreLocation.LocalMachine, issuerNameHashSet);
AddX509Names(nameStack, StoreLocation.CurrentUser, issuerNameHashSet);
Ssl.SslCtxSetClientCAList(context, nameStack);
// The handle ownership has been transferred into the CTX.
nameStack.SetHandleAsInvalid();
}
}
private static void AddX509Names(SafeX509NameStackHandle nameStack, StoreLocation storeLocation, HashSet<string> issuerNameHashSet)
{
using (var store = new X509Store(StoreName.Root, storeLocation))
{
store.Open(OpenFlags.ReadOnly);
foreach (var certificate in store.Certificates)
{
//Check if issuer name is already present
//Avoiding duplicate names
if (!issuerNameHashSet.Add(certificate.Issuer))
{
continue;
}
using (SafeX509Handle certHandle = Crypto.X509Duplicate(certificate.Handle))
{
using (SafeX509NameHandle nameHandle = Crypto.DuplicateX509Name(Crypto.X509GetIssuerName(certHandle)))
{
if (Crypto.PushX509NameStackField(nameStack, nameHandle))
{
// The handle ownership has been transferred into the STACK_OF(X509_NAME).
nameHandle.SetHandleAsInvalid();
}
else
{
throw new CryptographicException(SR.net_ssl_x509Name_push_failed_error);
}
}
}
}
}
}
private static int BioRead(SafeBioHandle bio, byte[] buffer, int count)
{
Debug.Assert(buffer != null);
Debug.Assert(count >= 0);
Debug.Assert(buffer.Length >= count);
int bytes = Crypto.BioRead(bio, buffer, count);
if (bytes != count)
{
throw CreateSslException(SR.net_ssl_read_bio_failed_error);
}
return bytes;
}
private static int BioWrite(SafeBioHandle bio, byte[] buffer, int offset, int count)
{
Debug.Assert(buffer != null);
Debug.Assert(offset >= 0);
Debug.Assert(count >= 0);
Debug.Assert(buffer.Length >= offset + count);
int bytes;
unsafe
{
fixed (byte* bufPtr = buffer)
{
bytes = Ssl.BioWrite(bio, bufPtr + offset, count);
}
}
if (bytes != count)
{
throw CreateSslException(SR.net_ssl_write_bio_failed_error);
}
return bytes;
}
private static Ssl.SslErrorCode GetSslError(SafeSslHandle context, int result)
{
Ssl.SslErrorCode retVal = Ssl.SslGetError(context, result);
if (retVal == Ssl.SslErrorCode.SSL_ERROR_SYSCALL)
{
retVal = (Ssl.SslErrorCode)Crypto.ErrGetError();
}
return retVal;
}
private static void SetSslCertificate(SafeSslContextHandle contextPtr, SafeX509Handle certPtr, SafeEvpPKeyHandle keyPtr)
{
Debug.Assert(certPtr != null && !certPtr.IsInvalid, "certPtr != null && !certPtr.IsInvalid");
Debug.Assert(keyPtr != null && !keyPtr.IsInvalid, "keyPtr != null && !keyPtr.IsInvalid");
int retVal = Ssl.SslCtxUseCertificate(contextPtr, certPtr);
if (1 != retVal)
{
throw CreateSslException(SR.net_ssl_use_cert_failed);
}
retVal = Ssl.SslCtxUsePrivateKey(contextPtr, keyPtr);
if (1 != retVal)
{
throw CreateSslException(SR.net_ssl_use_private_key_failed);
}
//check private key
retVal = Ssl.SslCtxCheckPrivateKey(contextPtr);
if (1 != retVal)
{
throw CreateSslException(SR.net_ssl_check_private_key_failed);
}
}
internal static SslException CreateSslException(string message)
{
ulong errorVal = Crypto.ErrGetError();
string msg = SR.Format(message, Marshal.PtrToStringAnsi(Crypto.ErrReasonErrorString(errorVal)));
return new SslException(msg, (int)errorVal);
}
private static SslException CreateSslException(string message, Ssl.SslErrorCode error)
{
string msg = SR.Format(message, error);
switch (error)
{
case Ssl.SslErrorCode.SSL_ERROR_SYSCALL:
return CreateSslException(msg);
case Ssl.SslErrorCode.SSL_ERROR_SSL:
Exception innerEx = Interop.Crypto.CreateOpenSslCryptographicException();
return new SslException(innerEx.Message, innerEx);
default:
return new SslException(msg, error);
}
}
private static SslException CreateSslException(SafeSslHandle context, string message, int error)
{
return CreateSslException(message, Ssl.SslGetError(context, error));
}
#endregion
#region Internal class
internal sealed class SslException : Exception
{
public SslException(string inputMessage)
: base(inputMessage)
{
}
public SslException(string inputMessage, Exception ex)
: base(inputMessage, ex)
{
}
public SslException(string inputMessage, Ssl.SslErrorCode error)
: this(inputMessage, (int)error)
{
}
public SslException(string inputMessage, int error)
: this(inputMessage)
{
HResult = error;
}
public SslException(int error)
: this(SR.Format(SR.net_generic_operation_failed, error))
{
HResult = error;
}
}
#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.
==================================================================== */
using System;
using NUnit.Framework;
using NPOI.HSSF.Extractor;
using TestCases.HSSF;
using System.Text.RegularExpressions;
namespace NPOI.XSSF.Extractor
{
/**
* Tests for {@link XSSFExcelExtractor}
*/
[TestFixture]
public class TestXSSFExcelExtractor
{
private static XSSFExcelExtractor GetExtractor(String sampleName)
{
return new XSSFExcelExtractor(XSSFTestDataSamples.OpenSampleWorkbook(sampleName));
}
/**
* Get text out of the simple file
*/
[Test]
public void TestGetSimpleText()
{
// a very simple file
XSSFExcelExtractor extractor = GetExtractor("sample.xlsx");
String text = extractor.Text;
Assert.IsTrue(text.Length > 0);
// Check sheet names
Assert.IsTrue(text.StartsWith("Sheet1"));
Assert.IsTrue(text.EndsWith("Sheet3\n"));
// Now without, will have text
extractor.SetIncludeSheetNames(false);
text = extractor.Text;
String CHUNK1 =
"Lorem\t111\n" +
"ipsum\t222\n" +
"dolor\t333\n" +
"sit\t444\n" +
"amet\t555\n" +
"consectetuer\t666\n" +
"adipiscing\t777\n" +
"elit\t888\n" +
"Nunc\t999\n";
String CHUNK2 =
"The quick brown fox jumps over the lazy dog\n" +
"hello, xssf hello, xssf\n" +
"hello, xssf hello, xssf\n" +
"hello, xssf hello, xssf\n" +
"hello, xssf hello, xssf\n";
Assert.AreEqual(
CHUNK1 +
"at\t4995\n" +
CHUNK2
, text);
// Now Get formulas not their values
extractor.SetFormulasNotResults(true);
text = extractor.Text;
Assert.AreEqual(
CHUNK1 +
"at\tSUM(B1:B9)\n" +
CHUNK2, text);
// With sheet names too
extractor.SetIncludeSheetNames(true);
text = extractor.Text;
Assert.AreEqual(
"Sheet1\n" +
CHUNK1 +
"at\tSUM(B1:B9)\n" +
"rich test\n" +
CHUNK2 +
"Sheet3\n"
, text);
}
[Test]
public void TestGetComplexText()
{
// A fairly complex file
XSSFExcelExtractor extractor = GetExtractor("AverageTaxRates.xlsx");
String text = extractor.Text;
Assert.IsTrue(text.Length > 0);
// Might not have all formatting it should do!
// TODO decide if we should really have the "null" in there
Assert.IsTrue(text.StartsWith(
"Avgtxfull\n" +
"\t(iii) AVERAGE TAX RATES ON ANNUAL"
));
}
/**
* Test that we return pretty much the same as
* ExcelExtractor does, when we're both passed
* the same file, just saved as xls and xlsx
*/
[Test]
public void TestComparedToOLE2()
{
// A fairly simple file - ooxml
XSSFExcelExtractor ooxmlExtractor = GetExtractor("SampleSS.xlsx");
ExcelExtractor ole2Extractor =
new ExcelExtractor(HSSFTestDataSamples.OpenSampleWorkbook("SampleSS.xls"));
POITextExtractor[] extractors =
new POITextExtractor[] { ooxmlExtractor, ole2Extractor };
for (int i = 0; i < extractors.Length; i++)
{
POITextExtractor extractor = extractors[i];
String text = Regex.Replace(extractor.Text,"[\r\t]", "");
Assert.IsTrue(text.StartsWith("First Sheet\nTest spreadsheet\n2nd row2nd row 2nd column\n"));
Regex pattern = new Regex(".*13(\\.0+)?\\s+Sheet3.*",RegexOptions.Compiled);
Assert.IsTrue(pattern.IsMatch(text));
}
}
/**
* From bug #45540
*/
[Test]
public void TestHeaderFooter()
{
String[] files = new String[] {
"45540_classic_Header.xlsx", "45540_form_Header.xlsx",
"45540_classic_Footer.xlsx", "45540_form_Footer.xlsx",
};
foreach (String sampleName in files)
{
XSSFExcelExtractor extractor = GetExtractor(sampleName);
String text = extractor.Text;
Assert.IsTrue(text.Contains("testdoc"), "Unable to find expected word in text from " + sampleName + "\n" + text);
Assert.IsTrue(text.Contains("test phrase"), "Unable to find expected word in text\n" + text);
}
}
/**
* From bug #45544
*/
[Test]
public void TestComments()
{
XSSFExcelExtractor extractor = GetExtractor("45544.xlsx");
String text = extractor.Text;
// No comments there yet
Assert.IsFalse(text.Contains("testdoc"), "Unable to find expected word in text\n" + text);
Assert.IsFalse(text.Contains("test phrase"), "Unable to find expected word in text\n" + text);
// Turn on comment extraction, will then be
extractor.SetIncludeCellComments(true);
text = extractor.Text;
Assert.IsTrue(text.Contains("testdoc"), "Unable to find expected word in text\n" + text);
Assert.IsTrue(text.Contains("test phrase"), "Unable to find expected word in text\n" + text);
}
[Test]
public void TestInlineStrings()
{
XSSFExcelExtractor extractor = GetExtractor("InlineStrings.xlsx");
extractor.SetFormulasNotResults(true);
String text = extractor.Text;
// Numbers
Assert.IsTrue(text.Contains("43"), "Unable to find expected word in text\n" + text);
Assert.IsTrue(text.Contains("22"), "Unable to find expected word in text\n" + text);
// Strings
Assert.IsTrue(text.Contains("ABCDE"), "Unable to find expected word in text\n" + text);
Assert.IsTrue(text.Contains("Long Text"), "Unable to find expected word in text\n" + text);
// Inline Strings
Assert.IsTrue(text.Contains("1st Inline String"), "Unable to find expected word in text\n" + text);
Assert.IsTrue(text.Contains("And More"), "Unable to find expected word in text\n" + text);
// Formulas
Assert.IsTrue(text.Contains("A2"), "Unable to find expected word in text\n" + text);
Assert.IsTrue(text.Contains("A5-A$2"), "Unable to find expected word in text\n" + text);
}
}
}
| |
/*
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 *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER
EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF
TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions and
limitations under the License.
*/
using Microsoft.Research.DryadLinq;
using Microsoft.Research.DryadLinq.Internal;
using Microsoft.Research.Peloponnese.Storage;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
namespace DryadLinqTests
{
public class Config
{
public static string accountName = @"";
public static string storageKey = @"";
public static string containerName = @"";
public static string cluster = @"";
public static string testLogPath = @"";
public Config(string clusterName, string container, string logPath)
{
cluster = clusterName;
AzureSubscriptions azs = new AzureSubscriptions();
Task<AzureCluster> clusterTask = azs.GetClusterAsync(clusterName);
clusterTask.Wait();
accountName = clusterTask.Result.StorageAccount;
storageKey = clusterTask.Result.StorageKey;
containerName = container;
testLogPath = logPath;
}
}
public class DataGenerator
{
public DataGenerator()
{
}
public static IQueryable<int> CreateSimpleFileSetsEx()
{
int[] input = { 0, 1, 2 };
IEnumerable<int> range = input.Apply(x => Enumerable.Range(0, 3)); // {0, 1, 2}
IEnumerable<int> partitions = range.HashPartition(x => x, 3); // create 3 partitions
IEnumerable<int> rangePartition = partitions.SelectMany(x => Enumerable.Range(x * 4, 4));
return rangePartition.AsQueryable();
}
public static IEnumerable<IEnumerable<int>> CreateSimpleFileSets()
{
IEnumerable<IEnumerable<int>> data = new int[][]
{
new[] { 1, 2, 3, 4 },
new[] { 5, 6, 7, 8 },
new[] { 9, 10, 11, 12 },
};
return data;
}
public static IEnumerable<IEnumerable<int>> CreateGroupByReduceDataSet()
{
// we need quite a few elements to ensure the combiner will be activated in Stage#1 groupBy.
// 33 elements per partition should suffice, but 100 per partition is safer.
IEnumerable<IEnumerable<int>> data = new int[][]
{
Enumerable.Range(1,100).ToArray(),
Enumerable.Range(101,100).ToArray(),
};
return data;
}
public static IEnumerable<IEnumerable<int>> CreateRangePartitionDataSet()
{
// we need a lot of data to ensure sampler will get some data.
// A few thousand should suffice.
IEnumerable<IEnumerable<int>> data = new int[][]
{
Enumerable.Range(1,1000).ToArray(),
Enumerable.Range(20000,2000).ToArray(),
Enumerable.Range(40000,5000).ToArray(),
};
return data;
}
public static IQueryable<int> GetSimpleFileSets(DryadLinqContext context)
{
//IEnumerable<IEnumerable<int>> data = new int[][]
// {
// new[] { 0, 1, 2, 3 },
// new[] { 4, 5, 6, 7 },
// new[] { 8, 9, 10, 11},
// };
//IQueryable<LineRecord> input = context.FromStore<LineRecord>(AzureUtils.ToAzureUri(Config.accountName, Config.containerName,
// "unittest/inputdata/SimpleFile.txt"));
IQueryable<int> input = context.FromEnumerable(new int[1]);
IQueryable<int> range = input.Apply(x => Enumerable.Range(0, 3)); // {0, 1, 2}
IQueryable<int> partitions = range.HashPartition(x => x, 3); // create 3 partitions
IQueryable<int> rangePartition = partitions.SelectMany(x => Enumerable.Range(x * 4, 4));
//IQueryable<int> store = rangePartition.ToStore(@"unittest/inputdata/SimpleFile.txt");
return rangePartition;
}
public static IQueryable<int> GetGroupByReduceDataSet(DryadLinqContext context)
{
//IEnumerable<IEnumerable<int>> data = new int[][] {
// Enumerable.Range(1,100).ToArray(),
// Enumerable.Range(101,100).ToArray(),
// };
IQueryable<int> input = context.FromEnumerable(new int[1]);
IQueryable<int> range = input.Apply(x => Enumerable.Range(0, 2)); // {0, 1}
IQueryable<int> partitions = range.HashPartition(x => x, 2); // create 2 partitions
IQueryable<int> rangePartition = partitions.SelectMany(x => Enumerable.Range(x * 100 + 1, 100));
return rangePartition;
}
public static IQueryable<int> GetRangePartitionDataSet(DryadLinqContext context)
{
// we need a lot of data to ensure sampler will get some data.
// A few thousand should suffice.
//IEnumerable<IEnumerable<int>> data = new int[][] {
// Enumerable.Range(1,1000).ToArray(),
// Enumerable.Range(20000,2000).ToArray(),
// Enumerable.Range(40000,5000).ToArray(),
// };
IQueryable<int> input = context.FromEnumerable(new int[1]);
IQueryable<int> range = input.Apply(x => Enumerable.Range(0, 3)); // {0, 1, 2}
IQueryable<int> partitions = range.HashPartition(x => x, 3); // create 3 partitions
IQueryable<int> rangePartition = partitions.SelectMany(x => Enumerable.Range(x * 20000 + 1, 1000));
return rangePartition;
}
}
[Serializable]
public class ReverseComparer<T> : IComparer<T>
{
IComparer<T> _originalComparer;
public ReverseComparer(IComparer<T> originalComparer)
{
_originalComparer = originalComparer ?? Comparer<T>.Default;
}
public int Compare(T x, T y)
{
return (_originalComparer.Compare(y, x)); //note reversed order of operands
}
public override bool Equals(object obj)
{
ReverseComparer<T> objTyped = obj as ReverseComparer<T>;
return objTyped != null && _originalComparer.Equals(objTyped._originalComparer);
}
public override int GetHashCode()
{
// Modify the hash code so that it differs from the hash code for the underlying comparer.
// It would also probably be good enough to just return _originalComparer.GetHashCode().
return unchecked((_originalComparer.GetHashCode() + 123457) * 10007);
}
}
public class Utils
{
public static bool DeleteFile(string accountName, string accountKey, string containerName, string fileName, bool delSubDirs)
{
try
{
CloudStorageAccount storageAccount = CloudStorageAccount.Parse("DefaultEndpointsProtocol=http;AccountName=" + accountName + ";AccountKey=" + accountKey);
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
CloudBlobContainer container = blobClient.GetContainerReference(containerName);
container.CreateIfNotExists();
BlobContainerPermissions containerPermissions = new BlobContainerPermissions();
containerPermissions.PublicAccess = BlobContainerPublicAccessType.Blob;
container.SetPermissions(containerPermissions);
if (false == delSubDirs)
{
CloudBlockBlob remoteFile = container.GetBlockBlobReference(fileName);
remoteFile.DeleteIfExists();
}
if (true == delSubDirs)
{
foreach (IListBlobItem item in container.ListBlobs(fileName, true))
{
CloudBlockBlob blob = (CloudBlockBlob)item;
blob.DeleteIfExists();
}
}
}
catch (Exception)
{
return false;
}
return true;
}
public static bool FileExists(string accountName, string accountKey, string containerName, string fileName)
{
try
{
CloudStorageAccount storageAccount = CloudStorageAccount.Parse("DefaultEndpointsProtocol=http;AccountName=" + accountName + ";AccountKey=" + accountKey);
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
CloudBlobContainer container = blobClient.GetContainerReference(containerName);
container.CreateIfNotExists();
BlobContainerPermissions containerPermissions = new BlobContainerPermissions();
containerPermissions.PublicAccess = BlobContainerPublicAccessType.Blob;
container.SetPermissions(containerPermissions);
IEnumerable<IListBlobItem> files = container.ListBlobs(fileName, true);
return (files.Count() > 0);
}
catch (Exception)
{
return false;
}
}
internal static DryadLinqContext MakeBasicConfig(string cluster) //???
{
var context = new DryadLinqContext(cluster);
try
{
context.JobFriendlyName = "DryadLinq_DevUnitTests";
context.CompileForVertexDebugging = true;
context.JobEnvironmentVariables.Add("DummyEnvVar", "hello"); //note: this is consumed by a unit-test.
if (File.Exists("Microsoft.Hpc.Linq.pdb")) // TODO: fix references
{
context.ResourcesToAdd.Add("Microsoft.Hpc.Linq.pdb");
}
if (File.Exists("Microsoft.Hpc.Dsc.Client.pdb")) // TODO: fix references
{
context.ResourcesToAdd.Add("Microsoft.Hpc.Dsc.Client.pdb");
}
// To prevent job from running forever, and blocking other test
context.JobRuntimeLimit = (int)TimeSpan.FromMinutes(30).TotalSeconds;
//config.AllowConcurrentUserDelegatesInSingleProcess = false;
// If we are on Azure, we have to set the nodeGroup to "NodeRole" so that the default of "ComputeNodes" is not used
// This fixes "FromEnumerableTests" on Azure which queries the active node-group.
// Note also, the headnode for an azure deployment defaults to "HPCCluster" (at least from James' script)
int onAzureInt = 0;
string onAzureString = Environment.GetEnvironmentVariable("CCP_SCHEDULERONAZURE");
if (onAzureString != null)
{
int.TryParse(onAzureString, out onAzureInt);
}
if (onAzureInt == 1)
{
context.NodeGroup = "NodeRole";
}
}
catch (DryadLinqException)
{
}
return context;
}
internal static DryadLinqRecordReader<TRecord> MakeDryadRecordReader<TRecord>(DryadLinqContext context, string readPath)
{
DryadLinqFactory<TRecord> factory = (DryadLinqFactory<TRecord>)DryadLinqCodeGen.GetFactory(context, typeof(TRecord));
NativeBlockStream nativeStream = ReflectionHelper.CreateDryadLinqFileStream(readPath, FileMode.Open, FileAccess.Read);
// ??? NativeBlockStream nativeStream = ReflectionHelper.CreateDryadLinqFileStream(readPath, FileMode.Open, FileAccess.Read, DscCompressionScheme.None);
DryadLinqRecordReader<TRecord> reader = factory.MakeReader(nativeStream);
return reader;
}
}
public class Validate
{
public static void
Check<T>(
IEnumerable<T>[] ss,
IComparer<T> comparer = null,
bool sort = true,
bool verbose = false,
IComparer<T> sortcomparer = null
)
{
if (ss.Length == 0) return;
if (comparer == null)
{
comparer = Comparer<T>.Default;
if (comparer == null)
{
throw new ArgumentNullException("Can't not be null.");
}
}
if (sortcomparer == null)
sortcomparer = comparer;
T[][] aa = new T[ss.Length][];
for (int i = 0; i < aa.Length; i++)
{
aa[i] = ss[i].ToArray();
if (sort) Array.Sort(aa[i], sortcomparer);
}
int len = aa[0].Length;
for (int i = 1; i < aa.Length; i++)
{
if (aa[i].Length != len)
{
throw new Exception("Wrong number of elements.");
}
}
for (int i = 0; i < len; i++)
{
T elem = aa[0][i];
for (int j = 1; j < aa.Length; j++)
{
if (verbose)
{
//TestOutput.WriteLine("Comparing {0} to {1}", elem.ToString(), aa[j][i].ToString());
}
if (comparer.Compare(elem, aa[j][i]) != 0)
{
throw new Exception("Elements failed to match: " + elem + " != " + aa[j][i]);
}
}
}
}
internal static bool outFileExists(string outFile)
{
try
{
return Utils.FileExists(Config.accountName, Config.storageKey, Config.containerName, outFile);
}
catch (Exception)
{
return false;
}
}
}
public static class ReflectionHelper
{
/// <summary>
/// Create DryadLinqFileStream object via reflection
/// </summary>
///<param name="parameters"></param>
/// <returns></returns>
public static NativeBlockStream CreateDryadLinqFileStream(params object[] parameters)
{
return Assembly.LoadWithPartialName("Microsoft.Hpc.Linq").GetType("Microsoft.Hpc.Linq.Internal.HpcLinqFileStream") //???
.GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, parameters.Select(p => p.GetType()).ToArray(), null)
.Invoke(parameters) as NativeBlockStream;
}
private static Type s_errorCodeType = null;
public static int GetDryadLinqErrorCode(string name)
{
if (s_errorCodeType == null)
{
Assembly asm = Assembly.Load("Microsoft.Research.DryadLinq");
Type[] types = asm.GetTypes();
foreach (var t in types)
{
if (t.Name == "DryadLinqErrorCode")
{
s_errorCodeType = t;
break;
}
}
}
var finfo = s_errorCodeType.GetField(name);
return (int)finfo.GetValue(null);
}
}
}
| |
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
namespace SelfLoad.Business.ERLevel
{
/// <summary>
/// C10Level11111 (editable child object).<br/>
/// This is a generated base class of <see cref="C10Level11111"/> business object.
/// </summary>
/// <remarks>
/// This class contains one child collection:<br/>
/// - <see cref="C11Level111111Objects"/> of type <see cref="C11Level111111Coll"/> (1:M relation to <see cref="C12Level111111"/>)<br/>
/// This class is an item of <see cref="C09Level11111Coll"/> collection.
/// </remarks>
[Serializable]
public partial class C10Level11111 : BusinessBase<C10Level11111>
{
#region Static Fields
private static int _lastID;
#endregion
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="Level_1_1_1_1_1_ID"/> property.
/// </summary>
public static readonly PropertyInfo<int> Level_1_1_1_1_1_IDProperty = RegisterProperty<int>(p => p.Level_1_1_1_1_1_ID, "Level_1_1_1_1_1 ID");
/// <summary>
/// Gets the Level_1_1_1_1_1 ID.
/// </summary>
/// <value>The Level_1_1_1_1_1 ID.</value>
public int Level_1_1_1_1_1_ID
{
get { return GetProperty(Level_1_1_1_1_1_IDProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="Level_1_1_1_1_1_Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> Level_1_1_1_1_1_NameProperty = RegisterProperty<string>(p => p.Level_1_1_1_1_1_Name, "Level_1_1_1_1_1 Name");
/// <summary>
/// Gets or sets the Level_1_1_1_1_1 Name.
/// </summary>
/// <value>The Level_1_1_1_1_1 Name.</value>
public string Level_1_1_1_1_1_Name
{
get { return GetProperty(Level_1_1_1_1_1_NameProperty); }
set { SetProperty(Level_1_1_1_1_1_NameProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="C11Level111111SingleObject"/> property.
/// </summary>
public static readonly PropertyInfo<C11Level111111Child> C11Level111111SingleObjectProperty = RegisterProperty<C11Level111111Child>(p => p.C11Level111111SingleObject, "C11 Level111111 Single Object", RelationshipTypes.Child);
/// <summary>
/// Gets the C11 Level111111 Single Object ("self load" child property).
/// </summary>
/// <value>The C11 Level111111 Single Object.</value>
public C11Level111111Child C11Level111111SingleObject
{
get { return GetProperty(C11Level111111SingleObjectProperty); }
private set { LoadProperty(C11Level111111SingleObjectProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="C11Level111111ASingleObject"/> property.
/// </summary>
public static readonly PropertyInfo<C11Level111111ReChild> C11Level111111ASingleObjectProperty = RegisterProperty<C11Level111111ReChild>(p => p.C11Level111111ASingleObject, "C11 Level111111 ASingle Object", RelationshipTypes.Child);
/// <summary>
/// Gets the C11 Level111111 ASingle Object ("self load" child property).
/// </summary>
/// <value>The C11 Level111111 ASingle Object.</value>
public C11Level111111ReChild C11Level111111ASingleObject
{
get { return GetProperty(C11Level111111ASingleObjectProperty); }
private set { LoadProperty(C11Level111111ASingleObjectProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="C11Level111111Objects"/> property.
/// </summary>
public static readonly PropertyInfo<C11Level111111Coll> C11Level111111ObjectsProperty = RegisterProperty<C11Level111111Coll>(p => p.C11Level111111Objects, "C11 Level111111 Objects", RelationshipTypes.Child);
/// <summary>
/// Gets the C11 Level111111 Objects ("self load" child property).
/// </summary>
/// <value>The C11 Level111111 Objects.</value>
public C11Level111111Coll C11Level111111Objects
{
get { return GetProperty(C11Level111111ObjectsProperty); }
private set { LoadProperty(C11Level111111ObjectsProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="C10Level11111"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="C10Level11111"/> object.</returns>
internal static C10Level11111 NewC10Level11111()
{
return DataPortal.CreateChild<C10Level11111>();
}
/// <summary>
/// Factory method. Loads a <see cref="C10Level11111"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
/// <returns>A reference to the fetched <see cref="C10Level11111"/> object.</returns>
internal static C10Level11111 GetC10Level11111(SafeDataReader dr)
{
C10Level11111 obj = new C10Level11111();
// show the framework that this is a child object
obj.MarkAsChild();
obj.Fetch(dr);
obj.MarkOld();
return obj;
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="C10Level11111"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
private C10Level11111()
{
// Prevent direct creation
// show the framework that this is a child object
MarkAsChild();
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="C10Level11111"/> object properties.
/// </summary>
[Csla.RunLocal]
protected override void Child_Create()
{
LoadProperty(Level_1_1_1_1_1_IDProperty, System.Threading.Interlocked.Decrement(ref _lastID));
LoadProperty(C11Level111111SingleObjectProperty, DataPortal.CreateChild<C11Level111111Child>());
LoadProperty(C11Level111111ASingleObjectProperty, DataPortal.CreateChild<C11Level111111ReChild>());
LoadProperty(C11Level111111ObjectsProperty, DataPortal.CreateChild<C11Level111111Coll>());
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="C10Level11111"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
// Value properties
LoadProperty(Level_1_1_1_1_1_IDProperty, dr.GetInt32("Level_1_1_1_1_1_ID"));
LoadProperty(Level_1_1_1_1_1_NameProperty, dr.GetString("Level_1_1_1_1_1_Name"));
var args = new DataPortalHookArgs(dr);
OnFetchRead(args);
}
/// <summary>
/// Loads child objects.
/// </summary>
internal void FetchChildren()
{
LoadProperty(C11Level111111SingleObjectProperty, C11Level111111Child.GetC11Level111111Child(Level_1_1_1_1_1_ID));
LoadProperty(C11Level111111ASingleObjectProperty, C11Level111111ReChild.GetC11Level111111ReChild(Level_1_1_1_1_1_ID));
LoadProperty(C11Level111111ObjectsProperty, C11Level111111Coll.GetC11Level111111Coll(Level_1_1_1_1_1_ID));
}
/// <summary>
/// Inserts a new <see cref="C10Level11111"/> object in the database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert(C08Level1111 parent)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("AddC10Level11111", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Level_1_1_1_1_ID", parent.Level_1_1_1_1_ID).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@Level_1_1_1_1_1_ID", ReadProperty(Level_1_1_1_1_1_IDProperty)).Direction = ParameterDirection.Output;
cmd.Parameters.AddWithValue("@Level_1_1_1_1_1_Name", ReadProperty(Level_1_1_1_1_1_NameProperty)).DbType = DbType.String;
var args = new DataPortalHookArgs(cmd);
OnInsertPre(args);
cmd.ExecuteNonQuery();
OnInsertPost(args);
LoadProperty(Level_1_1_1_1_1_IDProperty, (int) cmd.Parameters["@Level_1_1_1_1_1_ID"].Value);
}
FieldManager.UpdateChildren(this);
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="C10Level11111"/> object.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update()
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("UpdateC10Level11111", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Level_1_1_1_1_1_ID", ReadProperty(Level_1_1_1_1_1_IDProperty)).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@Level_1_1_1_1_1_Name", ReadProperty(Level_1_1_1_1_1_NameProperty)).DbType = DbType.String;
var args = new DataPortalHookArgs(cmd);
OnUpdatePre(args);
cmd.ExecuteNonQuery();
OnUpdatePost(args);
}
FieldManager.UpdateChildren(this);
}
}
/// <summary>
/// Self deletes the <see cref="C10Level11111"/> object from database.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf()
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
// flushes all pending data operations
FieldManager.UpdateChildren(this);
using (var cmd = new SqlCommand("DeleteC10Level11111", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Level_1_1_1_1_1_ID", ReadProperty(Level_1_1_1_1_1_IDProperty)).DbType = DbType.Int32;
var args = new DataPortalHookArgs(cmd);
OnDeletePre(args);
cmd.ExecuteNonQuery();
OnDeletePost(args);
}
}
// removes all previous references to children
LoadProperty(C11Level111111SingleObjectProperty, DataPortal.CreateChild<C11Level111111Child>());
LoadProperty(C11Level111111ASingleObjectProperty, DataPortal.CreateChild<C11Level111111ReChild>());
LoadProperty(C11Level111111ObjectsProperty, DataPortal.CreateChild<C11Level111111Coll>());
}
#endregion
#region Pseudo Events
/// <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 file="CslaDataSource.cs" company="Marimer LLC">
// Copyright (c) Marimer LLC. All rights reserved.
// Website: https://cslanet.com
// </copyright>
// <summary>A Web Forms data binding control designed to support</summary>
//-----------------------------------------------------------------------
using System;
using System.Web.UI;
using System.ComponentModel;
using System.Reflection;
using Csla.Properties;
namespace Csla.Web
{
/// <summary>
/// A Web Forms data binding control designed to support
/// CSLA .NET business objects as data sources.
/// </summary>
[Designer(typeof(Csla.Web.Design.CslaDataSourceDesigner))]
[DisplayName("CslaDataSource")]
[Description("CSLA .NET Data Source Control")]
[ToolboxData("<{0}:CslaDataSource runat=\"server\"></{0}:CslaDataSource>")]
public class CslaDataSource : DataSourceControl
{
private CslaDataSourceView _defaultView;
/// <summary>
/// Event raised when an object is to be created and
/// populated with data.
/// </summary>
/// <remarks>Handle this event in a page and set
/// e.BusinessObject to the populated business object.
/// </remarks>
public event EventHandler<SelectObjectArgs> SelectObject;
/// <summary>
/// Event raised when an object is to be populated with data
/// and inserted.
/// </summary>
/// <remarks>Handle this event in a page to create an
/// instance of the object, load the object with data and
/// insert the object into the database.</remarks>
public event EventHandler<InsertObjectArgs> InsertObject;
/// <summary>
/// Event raised when an object is to be updated.
/// </summary>
/// <remarks>Handle this event in a page to update an
/// existing instance of an object with new data and then
/// save the object into the database.</remarks>
public event EventHandler<UpdateObjectArgs> UpdateObject;
/// <summary>
/// Event raised when an object is to be deleted.
/// </summary>
/// <remarks>Handle this event in a page to delete
/// an object from the database.</remarks>
public event EventHandler<DeleteObjectArgs> DeleteObject;
/// <summary>
/// Returns the default view for this data control.
/// </summary>
/// <param name="viewName">Ignored.</param>
/// <returns></returns>
/// <remarks>This control only contains a "Default" view.</remarks>
protected override DataSourceView GetView(string viewName)
{
if (_defaultView == null)
_defaultView = new CslaDataSourceView(this, "Default");
return _defaultView;
}
/// <summary>
/// Get or set the name of the assembly (no longer used).
/// </summary>
/// <value>Obsolete - do not use.</value>
public string TypeAssemblyName
{
get { return ((CslaDataSourceView)this.GetView("Default")).TypeAssemblyName; }
set { ((CslaDataSourceView)this.GetView("Default")).TypeAssemblyName = value; }
}
/// <summary>
/// Get or set the full type name of the business object
/// class to be used as a data source.
/// </summary>
/// <value>Full type name of the business class,
/// including assembly name.</value>
public string TypeName
{
get { return ((CslaDataSourceView)this.GetView("Default")).TypeName; }
set { ((CslaDataSourceView)this.GetView("Default")).TypeName = value; }
}
/// <summary>
/// Get or set a value indicating whether the
/// business object data source supports paging.
/// </summary>
/// <remarks>
/// To support paging, the business object
/// (collection) must implement
/// <see cref="Csla.Core.IReportTotalRowCount"/>.
/// </remarks>
public bool TypeSupportsPaging
{
get { return ((CslaDataSourceView)this.GetView("Default")).TypeSupportsPaging; }
set { ((CslaDataSourceView)this.GetView("Default")).TypeSupportsPaging = value; }
}
/// <summary>
/// Get or set a value indicating whether the
/// business object data source supports sorting.
/// </summary>
public bool TypeSupportsSorting
{
get { return ((CslaDataSourceView)this.GetView("Default")).TypeSupportsSorting; }
set { ((CslaDataSourceView)this.GetView("Default")).TypeSupportsSorting = value; }
}
private static System.Collections.Generic.Dictionary<string,Type> _typeCache =
new System.Collections.Generic.Dictionary<string,Type>();
/// <summary>
/// Returns a <see cref="Type">Type</see> object based on the
/// assembly and type information provided.
/// </summary>
/// <param name="typeAssemblyName">Optional assembly name.</param>
/// <param name="typeName">Full type name of the class,
/// including assembly name.</param>
/// <remarks></remarks>
internal static Type GetType(
string typeAssemblyName, string typeName)
{
Type result = null;
if (!string.IsNullOrEmpty(typeAssemblyName))
{
// explicit assembly name provided
result = Type.GetType(string.Format(
"{0}, {1}", typeName, typeAssemblyName), true, true);
}
else if (typeName.IndexOf(",") > 0)
{
// assembly qualified type name provided
result = Type.GetType(typeName, true, true);
}
else
{
// no assembly name provided
result = _typeCache[typeName];
if (result == null)
foreach (Assembly asm in AppDomain.CurrentDomain.GetAssemblies())
{
result = asm.GetType(typeName, false, true);
if (result != null)
{
_typeCache.Add(typeName, result);
break;
}
}
}
if (result == null)
throw new TypeLoadException(String.Format(Resources.TypeLoadException, typeName));
return result;
}
/// <summary>
/// Returns a list of views available for this control.
/// </summary>
/// <remarks>This control only provides the "Default" view.</remarks>
protected override System.Collections.ICollection GetViewNames()
{
return new string[] { "Default" };
}
/// <summary>
/// Raises the SelectObject event.
/// </summary>
internal void OnSelectObject(SelectObjectArgs e)
{
if (SelectObject != null)
SelectObject(this, e);
}
/// <summary>
/// Raises the InsertObject event.
/// </summary>
internal void OnInsertObject(InsertObjectArgs e)
{
if (InsertObject != null)
InsertObject(this, e);
}
/// <summary>
/// Raises the UpdateObject event.
/// </summary>
internal void OnUpdateObject(UpdateObjectArgs e)
{
if (UpdateObject != null)
UpdateObject(this, e);
}
/// <summary>
/// Raises the DeleteObject event.
/// </summary>
internal void OnDeleteObject(DeleteObjectArgs e)
{
if (DeleteObject != null)
DeleteObject(this, e);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Windows.Devices.Enumeration;
using Windows.Media.Capture;
using Windows.Storage;
using Windows.Storage.Pickers;
using Plugin.Media.Abstractions;
using System.Diagnostics;
namespace Plugin.Media
{
/// <summary>
/// Implementation for Media
/// </summary>
public class MediaImplementation : IMedia
{
private static readonly IEnumerable<string> SupportedVideoFileTypes = new List<string> { ".mp4", ".wmv", ".avi" };
private static readonly IEnumerable<string> SupportedImageFileTypes = new List<string> { ".jpeg", ".jpg", ".png", ".gif", ".bmp" };
/// <summary>
/// Implementation
/// </summary>
public MediaImplementation()
{
watcher = DeviceInformation.CreateWatcher(DeviceClass.VideoCapture);
watcher.Added += OnDeviceAdded;
watcher.Updated += OnDeviceUpdated;
watcher.Removed += OnDeviceRemoved;
watcher.Start();
}
bool initialized = false;
public async Task<bool> Initialize()
{
try
{
var info = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture).AsTask().ConfigureAwait(false);
lock (devices)
{
foreach (var device in info)
{
if (device.IsEnabled)
devices.Add(device.Id);
}
isCameraAvailable = (devices.Count > 0);
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("Unable to detect cameras: " + ex);
}
initialized = true;
return true;
}
/// <inheritdoc/>
public bool IsCameraAvailable
{
get
{
if (!initialized)
Initialize().Wait();
return isCameraAvailable;
}
}
/// <inheritdoc/>
public bool IsTakePhotoSupported
{
get { return true; }
}
/// <inheritdoc/>
public bool IsPickPhotoSupported
{
get { return true; }
}
/// <inheritdoc/>
public bool IsTakeVideoSupported
{
get { return true; }
}
/// <inheritdoc/>
public bool IsPickVideoSupported
{
get { return true; }
}
/// <summary>
/// Take a photo async with specified options
/// </summary>
/// <param name="options">Camera Media Options</param>
/// <returns>Media file of photo or null if canceled</returns>
public async Task<MediaFile> TakePhotoAsync(StoreCameraMediaOptions options)
{
if (!initialized)
await Initialize();
if (!IsCameraAvailable)
throw new NotSupportedException();
options.VerifyOptions();
var capture = new CameraCaptureUI();
capture.PhotoSettings.Format = CameraCaptureUIPhotoFormat.Jpeg;
capture.PhotoSettings.MaxResolution = CameraCaptureUIMaxPhotoResolution.HighestAvailable;
var result = await capture.CaptureFileAsync(CameraCaptureUIMode.Photo);
if (result == null)
return null;
StorageFolder folder = ApplicationData.Current.LocalFolder;
string path = options.GetFilePath(folder.Path);
var directoryFull = Path.GetDirectoryName(path);
var newFolder = directoryFull.Replace(folder.Path, string.Empty);
if (!string.IsNullOrWhiteSpace(newFolder))
await folder.CreateFolderAsync(newFolder, CreationCollisionOption.OpenIfExists);
folder = await StorageFolder.GetFolderFromPathAsync(directoryFull);
string filename = Path.GetFileName(path);
string aPath = null;
if (options?.SaveToAlbum ?? false)
{
try
{
string fileNameNoEx = Path.GetFileNameWithoutExtension(path);
var copy = await result.CopyAsync(KnownFolders.PicturesLibrary, fileNameNoEx + result.FileType, NameCollisionOption.GenerateUniqueName);
aPath = copy.Path;
}
catch (Exception ex)
{
Debug.WriteLine("unable to save to album:" + ex);
}
}
var file = await result.CopyAsync(folder, filename, NameCollisionOption.GenerateUniqueName).AsTask();
return new MediaFile(file.Path, () => file.OpenStreamForReadAsync().Result, albumPath: aPath);
}
/// <summary>
/// Picks a photo from the default gallery
/// </summary>
/// <returns>Media file or null if canceled</returns>
public async Task<MediaFile> PickPhotoAsync()
{
var picker = new FileOpenPicker();
picker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
picker.ViewMode = PickerViewMode.Thumbnail;
foreach (var filter in SupportedImageFileTypes)
picker.FileTypeFilter.Add(filter);
var result = await picker.PickSingleFileAsync();
if (result == null)
return null;
return new MediaFile(result.Path, () => result.OpenStreamForReadAsync().Result);
}
/// <summary>
/// Take a video with specified options
/// </summary>
/// <param name="options">Video Media Options</param>
/// <returns>Media file of new video or null if canceled</returns>
public async Task<MediaFile> TakeVideoAsync(StoreVideoOptions options)
{
if (!initialized)
await Initialize();
if (!IsCameraAvailable)
throw new NotSupportedException();
options.VerifyOptions();
var capture = new CameraCaptureUI();
capture.VideoSettings.MaxResolution = GetResolutionFromQuality(options.Quality);
capture.VideoSettings.MaxDurationInSeconds = (float)options.DesiredLength.TotalSeconds;
capture.VideoSettings.Format = CameraCaptureUIVideoFormat.Mp4;
var result = await capture.CaptureFileAsync(CameraCaptureUIMode.Video);
if (result == null)
return null;
string aPath = null;
if (options?.SaveToAlbum ?? false)
{
try
{
string fileNameNoEx = Path.GetFileNameWithoutExtension(result.Path);
var copy = await result.CopyAsync(KnownFolders.VideosLibrary, fileNameNoEx + result.FileType, NameCollisionOption.GenerateUniqueName);
aPath = copy.Path;
}
catch (Exception ex)
{
Debug.WriteLine("unable to save to album:" + ex);
}
}
return new MediaFile(result.Path, () => result.OpenStreamForReadAsync().Result, albumPath: aPath);
}
/// <summary>
/// Picks a video from the default gallery
/// </summary>
/// <returns>Media file of video or null if canceled</returns>
public async Task<MediaFile> PickVideoAsync()
{
var picker = new FileOpenPicker();
picker.SuggestedStartLocation = PickerLocationId.VideosLibrary;
picker.ViewMode = PickerViewMode.Thumbnail;
foreach (var filter in SupportedVideoFileTypes)
picker.FileTypeFilter.Add(filter);
var result = await picker.PickSingleFileAsync();
if (result == null)
return null;
return new MediaFile(result.Path, () => result.OpenStreamForReadAsync().Result);
}
private readonly HashSet<string> devices = new HashSet<string>();
private readonly DeviceWatcher watcher;
private bool isCameraAvailable;
private CameraCaptureUIMaxVideoResolution GetResolutionFromQuality(VideoQuality quality)
{
switch (quality)
{
case VideoQuality.High:
return CameraCaptureUIMaxVideoResolution.HighestAvailable;
case VideoQuality.Medium:
return CameraCaptureUIMaxVideoResolution.StandardDefinition;
case VideoQuality.Low:
return CameraCaptureUIMaxVideoResolution.LowDefinition;
default:
return CameraCaptureUIMaxVideoResolution.HighestAvailable;
}
}
private void OnDeviceUpdated(DeviceWatcher sender, DeviceInformationUpdate update)
{
object value;
if (!update.Properties.TryGetValue("System.Devices.InterfaceEnabled", out value))
return;
lock (devices)
{
if ((bool)value)
devices.Add(update.Id);
else
devices.Remove(update.Id);
isCameraAvailable = devices.Count > 0;
}
}
private void OnDeviceRemoved(DeviceWatcher sender, DeviceInformationUpdate update)
{
lock (devices)
{
devices.Remove(update.Id);
if (devices.Count == 0)
isCameraAvailable = false;
}
}
private void OnDeviceAdded(DeviceWatcher sender, DeviceInformation device)
{
if (!device.IsEnabled)
return;
lock (devices)
{
devices.Add(device.Id);
isCameraAvailable = true;
}
}
}
}
| |
using System;
using System.Threading;
using System.Threading.Tasks;
using Marten.Events;
using Marten.Events.Aggregation;
using Marten.Testing.Documents;
using Marten.Testing.Harness;
using Shouldly;
using Xunit;
using Xunit.Abstractions;
namespace Marten.Testing.Events.Aggregation
{
public class when_doing_live_aggregations : AggregationContext
{
private readonly ITestOutputHelper _output;
public when_doing_live_aggregations(DefaultStoreFixture fixture, ITestOutputHelper output) : base(fixture)
{
_output = output;
}
[Fact]
public async Task sync_apply_and_default_create()
{
UsingDefinition<AllSync>();
var aggregate = await LiveAggregation(x =>
{
x.B();
x.C();
x.B();
x.C();
x.C();
x.A();
x.D();
});
aggregate.ACount.ShouldBe(1);
aggregate.BCount.ShouldBe(2);
aggregate.CCount.ShouldBe(3);
aggregate.DCount.ShouldBe(1);
}
[Fact]
public async Task sync_apply_and_specific_create()
{
UsingDefinition<AllSync>();
var aggregate = await LiveAggregation(x =>
{
x.Add(new CreateEvent(2, 3, 4, 5));
x.B();
x.C();
x.B();
x.C();
x.C();
x.A();
x.D();
});
_output.WriteLine(_projection.SourceCode());
aggregate.ACount.ShouldBe(3);
aggregate.BCount.ShouldBe(5);
aggregate.CCount.ShouldBe(7);
aggregate.DCount.ShouldBe(6);
}
[Fact]
public async Task async_create_and_apply_with_session()
{
var user1 = new User {UserName = "Creator"};
var user2 = new User {UserName = "Updater"};
theSession.Store(user1, user2);
await theSession.SaveChangesAsync();
UsingDefinition<AsyncEverything>();
_output.WriteLine(_projection.SourceCode());
var aggregate = await LiveAggregation(x =>
{
x.Add(new UserStarted {UserId = user1.Id});
x.Add(new UserUpdated {UserId = user2.Id});
});
aggregate.Created.ShouldBe(user1.UserName);
aggregate.UpdatedBy.ShouldBe(user2.UserName);
}
[Fact]
public async Task using_sync_value_task_with_otherwise_async_create()
{
var user1 = new User {UserName = "Creator"};
var user2 = new User {UserName = "Updater"};
theSession.Store(user1, user2);
await theSession.SaveChangesAsync();
UsingDefinition<AsyncEverything>();
var aggregate = await LiveAggregation(x =>
{
x.A();
x.A();
x.A();
});
aggregate.ACount.ShouldBe(3);
}
[Fact]
public async Task async_create_and_sync_apply()
{
var user1 = new User {UserName = "Creator"};
theSession.Store(user1);
await theSession.SaveChangesAsync();
UsingDefinition<AsyncCreateSyncApply>();
var aggregate = await LiveAggregation(x =>
{
x.Add(new UserStarted {UserId = user1.Id});
x.B();
x.C();
x.B();
x.C();
x.C();
x.A();
x.D();
});
_output.WriteLine(_projection.SourceCode());
aggregate.Created.ShouldBe(user1.UserName);
aggregate.ACount.ShouldBe(1);
aggregate.BCount.ShouldBe(2);
aggregate.CCount.ShouldBe(3);
aggregate.DCount.ShouldBe(1);
}
[Fact]
public async Task sync_create_and_async_apply()
{
var user1 = new User {UserName = "Updater"};
theSession.Store(user1);
await theSession.SaveChangesAsync();
UsingDefinition<SyncCreateAsyncApply>();
var aggregate = await LiveAggregation(x =>
{
x.Add(new CreateEvent(2, 3, 4, 5));
x.Add(new UserUpdated {UserId = user1.Id});
x.B();
x.C();
x.B();
x.C();
x.C();
x.A();
x.D();
});
_output.WriteLine(_projection.SourceCode());
aggregate.UpdatedBy.ShouldBe(user1.UserName);
aggregate.ACount.ShouldBe(3);
aggregate.BCount.ShouldBe(5);
aggregate.CCount.ShouldBe(7);
aggregate.DCount.ShouldBe(6);
}
[Fact]
public async Task using_event_metadata()
{
UsingDefinition<UsingMetadata>();
var streamId = Guid.NewGuid();
var aId = Guid.NewGuid();
var aggregate = await LiveAggregation(x =>
{
x.Add(new CreateEvent(2, 3, 4, 5)).StreamId = streamId;
x.A().Id = aId;
});
aggregate.Id.ShouldBe(streamId);
aggregate.EventId.ShouldBe(aId);
}
}
public class UserStarted
{
public Guid UserId { get; set; }
}
public class UserUpdated
{
public Guid UserId { get; set; }
}
public class UsingMetadata : AggregateProjection<MyAggregate>
{
public MyAggregate Create(CreateEvent create, IEvent e)
{
return new MyAggregate
{
ACount = create.A,
BCount = create.B,
CCount = create.C,
DCount = create.D,
Id = e.StreamId
};
}
public void Apply(IEvent<AEvent> @event, MyAggregate aggregate)
{
aggregate.EventId = @event.Id;
aggregate.ACount++;
}
}
public class AsyncEverything: AggregateProjection<MyAggregate>
{
public async Task<MyAggregate> Create(UserStarted @event, IQuerySession session, CancellationToken cancellation)
{
var user = await session.LoadAsync<User>(@event.UserId, cancellation);
return new MyAggregate
{
Created = user.UserName
};
}
public async Task Apply(UserUpdated @event, MyAggregate aggregate, IQuerySession session)
{
var user = await session.LoadAsync<User>(@event.UserId);
aggregate.UpdatedBy = user.UserName;
}
public void Apply(AEvent @event, MyAggregate aggregate)
{
aggregate.ACount++;
}
}
public class AsyncCreateSyncApply: AggregateProjection<MyAggregate>
{
public async Task<MyAggregate> Create(UserStarted @event, IQuerySession session, CancellationToken cancellation)
{
var user = await session.LoadAsync<User>(@event.UserId, cancellation);
return new MyAggregate
{
Created = user.UserName
};
}
public void Apply(AEvent @event, MyAggregate aggregate)
{
aggregate.ACount++;
}
public void Apply(BEvent @event, MyAggregate aggregate)
{
aggregate.BCount++;
}
public void Apply(MyAggregate aggregate, CEvent @event)
{
aggregate.CCount++;
}
public void Apply(MyAggregate aggregate, DEvent @event)
{
aggregate.DCount++;
}
}
public class SyncCreateAsyncApply: AggregateProjection<MyAggregate>
{
public MyAggregate Create(CreateEvent @event)
{
return new MyAggregate
{
ACount = @event.A,
BCount = @event.B,
CCount = @event.C,
DCount = @event.D
};
}
public async Task Apply(UserUpdated @event, MyAggregate aggregate, IQuerySession session)
{
var user = await session.LoadAsync<User>(@event.UserId);
aggregate.UpdatedBy = user.UserName;
}
public void Apply(AEvent @event, MyAggregate aggregate)
{
aggregate.ACount++;
}
public void Apply(BEvent @event, MyAggregate aggregate)
{
aggregate.BCount++;
}
public void Apply(MyAggregate aggregate, CEvent @event)
{
aggregate.CCount++;
}
public void Apply(MyAggregate aggregate, DEvent @event)
{
aggregate.DCount++;
}
}
public class AllSync: AggregateProjection<MyAggregate>
{
public AllSync()
{
ProjectionName = "AllSync";
}
public MyAggregate Create(CreateEvent @event)
{
return new MyAggregate
{
ACount = @event.A,
BCount = @event.B,
CCount = @event.C,
DCount = @event.D
};
}
public void Apply(AEvent @event, MyAggregate aggregate)
{
aggregate.ACount++;
}
public MyAggregate Apply(BEvent @event, MyAggregate aggregate)
{
return new MyAggregate
{
ACount = aggregate.ACount,
BCount = aggregate.BCount + 1,
CCount = aggregate.CCount,
DCount = aggregate.DCount,
Id = aggregate.Id
};
}
public void Apply(MyAggregate aggregate, CEvent @event)
{
aggregate.CCount++;
}
public MyAggregate Apply(MyAggregate aggregate, DEvent @event)
{
return new MyAggregate
{
ACount = aggregate.ACount,
BCount = aggregate.BCount,
CCount = aggregate.CCount,
DCount = aggregate.DCount + 1,
Id = aggregate.Id
};
}
}
}
| |
using System;
using System.Data;
using System.Data.OleDb;
using PCSComUtils.DataAccess;
using PCSComUtils.PCSExc;
using PCSComUtils.Common;
namespace PCSComUtils.MasterSetup.DS
{
public class MST_EmployeeDS
{
public MST_EmployeeDS()
{
}
private const string THIS = "PCSComUtils.MasterSetup.DS.MST_EmployeeDS";
//**************************************************************************
/// <Description>
/// This method uses to add data to MST_Employee
/// </Description>
/// <Inputs>
/// MST_EmployeeVO
/// </Inputs>
/// <Outputs>
/// newly inserted primarkey value
/// </Outputs>
/// <Returns>
/// void
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Tuesday, January 25, 2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void Add(object pobjObjectVO)
{
const string METHOD_NAME = THIS + ".Add()";
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS =null;
try
{
MST_EmployeeVO objObject = (MST_EmployeeVO) pobjObjectVO;
string strSql = String.Empty;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand("", oconPCS);
strSql= "INSERT INTO MST_Employee("
+ MST_EmployeeTable.CODE_FLD + ","
+ MST_EmployeeTable.NAME_FLD + ","
+ MST_EmployeeTable.DEPARTMENTID_FLD + ","
+ MST_EmployeeTable.SHIFT_FLD + ")"
+ "VALUES(?,?,?,?)";
ocmdPCS.Parameters.Add(new OleDbParameter(MST_EmployeeTable.CODE_FLD, OleDbType.VarWChar));
ocmdPCS.Parameters[MST_EmployeeTable.CODE_FLD].Value = objObject.Code;
ocmdPCS.Parameters.Add(new OleDbParameter(MST_EmployeeTable.NAME_FLD, OleDbType.VarWChar));
ocmdPCS.Parameters[MST_EmployeeTable.NAME_FLD].Value = objObject.Name;
ocmdPCS.Parameters.Add(new OleDbParameter(MST_EmployeeTable.DEPARTMENTID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[MST_EmployeeTable.DEPARTMENTID_FLD].Value = objObject.DepartmentID;
ocmdPCS.Parameters.Add(new OleDbParameter(MST_EmployeeTable.SHIFT_FLD, OleDbType.Integer));
ocmdPCS.Parameters[MST_EmployeeTable.SHIFT_FLD].Value = objObject.Shift;
ocmdPCS.CommandText = strSql;
ocmdPCS.Connection.Open();
ocmdPCS.ExecuteNonQuery();
}
catch(OleDbException ex)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE)
{
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
}
catch(InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to delete data from MST_Employee
/// </Description>
/// <Inputs>
/// ID
/// </Inputs>
/// <Outputs>
/// void
/// </Outputs>
/// <Returns>
///
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// 09-Dec-2004
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void Delete(int pintID)
{
const string METHOD_NAME = THIS + ".Delete()";
string strSql = String.Empty;
strSql= "DELETE " + MST_EmployeeTable.TABLE_NAME + " WHERE " + "EmployeeID" + "=" + pintID.ToString();
OleDbConnection oconPCS=null;
OleDbCommand ocmdPCS =null;
try
{
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
ocmdPCS.ExecuteNonQuery();
ocmdPCS = null;
}
catch(OleDbException ex)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE)
{
throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to get data from MST_Employee
/// </Description>
/// <Inputs>
/// ID
/// </Inputs>
/// <Outputs>
/// MST_EmployeeVO
/// </Outputs>
/// <Returns>
/// MST_EmployeeVO
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Tuesday, January 25, 2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public object GetObjectVO(int pintID)
{
const string METHOD_NAME = THIS + ".GetObjectVO()";
DataSet dstPCS = new DataSet();
OleDbDataReader odrPCS = null;
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql= "SELECT "
+ MST_EmployeeTable.EMPLOYEEID_FLD + ","
+ MST_EmployeeTable.CODE_FLD + ","
+ MST_EmployeeTable.NAME_FLD + ","
+ MST_EmployeeTable.DEPARTMENTID_FLD + ","
+ MST_EmployeeTable.SHIFT_FLD
+ " FROM " + MST_EmployeeTable.TABLE_NAME
+" WHERE " + MST_EmployeeTable.EMPLOYEEID_FLD + "=" + pintID;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
odrPCS = ocmdPCS.ExecuteReader();
MST_EmployeeVO objObject = new MST_EmployeeVO();
while (odrPCS.Read())
{
objObject.EmployeeID = int.Parse(odrPCS[MST_EmployeeTable.EMPLOYEEID_FLD].ToString().Trim());
objObject.Code = odrPCS[MST_EmployeeTable.CODE_FLD].ToString().Trim();
objObject.Name = odrPCS[MST_EmployeeTable.NAME_FLD].ToString().Trim();
objObject.DepartmentID = int.Parse(odrPCS[MST_EmployeeTable.DEPARTMENTID_FLD].ToString().Trim());
objObject.Shift = int.Parse(odrPCS[MST_EmployeeTable.SHIFT_FLD].ToString().Trim());
}
return objObject;
}
catch(OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to update data to MST_Employee
/// </Description>
/// <Inputs>
/// MST_EmployeeVO
/// </Inputs>
/// <Outputs>
///
/// </Outputs>
/// <Returns>
///
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// 09-Dec-2004
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void Update(object pobjObjecVO)
{
const string METHOD_NAME = THIS + ".Update()";
MST_EmployeeVO objObject = (MST_EmployeeVO) pobjObjecVO;
//prepare value for parameters
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
strSql= "UPDATE MST_Employee SET "
+ MST_EmployeeTable.CODE_FLD + "= ?" + ","
+ MST_EmployeeTable.NAME_FLD + "= ?" + ","
+ MST_EmployeeTable.DEPARTMENTID_FLD + "= ?" + ","
+ MST_EmployeeTable.SHIFT_FLD + "= ?"
+" WHERE " + MST_EmployeeTable.EMPLOYEEID_FLD + "= ?";
ocmdPCS.Parameters.Add(new OleDbParameter(MST_EmployeeTable.CODE_FLD, OleDbType.VarWChar));
ocmdPCS.Parameters[MST_EmployeeTable.CODE_FLD].Value = objObject.Code;
ocmdPCS.Parameters.Add(new OleDbParameter(MST_EmployeeTable.NAME_FLD, OleDbType.VarWChar));
ocmdPCS.Parameters[MST_EmployeeTable.NAME_FLD].Value = objObject.Name;
ocmdPCS.Parameters.Add(new OleDbParameter(MST_EmployeeTable.DEPARTMENTID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[MST_EmployeeTable.DEPARTMENTID_FLD].Value = objObject.DepartmentID;
ocmdPCS.Parameters.Add(new OleDbParameter(MST_EmployeeTable.SHIFT_FLD, OleDbType.Integer));
ocmdPCS.Parameters[MST_EmployeeTable.SHIFT_FLD].Value = objObject.Shift;
ocmdPCS.Parameters.Add(new OleDbParameter(MST_EmployeeTable.EMPLOYEEID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[MST_EmployeeTable.EMPLOYEEID_FLD].Value = objObject.EmployeeID;
ocmdPCS.CommandText = strSql;
ocmdPCS.Connection.Open();
ocmdPCS.ExecuteNonQuery();
}
catch(OleDbException ex)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE)
{
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
}
catch(InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to get all data from MST_Employee
/// </Description>
/// <Inputs>
///
/// </Inputs>
/// <Outputs>
/// DataSet
/// </Outputs>
/// <Returns>
/// DataSet
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Tuesday, January 25, 2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public DataSet List()
{
const string METHOD_NAME = THIS + ".List()";
DataSet dstPCS = new DataSet();
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql= "SELECT "
+ MST_EmployeeTable.EMPLOYEEID_FLD + ","
+ MST_EmployeeTable.CODE_FLD + ","
+ MST_EmployeeTable.NAME_FLD + ","
+ MST_EmployeeTable.DEPARTMENTID_FLD + ","
+ MST_EmployeeTable.SHIFT_FLD
+ " FROM " + MST_EmployeeTable.TABLE_NAME;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS);
odadPCS.Fill(dstPCS,MST_EmployeeTable.TABLE_NAME);
return dstPCS;
}
catch(OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to update a DataSet
/// </Description>
/// <Inputs>
/// DataSet
/// </Inputs>
/// <Outputs>
///
/// </Outputs>
/// <Returns>
///
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Tuesday, January 25, 2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void UpdateDataSet(DataSet pData)
{
const string METHOD_NAME = THIS + ".UpdateDataSet()";
string strSql;
OleDbConnection oconPCS =null;
OleDbCommandBuilder odcbPCS ;
OleDbDataAdapter odadPCS = new OleDbDataAdapter();
try
{
strSql= "SELECT "
+ MST_EmployeeTable.EMPLOYEEID_FLD + ","
+ MST_EmployeeTable.CODE_FLD + ","
+ MST_EmployeeTable.NAME_FLD + ","
+ MST_EmployeeTable.DEPARTMENTID_FLD + ","
+ MST_EmployeeTable.SHIFT_FLD
+ " FROM " + MST_EmployeeTable.TABLE_NAME;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
odadPCS.SelectCommand = new OleDbCommand(strSql, oconPCS);
odcbPCS = new OleDbCommandBuilder(odadPCS);
pData.EnforceConstraints = false;
odadPCS.Update(pData,MST_EmployeeTable.TABLE_NAME);
}
catch(OleDbException ex)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE)
{
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
}
else if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE)
{
throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
}
catch(InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
}
}
| |
//
// ClipboardBackend.cs
//
// Author:
// Lluis Sanchez <lluis@xamarin.com>
//
// Copyright (c) 2012 Xamarin Inc
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Linq;
using Xwt.Backends;
using System.Collections.Generic;
using System.Threading;
namespace Xwt.GtkBackend
{
public class GtkClipboardBackend: ClipboardBackend
{
Gtk.Clipboard primaryClipboard;
Gtk.Clipboard clipboard;
public GtkClipboardBackend ()
{
clipboard = Gtk.Clipboard.Get (Gdk.Atom.Intern ("CLIPBOARD", false));
primaryClipboard = Gtk.Clipboard.Get (Gdk.Atom.Intern ("PRIMARY", false));
}
#region IClipboardBackend implementation
public override void Clear ()
{
clipboard.Clear ();
}
public override void SetData (TransferDataType type, Func<object> dataSource)
{
var targetClipboard = clipboard;
if (type == TransferDataType.PrimaryText) {
targetClipboard = primaryClipboard;
// We set the type to Text because otherwise copying to PRIMARY stops working
// after the first time we copy to the CLIPBOARD.
type = TransferDataType.Text;
}
targetClipboard.SetWithData ((Gtk.TargetEntry[])Util.BuildTargetTable (new TransferDataType[] { type }),
delegate (Gtk.Clipboard cb, Gtk.SelectionData data, uint id) {
TransferDataType ttype = Util.AtomToType (data.Target.Name);
if (ttype == type)
Util.SetSelectionData (data, data.Target.Name, dataSource ());
},
delegate {
});
}
public override bool IsTypeAvailable (TransferDataType type)
{
if (type == TransferDataType.Text)
return clipboard.WaitIsTextAvailable ();
if (type == TransferDataType.PrimaryText)
return primaryClipboard.WaitIsTextAvailable ();
if (type == TransferDataType.Image)
return clipboard.WaitIsImageAvailable ();
foreach (var at in GetAtomsForType (type)) {
if (clipboard.WaitIsTargetAvailable (at))
return true;
}
return false;
}
IEnumerable<Gdk.Atom> GetAtomsForType (TransferDataType type)
{
foreach (Gtk.TargetEntry te in (Gtk.TargetEntry[])Util.BuildTargetTable (new TransferDataType[] { type }))
yield return Gdk.Atom.Intern (te.Target, false);
}
public override object GetData (TransferDataType type)
{
if (type == TransferDataType.Text)
return clipboard.WaitForText ();
if (type == TransferDataType.PrimaryText)
return primaryClipboard.WaitForText ();
if (type == TransferDataType.Text)
return clipboard.WaitForImage ();
TransferDataStore store = new TransferDataStore ();
foreach (var at in GetAtomsForType (type)) {
var data = clipboard.WaitForContents (at);
Util.GetSelectionData (ApplicationContext, data, store);
}
return ((ITransferData)store).GetValue (type);
}
public override IAsyncResult BeginGetData (TransferDataType type, AsyncCallback callback, object state)
{
var atts = GetAtomsForType (type).ToArray ();
var targetClipboard = type == TransferDataType.PrimaryText ? primaryClipboard : clipboard;
return new DataRequest (ApplicationContext, targetClipboard, callback, state, type, atts);
}
public override object EndGetData (IAsyncResult ares)
{
return ((DataRequest)ares).Result;
}
#endregion
}
class DataRequest: IAsyncResult
{
Gtk.Clipboard clipboard;
Gdk.Atom[] atoms;
int index = 0;
ManualResetEvent doneEvent;
bool complete;
TransferDataType type;
AsyncCallback callback;
ApplicationContext context;
public DataRequest (ApplicationContext context, Gtk.Clipboard clipboard, AsyncCallback callback, object state, TransferDataType type, Gdk.Atom[] atoms)
{
this.context = context;
this.callback = callback;
this.type = type;
AsyncState = state;
this.atoms = atoms;
this.clipboard = clipboard;
RequestData ();
}
public object Result { get; set; }
void RequestData ()
{
clipboard.RequestContents (atoms[index], DataReceived);
}
void DataReceived (Gtk.Clipboard cb, Gtk.SelectionData data)
{
TransferDataStore store = new TransferDataStore ();
if (Util.GetSelectionData (context, data, store)) {
Result = ((ITransferData)store).GetValue (type);
SetComplete ();
} else {
if (++index < atoms.Length)
RequestData ();
else
SetComplete ();
}
}
void SetComplete ()
{
lock (atoms) {
complete = true;
if (doneEvent != null)
doneEvent.Set ();
}
if (callback != null) {
Application.Invoke (delegate {
callback (this);
});
}
}
#region IAsyncResult implementation
public object AsyncState { get; set; }
public WaitHandle AsyncWaitHandle {
get {
lock (atoms) {
if (doneEvent == null)
doneEvent = new ManualResetEvent (complete);
}
return doneEvent;
}
}
public bool CompletedSynchronously {
get {
return false;
}
}
public bool IsCompleted {
get {
return complete;
}
}
#endregion
}
}
| |
using System;
using System.Linq.Expressions;
using NUnit.Framework;
namespace DelegateDecompiler.Tests
{
[TestFixture]
public class DecimalNullTests : DecompilerTestsBase
{
[Test]
public void ExpressionWithNullable()
{
Expression<Func<decimal, decimal?>> expected = x => (decimal?)x;
Func<decimal, decimal?> compiled = x => (decimal?)x;
Test(expected, compiled);
}
[Test]
public void ExpressionWithNullableEqual()
{
Expression<Func<decimal?, decimal?, bool>> expected = (x, y) => x == y;
Func<decimal?, decimal?, bool> compiled = (x, y) => x == y;
Test(expected, compiled);
}
[Test]
public void ExpressionWithNullableNotEqual()
{
Expression<Func<decimal?, decimal?, bool>> expected = (x, y) => x != y;
Func<decimal?, decimal?, bool> compiled = (x, y) => x != y;
Test(expected, compiled);
}
[Test]
public void ExpressionWithNullableGreaterThan()
{
Expression<Func<decimal?, decimal?, bool>> expected = (x, y) => x > y;
Func<decimal?, decimal?, bool> compiled = (x, y) => x > y;
Test(expected, compiled);
}
[Test]
public void ExpressionWithNullableGreaterThanOrEqual()
{
Expression<Func<decimal?, decimal?, bool>> expected = (x, y) => x >= y;
Func<decimal?, decimal?, bool> compiled = (x, y) => x >= y;
Test(expected, compiled);
}
[Test]
public void ExpressionWithNullableLessThan()
{
Expression<Func<decimal?, decimal?, bool>> expected = (x, y) => x < y;
Func<decimal?, decimal?, bool> compiled = (x, y) => x < y;
Test(expected, compiled);
}
[Test]
public void ExpressionWithNullableLessThanOrEqual()
{
Expression<Func<decimal?, decimal?, bool>> expected = (x, y) => x <= y;
Func<decimal?, decimal?, bool> compiled = (x, y) => x <= y;
Test(expected, compiled);
}
[Test]
public void ExpressionWithNullableMul()
{
Expression<Func<decimal?, decimal?, decimal?>> expected = (x, y) => x * y;
Func<decimal?, decimal?, decimal?> compiled = (x, y) => x * y;
Test(expected, compiled);
}
[Test]
public void ExpressionWithNullablePlus()
{
Expression<Func<decimal?, decimal?, decimal?>> expected = (x, y) => x + y;
Func<decimal?, decimal?, decimal?> compiled = (x, y) => x + y;
Test(expected, compiled);
}
[Test]
public void ExpressionWithNullableMinus()
{
Expression<Func<decimal?, decimal?, decimal?>> expected = (x, y) => x - y;
Func<decimal?, decimal?, decimal?> compiled = (x, y) => x - y;
Test(expected, compiled);
}
[Test]
public void ExpressionWithNullableDiv()
{
Expression<Func<decimal?, decimal?, decimal?>> expected = (x, y) => x / y;
Func<decimal?, decimal?, decimal?> compiled = (x, y) => x / y;
Test(expected, compiled);
}
[Test]
public void ExpressionWithNullableEqual2()
{
Expression<Func<decimal?, decimal, bool>> expected = (x, y) => x == y;
Func<decimal?, decimal, bool> compiled = (x, y) => x == y;
Test(expected, compiled);
}
[Test]
public void ExpressionWithNullableNotEqual2()
{
Expression<Func<decimal?, decimal, bool>> expected = (x, y) => x != y;
Func<decimal?, decimal, bool> compiled = (x, y) => x != y;
Test(expected, compiled);
}
[Test]
public void ExpressionWithNullableGreaterThan2()
{
Expression<Func<decimal?, decimal, bool>> expected = (x, y) => x > y;
Func<decimal?, decimal, bool> compiled = (x, y) => x > y;
Test(expected, compiled);
}
[Test]
public void ExpressionWithNullableGreaterThanOrEqual2()
{
Expression<Func<decimal?, decimal, bool>> expected = (x, y) => x >= y;
Func<decimal?, decimal, bool> compiled = (x, y) => x >= y;
Test(expected, compiled);
}
[Test]
public void ExpressionWithNullableLessThan2()
{
Expression<Func<decimal?, decimal, bool>> expected = (x, y) => x < y;
Func<decimal?, decimal, bool> compiled = (x, y) => x < y;
Test(expected, compiled);
}
[Test]
public void ExpressionWithNullableLessThanOrEqual2()
{
Expression<Func<decimal?, decimal, bool>> expected = (x, y) => x <= y;
Func<decimal?, decimal, bool> compiled = (x, y) => x <= y;
Test(expected, compiled);
}
[Test]
public void ExpressionWithNullableMul2()
{
Expression<Func<decimal?, decimal, decimal?>> expected = (x, y) => x * y;
Func<decimal?, decimal, decimal?> compiled = (x, y) => x * y;
Test(expected, compiled);
}
[Test]
public void ExpressionWithNullablePlus2()
{
Expression<Func<decimal?, decimal, decimal?>> expected = (x, y) => x + y;
Func<decimal?, decimal, decimal?> compiled = (x, y) => x + y;
Test(expected, compiled);
}
[Test]
public void ExpressionWithNullableMinus2()
{
Expression<Func<decimal?, decimal, decimal?>> expected = (x, y) => x - y;
Func<decimal?, decimal, decimal?> compiled = (x, y) => x - y;
Test(expected, compiled);
}
[Test]
public void ExpressionWithNullableDiv2()
{
Expression<Func<decimal?, decimal, decimal?>> expected = (x, y) => x / y;
Func<decimal?, decimal, decimal?> compiled = (x, y) => x / y;
Test(expected, compiled);
}
[Test]
public void ExpressionWithNullableEqual3()
{
Expression<Func<decimal, decimal?, bool>> expected = (x, y) => x == y;
Func<decimal, decimal?, bool> compiled = (x, y) => x == y;
Test(expected, compiled);
}
[Test]
public void ExpressionWithNullableNotEqual3()
{
Expression<Func<decimal, decimal?, bool>> expected = (x, y) => x != y;
Func<decimal, decimal?, bool> compiled = (x, y) => x != y;
Test(expected, compiled);
}
[Test]
public void ExpressionWithNullableGreaterThan3()
{
Expression<Func<decimal, decimal?, bool>> expected = (x, y) => x > y;
Func<decimal, decimal?, bool> compiled = (x, y) => x > y;
Test(expected, compiled);
}
[Test]
public void ExpressionWithNullableGreaterThanOrEqual3()
{
Expression<Func<decimal, decimal?, bool>> expected = (x, y) => x >= y;
Func<decimal, decimal?, bool> compiled = (x, y) => x >= y;
Test(expected, compiled);
}
[Test]
public void ExpressionWithNullableLessThan3()
{
Expression<Func<decimal, decimal?, bool>> expected = (x, y) => x < y;
Func<decimal, decimal?, bool> compiled = (x, y) => x < y;
Test(expected, compiled);
}
[Test]
public void ExpressionWithNullableLessThanOrEqual3()
{
Expression<Func<decimal, decimal?, bool>> expected = (x, y) => x <= y;
Func<decimal, decimal?, bool> compiled = (x, y) => x <= y;
Test(expected, compiled);
}
[Test]
public void ExpressionWithNullableMul3()
{
Expression<Func<decimal, decimal?, decimal?>> expected = (x, y) => x * y;
Func<decimal, decimal?, decimal?> compiled = (x, y) => x * y;
Test(expected, compiled);
}
[Test]
public void ExpressionWithNullablePlus3()
{
Expression<Func<decimal, decimal?, decimal?>> expected = (x, y) => x + y;
Func<decimal, decimal?, decimal?> compiled = (x, y) => x + y;
Test(expected, compiled);
}
[Test]
public void ExpressionWithNullableMinus3()
{
Expression<Func<decimal, decimal?, decimal?>> expected = (x, y) => x - y;
Func<decimal, decimal?, decimal?> compiled = (x, y) => x - y;
Test(expected, compiled);
}
[Test]
public void ExpressionWithNullableDiv3()
{
Expression<Func<decimal, decimal?, decimal?>> expected = (x, y) => x / y;
Func<decimal, decimal?, decimal?> compiled = (x, y) => x / y;
Test(expected, compiled);
}
[Test]
public void ExpressionWithNullableSum3()
{
Expression<Func<decimal?, decimal?, decimal?, decimal?>> expected = (x, y, z) => x + y + z;
Func<decimal?, decimal?, decimal?, decimal?> compiled = (x, y, z) => x + y + z;
Test(expected, compiled);
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gagvr = Google.Ads.GoogleAds.V8.Resources;
using gaxgrpc = Google.Api.Gax.Grpc;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using NUnit.Framework;
using Google.Ads.GoogleAds.V8.Services;
namespace Google.Ads.GoogleAds.Tests.V8.Services
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedCustomerClientServiceClientTest
{
[Category("Autogenerated")][Test]
public void GetCustomerClientRequestObject()
{
moq::Mock<CustomerClientService.CustomerClientServiceClient> mockGrpcClient = new moq::Mock<CustomerClientService.CustomerClientServiceClient>(moq::MockBehavior.Strict);
GetCustomerClientRequest request = new GetCustomerClientRequest
{
ResourceNameAsCustomerClientName = gagvr::CustomerClientName.FromCustomerClientCustomer("[CUSTOMER_ID]", "[CLIENT_CUSTOMER_ID]"),
};
gagvr::CustomerClient expectedResponse = new gagvr::CustomerClient
{
ResourceNameAsCustomerClientName = gagvr::CustomerClientName.FromCustomerClientCustomer("[CUSTOMER_ID]", "[CLIENT_CUSTOMER_ID]"),
ClientCustomerAsCustomerName = gagvr::CustomerName.FromCustomer("[CUSTOMER_ID]"),
Hidden = true,
Level = -1767934904342353463L,
TimeZone = "time_zone73f23b20",
TestAccount = true,
Manager = false,
DescriptiveName = "descriptive_nameee37a0bc",
CurrencyCode = "currency_code7f81e352",
Id = -6774108720365892680L,
AppliedLabelsAsLabelNames =
{
gagvr::LabelName.FromCustomerLabel("[CUSTOMER_ID]", "[LABEL_ID]"),
},
};
mockGrpcClient.Setup(x => x.GetCustomerClient(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CustomerClientServiceClient client = new CustomerClientServiceClientImpl(mockGrpcClient.Object, null);
gagvr::CustomerClient response = client.GetCustomerClient(request);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GetCustomerClientRequestObjectAsync()
{
moq::Mock<CustomerClientService.CustomerClientServiceClient> mockGrpcClient = new moq::Mock<CustomerClientService.CustomerClientServiceClient>(moq::MockBehavior.Strict);
GetCustomerClientRequest request = new GetCustomerClientRequest
{
ResourceNameAsCustomerClientName = gagvr::CustomerClientName.FromCustomerClientCustomer("[CUSTOMER_ID]", "[CLIENT_CUSTOMER_ID]"),
};
gagvr::CustomerClient expectedResponse = new gagvr::CustomerClient
{
ResourceNameAsCustomerClientName = gagvr::CustomerClientName.FromCustomerClientCustomer("[CUSTOMER_ID]", "[CLIENT_CUSTOMER_ID]"),
ClientCustomerAsCustomerName = gagvr::CustomerName.FromCustomer("[CUSTOMER_ID]"),
Hidden = true,
Level = -1767934904342353463L,
TimeZone = "time_zone73f23b20",
TestAccount = true,
Manager = false,
DescriptiveName = "descriptive_nameee37a0bc",
CurrencyCode = "currency_code7f81e352",
Id = -6774108720365892680L,
AppliedLabelsAsLabelNames =
{
gagvr::LabelName.FromCustomerLabel("[CUSTOMER_ID]", "[LABEL_ID]"),
},
};
mockGrpcClient.Setup(x => x.GetCustomerClientAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::CustomerClient>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CustomerClientServiceClient client = new CustomerClientServiceClientImpl(mockGrpcClient.Object, null);
gagvr::CustomerClient responseCallSettings = await client.GetCustomerClientAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::CustomerClient responseCancellationToken = await client.GetCustomerClientAsync(request, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void GetCustomerClient()
{
moq::Mock<CustomerClientService.CustomerClientServiceClient> mockGrpcClient = new moq::Mock<CustomerClientService.CustomerClientServiceClient>(moq::MockBehavior.Strict);
GetCustomerClientRequest request = new GetCustomerClientRequest
{
ResourceNameAsCustomerClientName = gagvr::CustomerClientName.FromCustomerClientCustomer("[CUSTOMER_ID]", "[CLIENT_CUSTOMER_ID]"),
};
gagvr::CustomerClient expectedResponse = new gagvr::CustomerClient
{
ResourceNameAsCustomerClientName = gagvr::CustomerClientName.FromCustomerClientCustomer("[CUSTOMER_ID]", "[CLIENT_CUSTOMER_ID]"),
ClientCustomerAsCustomerName = gagvr::CustomerName.FromCustomer("[CUSTOMER_ID]"),
Hidden = true,
Level = -1767934904342353463L,
TimeZone = "time_zone73f23b20",
TestAccount = true,
Manager = false,
DescriptiveName = "descriptive_nameee37a0bc",
CurrencyCode = "currency_code7f81e352",
Id = -6774108720365892680L,
AppliedLabelsAsLabelNames =
{
gagvr::LabelName.FromCustomerLabel("[CUSTOMER_ID]", "[LABEL_ID]"),
},
};
mockGrpcClient.Setup(x => x.GetCustomerClient(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CustomerClientServiceClient client = new CustomerClientServiceClientImpl(mockGrpcClient.Object, null);
gagvr::CustomerClient response = client.GetCustomerClient(request.ResourceName);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GetCustomerClientAsync()
{
moq::Mock<CustomerClientService.CustomerClientServiceClient> mockGrpcClient = new moq::Mock<CustomerClientService.CustomerClientServiceClient>(moq::MockBehavior.Strict);
GetCustomerClientRequest request = new GetCustomerClientRequest
{
ResourceNameAsCustomerClientName = gagvr::CustomerClientName.FromCustomerClientCustomer("[CUSTOMER_ID]", "[CLIENT_CUSTOMER_ID]"),
};
gagvr::CustomerClient expectedResponse = new gagvr::CustomerClient
{
ResourceNameAsCustomerClientName = gagvr::CustomerClientName.FromCustomerClientCustomer("[CUSTOMER_ID]", "[CLIENT_CUSTOMER_ID]"),
ClientCustomerAsCustomerName = gagvr::CustomerName.FromCustomer("[CUSTOMER_ID]"),
Hidden = true,
Level = -1767934904342353463L,
TimeZone = "time_zone73f23b20",
TestAccount = true,
Manager = false,
DescriptiveName = "descriptive_nameee37a0bc",
CurrencyCode = "currency_code7f81e352",
Id = -6774108720365892680L,
AppliedLabelsAsLabelNames =
{
gagvr::LabelName.FromCustomerLabel("[CUSTOMER_ID]", "[LABEL_ID]"),
},
};
mockGrpcClient.Setup(x => x.GetCustomerClientAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::CustomerClient>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CustomerClientServiceClient client = new CustomerClientServiceClientImpl(mockGrpcClient.Object, null);
gagvr::CustomerClient responseCallSettings = await client.GetCustomerClientAsync(request.ResourceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::CustomerClient responseCancellationToken = await client.GetCustomerClientAsync(request.ResourceName, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void GetCustomerClientResourceNames()
{
moq::Mock<CustomerClientService.CustomerClientServiceClient> mockGrpcClient = new moq::Mock<CustomerClientService.CustomerClientServiceClient>(moq::MockBehavior.Strict);
GetCustomerClientRequest request = new GetCustomerClientRequest
{
ResourceNameAsCustomerClientName = gagvr::CustomerClientName.FromCustomerClientCustomer("[CUSTOMER_ID]", "[CLIENT_CUSTOMER_ID]"),
};
gagvr::CustomerClient expectedResponse = new gagvr::CustomerClient
{
ResourceNameAsCustomerClientName = gagvr::CustomerClientName.FromCustomerClientCustomer("[CUSTOMER_ID]", "[CLIENT_CUSTOMER_ID]"),
ClientCustomerAsCustomerName = gagvr::CustomerName.FromCustomer("[CUSTOMER_ID]"),
Hidden = true,
Level = -1767934904342353463L,
TimeZone = "time_zone73f23b20",
TestAccount = true,
Manager = false,
DescriptiveName = "descriptive_nameee37a0bc",
CurrencyCode = "currency_code7f81e352",
Id = -6774108720365892680L,
AppliedLabelsAsLabelNames =
{
gagvr::LabelName.FromCustomerLabel("[CUSTOMER_ID]", "[LABEL_ID]"),
},
};
mockGrpcClient.Setup(x => x.GetCustomerClient(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CustomerClientServiceClient client = new CustomerClientServiceClientImpl(mockGrpcClient.Object, null);
gagvr::CustomerClient response = client.GetCustomerClient(request.ResourceNameAsCustomerClientName);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GetCustomerClientResourceNamesAsync()
{
moq::Mock<CustomerClientService.CustomerClientServiceClient> mockGrpcClient = new moq::Mock<CustomerClientService.CustomerClientServiceClient>(moq::MockBehavior.Strict);
GetCustomerClientRequest request = new GetCustomerClientRequest
{
ResourceNameAsCustomerClientName = gagvr::CustomerClientName.FromCustomerClientCustomer("[CUSTOMER_ID]", "[CLIENT_CUSTOMER_ID]"),
};
gagvr::CustomerClient expectedResponse = new gagvr::CustomerClient
{
ResourceNameAsCustomerClientName = gagvr::CustomerClientName.FromCustomerClientCustomer("[CUSTOMER_ID]", "[CLIENT_CUSTOMER_ID]"),
ClientCustomerAsCustomerName = gagvr::CustomerName.FromCustomer("[CUSTOMER_ID]"),
Hidden = true,
Level = -1767934904342353463L,
TimeZone = "time_zone73f23b20",
TestAccount = true,
Manager = false,
DescriptiveName = "descriptive_nameee37a0bc",
CurrencyCode = "currency_code7f81e352",
Id = -6774108720365892680L,
AppliedLabelsAsLabelNames =
{
gagvr::LabelName.FromCustomerLabel("[CUSTOMER_ID]", "[LABEL_ID]"),
},
};
mockGrpcClient.Setup(x => x.GetCustomerClientAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::CustomerClient>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CustomerClientServiceClient client = new CustomerClientServiceClientImpl(mockGrpcClient.Object, null);
gagvr::CustomerClient responseCallSettings = await client.GetCustomerClientAsync(request.ResourceNameAsCustomerClientName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::CustomerClient responseCancellationToken = await client.GetCustomerClientAsync(request.ResourceNameAsCustomerClientName, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.IO;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Text;
using System.Threading;
using System.Globalization;
using System.Security;
namespace System.Text
{
// SBCSCodePageEncoding
internal class SBCSCodePageEncoding : BaseCodePageEncoding
{
// Pointers to our memory section parts
[SecurityCritical]
private unsafe char* _mapBytesToUnicode = null; // char 256
[SecurityCritical]
private unsafe byte* _mapUnicodeToBytes = null; // byte 65536
private const char UNKNOWN_CHAR = (char)0xFFFD;
// byteUnknown is used for default fallback only
private byte _byteUnknown;
private char _charUnknown;
[System.Security.SecurityCritical] // auto-generated
public SBCSCodePageEncoding(int codePage) : this(codePage, codePage)
{
}
[System.Security.SecurityCritical] // auto-generated
public SBCSCodePageEncoding(int codePage, int dataCodePage) : base(codePage, dataCodePage)
{
}
// We have a managed code page entry, so load our tables
// SBCS data section looks like:
//
// char[256] - what each byte maps to in unicode. No support for surrogates. 0 is undefined code point
// (except 0 for byte 0 is expected to be a real 0)
//
// byte/char* - Data for best fit (unicode->bytes), again no best fit for Unicode
// 1st WORD is Unicode // of 1st character position
// Next bytes are best fit byte for that position. Position is incremented after each byte
// byte < 0x20 means skip the next n positions. (Where n is the byte #)
// byte == 1 means that next word is another unicode code point #
// byte == 0 is unknown. (doesn't override initial WCHAR[256] table!
[System.Security.SecurityCritical] // auto-generated
protected override unsafe void LoadManagedCodePage()
{
fixed (byte* pBytes = m_codePageHeader)
{
CodePageHeader* pCodePage = (CodePageHeader*)pBytes;
// Should be loading OUR code page
Debug.Assert(pCodePage->CodePage == dataTableCodePage,
"[SBCSCodePageEncoding.LoadManagedCodePage]Expected to load data table code page");
// Make sure we're really a 1 byte code page
if (pCodePage->ByteCount != 1)
throw new NotSupportedException(SR.Format(SR.NotSupported_NoCodepageData, CodePage));
// Remember our unknown bytes & chars
_byteUnknown = (byte)pCodePage->ByteReplace;
_charUnknown = pCodePage->UnicodeReplace;
// Get our mapped section 65536 bytes for unicode->bytes, 256 * 2 bytes for bytes->unicode
// Plus 4 byte to remember CP # when done loading it. (Don't want to get IA64 or anything out of alignment)
byte* pNativeMemory = GetNativeMemory(65536 * 1 + 256 * 2 + 4 + iExtraBytes);
_mapBytesToUnicode = (char*)pNativeMemory;
_mapUnicodeToBytes = (byte*)(pNativeMemory + 256 * 2);
// Need to read our data file and fill in our section.
// WARNING: Multiple code pieces could do this at once (so we don't have to lock machine-wide)
// so be careful here. Only stick legal values in here, don't stick temporary values.
// Read our data file and set mapBytesToUnicode and mapUnicodeToBytes appropriately
// First table is just all 256 mappings
byte[] buffer = new byte[256 * sizeof(char)];
lock (s_streamLock)
{
s_codePagesEncodingDataStream.Seek(m_firstDataWordOffset, SeekOrigin.Begin);
s_codePagesEncodingDataStream.Read(buffer, 0, buffer.Length);
}
fixed (byte* pBuffer = buffer)
{
char* pTemp = (char*)pBuffer;
for (int b = 0; b < 256; b++)
{
// Don't want to force 0's to map Unicode wrong. 0 byte == 0 unicode already taken care of
if (pTemp[b] != 0 || b == 0)
{
_mapBytesToUnicode[b] = pTemp[b];
if (pTemp[b] != UNKNOWN_CHAR)
_mapUnicodeToBytes[pTemp[b]] = (byte)b;
}
else
{
_mapBytesToUnicode[b] = UNKNOWN_CHAR;
}
}
}
}
}
// Private object for locking instead of locking on a public type for SQL reliability work.
private static Object s_InternalSyncObject;
private static Object InternalSyncObject
{
get
{
if (s_InternalSyncObject == null)
{
Object o = new Object();
Interlocked.CompareExchange<Object>(ref s_InternalSyncObject, o, null);
}
return s_InternalSyncObject;
}
}
// Read in our best fit table
[System.Security.SecurityCritical] // auto-generated
protected unsafe override void ReadBestFitTable()
{
// Lock so we don't confuse ourselves.
lock (InternalSyncObject)
{
// If we got a best fit array already, then don't do this
if (arrayUnicodeBestFit == null)
{
//
// Read in Best Fit table.
//
// First check the SBCS->Unicode best fit table, which starts right after the
// 256 word data table. This table looks like word, word where 1st word is byte and 2nd
// word is replacement for that word. It ends when byte == 0.
byte[] buffer = new byte[m_dataSize - 512];
lock (s_streamLock)
{
s_codePagesEncodingDataStream.Seek(m_firstDataWordOffset + 512, SeekOrigin.Begin);
s_codePagesEncodingDataStream.Read(buffer, 0, buffer.Length);
}
fixed (byte* pBuffer = buffer)
{
byte* pData = pBuffer;
// Need new best fit array
char[] arrayTemp = new char[256];
for (int i = 0; i < 256; i++)
arrayTemp[i] = _mapBytesToUnicode[i];
// See if our words are zero
ushort byteTemp;
while ((byteTemp = *((ushort*)pData)) != 0)
{
Debug.Assert(arrayTemp[byteTemp] == UNKNOWN_CHAR, String.Format(CultureInfo.InvariantCulture,
"[SBCSCodePageEncoding::ReadBestFitTable] Expected unallocated byte (not 0x{2:X2}) for best fit byte at 0x{0:X2} for code page {1}",
byteTemp, CodePage, (int)arrayTemp[byteTemp]));
pData += 2;
arrayTemp[byteTemp] = *((char*)pData);
pData += 2;
}
// Remember our new array
arrayBytesBestFit = arrayTemp;
// It was on 0, it needs to be on next byte
pData += 2;
byte* pUnicodeToSBCS = pData;
// Now count our characters from our Unicode->SBCS best fit table,
// which is right after our 256 byte data table
int iBestFitCount = 0;
// Now do the UnicodeToBytes Best Fit mapping (this is the one we normally think of when we say "best fit")
// pData should be pointing at the first data point for Bytes->Unicode table
int unicodePosition = *((ushort*)pData);
pData += 2;
while (unicodePosition < 0x10000)
{
// Get the next byte
byte input = *pData;
pData++;
// build our table:
if (input == 1)
{
// Use next 2 bytes as our byte position
unicodePosition = *((ushort*)pData);
pData += 2;
}
else if (input < 0x20 && input > 0 && input != 0x1e)
{
// Advance input characters
unicodePosition += input;
}
else
{
// Use this character if it isn't zero
if (input > 0)
iBestFitCount++;
// skip this unicode position in any case
unicodePosition++;
}
}
// Make an array for our best fit data
arrayTemp = new char[iBestFitCount * 2];
// Now actually read in the data
// reset pData should be pointing at the first data point for Bytes->Unicode table
pData = pUnicodeToSBCS;
unicodePosition = *((ushort*)pData);
pData += 2;
iBestFitCount = 0;
while (unicodePosition < 0x10000)
{
// Get the next byte
byte input = *pData;
pData++;
// build our table:
if (input == 1)
{
// Use next 2 bytes as our byte position
unicodePosition = *((ushort*)pData);
pData += 2;
}
else if (input < 0x20 && input > 0 && input != 0x1e)
{
// Advance input characters
unicodePosition += input;
}
else
{
// Check for escape for glyph range
if (input == 0x1e)
{
// Its an escape, so just read next byte directly
input = *pData;
pData++;
}
// 0 means just skip me
if (input > 0)
{
// Use this character
arrayTemp[iBestFitCount++] = (char)unicodePosition;
// Have to map it to Unicode because best fit will need unicode value of best fit char.
arrayTemp[iBestFitCount++] = _mapBytesToUnicode[input];
// This won't work if it won't round trip.
Debug.Assert(arrayTemp[iBestFitCount - 1] != (char)0,
String.Format(CultureInfo.InvariantCulture,
"[SBCSCodePageEncoding.ReadBestFitTable] No valid Unicode value {0:X4} for round trip bytes {1:X4}, encoding {2}",
(int)_mapBytesToUnicode[input], (int)input, CodePage));
}
unicodePosition++;
}
}
// Remember it
arrayUnicodeBestFit = arrayTemp;
} // Fixed()
}
}
}
// GetByteCount
// Note: We start by assuming that the output will be the same as count. Having
// an encoder or fallback may change that assumption
[System.Security.SecurityCritical] // auto-generated
public override unsafe int GetByteCount(char* chars, int count, EncoderNLS encoder)
{
// Just need to ASSERT, this is called by something else internal that checked parameters already
Debug.Assert(count >= 0, "[SBCSCodePageEncoding.GetByteCount]count is negative");
Debug.Assert(chars != null, "[SBCSCodePageEncoding.GetByteCount]chars is null");
// Assert because we shouldn't be able to have a null encoder.
Debug.Assert(EncoderFallback != null, "[SBCSCodePageEncoding.GetByteCount]Attempting to use null fallback");
CheckMemorySection();
// Need to test fallback
EncoderReplacementFallback fallback = null;
// Get any left over characters
char charLeftOver = (char)0;
if (encoder != null)
{
charLeftOver = encoder.charLeftOver;
Debug.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver),
"[SBCSCodePageEncoding.GetByteCount]leftover character should be high surrogate");
fallback = encoder.Fallback as EncoderReplacementFallback;
// Verify that we have no fallbackbuffer, actually for SBCS this is always empty, so just assert
Debug.Assert(!encoder.m_throwOnOverflow || !encoder.InternalHasFallbackBuffer ||
encoder.FallbackBuffer.Remaining == 0,
"[SBCSCodePageEncoding.GetByteCount]Expected empty fallback buffer at start");
}
else
{
// If we aren't using default fallback then we may have a complicated count.
fallback = EncoderFallback as EncoderReplacementFallback;
}
if ((fallback != null && fallback.MaxCharCount == 1)/* || bIsBestFit*/)
{
// Replacement fallback encodes surrogate pairs as two ?? (or two whatever), so return size is always
// same as input size.
// Note that no existing SBCS code pages map code points to supplimentary characters, so this is easy.
// We could however have 1 extra byte if the last call had an encoder and a funky fallback and
// if we don't use the funky fallback this time.
// Do we have an extra char left over from last time?
if (charLeftOver > 0)
count++;
return (count);
}
// It had a funky fallback, so it's more complicated
// May need buffer later
EncoderFallbackBuffer fallbackBuffer = null;
// prepare our end
int byteCount = 0;
char* charEnd = chars + count;
EncoderFallbackBufferHelper fallbackHelper = new EncoderFallbackBufferHelper(fallbackBuffer);
// We may have a left over character from last time, try and process it.
if (charLeftOver > 0)
{
// Since leftover char was a surrogate, it'll have to be fallen back.
// Get fallback
Debug.Assert(encoder != null, "[SBCSCodePageEncoding.GetByteCount]Expect to have encoder if we have a charLeftOver");
fallbackBuffer = encoder.FallbackBuffer;
fallbackHelper = new EncoderFallbackBufferHelper(fallbackBuffer);
fallbackHelper.InternalInitialize(chars, charEnd, encoder, false);
// This will fallback a pair if *chars is a low surrogate
fallbackHelper.InternalFallback(charLeftOver, ref chars);
}
// Now we may have fallback char[] already from the encoder
// Go ahead and do it, including the fallback.
char ch;
while ((ch = (fallbackBuffer == null) ? '\0' : fallbackHelper.InternalGetNextChar()) != 0 || chars < charEnd)
{
// First unwind any fallback
if (ch == 0)
{
// No fallback, just get next char
ch = *chars;
chars++;
}
// get byte for this char
byte bTemp = _mapUnicodeToBytes[ch];
// Check for fallback, this'll catch surrogate pairs too.
if (bTemp == 0 && ch != (char)0)
{
if (fallbackBuffer == null)
{
// Create & init fallback buffer
if (encoder == null)
fallbackBuffer = EncoderFallback.CreateFallbackBuffer();
else
fallbackBuffer = encoder.FallbackBuffer;
fallbackHelper = new EncoderFallbackBufferHelper(fallbackBuffer);
// chars has moved so we need to remember figure it out so Exception fallback
// index will be correct
fallbackHelper.InternalInitialize(charEnd - count, charEnd, encoder, false);
}
// Get Fallback
fallbackHelper.InternalFallback(ch, ref chars);
continue;
}
// We'll use this one
byteCount++;
}
Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
"[SBCSEncoding.GetByteCount]Expected Empty fallback buffer at end");
return (int)byteCount;
}
[System.Security.SecurityCritical] // auto-generated
public override unsafe int GetBytes(char* chars, int charCount,
byte* bytes, int byteCount, EncoderNLS encoder)
{
// Just need to ASSERT, this is called by something else internal that checked parameters already
Debug.Assert(bytes != null, "[SBCSCodePageEncoding.GetBytes]bytes is null");
Debug.Assert(byteCount >= 0, "[SBCSCodePageEncoding.GetBytes]byteCount is negative");
Debug.Assert(chars != null, "[SBCSCodePageEncoding.GetBytes]chars is null");
Debug.Assert(charCount >= 0, "[SBCSCodePageEncoding.GetBytes]charCount is negative");
// Assert because we shouldn't be able to have a null encoder.
Debug.Assert(EncoderFallback != null, "[SBCSCodePageEncoding.GetBytes]Attempting to use null encoder fallback");
CheckMemorySection();
// Need to test fallback
EncoderReplacementFallback fallback = null;
// Get any left over characters
char charLeftOver = (char)0;
if (encoder != null)
{
charLeftOver = encoder.charLeftOver;
Debug.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver),
"[SBCSCodePageEncoding.GetBytes]leftover character should be high surrogate");
fallback = encoder.Fallback as EncoderReplacementFallback;
// Verify that we have no fallbackbuffer, for SBCS its always empty, so just assert
Debug.Assert(!encoder.m_throwOnOverflow || !encoder.InternalHasFallbackBuffer ||
encoder.FallbackBuffer.Remaining == 0,
"[SBCSCodePageEncoding.GetBytes]Expected empty fallback buffer at start");
// if (encoder.m_throwOnOverflow && encoder.InternalHasFallbackBuffer &&
// encoder.FallbackBuffer.Remaining > 0)
// throw new ArgumentException(Environment.GetResourceString("Argument_EncoderFallbackNotEmpty",
// EncodingName, encoder.Fallback.GetType()));
}
else
{
// If we aren't using default fallback then we may have a complicated count.
fallback = EncoderFallback as EncoderReplacementFallback;
}
// prepare our end
char* charEnd = chars + charCount;
byte* byteStart = bytes;
char* charStart = chars;
// See if we do the fast default or slightly slower fallback
if (fallback != null && fallback.MaxCharCount == 1)
{
// Make sure our fallback character is valid first
byte bReplacement = _mapUnicodeToBytes[fallback.DefaultString[0]];
// Check for replacements in range, otherwise fall back to slow version.
if (bReplacement != 0)
{
// We should have exactly as many output bytes as input bytes, unless there's a leftover
// character, in which case we may need one more.
// If we had a leftover character we will have to add a ? (This happens if they had a funky
// fallback last time, but not this time. We can't spit any out though,
// because with fallback encoder each surrogate is treated as a seperate code point)
if (charLeftOver > 0)
{
// Have to have room
// Throw even if doing no throw version because this is just 1 char,
// so buffer will never be big enough
if (byteCount == 0)
ThrowBytesOverflow(encoder, true);
// This'll make sure we still have more room and also make sure our return value is correct.
*(bytes++) = bReplacement;
byteCount--; // We used one of the ones we were counting.
}
// This keeps us from overrunning our output buffer
if (byteCount < charCount)
{
// Throw or make buffer smaller?
ThrowBytesOverflow(encoder, byteCount < 1);
// Just use what we can
charEnd = chars + byteCount;
}
// Simple way
while (chars < charEnd)
{
char ch2 = *chars;
chars++;
byte bTemp = _mapUnicodeToBytes[ch2];
// Check for fallback
if (bTemp == 0 && ch2 != (char)0)
*bytes = bReplacement;
else
*bytes = bTemp;
bytes++;
}
// Clear encoder
if (encoder != null)
{
encoder.charLeftOver = (char)0;
encoder.m_charsUsed = (int)(chars - charStart);
}
return (int)(bytes - byteStart);
}
}
// Slower version, have to do real fallback.
// For fallback we may need a fallback buffer, we know we aren't default fallback
EncoderFallbackBuffer fallbackBuffer = null;
// prepare our end
byte* byteEnd = bytes + byteCount;
EncoderFallbackBufferHelper fallbackHelper = new EncoderFallbackBufferHelper(fallbackBuffer);
// We may have a left over character from last time, try and process it.
if (charLeftOver > 0)
{
// Since left over char was a surrogate, it'll have to be fallen back.
// Get Fallback
Debug.Assert(encoder != null, "[SBCSCodePageEncoding.GetBytes]Expect to have encoder if we have a charLeftOver");
fallbackBuffer = encoder.FallbackBuffer;
fallbackHelper = new EncoderFallbackBufferHelper(fallbackBuffer);
fallbackHelper.InternalInitialize(chars, charEnd, encoder, true);
// This will fallback a pair if *chars is a low surrogate
fallbackHelper.InternalFallback(charLeftOver, ref chars);
if (fallbackBuffer.Remaining > byteEnd - bytes)
{
// Throw it, if we don't have enough for this we never will
ThrowBytesOverflow(encoder, true);
}
}
// Now we may have fallback char[] already from the encoder fallback above
// Go ahead and do it, including the fallback.
char ch;
while ((ch = (fallbackBuffer == null) ? '\0' : fallbackHelper.InternalGetNextChar()) != 0 ||
chars < charEnd)
{
// First unwind any fallback
if (ch == 0)
{
// No fallback, just get next char
ch = *chars;
chars++;
}
// get byte for this char
byte bTemp = _mapUnicodeToBytes[ch];
// Check for fallback, this'll catch surrogate pairs too.
if (bTemp == 0 && ch != (char)0)
{
// Get Fallback
if (fallbackBuffer == null)
{
// Create & init fallback buffer
if (encoder == null)
fallbackBuffer = EncoderFallback.CreateFallbackBuffer();
else
fallbackBuffer = encoder.FallbackBuffer;
fallbackHelper = new EncoderFallbackBufferHelper(fallbackBuffer);
// chars has moved so we need to remember figure it out so Exception fallback
// index will be correct
fallbackHelper.InternalInitialize(charEnd - charCount, charEnd, encoder, true);
}
// Make sure we have enough room. Each fallback char will be 1 output char
// (or recursion exception will be thrown)
fallbackHelper.InternalFallback(ch, ref chars);
if (fallbackBuffer.Remaining > byteEnd - bytes)
{
// Didn't use this char, reset it
Debug.Assert(chars > charStart, "[SBCSCodePageEncoding.GetBytes]Expected chars to have advanced (fallback)");
chars--;
fallbackHelper.InternalReset();
// Throw it & drop this data
ThrowBytesOverflow(encoder, chars == charStart);
break;
}
continue;
}
// We'll use this one
// Bounds check
if (bytes >= byteEnd)
{
// didn't use this char, we'll throw or use buffer
Debug.Assert(fallbackBuffer == null || fallbackHelper.bFallingBack == false, "[SBCSCodePageEncoding.GetBytes]Expected to NOT be falling back");
if (fallbackBuffer == null || fallbackHelper.bFallingBack == false)
{
Debug.Assert(chars > charStart, "[SBCSCodePageEncoding.GetBytes]Expected chars to have advanced (normal)");
chars--; // don't use last char
}
ThrowBytesOverflow(encoder, chars == charStart); // throw ?
break; // don't throw, stop
}
// Go ahead and add it
*bytes = bTemp;
bytes++;
}
// encoder stuff if we have one
if (encoder != null)
{
// Fallback stuck it in encoder if necessary, but we have to clear MustFlush cases
if (fallbackBuffer != null && !fallbackHelper.bUsedEncoder)
// Clear it in case of MustFlush
encoder.charLeftOver = (char)0;
// Set our chars used count
encoder.m_charsUsed = (int)(chars - charStart);
}
// Expect Empty fallback buffer for SBCS
Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0, "[SBCSEncoding.GetBytes]Expected Empty fallback buffer at end");
return (int)(bytes - byteStart);
}
// This is internal and called by something else,
[System.Security.SecurityCritical] // auto-generated
public override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS decoder)
{
// Just assert, we're called internally so these should be safe, checked already
Debug.Assert(bytes != null, "[SBCSCodePageEncoding.GetCharCount]bytes is null");
Debug.Assert(count >= 0, "[SBCSCodePageEncoding.GetCharCount]byteCount is negative");
CheckMemorySection();
// See if we have best fit
bool bUseBestFit = false;
// Only need decoder fallback buffer if not using default replacement fallback or best fit fallback.
DecoderReplacementFallback fallback = null;
if (decoder == null)
{
fallback = DecoderFallback as DecoderReplacementFallback;
bUseBestFit = DecoderFallback is InternalDecoderBestFitFallback;
}
else
{
fallback = decoder.Fallback as DecoderReplacementFallback;
bUseBestFit = decoder.Fallback is InternalDecoderBestFitFallback;
Debug.Assert(!decoder.m_throwOnOverflow || !decoder.InternalHasFallbackBuffer ||
decoder.FallbackBuffer.Remaining == 0,
"[SBCSCodePageEncoding.GetChars]Expected empty fallback buffer at start");
}
if (bUseBestFit || (fallback != null && fallback.MaxCharCount == 1))
{
// Just return length, SBCS stay the same length because they don't map to surrogate
// pairs and we don't have a decoder fallback.
return count;
}
// Might need one of these later
DecoderFallbackBuffer fallbackBuffer = null;
DecoderFallbackBufferHelper fallbackHelper = new DecoderFallbackBufferHelper(fallbackBuffer);
// Have to do it the hard way.
// Assume charCount will be == count
int charCount = count;
byte[] byteBuffer = new byte[1];
// Do it our fast way
byte* byteEnd = bytes + count;
// Quick loop
while (bytes < byteEnd)
{
// Faster if don't use *bytes++;
char c;
c = _mapBytesToUnicode[*bytes];
bytes++;
// If unknown we have to do fallback count
if (c == UNKNOWN_CHAR)
{
// Must have a fallback buffer
if (fallbackBuffer == null)
{
// Need to adjust count so we get real start
if (decoder == null)
fallbackBuffer = DecoderFallback.CreateFallbackBuffer();
else
fallbackBuffer = decoder.FallbackBuffer;
fallbackHelper = new DecoderFallbackBufferHelper(fallbackBuffer);
fallbackHelper.InternalInitialize(byteEnd - count, null);
}
// Use fallback buffer
byteBuffer[0] = *(bytes - 1);
charCount--; // We'd already reserved one for *(bytes-1)
charCount += fallbackHelper.InternalFallback(byteBuffer, bytes);
}
}
// Fallback buffer must be empty
Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
"[SBCSEncoding.GetCharCount]Expected Empty fallback buffer at end");
// Converted sequence is same length as input
return charCount;
}
[System.Security.SecurityCritical] // auto-generated
public override unsafe int GetChars(byte* bytes, int byteCount,
char* chars, int charCount, DecoderNLS decoder)
{
// Just need to ASSERT, this is called by something else internal that checked parameters already
Debug.Assert(bytes != null, "[SBCSCodePageEncoding.GetChars]bytes is null");
Debug.Assert(byteCount >= 0, "[SBCSCodePageEncoding.GetChars]byteCount is negative");
Debug.Assert(chars != null, "[SBCSCodePageEncoding.GetChars]chars is null");
Debug.Assert(charCount >= 0, "[SBCSCodePageEncoding.GetChars]charCount is negative");
CheckMemorySection();
// See if we have best fit
bool bUseBestFit = false;
// Do it fast way if using ? replacement or best fit fallbacks
byte* byteEnd = bytes + byteCount;
byte* byteStart = bytes;
char* charStart = chars;
// Only need decoder fallback buffer if not using default replacement fallback or best fit fallback.
DecoderReplacementFallback fallback = null;
if (decoder == null)
{
fallback = DecoderFallback as DecoderReplacementFallback;
bUseBestFit = DecoderFallback is InternalDecoderBestFitFallback;
}
else
{
fallback = decoder.Fallback as DecoderReplacementFallback;
bUseBestFit = decoder.Fallback is InternalDecoderBestFitFallback;
Debug.Assert(!decoder.m_throwOnOverflow || !decoder.InternalHasFallbackBuffer ||
decoder.FallbackBuffer.Remaining == 0,
"[SBCSCodePageEncoding.GetChars]Expected empty fallback buffer at start");
}
if (bUseBestFit || (fallback != null && fallback.MaxCharCount == 1))
{
// Try it the fast way
char replacementChar;
if (fallback == null)
replacementChar = '?'; // Best fit alwasy has ? for fallback for SBCS
else
replacementChar = fallback.DefaultString[0];
// Need byteCount chars, otherwise too small buffer
if (charCount < byteCount)
{
// Need at least 1 output byte, throw if must throw
ThrowCharsOverflow(decoder, charCount < 1);
// Not throwing, use what we can
byteEnd = bytes + charCount;
}
// Quick loop, just do '?' replacement because we don't have fallbacks for decodings.
while (bytes < byteEnd)
{
char c;
if (bUseBestFit)
{
if (arrayBytesBestFit == null)
{
ReadBestFitTable();
}
c = arrayBytesBestFit[*bytes];
}
else
c = _mapBytesToUnicode[*bytes];
bytes++;
if (c == UNKNOWN_CHAR)
// This is an invalid byte in the ASCII encoding.
*chars = replacementChar;
else
*chars = c;
chars++;
}
// bytes & chars used are the same
if (decoder != null)
decoder.m_bytesUsed = (int)(bytes - byteStart);
return (int)(chars - charStart);
}
// Slower way's going to need a fallback buffer
DecoderFallbackBuffer fallbackBuffer = null;
byte[] byteBuffer = new byte[1];
char* charEnd = chars + charCount;
DecoderFallbackBufferHelper fallbackHelper = new DecoderFallbackBufferHelper(decoder.FallbackBuffer);
// Not quite so fast loop
while (bytes < byteEnd)
{
// Faster if don't use *bytes++;
char c = _mapBytesToUnicode[*bytes];
bytes++;
// See if it was unknown
if (c == UNKNOWN_CHAR)
{
// Make sure we have a fallback buffer
if (fallbackBuffer == null)
{
if (decoder == null)
fallbackBuffer = DecoderFallback.CreateFallbackBuffer();
else
fallbackBuffer = decoder.FallbackBuffer;
fallbackHelper = new DecoderFallbackBufferHelper(fallbackBuffer);
fallbackHelper.InternalInitialize(byteEnd - byteCount, charEnd);
}
// Use fallback buffer
Debug.Assert(bytes > byteStart,
"[SBCSCodePageEncoding.GetChars]Expected bytes to have advanced already (unknown byte)");
byteBuffer[0] = *(bytes - 1);
// Fallback adds fallback to chars, but doesn't increment chars unless the whole thing fits.
if (!fallbackHelper.InternalFallback(byteBuffer, bytes, ref chars))
{
// May or may not throw, but we didn't get this byte
bytes--; // unused byte
fallbackHelper.InternalReset(); // Didn't fall this back
ThrowCharsOverflow(decoder, bytes == byteStart); // throw?
break; // don't throw, but stop loop
}
}
else
{
// Make sure we have buffer space
if (chars >= charEnd)
{
Debug.Assert(bytes > byteStart,
"[SBCSCodePageEncoding.GetChars]Expected bytes to have advanced already (known byte)");
bytes--; // unused byte
ThrowCharsOverflow(decoder, bytes == byteStart); // throw?
break; // don't throw, but stop loop
}
*(chars) = c;
chars++;
}
}
// Might have had decoder fallback stuff.
if (decoder != null)
decoder.m_bytesUsed = (int)(bytes - byteStart);
// Expect Empty fallback buffer for GetChars
Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
"[SBCSEncoding.GetChars]Expected Empty fallback buffer at end");
return (int)(chars - charStart);
}
public override int GetMaxByteCount(int charCount)
{
if (charCount < 0)
throw new ArgumentOutOfRangeException("charCount", SR.ArgumentOutOfRange_NeedNonNegNum);
Contract.EndContractBlock();
// Characters would be # of characters + 1 in case high surrogate is ? * max fallback
long byteCount = (long)charCount + 1;
if (EncoderFallback.MaxCharCount > 1)
byteCount *= EncoderFallback.MaxCharCount;
// 1 to 1 for most characters. Only surrogates with fallbacks have less.
if (byteCount > 0x7fffffff)
throw new ArgumentOutOfRangeException("charCount", SR.ArgumentOutOfRange_GetByteCountOverflow);
return (int)byteCount;
}
public override int GetMaxCharCount(int byteCount)
{
if (byteCount < 0)
throw new ArgumentOutOfRangeException("byteCount", SR.ArgumentOutOfRange_NeedNonNegNum);
Contract.EndContractBlock();
// Just return length, SBCS stay the same length because they don't map to surrogate
long charCount = (long)byteCount;
// 1 to 1 for most characters. Only surrogates with fallbacks have less, unknown fallbacks could be longer.
if (DecoderFallback.MaxCharCount > 1)
charCount *= DecoderFallback.MaxCharCount;
if (charCount > 0x7fffffff)
throw new ArgumentOutOfRangeException("byteCount", SR.ArgumentOutOfRange_GetCharCountOverflow);
return (int)charCount;
}
// True if and only if the encoding only uses single byte code points. (Ie, ASCII, 1252, etc)
public override bool IsSingleByte
{
get
{
return true;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
namespace System.Globalization
{
/// <remarks>
/// Calendar support range:
/// Calendar Minimum Maximum
/// ========== ========== ==========
/// Gregorian 1900/04/30 2077/05/13
/// UmAlQura 1318/01/01 1500/12/30
/// </remarks>
public partial class UmAlQuraCalendar : Calendar
{
private const int MinCalendarYear = 1318;
private const int MaxCalendarYear = 1500;
private struct DateMapping
{
internal DateMapping(int MonthsLengthFlags, int GYear, int GMonth, int GDay)
{
HijriMonthsLengthFlags = MonthsLengthFlags;
GregorianDate = new DateTime(GYear, GMonth, GDay);
}
internal int HijriMonthsLengthFlags;
internal DateTime GregorianDate;
}
private static readonly DateMapping[] s_hijriYearInfo = InitDateMapping();
private static DateMapping[] InitDateMapping()
{
short[] rawData = new short[]
{
//These data is taken from Tables/Excel/UmAlQura.xls please make sure that the two places are in sync
/* DaysPerM GY GM GD D1 D2 D3 D4 D5 D6 D7 D8 D9 D10 D11 D12
1318*/0x02EA, 1900, 4, 30,/* 0 1 0 1 0 1 1 1 0 1 0 0 4/30/1900
1319*/0x06E9, 1901, 4, 19,/* 1 0 0 1 0 1 1 1 0 1 1 0 4/19/1901
1320*/0x0ED2, 1902, 4, 9,/* 0 1 0 0 1 0 1 1 0 1 1 1 4/9/1902
1321*/0x0EA4, 1903, 3, 30,/* 0 0 1 0 0 1 0 1 0 1 1 1 3/30/1903
1322*/0x0D4A, 1904, 3, 18,/* 0 1 0 1 0 0 1 0 1 0 1 1 3/18/1904
1323*/0x0A96, 1905, 3, 7,/* 0 1 1 0 1 0 0 1 0 1 0 1 3/7/1905
1324*/0x0536, 1906, 2, 24,/* 0 1 1 0 1 1 0 0 1 0 1 0 2/24/1906
1325*/0x0AB5, 1907, 2, 13,/* 1 0 1 0 1 1 0 1 0 1 0 1 2/13/1907
1326*/0x0DAA, 1908, 2, 3,/* 0 1 0 1 0 1 0 1 1 0 1 1 2/3/1908
1327*/0x0BA4, 1909, 1, 23,/* 0 0 1 0 0 1 0 1 1 1 0 1 1/23/1909
1328*/0x0B49, 1910, 1, 12,/* 1 0 0 1 0 0 1 0 1 1 0 1 1/12/1910
1329*/0x0A93, 1911, 1, 1,/* 1 1 0 0 1 0 0 1 0 1 0 1 1/1/1911
1330*/0x052B, 1911, 12, 21,/* 1 1 0 1 0 1 0 0 1 0 1 0 12/21/1911
1331*/0x0A57, 1912, 12, 9,/* 1 1 1 0 1 0 1 0 0 1 0 1 12/9/1912
1332*/0x04B6, 1913, 11, 29,/* 0 1 1 0 1 1 0 1 0 0 1 0 11/29/1913
1333*/0x0AB5, 1914, 11, 18,/* 1 0 1 0 1 1 0 1 0 1 0 1 11/18/1914
1334*/0x05AA, 1915, 11, 8,/* 0 1 0 1 0 1 0 1 1 0 1 0 11/8/1915
1335*/0x0D55, 1916, 10, 27,/* 1 0 1 0 1 0 1 0 1 0 1 1 10/27/1916
1336*/0x0D2A, 1917, 10, 17,/* 0 1 0 1 0 1 0 0 1 0 1 1 10/17/1917
1337*/0x0A56, 1918, 10, 6,/* 0 1 1 0 1 0 1 0 0 1 0 1 10/6/1918
1338*/0x04AE, 1919, 9, 25,/* 0 1 1 1 0 1 0 1 0 0 1 0 9/25/1919
1339*/0x095D, 1920, 9, 13,/* 1 0 1 1 1 0 1 0 1 0 0 1 9/13/1920
1340*/0x02EC, 1921, 9, 3,/* 0 0 1 1 0 1 1 1 0 1 0 0 9/3/1921
1341*/0x06D5, 1922, 8, 23,/* 1 0 1 0 1 0 1 1 0 1 1 0 8/23/1922
1342*/0x06AA, 1923, 8, 13,/* 0 1 0 1 0 1 0 1 0 1 1 0 8/13/1923
1343*/0x0555, 1924, 8, 1,/* 1 0 1 0 1 0 1 0 1 0 1 0 8/1/1924
1344*/0x04AB, 1925, 7, 21,/* 1 1 0 1 0 1 0 1 0 0 1 0 7/21/1925
1345*/0x095B, 1926, 7, 10,/* 1 1 0 1 1 0 1 0 1 0 0 1 7/10/1926
1346*/0x02BA, 1927, 6, 30,/* 0 1 0 1 1 1 0 1 0 1 0 0 6/30/1927
1347*/0x0575, 1928, 6, 18,/* 1 0 1 0 1 1 1 0 1 0 1 0 6/18/1928
1348*/0x0BB2, 1929, 6, 8,/* 0 1 0 0 1 1 0 1 1 1 0 1 6/8/1929
1349*/0x0764, 1930, 5, 29,/* 0 0 1 0 0 1 1 0 1 1 1 0 5/29/1930
1350*/0x0749, 1931, 5, 18,/* 1 0 0 1 0 0 1 0 1 1 1 0 5/18/1931
1351*/0x0655, 1932, 5, 6,/* 1 0 1 0 1 0 1 0 0 1 1 0 5/6/1932
1352*/0x02AB, 1933, 4, 25,/* 1 1 0 1 0 1 0 1 0 1 0 0 4/25/1933
1353*/0x055B, 1934, 4, 14,/* 1 1 0 1 1 0 1 0 1 0 1 0 4/14/1934
1354*/0x0ADA, 1935, 4, 4,/* 0 1 0 1 1 0 1 1 0 1 0 1 4/4/1935
1355*/0x06D4, 1936, 3, 24,/* 0 0 1 0 1 0 1 1 0 1 1 0 3/24/1936
1356*/0x0EC9, 1937, 3, 13,/* 1 0 0 1 0 0 1 1 0 1 1 1 3/13/1937
1357*/0x0D92, 1938, 3, 3,/* 0 1 0 0 1 0 0 1 1 0 1 1 3/3/1938
1358*/0x0D25, 1939, 2, 20,/* 1 0 1 0 0 1 0 0 1 0 1 1 2/20/1939
1359*/0x0A4D, 1940, 2, 9,/* 1 0 1 1 0 0 1 0 0 1 0 1 2/9/1940
1360*/0x02AD, 1941, 1, 28,/* 1 0 1 1 0 1 0 1 0 1 0 0 1/28/1941
1361*/0x056D, 1942, 1, 17,/* 1 0 1 1 0 1 1 0 1 0 1 0 1/17/1942
1362*/0x0B6A, 1943, 1, 7,/* 0 1 0 1 0 1 1 0 1 1 0 1 1/7/1943
1363*/0x0B52, 1943, 12, 28,/* 0 1 0 0 1 0 1 0 1 1 0 1 12/28/1943
1364*/0x0AA5, 1944, 12, 16,/* 1 0 1 0 0 1 0 1 0 1 0 1 12/16/1944
1365*/0x0A4B, 1945, 12, 5,/* 1 1 0 1 0 0 1 0 0 1 0 1 12/5/1945
1366*/0x0497, 1946, 11, 24,/* 1 1 1 0 1 0 0 1 0 0 1 0 11/24/1946
1367*/0x0937, 1947, 11, 13,/* 1 1 1 0 1 1 0 0 1 0 0 1 11/13/1947
1368*/0x02B6, 1948, 11, 2,/* 0 1 1 0 1 1 0 1 0 1 0 0 11/2/1948
1369*/0x0575, 1949, 10, 22,/* 1 0 1 0 1 1 1 0 1 0 1 0 10/22/1949
1370*/0x0D6A, 1950, 10, 12,/* 0 1 0 1 0 1 1 0 1 0 1 1 10/12/1950
1371*/0x0D52, 1951, 10, 2,/* 0 1 0 0 1 0 1 0 1 0 1 1 10/2/1951
1372*/0x0A96, 1952, 9, 20,/* 0 1 1 0 1 0 0 1 0 1 0 1 9/20/1952
1373*/0x092D, 1953, 9, 9,/* 1 0 1 1 0 1 0 0 1 0 0 1 9/9/1953
1374*/0x025D, 1954, 8, 29,/* 1 0 1 1 1 0 1 0 0 1 0 0 8/29/1954
1375*/0x04DD, 1955, 8, 18,/* 1 0 1 1 1 0 1 1 0 0 1 0 8/18/1955
1376*/0x0ADA, 1956, 8, 7,/* 0 1 0 1 1 0 1 1 0 1 0 1 8/7/1956
1377*/0x05D4, 1957, 7, 28,/* 0 0 1 0 1 0 1 1 1 0 1 0 7/28/1957
1378*/0x0DA9, 1958, 7, 17,/* 1 0 0 1 0 1 0 1 1 0 1 1 7/17/1958
1379*/0x0D52, 1959, 7, 7,/* 0 1 0 0 1 0 1 0 1 0 1 1 7/7/1959
1380*/0x0AAA, 1960, 6, 25,/* 0 1 0 1 0 1 0 1 0 1 0 1 6/25/1960
1381*/0x04D6, 1961, 6, 14,/* 0 1 1 0 1 0 1 1 0 0 1 0 6/14/1961
1382*/0x09B6, 1962, 6, 3,/* 0 1 1 0 1 1 0 1 1 0 0 1 6/3/1962
1383*/0x0374, 1963, 5, 24,/* 0 0 1 0 1 1 1 0 1 1 0 0 5/24/1963
1384*/0x0769, 1964, 5, 12,/* 1 0 0 1 0 1 1 0 1 1 1 0 5/12/1964
1385*/0x0752, 1965, 5, 2,/* 0 1 0 0 1 0 1 0 1 1 1 0 5/2/1965
1386*/0x06A5, 1966, 4, 21,/* 1 0 1 0 0 1 0 1 0 1 1 0 4/21/1966
1387*/0x054B, 1967, 4, 10,/* 1 1 0 1 0 0 1 0 1 0 1 0 4/10/1967
1388*/0x0AAB, 1968, 3, 29,/* 1 1 0 1 0 1 0 1 0 1 0 1 3/29/1968
1389*/0x055A, 1969, 3, 19,/* 0 1 0 1 1 0 1 0 1 0 1 0 3/19/1969
1390*/0x0AD5, 1970, 3, 8,/* 1 0 1 0 1 0 1 1 0 1 0 1 3/8/1970
1391*/0x0DD2, 1971, 2, 26,/* 0 1 0 0 1 0 1 1 1 0 1 1 2/26/1971
1392*/0x0DA4, 1972, 2, 16,/* 0 0 1 0 0 1 0 1 1 0 1 1 2/16/1972
1393*/0x0D49, 1973, 2, 4,/* 1 0 0 1 0 0 1 0 1 0 1 1 2/4/1973
1394*/0x0A95, 1974, 1, 24,/* 1 0 1 0 1 0 0 1 0 1 0 1 1/24/1974
1395*/0x052D, 1975, 1, 13,/* 1 0 1 1 0 1 0 0 1 0 1 0 1/13/1975
1396*/0x0A5D, 1976, 1, 2,/* 1 0 1 1 1 0 1 0 0 1 0 1 1/2/1976
1397*/0x055A, 1976, 12, 22,/* 0 1 0 1 1 0 1 0 1 0 1 0 12/22/1976
1398*/0x0AD5, 1977, 12, 11,/* 1 0 1 0 1 0 1 1 0 1 0 1 12/11/1977
1399*/0x06AA, 1978, 12, 1,/* 0 1 0 1 0 1 0 1 0 1 1 0 12/1/1978
1400*/0x0695, 1979, 11, 20,/* 1 0 1 0 1 0 0 1 0 1 1 0 11/20/1979
1401*/0x052B, 1980, 11, 8,/* 1 1 0 1 0 1 0 0 1 0 1 0 11/8/1980
1402*/0x0A57, 1981, 10, 28,/* 1 1 1 0 1 0 1 0 0 1 0 1 10/28/1981
1403*/0x04AE, 1982, 10, 18,/* 0 1 1 1 0 1 0 1 0 0 1 0 10/18/1982
1404*/0x0976, 1983, 10, 7,/* 0 1 1 0 1 1 1 0 1 0 0 1 10/7/1983
1405*/0x056C, 1984, 9, 26,/* 0 0 1 1 0 1 1 0 1 0 1 0 9/26/1984
1406*/0x0B55, 1985, 9, 15,/* 1 0 1 0 1 0 1 0 1 1 0 1 9/15/1985
1407*/0x0AAA, 1986, 9, 5,/* 0 1 0 1 0 1 0 1 0 1 0 1 9/5/1986
1408*/0x0A55, 1987, 8, 25,/* 1 0 1 0 1 0 1 0 0 1 0 1 8/25/1987
1409*/0x04AD, 1988, 8, 13,/* 1 0 1 1 0 1 0 1 0 0 1 0 8/13/1988
1410*/0x095D, 1989, 8, 2,/* 1 0 1 1 1 0 1 0 1 0 0 1 8/2/1989
1411*/0x02DA, 1990, 7, 23,/* 0 1 0 1 1 0 1 1 0 1 0 0 7/23/1990
1412*/0x05D9, 1991, 7, 12,/* 1 0 0 1 1 0 1 1 1 0 1 0 7/12/1991
1413*/0x0DB2, 1992, 7, 1,/* 0 1 0 0 1 1 0 1 1 0 1 1 7/1/1992
1414*/0x0BA4, 1993, 6, 21,/* 0 0 1 0 0 1 0 1 1 1 0 1 6/21/1993
1415*/0x0B4A, 1994, 6, 10,/* 0 1 0 1 0 0 1 0 1 1 0 1 6/10/1994
1416*/0x0A55, 1995, 5, 30,/* 1 0 1 0 1 0 1 0 0 1 0 1 5/30/1995
1417*/0x02B5, 1996, 5, 18,/* 1 0 1 0 1 1 0 1 0 1 0 0 5/18/1996
1418*/0x0575, 1997, 5, 7,/* 1 0 1 0 1 1 1 0 1 0 1 0 5/7/1997
1419*/0x0B6A, 1998, 4, 27,/* 0 1 0 1 0 1 1 0 1 1 0 1 4/27/1998
1420*/0x0BD2, 1999, 4, 17,/* 0 1 0 0 1 0 1 1 1 1 0 1 4/17/1999
1421*/0x0BC4, 2000, 4, 6,/* 0 0 1 0 0 0 1 1 1 1 0 1 4/6/2000
1422*/0x0B89, 2001, 3, 26,/* 1 0 0 1 0 0 0 1 1 1 0 1 3/26/2001
1423*/0x0A95, 2002, 3, 15,/* 1 0 1 0 1 0 0 1 0 1 0 1 3/15/2002
1424*/0x052D, 2003, 3, 4,/* 1 0 1 1 0 1 0 0 1 0 1 0 3/4/2003
1425*/0x05AD, 2004, 2, 21,/* 1 0 1 1 0 1 0 1 1 0 1 0 2/21/2004
1426*/0x0B6A, 2005, 2, 10,/* 0 1 0 1 0 1 1 0 1 1 0 1 2/10/2005
1427*/0x06D4, 2006, 1, 31,/* 0 0 1 0 1 0 1 1 0 1 1 0 1/31/2006
1428*/0x0DC9, 2007, 1, 20,/* 1 0 0 1 0 0 1 1 1 0 1 1 1/20/2007
1429*/0x0D92, 2008, 1, 10,/* 0 1 0 0 1 0 0 1 1 0 1 1 1/10/2008
1430*/0x0AA6, 2008, 12, 29,/* 0 1 1 0 0 1 0 1 0 1 0 1 12/29/2008
1431*/0x0956, 2009, 12, 18,/* 0 1 1 0 1 0 1 0 1 0 0 1 12/18/2009
1432*/0x02AE, 2010, 12, 7,/* 0 1 1 1 0 1 0 1 0 1 0 0 12/7/2010
1433*/0x056D, 2011, 11, 26,/* 1 0 1 1 0 1 1 0 1 0 1 0 11/26/2011
1434*/0x036A, 2012, 11, 15,/* 0 1 0 1 0 1 1 0 1 1 0 0 11/15/2012
1435*/0x0B55, 2013, 11, 4,/* 1 0 1 0 1 0 1 0 1 1 0 1 11/4/2013
1436*/0x0AAA, 2014, 10, 25,/* 0 1 0 1 0 1 0 1 0 1 0 1 10/25/2014
1437*/0x094D, 2015, 10, 14,/* 1 0 1 1 0 0 1 0 1 0 0 1 10/14/2015
1438*/0x049D, 2016, 10, 2,/* 1 0 1 1 1 0 0 1 0 0 1 0 10/2/2016
1439*/0x095D, 2017, 9, 21,/* 1 0 1 1 1 0 1 0 1 0 0 1 9/21/2017
1440*/0x02BA, 2018, 9, 11,/* 0 1 0 1 1 1 0 1 0 1 0 0 9/11/2018
1441*/0x05B5, 2019, 8, 31,/* 1 0 1 0 1 1 0 1 1 0 1 0 8/31/2019
1442*/0x05AA, 2020, 8, 20,/* 0 1 0 1 0 1 0 1 1 0 1 0 8/20/2020
1443*/0x0D55, 2021, 8, 9,/* 1 0 1 0 1 0 1 0 1 0 1 1 8/9/2021
1444*/0x0A9A, 2022, 7, 30,/* 0 1 0 1 1 0 0 1 0 1 0 1 7/30/2022
1445*/0x092E, 2023, 7, 19,/* 0 1 1 1 0 1 0 0 1 0 0 1 7/19/2023
1446*/0x026E, 2024, 7, 7,/* 0 1 1 1 0 1 1 0 0 1 0 0 7/7/2024
1447*/0x055D, 2025, 6, 26,/* 1 0 1 1 1 0 1 0 1 0 1 0 6/26/2025
1448*/0x0ADA, 2026, 6, 16,/* 0 1 0 1 1 0 1 1 0 1 0 1 6/16/2026
1449*/0x06D4, 2027, 6, 6,/* 0 0 1 0 1 0 1 1 0 1 1 0 6/6/2027
1450*/0x06A5, 2028, 5, 25,/* 1 0 1 0 0 1 0 1 0 1 1 0 5/25/2028
1451*/0x054B, 2029, 5, 14,/* 1 1 0 1 0 0 1 0 1 0 1 0 5/14/2029
1452*/0x0A97, 2030, 5, 3,/* 1 1 1 0 1 0 0 1 0 1 0 1 5/3/2030
1453*/0x054E, 2031, 4, 23,/* 0 1 1 1 0 0 1 0 1 0 1 0 4/23/2031
1454*/0x0AAE, 2032, 4, 11,/* 0 1 1 1 0 1 0 1 0 1 0 1 4/11/2032
1455*/0x05AC, 2033, 4, 1,/* 0 0 1 1 0 1 0 1 1 0 1 0 4/1/2033
1456*/0x0BA9, 2034, 3, 21,/* 1 0 0 1 0 1 0 1 1 1 0 1 3/21/2034
1457*/0x0D92, 2035, 3, 11,/* 0 1 0 0 1 0 0 1 1 0 1 1 3/11/2035
1458*/0x0B25, 2036, 2, 28,/* 1 0 1 0 0 1 0 0 1 1 0 1 2/28/2036
1459*/0x064B, 2037, 2, 16,/* 1 1 0 1 0 0 1 0 0 1 1 0 2/16/2037
1460*/0x0CAB, 2038, 2, 5,/* 1 1 0 1 0 1 0 1 0 0 1 1 2/5/2038
1461*/0x055A, 2039, 1, 26,/* 0 1 0 1 1 0 1 0 1 0 1 0 1/26/2039
1462*/0x0B55, 2040, 1, 15,/* 1 0 1 0 1 0 1 0 1 1 0 1 1/15/2040
1463*/0x06D2, 2041, 1, 4,/* 0 1 0 0 1 0 1 1 0 1 1 0 1/4/2041
1464*/0x0EA5, 2041, 12, 24,/* 1 0 1 0 0 1 0 1 0 1 1 1 12/24/2041
1465*/0x0E4A, 2042, 12, 14,/* 0 1 0 1 0 0 1 0 0 1 1 1 12/14/2042
1466*/0x0A95, 2043, 12, 3,/* 1 0 1 0 1 0 0 1 0 1 0 1 12/3/2043
1467*/0x052D, 2044, 11, 21,/* 1 0 1 1 0 1 0 0 1 0 1 0 11/21/2044
1468*/0x0AAD, 2045, 11, 10,/* 1 0 1 1 0 1 0 1 0 1 0 1 11/10/2045
1469*/0x036C, 2046, 10, 31,/* 0 0 1 1 0 1 1 0 1 1 0 0 10/31/2046
1470*/0x0759, 2047, 10, 20,/* 1 0 0 1 1 0 1 0 1 1 1 0 10/20/2047
1471*/0x06D2, 2048, 10, 9,/* 0 1 0 0 1 0 1 1 0 1 1 0 10/9/2048
1472*/0x0695, 2049, 9, 28,/* 1 0 1 0 1 0 0 1 0 1 1 0 9/28/2049
1473*/0x052D, 2050, 9, 17,/* 1 0 1 1 0 1 0 0 1 0 1 0 9/17/2050
1474*/0x0A5B, 2051, 9, 6,/* 1 1 0 1 1 0 1 0 0 1 0 1 9/6/2051
1475*/0x04BA, 2052, 8, 26,/* 0 1 0 1 1 1 0 1 0 0 1 0 8/26/2052
1476*/0x09BA, 2053, 8, 15,/* 0 1 0 1 1 1 0 1 1 0 0 1 8/15/2053
1477*/0x03B4, 2054, 8, 5,/* 0 0 1 0 1 1 0 1 1 1 0 0 8/5/2054
1478*/0x0B69, 2055, 7, 25,/* 1 0 0 1 0 1 1 0 1 1 0 1 7/25/2055
1479*/0x0B52, 2056, 7, 14,/* 0 1 0 0 1 0 1 0 1 1 0 1 7/14/2056
1480*/0x0AA6, 2057, 7, 3,/* 0 1 1 0 0 1 0 1 0 1 0 1 7/3/2057
1481*/0x04B6, 2058, 6, 22,/* 0 1 1 0 1 1 0 1 0 0 1 0 6/22/2058
1482*/0x096D, 2059, 6, 11,/* 1 0 1 1 0 1 1 0 1 0 0 1 6/11/2059
1483*/0x02EC, 2060, 5, 31,/* 0 0 1 1 0 1 1 1 0 1 0 0 5/31/2060
1484*/0x06D9, 2061, 5, 20,/* 1 0 0 1 1 0 1 1 0 1 1 0 5/20/2061
1485*/0x0EB2, 2062, 5, 10,/* 0 1 0 0 1 1 0 1 0 1 1 1 5/10/2062
1486*/0x0D54, 2063, 4, 30,/* 0 0 1 0 1 0 1 0 1 0 1 1 4/30/2063
1487*/0x0D2A, 2064, 4, 18,/* 0 1 0 1 0 1 0 0 1 0 1 1 4/18/2064
1488*/0x0A56, 2065, 4, 7,/* 0 1 1 0 1 0 1 0 0 1 0 1 4/7/2065
1489*/0x04AE, 2066, 3, 27,/* 0 1 1 1 0 1 0 1 0 0 1 0 3/27/2066
1490*/0x096D, 2067, 3, 16,/* 1 0 1 1 0 1 1 0 1 0 0 1 3/16/2067
1491*/0x0D6A, 2068, 3, 5,/* 0 1 0 1 0 1 1 0 1 0 1 1 3/5/2068
1492*/0x0B54, 2069, 2, 23,/* 0 0 1 0 1 0 1 0 1 1 0 1 2/23/2069
1493*/0x0B29, 2070, 2, 12,/* 1 0 0 1 0 1 0 0 1 1 0 1 2/12/2070
1494*/0x0A93, 2071, 2, 1,/* 1 1 0 0 1 0 0 1 0 1 0 1 2/1/2071
1495*/0x052B, 2072, 1, 21,/* 1 1 0 1 0 1 0 0 1 0 1 0 1/21/2072
1496*/0x0A57, 2073, 1, 9,/* 1 1 1 0 1 0 1 0 0 1 0 1 1/9/2073
1497*/0x0536, 2073, 12, 30,/* 0 1 1 0 1 1 0 0 1 0 1 0 12/30/2073
1498*/0x0AB5, 2074, 12, 19,/* 1 0 1 0 1 1 0 1 0 1 0 1 12/19/2074
1499*/0x06AA, 2075, 12, 9,/* 0 1 0 1 0 1 0 1 0 1 1 0 12/9/2075
1500*/0x0E93, 2076, 11, 27,/* 1 1 0 0 1 0 0 1 0 1 1 1 11/27/2076
1501*/ 0, 2077, 11, 17,/* 0 0 0 0 0 0 0 0 0 0 0 0 11/17/2077
*/ };
// Direct inline initialization of DateMapping array would produce a lot of code bloat.
// We take advantage of C# compiler compiles inline initialization of primitive type array into very compact code.
// So we start with raw data stored in primitive type array, and initialize the DateMapping out of it
DateMapping[] mapping = new DateMapping[rawData.Length / 4];
for (int i = 0; i < mapping.Length; i++)
mapping[i] = new DateMapping(rawData[i * 4], rawData[i * 4 + 1], rawData[i * 4 + 2], rawData[i * 4 + 3]);
return mapping;
}
public const int UmAlQuraEra = 1;
private const int DatePartYear = 0;
private const int DatePartDayOfYear = 1;
private const int DatePartMonth = 2;
private const int DatePartDay = 3;
private static readonly DateTime s_minDate = new DateTime(1900, 4, 30);
private static readonly DateTime s_maxDate = new DateTime((new DateTime(2077, 11, 16, 23, 59, 59, 999)).Ticks + 9999);
public override DateTime MinSupportedDateTime => s_minDate;
public override DateTime MaxSupportedDateTime => s_maxDate;
public override CalendarAlgorithmType AlgorithmType => CalendarAlgorithmType.LunarCalendar;
public UmAlQuraCalendar()
{
}
internal override CalendarId BaseCalendarID => CalendarId.HIJRI;
internal override CalendarId ID => CalendarId.UMALQURA;
protected override int DaysInYearBeforeMinSupportedYear
{
get
{
// HijriCalendar has same number of days as UmAlQuraCalendar for any given year
// HijriCalendar says year 1317 has 355 days.
return 355;
}
}
private static void ConvertHijriToGregorian(int HijriYear, int HijriMonth, int HijriDay, out int yg, out int mg, out int dg)
{
Debug.Assert((HijriYear >= MinCalendarYear) && (HijriYear <= MaxCalendarYear), "Hijri year is out of range.");
Debug.Assert(HijriMonth >= 1, "Hijri month is out of range.");
Debug.Assert(HijriDay >= 1, "Hijri day is out of range.");
int nDays = HijriDay - 1;
int index = HijriYear - MinCalendarYear;
DateTime dt = s_hijriYearInfo[index].GregorianDate;
int b = s_hijriYearInfo[index].HijriMonthsLengthFlags;
for (int m = 1; m < HijriMonth; m++)
{
// Add the months lengths before mh
nDays = nDays + 29 + (b & 1);
b = b >> 1;
}
dt = dt.AddDays(nDays);
dt.GetDatePart(out yg, out mg, out dg);
}
private static long GetAbsoluteDateUmAlQura(int year, int month, int day)
{
ConvertHijriToGregorian(year, month, day, out int yg, out int mg, out int dg);
return GregorianCalendar.GetAbsoluteDate(yg, mg, dg);
}
internal static void CheckTicksRange(long ticks)
{
if (ticks < s_minDate.Ticks || ticks > s_maxDate.Ticks)
{
throw new ArgumentOutOfRangeException(
"time",
ticks,
SR.Format(
CultureInfo.InvariantCulture,
SR.ArgumentOutOfRange_CalendarRange,
s_minDate,
s_maxDate));
}
}
internal static void CheckEraRange(int era)
{
if (era != CurrentEra && era != UmAlQuraEra)
{
throw new ArgumentOutOfRangeException(nameof(era), era, SR.ArgumentOutOfRange_InvalidEraValue);
}
}
internal static void CheckYearRange(int year, int era)
{
CheckEraRange(era);
if (year < MinCalendarYear || year > MaxCalendarYear)
{
throw new ArgumentOutOfRangeException(
nameof(year),
year,
SR.Format(SR.ArgumentOutOfRange_Range, MinCalendarYear, MaxCalendarYear));
}
}
internal static void CheckYearMonthRange(int year, int month, int era)
{
CheckYearRange(year, era);
if (month < 1 || month > 12)
{
throw new ArgumentOutOfRangeException(nameof(month), month, SR.ArgumentOutOfRange_Month);
}
}
private static void ConvertGregorianToHijri(DateTime time, out int HijriYear, out int HijriMonth, out int HijriDay)
{
Debug.Assert((time.Ticks >= s_minDate.Ticks) && (time.Ticks <= s_maxDate.Ticks), "Gregorian date is out of range.");
// Find the index where we should start our search by quessing the Hijri year that we will be in HijriYearInfo.
// A Hijri year is 354 or 355 days. Use 355 days so that we will search from a lower index.
int index = (int)((time.Ticks - s_minDate.Ticks) / Calendar.TicksPerDay) / 355;
do
{
} while (time.CompareTo(s_hijriYearInfo[++index].GregorianDate) > 0); //while greater
if (time.CompareTo(s_hijriYearInfo[index].GregorianDate) != 0)
{
index--;
}
TimeSpan ts = time.Subtract(s_hijriYearInfo[index].GregorianDate);
int yh1 = index + MinCalendarYear;
int mh1 = 1;
int dh1 = 1;
double nDays = ts.TotalDays;
int b = s_hijriYearInfo[index].HijriMonthsLengthFlags;
int daysPerThisMonth = 29 + (b & 1);
while (nDays >= daysPerThisMonth)
{
nDays -= daysPerThisMonth;
b = b >> 1;
daysPerThisMonth = 29 + (b & 1);
mh1++;
}
dh1 += (int)nDays;
HijriDay = dh1;
HijriMonth = mh1;
HijriYear = yh1;
}
/// <summary>
/// First, we get the absolute date (the number of days from January 1st, 1 A.C) for the given ticks.
/// Use the formula (((AbsoluteDate - 226894) * 33) / (33 * 365 + 8)) + 1, we can a rough value for the UmAlQura year.
/// In order to get the exact UmAlQura year, we compare the exact absolute date for UmAlQuraYear and (UmAlQuraYear + 1).
/// From here, we can get the correct UmAlQura year.
/// </summary>
private int GetDatePart(DateTime time, int part)
{
long ticks = time.Ticks;
CheckTicksRange(ticks);
ConvertGregorianToHijri(time, out int UmAlQuraYear, out int UmAlQuraMonth, out int UmAlQuraDay);
if (part == DatePartYear)
{
return UmAlQuraYear;
}
if (part == DatePartMonth)
{
return UmAlQuraMonth;
}
if (part == DatePartDay)
{
return UmAlQuraDay;
}
if (part == DatePartDayOfYear)
{
return (int)(GetAbsoluteDateUmAlQura(UmAlQuraYear, UmAlQuraMonth, UmAlQuraDay) - GetAbsoluteDateUmAlQura(UmAlQuraYear, 1, 1) + 1);
}
// Incorrect part value.
throw new InvalidOperationException(SR.InvalidOperation_DateTimeParsing);
}
public override DateTime AddMonths(DateTime time, int months)
{
if (months < -120000 || months > 120000)
{
throw new ArgumentOutOfRangeException(
nameof(months),
months,
SR.Format(SR.ArgumentOutOfRange_Range, -120000, 120000));
}
// Get the date in UmAlQura calendar.
int y = GetDatePart(time, DatePartYear);
int m = GetDatePart(time, DatePartMonth);
int d = GetDatePart(time, DatePartDay);
int i = m - 1 + months;
if (i >= 0)
{
m = i % 12 + 1;
y = y + i / 12;
}
else
{
m = 12 + (i + 1) % 12;
y = y + (i - 11) / 12;
}
if (d > 29)
{
int days = GetDaysInMonth(y, m);
if (d > days)
{
d = days;
}
}
CheckYearRange(y, UmAlQuraEra);
DateTime dt = new DateTime(GetAbsoluteDateUmAlQura(y, m, d) * TicksPerDay + time.Ticks % TicksPerDay);
Calendar.CheckAddResult(dt.Ticks, MinSupportedDateTime, MaxSupportedDateTime);
return dt;
}
public override DateTime AddYears(DateTime time, int years)
{
return AddMonths(time, years * 12);
}
public override int GetDayOfMonth(DateTime time)
{
return GetDatePart(time, DatePartDay);
}
public override DayOfWeek GetDayOfWeek(DateTime time)
{
return (DayOfWeek)((int)(time.Ticks / TicksPerDay + 1) % 7);
}
public override int GetDayOfYear(DateTime time)
{
return GetDatePart(time, DatePartDayOfYear);
}
public override int GetDaysInMonth(int year, int month, int era)
{
CheckYearMonthRange(year, month, era);
if ((s_hijriYearInfo[year - MinCalendarYear].HijriMonthsLengthFlags & (1 << month - 1)) == 0)
{
return 29;
}
else
{
return 30;
}
}
internal static int RealGetDaysInYear(int year)
{
int days = 0;
Debug.Assert((year >= MinCalendarYear) && (year <= MaxCalendarYear), "Hijri year is out of range.");
int b = s_hijriYearInfo[year - MinCalendarYear].HijriMonthsLengthFlags;
for (int m = 1; m <= 12; m++)
{
days = days + 29 + (b & 1); /* Add the months lengths before mh */
b = b >> 1;
}
Debug.Assert((days == 354) || (days == 355), "Hijri year has to be 354 or 355 days.");
return days;
}
public override int GetDaysInYear(int year, int era)
{
CheckYearRange(year, era);
return RealGetDaysInYear(year);
}
public override int GetEra(DateTime time)
{
CheckTicksRange(time.Ticks);
return UmAlQuraEra;
}
public override int[] Eras => new int[] { UmAlQuraEra };
public override int GetMonth(DateTime time)
{
return GetDatePart(time, DatePartMonth);
}
public override int GetMonthsInYear(int year, int era)
{
CheckYearRange(year, era);
return 12;
}
public override int GetYear(DateTime time)
{
return GetDatePart(time, DatePartYear);
}
public override bool IsLeapDay(int year, int month, int day, int era)
{
if (day >= 1 && day <= 29)
{
CheckYearMonthRange(year, month, era);
return false;
}
// The year/month/era value checking is done in GetDaysInMonth().
int daysInMonth = GetDaysInMonth(year, month, era);
if (day < 1 || day > daysInMonth)
{
throw new ArgumentOutOfRangeException(
nameof(day),
day,
SR.Format(SR.ArgumentOutOfRange_Day, daysInMonth, month));
}
return false;
}
public override int GetLeapMonth(int year, int era)
{
CheckYearRange(year, era);
return 0;
}
public override bool IsLeapMonth(int year, int month, int era)
{
CheckYearMonthRange(year, month, era);
return false;
}
public override bool IsLeapYear(int year, int era)
{
CheckYearRange(year, era);
return RealGetDaysInYear(year) == 355;
}
public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era)
{
if (day >= 1 && day <= 29)
{
CheckYearMonthRange(year, month, era);
goto DayInRang;
}
// The year/month/era value checking is done in GetDaysInMonth().
int daysInMonth = GetDaysInMonth(year, month, era);
if (day < 1 || day > daysInMonth)
{
throw new ArgumentOutOfRangeException(
nameof(day),
day,
SR.Format(SR.ArgumentOutOfRange_Day, daysInMonth, month));
}
DayInRang:
long lDate = GetAbsoluteDateUmAlQura(year, month, day);
if (lDate < 0)
{
throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadYearMonthDay);
}
return new DateTime(lDate * GregorianCalendar.TicksPerDay + TimeToTicks(hour, minute, second, millisecond));
}
private const int DefaultTwoDigitYearMax = 1451;
public override int TwoDigitYearMax
{
get
{
if (_twoDigitYearMax == -1)
{
_twoDigitYearMax = GetSystemTwoDigitYearSetting(ID, DefaultTwoDigitYearMax);
}
return _twoDigitYearMax;
}
set
{
if (value != 99 && (value < MinCalendarYear || value > MaxCalendarYear))
{
throw new ArgumentOutOfRangeException(
nameof(value),
value,
SR.Format(SR.ArgumentOutOfRange_Range, MinCalendarYear, MaxCalendarYear));
}
VerifyWritable();
// We allow year 99 to be set so that one can make ToFourDigitYearMax a no-op by setting TwoDigitYearMax to 99.
_twoDigitYearMax = value;
}
}
public override int ToFourDigitYear(int year)
{
if (year < 0)
{
throw new ArgumentOutOfRangeException(nameof(year), year, SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (year < 100)
{
return base.ToFourDigitYear(year);
}
if (year < MinCalendarYear || year > MaxCalendarYear)
{
throw new ArgumentOutOfRangeException(
nameof(year),
year,
SR.Format(SR.ArgumentOutOfRange_Range, MinCalendarYear, MaxCalendarYear));
}
return year;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace FFWebApp462.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using Microsoft.Azure.Management.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core;
using Microsoft.Azure.Management.Samples.Common;
using Microsoft.Azure.Management.Storage.Fluent.Models;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
using Microsoft.WindowsAzure.Storage.Shared.Protocol;
using System;
using System.Linq;
using System.IO;
namespace QueryMetricsAndActivityLogs
{
public class Program
{
/**
* This sample shows examples of retrieving metrics and activity logs for Storage Account.
* - List all metric definitions available for a storage account
* - Retrieve and show metrics for the past 7 days for Transactions where
* - Api name was 'PutBlob' and
* - response type was 'Success' and
* - Geo type was 'Primary'
* - Retrieve and show all activity logs for the past 7 days for the same Storage account.
*/
public static void RunSample(IAzure azure)
{
string storageAccountName = SdkContext.RandomResourceName("saMonitor", 15);
string rgName = SdkContext.RandomResourceName("rgMonitor", 15);
try
{
// ============================================================
// Create a storage account
Utilities.Log("Creating a Storage Account");
var storageAccount = azure.StorageAccounts.Define(storageAccountName)
.WithRegion(Region.USEast)
.WithNewResourceGroup(rgName)
.WithBlobStorageAccountKind()
.WithAccessTier(AccessTier.Cool)
.Create();
Utilities.Log("Created a Storage Account:");
Utilities.PrintStorageAccount(storageAccount);
var storageAccountKeys = storageAccount.GetKeys();
var storageConnectionString = $"DefaultEndpointsProtocol=http;AccountName={storageAccount.Name};AccountKey={storageAccountKeys.First().Value}";
// Add some blob transaction events
AddBlobTransactions(storageConnectionString);
DateTime recordDateTime = DateTime.Now;
// get metric definitions for storage account.
foreach (var metricDefinition in azure.MetricDefinitions.ListByResource(storageAccount.Id))
{
// find metric definition for Transactions
if (metricDefinition.Name.LocalizedValue.Equals("transactions", StringComparison.OrdinalIgnoreCase))
{
// get metric records
var metricCollection = metricDefinition.DefineQuery()
.StartingFrom(recordDateTime.AddDays(-7))
.EndsBefore(recordDateTime)
.WithAggregation("Average")
.WithInterval(TimeSpan.FromMinutes(5))
.WithOdataFilter("apiName eq 'PutBlob' and responseType eq 'Success' and geoType eq 'Primary'")
.Execute();
Utilities.Log("Metrics for '" + storageAccount.Id + "':");
Utilities.Log("Namespacse: " + metricCollection.Namespace);
Utilities.Log("Query time: " + metricCollection.Timespan);
Utilities.Log("Time Grain: " + metricCollection.Interval);
Utilities.Log("Cost: " + metricCollection.Cost);
foreach (var metric in metricCollection.Metrics)
{
Utilities.Log("\tMetric: " + metric.Name.LocalizedValue);
Utilities.Log("\tType: " + metric.Type);
Utilities.Log("\tUnit: " + metric.Unit);
Utilities.Log("\tTime Series: ");
foreach (var timeElement in metric.Timeseries)
{
Utilities.Log("\t\tMetadata: ");
foreach (var metadata in timeElement.Metadatavalues)
{
Utilities.Log("\t\t\t" + metadata.Name.LocalizedValue + ": " + metadata.Value);
}
Utilities.Log("\t\tData: ");
foreach (var data in timeElement.Data)
{
Utilities.Log("\t\t\t" + data.TimeStamp
+ " : (Min) " + data.Minimum
+ " : (Max) " + data.Maximum
+ " : (Avg) " + data.Average
+ " : (Total) " + data.Total
+ " : (Count) " + data.Count);
}
}
}
break;
}
}
// get activity logs for the same period.
var logs = azure.ActivityLogs.DefineQuery()
.StartingFrom(recordDateTime.AddDays(-7))
.EndsBefore(recordDateTime)
.WithAllPropertiesInResponse()
.FilterByResource(storageAccount.Id)
.Execute();
Utilities.Log("Activity logs for the Storage Account:");
foreach (var eventData in logs)
{
Utilities.Log("\tEvent: " + eventData.EventName?.LocalizedValue);
Utilities.Log("\tOperation: " + eventData.OperationName?.LocalizedValue);
Utilities.Log("\tCaller: " + eventData.Caller);
Utilities.Log("\tCorrelationId: " + eventData.CorrelationId);
Utilities.Log("\tSubscriptionId: " + eventData.SubscriptionId);
}
}
finally
{
if (azure.ResourceGroups.GetByName(rgName) != null)
{
Utilities.Log("Deleting Resource Group: " + rgName);
azure.ResourceGroups.BeginDeleteByName(rgName);
Utilities.Log("Deleted Resource Group: " + rgName);
}
else
{
Utilities.Log("Did not create any resources in Azure. No clean up is necessary");
}
}
}
public static void Main(string[] args)
{
try
{
//=================================================================
// Authenticate
var credentials = SdkContext.AzureCredentialsFactory.FromFile(Environment.GetEnvironmentVariable("AZURE_AUTH_LOCATION"));
var azure = Azure
.Configure()
.WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
.Authenticate(credentials)
.WithDefaultSubscription();
// Print selected subscription
Utilities.Log("Selected subscription: " + azure.SubscriptionId);
RunSample(azure);
}
catch (Exception ex)
{
Utilities.Log(ex);
}
}
private static void AddBlobTransactions(string storageConnectionString)
{
// Upload the script file as block blob
//
var account = CloudStorageAccount.Parse(storageConnectionString);
var cloudBlobClient = account.CreateCloudBlobClient();
var container = cloudBlobClient.GetContainerReference("scripts");
container.CreateIfNotExistsAsync().GetAwaiter().GetResult();
var serviceProps = cloudBlobClient.GetServicePropertiesAsync().GetAwaiter().GetResult();
// configure Storage logging and metrics
serviceProps.Logging = new LoggingProperties
{
LoggingOperations = LoggingOperations.All,
RetentionDays = 2,
Version = "1.0"
};
var metricProps = new MetricsProperties
{
MetricsLevel = MetricsLevel.ServiceAndApi,
RetentionDays = 2,
Version = "1.0"
};
serviceProps.HourMetrics = metricProps;
serviceProps.MinuteMetrics = metricProps;
// Set the default service version to be used for anonymous requests.
serviceProps.DefaultServiceVersion = "2015-04-05";
// Set the service properties.
cloudBlobClient.SetServicePropertiesAsync(serviceProps).GetAwaiter().GetResult();
var containerPermissions = new BlobContainerPermissions();
// Include public access in the permissions object
containerPermissions.PublicAccess = BlobContainerPublicAccessType.Container;
// Set the permissions on the container
container.SetPermissionsAsync(containerPermissions).GetAwaiter().GetResult();
var blob = container.GetBlockBlobReference("install_apache.sh");
blob.UploadFromFileAsync(Path.Combine(Utilities.ProjectPath, "Asset", "install_apache.sh")).GetAwaiter().GetResult();
// give sometime for the infrastructure to process the records and fit into time grain.
SdkContext.DelayProvider.Delay(6 * 60000);
}
}
}
| |
using System;
using System.Linq;
using System.Threading;
using Microsoft.Deployment.WindowsInstaller;
using WixSharp.CommonTasks;
using WixSharp.UI.ManagedUI;
using System.Diagnostics;
using WixSharp.UI.Forms;
using System.Xml.Linq;
using System.Text;
using System.Drawing;
using System.Windows.Forms;
namespace WixSharp
{
/// <summary>
/// Implements as standard dialog-based MSI embedded UI.
/// <para>
/// This class allows defining separate sequences of UI dialogs for 'install'
/// and 'modify' MSI executions. The dialog sequence can contain any mixture
/// of built-in standard dialogs and/or custom dialogs (Form inherited from <see cref="T:WixSharp.UI.Forms.ManagedForm"/>).
/// </para>
/// </summary>
/// <example>The following is an example of installing <c>MyLibrary.dll</c> assembly and registering it in GAC.
/// <code>
/// ...
/// project.ManagedUI = new ManagedUI();
/// project.ManagedUI.InstallDialogs.Add(Dialogs.Welcome)
/// .Add(Dialogs.Licence)
/// .Add(Dialogs.SetupType)
/// .Add(Dialogs.Features)
/// .Add(Dialogs.InstallDir)
/// .Add(Dialogs.Progress)
/// .Add(Dialogs.Exit);
///
/// project.ManagedUI.ModifyDialogs.Add(Dialogs.MaintenanceType)
/// .Add(Dialogs.Features)
/// .Add(Dialogs.Progress)
/// .Add(Dialogs.Exit);
///
/// </code>
/// </example>
public class ManagedUI : IManagedUI, IEmbeddedUI
{
/// <summary>
/// The default implementation of ManagedUI. It implements all major dialogs of a typical MSI UI.
/// </summary>
static public ManagedUI Default = new ManagedUI
{
InstallDialogs = new ManagedDialogs()
.Add<WelcomeDialog>()
.Add<LicenceDialog>()
.Add<SetupTypeDialog>()
.Add<FeaturesDialog>()
.Add<InstallDirDialog>()
.Add<ProgressDialog>()
.Add<ExitDialog>(),
ModifyDialogs = new ManagedDialogs()
.Add<MaintenanceTypeDialog>()
.Add<FeaturesDialog>()
.Add<ProgressDialog>()
.Add<ExitDialog>()
};
/// <summary>
/// The default implementation of ManagedUI with no UI dialogs.
/// </summary>
static public ManagedUI Empty = new ManagedUI();
/// <summary>
/// Initializes a new instance of the <see cref="ManagedUI"/> class.
/// </summary>
public ManagedUI()
{
InstallDialogs = new ManagedDialogs();
ModifyDialogs = new ManagedDialogs();
}
/// <summary>
/// This method is called (indirectly) by Wix# compiler just before building the MSI. It allows embedding UI specific resources (e.g. license file, properties)
/// into the MSI.
/// </summary>
/// <param name="project">The project.</param>
public void BeforeBuild(ManagedProject project)
{
var file = LocalizationFileFor(project);
ValidateUITextFile(file);
project.AddBinary(new Binary(new Id("WixSharp_UIText"), file));
project.AddBinary(new Binary(new Id("WixSharp_LicenceFile"), LicenceFileFor(project)));
project.AddBinary(new Binary(new Id("WixUI_Bmp_Dialog"), DialogBitmapFileFor(project)));
project.AddBinary(new Binary(new Id("WixUI_Bmp_Banner"), DialogBannerFileFor(project)));
}
/// <summary>
/// Validates the UI text file (localization file) for being compatible with ManagedUI.
/// </summary>
/// <param name="file">The file.</param>
/// <param name="throwOnError">if set to <c>true</c> [throw on error].</param>
/// <returns></returns>
public static bool ValidateUITextFile(string file, bool throwOnError = true)
{
try
{
var data = new ResourcesData();
data.InitFromWxl(System.IO.File.ReadAllBytes(file));
}
catch (Exception e)
{
//may need to do extra logging; not important for now
if (throwOnError)
throw new Exception("Localization file is incompatible with ManagedUI.", e);
else
return false;
}
return true;
}
/// <summary>
/// Gets or sets the id of the 'installdir' (destination folder) directory. It is the directory,
/// which is bound to the input UI elements of the Browse dialog (e.g. WiX BrowseDlg, Wix# InstallDirDialog).
/// </summary>
/// <value>
/// The install dir identifier.
/// </value>
public string InstallDirId { get; set; }
internal string LocalizationFileFor(Project project)
{
return UIExtensions.UserOrDefaultContentOf(project.LocalizationFile, project.SourceBaseDir, project.OutDir, project.Name + ".wxl", Resources.WixUI_en_us);
}
internal string LicenceFileFor(Project project)
{
return UIExtensions.UserOrDefaultContentOf(project.LicenceFile, project.SourceBaseDir, project.OutDir, project.Name + ".licence.rtf", Resources.WixSharp_LicenceFile);
}
internal string DialogBitmapFileFor(Project project)
{
return UIExtensions.UserOrDefaultContentOf(project.BackgroundImage, project.SourceBaseDir, project.OutDir, project.Name + ".dialog_bmp.png", Resources.WixUI_Bmp_Dialog);
}
internal string DialogBannerFileFor(Project project)
{
return UIExtensions.UserOrDefaultContentOf(project.BannerImage, project.SourceBaseDir, project.OutDir, project.Name + ".dialog_banner.png", Resources.WixUI_Bmp_Banner);
}
/// <summary>
/// Sequence of the dialogs to be displayed during the installation of the product.
/// </summary>
public ManagedDialogs InstallDialogs { get; set; }
/// <summary>
/// Sequence of the dialogs to be displayed during the customization of the installed product.
/// </summary>
public ManagedDialogs ModifyDialogs { get; set; }
/// <summary>
/// A window icon that appears in the left top corner of the UI shell window.
/// </summary>
public string Icon { get; set; }
ManualResetEvent uiExitEvent = new ManualResetEvent(false);
IUIContainer shell;
void ReadDialogs(Session session)
{
// System.Diagnostics.Debug.Assert(false);
InstallDialogs.Clear()
.AddRange(ManagedProject.ReadDialogs(session.Property("WixSharp_InstallDialogs")));
ModifyDialogs.Clear()
.AddRange(ManagedProject.ReadDialogs(session.Property("WixSharp_ModifyDialogs")));
}
Mutex cancelRequest = null;
/// <summary>
/// Initializes the specified session.
/// </summary>
/// <param name="session">The session.</param>
/// <param name="resourcePath">The resource path.</param>
/// <param name="uiLevel">The UI level.</param>
/// <returns></returns>
/// <exception cref="Microsoft.Deployment.WindowsInstaller.InstallCanceledException"></exception>
public bool Initialize(Session session, string resourcePath, ref InstallUIOptions uiLevel)
{
if (session != null && (session.IsUninstalling() || uiLevel.IsBasic()))
return false; //use built-in MSI basic UI
string upgradeCode = session["UpgradeCode"];
using (cancelRequest)
{
try
{
ReadDialogs(session);
var startEvent = new ManualResetEvent(false);
var uiThread = new Thread(() =>
{
session["WIXSHARP_MANAGED_UI"] = System.Reflection.Assembly.GetExecutingAssembly().ToString();
shell = new UIShell(); //important to create the instance in the same thread that call ShowModal
shell.ShowModal(
new MsiRuntime(session)
{
StartExecute = () => startEvent.Set(),
CancelExecute = () =>
{
// NOTE: IEmbeddedUI interface has no way to cancel the installation, which has been started
// (e.g. ProgressDialog is displayed). What is even worse is that UI can pass back to here
// a signal the user pressed 'Cancel' but nothing we can do with it. Install is already started
// and session object is now invalid.
// To solve this we use this work around - set a unique "cancel request mutex" form here
// and ManagedProjectActions.CancelRequestHandler built-in CA will pick the request and yield
// return code UserExit.
cancelRequest = new Mutex(true, "WIXSHARP_UI_CANCEL_REQUEST." + upgradeCode);
}
},
this);
uiExitEvent.Set();
});
uiThread.SetApartmentState(ApartmentState.STA);
uiThread.Start();
int waitResult = WaitHandle.WaitAny(new[] { startEvent, uiExitEvent });
if (waitResult == 1)
{
//UI exited without starting the install. Cancel the installation.
throw new InstallCanceledException();
}
else
{
// Start the installation with a silenced internal UI.
// This "embedded external UI" will handle message types except for source resolution.
uiLevel = InstallUIOptions.NoChange | InstallUIOptions.SourceResolutionOnly;
shell.OnExecuteStarted();
return true;
}
}
catch (Exception e)
{
session.Log("Cannot attach ManagedUI: " + e);
throw;
}
}
}
/// <summary>
/// Processes information and progress messages sent to the user interface.
/// </summary>
/// <param name="messageType">Message type.</param>
/// <param name="messageRecord">Record that contains message data.</param>
/// <param name="buttons">Message buttons.</param>
/// <param name="icon">Message box icon.</param>
/// <param name="defaultButton">Message box default button.</param>
/// <returns>
/// Result of processing the message.
/// </returns>
/// <remarks>
/// <p>
/// Win32 MSI API:
/// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/embeddeduihandler.asp">EmbeddedUIHandler</a></p>
/// </remarks>
public MessageResult ProcessMessage(InstallMessage messageType, Record messageRecord, MessageButtons buttons, MessageIcon icon, MessageDefaultButton defaultButton)
{
return shell.ProcessMessage(messageType, messageRecord, buttons, icon, defaultButton);
}
/// <summary>
/// Shuts down the embedded UI at the end of the installation.
/// </summary>
/// <remarks>
/// If the installation was canceled during initialization, this method will not be called.
/// If the installation was canceled or failed at any later point, this method will be called at the end.
/// <p>
/// Win32 MSI API:
/// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/shutdownembeddedui.asp">ShutdownEmbeddedUI</a></p>
/// </remarks>
public void Shutdown()
{
shell.OnExecuteComplete();
uiExitEvent.WaitOne();
}
}
}
| |
/*
* Farseer Physics Engine:
* Copyright (c) 2012 Ian Qvist
*
* Original source Box2D:
* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
//#define USE_IGNORE_CCD_CATEGORIES
using System;
using System.Collections.Generic;
using System.Diagnostics;
using FarseerPhysics.Collision;
using FarseerPhysics.Collision.Shapes;
using FarseerPhysics.Common;
using FarseerPhysics.Dynamics.Contacts;
using Microsoft.Xna.Framework;
namespace FarseerPhysics.Dynamics
{
[Flags]
public enum Category
{
None = 0,
All = int.MaxValue,
Cat1 = 1,
Cat2 = 2,
Cat3 = 4,
Cat4 = 8,
Cat5 = 16,
Cat6 = 32,
Cat7 = 64,
Cat8 = 128,
Cat9 = 256,
Cat10 = 512,
Cat11 = 1024,
Cat12 = 2048,
Cat13 = 4096,
Cat14 = 8192,
Cat15 = 16384,
Cat16 = 32768,
Cat17 = 65536,
Cat18 = 131072,
Cat19 = 262144,
Cat20 = 524288,
Cat21 = 1048576,
Cat22 = 2097152,
Cat23 = 4194304,
Cat24 = 8388608,
Cat25 = 16777216,
Cat26 = 33554432,
Cat27 = 67108864,
Cat28 = 134217728,
Cat29 = 268435456,
Cat30 = 536870912,
Cat31 = 1073741824
}
/// <summary>
/// This proxy is used internally to connect fixtures to the broad-phase.
/// </summary>
public struct FixtureProxy
{
public AABB AABB;
public int ChildIndex;
public Fixture Fixture;
public int ProxyId;
}
/// <summary>
/// A fixture is used to attach a Shape to a body for collision detection. A fixture
/// inherits its transform from its parent. Fixtures hold additional non-geometric data
/// such as friction, collision filters, etc.
/// Fixtures are created via Body.CreateFixture.
/// Warning: You cannot reuse fixtures.
/// </summary>
public class Fixture : IDisposable
{
#region Properties/Fields/Events
public FixtureProxy[] Proxies;
public int ProxyCount;
public Category IgnoreCCDWith;
/// <summary>
/// Defaults to 0
///
/// If Settings.useFPECollisionCategories is set to false:
/// Collision groups allow a certain group of objects to never collide (negative)
/// or always collide (positive). Zero means no collision group. Non-zero group
/// filtering always wins against the mask bits.
///
/// If Settings.useFPECollisionCategories is set to true:
/// If 2 fixtures are in the same collision group, they will not collide.
/// </summary>
public short CollisionGroup
{
set
{
if (_collisionGroup == value)
return;
_collisionGroup = value;
Refilter();
}
get => _collisionGroup;
}
/// <summary>
/// Defaults to Category.All
///
/// The collision mask bits. This states the categories that this
/// fixture would accept for collision.
/// Use Settings.UseFPECollisionCategories to change the behavior.
/// </summary>
public Category CollidesWith
{
get => _collidesWith;
set
{
if (_collidesWith == value)
return;
_collidesWith = value;
Refilter();
}
}
/// <summary>
/// The collision categories this fixture is a part of.
///
/// If Settings.UseFPECollisionCategories is set to false:
/// Defaults to Category.Cat1
///
/// If Settings.UseFPECollisionCategories is set to true:
/// Defaults to Category.All
/// </summary>
public Category CollisionCategories
{
get => _collisionCategories;
set
{
if (_collisionCategories == value)
return;
_collisionCategories = value;
Refilter();
}
}
/// <summary>
/// Get the child Shape. You can modify the child Shape, however you should not change the
/// number of vertices because this will crash some collision caching mechanisms.
/// </summary>
/// <value>The shape.</value>
public Shape Shape { get; internal set; }
/// <summary>
/// Gets or sets a value indicating whether this fixture is a sensor.
/// </summary>
/// <value><c>true</c> if this instance is a sensor; otherwise, <c>false</c>.</value>
public bool IsSensor
{
get => _isSensor;
set
{
if (Body != null)
Body.IsAwake = true;
_isSensor = value;
}
}
/// <summary>
/// Get the parent body of this fixture. This is null if the fixture is not attached.
/// </summary>
/// <value>The body.</value>
public Body Body { get; internal set; }
/// <summary>
/// Set the user data. Use this to store your application specific data.
/// </summary>
/// <value>The user data.</value>
public object UserData;
/// <summary>
/// Set the coefficient of friction. This will _not_ change the friction of existing contacts.
/// </summary>
/// <value>The friction.</value>
public float Friction
{
get => _friction;
set
{
Debug.Assert(!float.IsNaN(value));
_friction = value;
}
}
/// <summary>
/// Set the coefficient of restitution. This will not change the restitution of existing contacts.
/// </summary>
/// <value>The restitution.</value>
public float Restitution
{
get => _restitution;
set
{
Debug.Assert(!float.IsNaN(value));
_restitution = value;
}
}
/// <summary>
/// Gets a unique ID for this fixture.
/// </summary>
/// <value>The fixture id.</value>
public int FixtureId { get; internal set; }
/// <summary>
/// Fires after two shapes have collided and are solved. This gives you a chance to get the impact force.
/// </summary>
public AfterCollisionEventHandler AfterCollision;
/// <summary>
/// Fires when two fixtures are close to each other.
/// Due to how the broadphase works, this can be quite inaccurate as shapes are approximated using AABBs.
/// </summary>
public BeforeCollisionEventHandler BeforeCollision;
/// <summary>
/// Fires when two shapes collide and a contact is created between them.
/// Note: the first fixture argument is always the fixture that the delegate is subscribed to.
/// </summary>
public OnCollisionEventHandler OnCollision;
/// <summary>
/// Fires when two shapes separate and a contact is removed between them.
/// Note: this can in some cases be called multiple times, as a fixture can have multiple contacts.
/// Note: the first fixture argument is always the fixture that the delegate is subscribed to.
/// </summary>
public OnSeparationEventHandler OnSeparation;
[ThreadStatic] static int _fixtureIdCounter;
bool _isSensor;
float _friction;
float _restitution;
internal Category _collidesWith;
internal Category _collisionCategories;
internal short _collisionGroup;
internal HashSet<int> _collisionIgnores;
#endregion
internal Fixture()
{
FixtureId = _fixtureIdCounter++;
_collisionCategories = Settings.DefaultFixtureCollisionCategories;
_collidesWith = Settings.DefaultFixtureCollidesWith;
_collisionGroup = 0;
_collisionIgnores = new HashSet<int>();
IgnoreCCDWith = Settings.DefaultFixtureIgnoreCCDWith;
//Fixture defaults
Friction = 0.2f;
Restitution = 0;
}
internal Fixture(Body body, Shape shape, object userData = null) : this()
{
#if DEBUG
if (shape.ShapeType == ShapeType.Polygon)
((PolygonShape) shape).Vertices.attachedToBody = true;
#endif
this.Body = body;
this.UserData = userData;
this.Shape = shape.Clone();
RegisterFixture();
}
#region IDisposable Members
public bool IsDisposed { get; set; }
public void Dispose()
{
if (!IsDisposed)
{
Body.DestroyFixture(this);
IsDisposed = true;
GC.SuppressFinalize(this);
}
}
#endregion
/// <summary>
/// Restores collisions between this fixture and the provided fixture.
/// </summary>
/// <param name="fixture">The fixture.</param>
public void RestoreCollisionWith(Fixture fixture)
{
if (_collisionIgnores.Contains(fixture.FixtureId))
{
_collisionIgnores.Remove(fixture.FixtureId);
Refilter();
}
}
/// <summary>
/// Ignores collisions between this fixture and the provided fixture.
/// </summary>
/// <param name="fixture">The fixture.</param>
public void IgnoreCollisionWith(Fixture fixture)
{
if (!_collisionIgnores.Contains(fixture.FixtureId))
{
_collisionIgnores.Add(fixture.FixtureId);
Refilter();
}
}
/// <summary>
/// Determines whether collisions are ignored between this fixture and the provided fixture.
/// </summary>
/// <param name="fixture">The fixture.</param>
/// <returns>
/// <c>true</c> if the fixture is ignored; otherwise, <c>false</c>.
/// </returns>
public bool IsFixtureIgnored(Fixture fixture)
{
return _collisionIgnores.Contains(fixture.FixtureId);
}
/// <summary>
/// Contacts are persistant and will keep being persistant unless they are
/// flagged for filtering.
/// This methods flags all contacts associated with the body for filtering.
/// </summary>
void Refilter()
{
// Flag associated contacts for filtering.
ContactEdge edge = Body.ContactList;
while (edge != null)
{
Contact contact = edge.Contact;
Fixture fixtureA = contact.FixtureA;
Fixture fixtureB = contact.FixtureB;
if (fixtureA == this || fixtureB == this)
{
contact.filterFlag = true;
}
edge = edge.Next;
}
World world = Body._world;
if (world == null)
{
return;
}
// Touch each proxy so that new pairs may be created
var broadPhase = world.ContactManager.BroadPhase;
for (var i = 0; i < ProxyCount; ++i)
broadPhase.TouchProxy(Proxies[i].ProxyId);
}
void RegisterFixture()
{
// Reserve proxy space
Proxies = new FixtureProxy[Shape.ChildCount];
ProxyCount = 0;
if (Body.Enabled)
{
var broadPhase = Body._world.ContactManager.BroadPhase;
CreateProxies(broadPhase, ref Body._xf);
}
Body.FixtureList.Add(this);
// Adjust mass properties if needed.
if (Shape._density > 0.0f)
Body.ResetMassData();
// Let the world know we have a new fixture. This will cause new contacts
// to be created at the beginning of the next time step.
Body._world._worldHasNewFixture = true;
//FPE: Added event
if (Body._world.OnFixtureAdded != null)
Body._world.OnFixtureAdded(this);
}
/// <summary>
/// Test a point for containment in this fixture.
/// </summary>
/// <param name="point">A point in world coordinates.</param>
/// <returns></returns>
public bool TestPoint(ref Vector2 point)
{
return Shape.TestPoint(ref Body._xf, ref point);
}
/// <summary>
/// Cast a ray against this Fixture by passing the call through to the Shape
/// </summary>
/// <param name="output">The ray-cast results.</param>
/// <param name="input">The ray-cast input parameters.</param>
/// <param name="childIndex">Index of the child.</param>
/// <returns></returns>
public bool RayCast(out RayCastOutput output, ref RayCastInput input, int childIndex)
{
return Shape.RayCast(out output, ref input, ref Body._xf, childIndex);
}
/// <summary>
/// Get the fixture's AABB. This AABB may be enlarged and/or stale. If you need a more accurate AABB, compute it using the Shape and
/// the body transform.
/// </summary>
/// <param name="aabb">The aabb.</param>
/// <param name="childIndex">Index of the child.</param>
public void GetAABB(out AABB aabb, int childIndex)
{
Debug.Assert(0 <= childIndex && childIndex < ProxyCount);
aabb = Proxies[childIndex].AABB;
}
internal void Destroy()
{
#if DEBUG
if (Shape.ShapeType == ShapeType.Polygon)
((PolygonShape) Shape).Vertices.attachedToBody = false;
#endif
// The proxies must be destroyed before calling this.
Debug.Assert(ProxyCount == 0);
// Free the proxy array.
Proxies = null;
Shape = null;
//FPE: We set the userdata to null here to help prevent bugs related to stale references in GC
UserData = null;
BeforeCollision = null;
OnCollision = null;
OnSeparation = null;
AfterCollision = null;
if (Body._world.OnFixtureRemoved != null)
{
Body._world.OnFixtureRemoved(this);
}
Body._world.OnFixtureAdded = null;
Body._world.OnFixtureRemoved = null;
OnSeparation = null;
OnCollision = null;
}
// These support body activation/deactivation.
internal void CreateProxies(DynamicTreeBroadPhase broadPhase, ref Transform xf)
{
Debug.Assert(ProxyCount == 0);
// Create proxies in the broad-phase.
ProxyCount = Shape.ChildCount;
for (int i = 0; i < ProxyCount; ++i)
{
FixtureProxy proxy = new FixtureProxy();
Shape.ComputeAABB(out proxy.AABB, ref xf, i);
proxy.Fixture = this;
proxy.ChildIndex = i;
//FPE note: This line needs to be after the previous two because FixtureProxy is a struct
proxy.ProxyId = broadPhase.AddProxy(ref proxy);
Proxies[i] = proxy;
}
}
internal void DestroyProxies(DynamicTreeBroadPhase broadPhase)
{
// Destroy proxies in the broad-phase.
for (int i = 0; i < ProxyCount; ++i)
{
broadPhase.RemoveProxy(Proxies[i].ProxyId);
Proxies[i].ProxyId = -1;
}
ProxyCount = 0;
}
internal void Synchronize(DynamicTreeBroadPhase broadPhase, ref Transform transform1, ref Transform transform2)
{
if (ProxyCount == 0)
return;
for (var i = 0; i < ProxyCount; ++i)
{
var proxy = Proxies[i];
// Compute an AABB that covers the swept Shape (may miss some rotation effect).
AABB aabb1, aabb2;
Shape.ComputeAABB(out aabb1, ref transform1, proxy.ChildIndex);
Shape.ComputeAABB(out aabb2, ref transform2, proxy.ChildIndex);
proxy.AABB.Combine(ref aabb1, ref aabb2);
Vector2 displacement = transform2.P - transform1.P;
broadPhase.MoveProxy(proxy.ProxyId, ref proxy.AABB, displacement);
}
}
/// <summary>
/// Only compares the values of this fixture, and not the attached shape or body.
/// This is used for deduplication in serialization only.
/// </summary>
internal bool CompareTo(Fixture fixture)
{
return (_collidesWith == fixture._collidesWith &&
_collisionCategories == fixture._collisionCategories &&
_collisionGroup == fixture._collisionGroup &&
Friction == fixture.Friction &&
IsSensor == fixture.IsSensor &&
Restitution == fixture.Restitution &&
UserData == fixture.UserData &&
IgnoreCCDWith == fixture.IgnoreCCDWith &&
SequenceEqual(_collisionIgnores, fixture._collisionIgnores));
}
bool SequenceEqual<T>(HashSet<T> first, HashSet<T> second)
{
if (first.Count != second.Count)
return false;
using (IEnumerator<T> enumerator1 = first.GetEnumerator())
{
using (IEnumerator<T> enumerator2 = second.GetEnumerator())
{
while (enumerator1.MoveNext())
{
if (!enumerator2.MoveNext() || !Equals(enumerator1.Current, enumerator2.Current))
return false;
}
if (enumerator2.MoveNext())
return false;
}
}
return true;
}
/// <summary>
/// Clones the fixture and attached shape onto the specified body.
/// </summary>
/// <param name="body">The body you wish to clone the fixture onto.</param>
/// <returns>The cloned fixture.</returns>
public Fixture CloneOnto(Body body)
{
var fixture = new Fixture();
fixture.Body = body;
fixture.Shape = Shape.Clone();
fixture.UserData = UserData;
fixture.Restitution = Restitution;
fixture.Friction = Friction;
fixture.IsSensor = IsSensor;
fixture._collisionGroup = _collisionGroup;
fixture._collisionCategories = _collisionCategories;
fixture._collidesWith = _collidesWith;
fixture.IgnoreCCDWith = IgnoreCCDWith;
foreach (int ignore in _collisionIgnores)
{
fixture._collisionIgnores.Add(ignore);
}
fixture.RegisterFixture();
return fixture;
}
}
}
| |
using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Localization;
using Microsoft.Extensions.Localization;
using OrchardCore.Admin;
using OrchardCore.DisplayManagement;
using OrchardCore.DisplayManagement.Notify;
using OrchardCore.Environment.Shell;
using OrchardCore.Environment.Shell.Descriptor.Models;
using OrchardCore.Environment.Shell.Models;
using OrchardCore.Modules;
using OrchardCore.Navigation;
using OrchardCore.OpenId.Abstractions.Descriptors;
using OrchardCore.OpenId.Abstractions.Managers;
using OrchardCore.OpenId.ViewModels;
using OrchardCore.Settings;
namespace OrchardCore.OpenId.Controllers
{
[Admin, Feature(OpenIdConstants.Features.Management)]
public class ScopeController : Controller
{
private readonly IAuthorizationService _authorizationService;
private readonly IStringLocalizer S;
private readonly IOpenIdScopeManager _scopeManager;
private readonly ISiteService _siteService;
private readonly INotifier _notifier;
private readonly ShellDescriptor _shellDescriptor;
private readonly ShellSettings _shellSettings;
private readonly IShellHost _shellHost;
private readonly dynamic New;
public ScopeController(
IOpenIdScopeManager scopeManager,
IShapeFactory shapeFactory,
ISiteService siteService,
IStringLocalizer<ScopeController> stringLocalizer,
IAuthorizationService authorizationService,
IHtmlLocalizer<ScopeController> htmlLocalizer,
INotifier notifier,
ShellDescriptor shellDescriptor,
ShellSettings shellSettings,
IShellHost shellHost)
{
_scopeManager = scopeManager;
New = shapeFactory;
_siteService = siteService;
S = stringLocalizer;
_authorizationService = authorizationService;
_notifier = notifier;
_shellDescriptor = shellDescriptor;
_shellSettings = shellSettings;
_shellHost = shellHost;
}
public async Task<ActionResult> Index(PagerParameters pagerParameters)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageScopes))
{
return Forbid();
}
var siteSettings = await _siteService.GetSiteSettingsAsync();
var pager = new Pager(pagerParameters, siteSettings.PageSize);
var count = await _scopeManager.CountAsync();
var model = new OpenIdScopeIndexViewModel
{
Pager = (await New.Pager(pager)).TotalItemCount(count)
};
foreach (var scope in await _scopeManager.ListAsync(pager.PageSize, pager.GetStartIndex()))
{
model.Scopes.Add(new OpenIdScopeEntry
{
Description = await _scopeManager.GetDescriptionAsync(scope),
DisplayName = await _scopeManager.GetDisplayNameAsync(scope),
Id = await _scopeManager.GetPhysicalIdAsync(scope),
Name = await _scopeManager.GetNameAsync(scope)
});
}
return View(model);
}
[HttpGet]
public async Task<IActionResult> Create(string returnUrl = null)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageScopes))
{
return Forbid();
}
var model = new CreateOpenIdScopeViewModel();
foreach (var tenant in _shellHost.GetAllSettings().Where(s => s.State == TenantState.Running))
{
model.Tenants.Add(new CreateOpenIdScopeViewModel.TenantEntry
{
Current = string.Equals(tenant.Name, _shellSettings.Name),
Name = tenant.Name
});
}
ViewData["ReturnUrl"] = returnUrl;
return View(model);
}
[HttpPost]
public async Task<IActionResult> Create(CreateOpenIdScopeViewModel model, string returnUrl = null)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageScopes))
{
return Forbid();
}
if (await _scopeManager.FindByNameAsync(model.Name) != null)
{
ModelState.AddModelError(nameof(model.Name), S["The name is already taken by another scope."]);
}
if (!ModelState.IsValid)
{
ViewData["ReturnUrl"] = returnUrl;
return View(model);
}
var descriptor = new OpenIdScopeDescriptor
{
Description = model.Description,
DisplayName = model.DisplayName,
Name = model.Name
};
if (!string.IsNullOrEmpty(model.Resources))
{
descriptor.Resources.UnionWith(model.Resources.Split(' ', StringSplitOptions.RemoveEmptyEntries));
}
descriptor.Resources.UnionWith(model.Tenants
.Where(tenant => tenant.Selected)
.Where(tenant => !string.Equals(tenant.Name, _shellSettings.Name))
.Select(tenant => OpenIdConstants.Prefixes.Tenant + tenant.Name));
await _scopeManager.CreateAsync(descriptor);
if (string.IsNullOrEmpty(returnUrl))
{
return RedirectToAction("Index");
}
return LocalRedirect(returnUrl);
}
public async Task<IActionResult> Edit(string id, string returnUrl = null)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageScopes))
{
return Forbid();
}
var scope = await _scopeManager.FindByPhysicalIdAsync(id);
if (scope == null)
{
return NotFound();
}
var model = new EditOpenIdScopeViewModel
{
Description = await _scopeManager.GetDescriptionAsync(scope),
DisplayName = await _scopeManager.GetDisplayNameAsync(scope),
Id = await _scopeManager.GetPhysicalIdAsync(scope),
Name = await _scopeManager.GetNameAsync(scope)
};
var resources = await _scopeManager.GetResourcesAsync(scope);
model.Resources = string.Join(" ",
from resource in resources
where !string.IsNullOrEmpty(resource) && !resource.StartsWith(OpenIdConstants.Prefixes.Tenant, StringComparison.Ordinal)
select resource);
foreach (var tenant in _shellHost.GetAllSettings().Where(s => s.State == TenantState.Running))
{
model.Tenants.Add(new EditOpenIdScopeViewModel.TenantEntry
{
Current = string.Equals(tenant.Name, _shellSettings.Name),
Name = tenant.Name,
Selected = resources.Contains(OpenIdConstants.Prefixes.Tenant + tenant.Name)
});
}
ViewData["ReturnUrl"] = returnUrl;
return View(model);
}
[HttpPost]
public async Task<IActionResult> Edit(EditOpenIdScopeViewModel model, string returnUrl = null)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageScopes))
{
return Forbid();
}
var scope = await _scopeManager.FindByPhysicalIdAsync(model.Id);
if (scope == null)
{
return NotFound();
}
if (ModelState.IsValid)
{
var other = await _scopeManager.FindByNameAsync(model.Name);
if (other != null && !string.Equals(
await _scopeManager.GetIdAsync(other),
await _scopeManager.GetIdAsync(scope)))
{
ModelState.AddModelError(nameof(model.Name), S["The name is already taken by another scope."]);
}
}
if (!ModelState.IsValid)
{
ViewData["ReturnUrl"] = returnUrl;
return View(model);
}
var descriptor = new OpenIdScopeDescriptor();
await _scopeManager.PopulateAsync(descriptor, scope);
descriptor.Description = model.Description;
descriptor.DisplayName = model.DisplayName;
descriptor.Name = model.Name;
descriptor.Resources.Clear();
if (!string.IsNullOrEmpty(model.Resources))
{
descriptor.Resources.UnionWith(model.Resources.Split(' ', StringSplitOptions.RemoveEmptyEntries));
}
descriptor.Resources.UnionWith(model.Tenants
.Where(tenant => tenant.Selected)
.Where(tenant => !string.Equals(tenant.Name, _shellSettings.Name))
.Select(tenant => OpenIdConstants.Prefixes.Tenant + tenant.Name));
await _scopeManager.UpdateAsync(scope, descriptor);
if (string.IsNullOrEmpty(returnUrl))
{
return RedirectToAction("Index");
}
return LocalRedirect(returnUrl);
}
[HttpPost]
public async Task<IActionResult> Delete(string id)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageScopes))
{
return Forbid();
}
var scope = await _scopeManager.FindByPhysicalIdAsync(id);
if (scope == null)
{
return NotFound();
}
await _scopeManager.DeleteAsync(scope);
return RedirectToAction(nameof(Index));
}
}
}
| |
//
// Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using NLog.Config;
using NLog.Internal;
namespace NLog.MessageTemplates
{
/// <summary>
/// Convert Render or serialize a value, with optionally backwards-compatible with <see cref="string.Format(System.IFormatProvider,string,object[])"/>
/// </summary>
internal class ValueFormatter : IValueFormatter
{
public static IValueFormatter Instance
{
get => _instance ?? (_instance = new ValueFormatter());
set => _instance = value ?? new ValueFormatter();
}
private static IValueFormatter _instance;
private static readonly IEqualityComparer<object> _referenceEqualsComparer = SingleItemOptimizedHashSet<object>.ReferenceEqualityComparer.Default;
/// <summary>Singleton</summary>
private ValueFormatter()
{
}
private const int MaxRecursionDepth = 2;
private const int MaxValueLength = 512 * 1024;
private const string LiteralFormatSymbol = "l";
private readonly MruCache<Enum, string> _enumCache = new MruCache<Enum, string>(2000);
public const string FormatAsJson = "@";
public const string FormatAsString = "$";
/// <summary>
/// Serialization of an object, e.g. JSON and append to <paramref name="builder"/>
/// </summary>
/// <param name="value">The object to serialize to string.</param>
/// <param name="format">Parameter Format</param>
/// <param name="captureType">Parameter CaptureType</param>
/// <param name="formatProvider">An object that supplies culture-specific formatting information.</param>
/// <param name="builder">Output destination.</param>
/// <returns>Serialize succeeded (true/false)</returns>
public bool FormatValue(object value, string format, CaptureType captureType, IFormatProvider formatProvider, StringBuilder builder)
{
switch (captureType)
{
case CaptureType.Serialize:
{
return ConfigurationItemFactory.Default.JsonConverter.SerializeObject(value, builder);
}
case CaptureType.Stringify:
{
builder.Append('"');
FormatToString(value, null, formatProvider, builder);
builder.Append('"');
return true;
}
default:
{
return FormatObject(value, format, formatProvider, builder);
}
}
}
/// <summary>
/// Format an object to a readable string, or if it's an object, serialize
/// </summary>
/// <param name="value">The value to convert</param>
/// <param name="format"></param>
/// <param name="formatProvider"></param>
/// <param name="builder"></param>
/// <returns></returns>
public bool FormatObject(object value, string format, IFormatProvider formatProvider, StringBuilder builder)
{
if (SerializeSimpleObject(value, format, formatProvider, builder, false))
{
return true;
}
IEnumerable collection = value as IEnumerable;
if (collection != null)
{
return SerializeWithoutCyclicLoop(collection, format, formatProvider, builder, default(SingleItemOptimizedHashSet<object>), 0);
}
SerializeConvertToString(value, formatProvider, builder);
return true;
}
/// <summary>
/// Try serializing a scalar (string, int, NULL) or simple type (IFormattable)
/// </summary>
private bool SerializeSimpleObject(object value, string format, IFormatProvider formatProvider, StringBuilder builder, bool convertToString = true)
{
if (value is string stringValue)
{
SerializeStringObject(stringValue, format, builder);
return true;
}
if (value == null)
{
builder.Append("NULL");
return true;
}
// Optimize for types that are pretty much invariant in all cultures when no format-string
if (value is IConvertible convertibleValue)
{
SerializeConvertibleObject(convertibleValue, format, formatProvider, builder);
return true;
}
else
{
if (!string.IsNullOrEmpty(format) && value is IFormattable formattable)
{
builder.Append(formattable.ToString(format, formatProvider));
return true;
}
if (convertToString)
{
SerializeConvertToString(value, formatProvider, builder);
return true;
}
return false;
}
}
private void SerializeConvertibleObject(IConvertible value, string format, IFormatProvider formatProvider, StringBuilder builder)
{
TypeCode convertibleTypeCode = value.GetTypeCode();
if (convertibleTypeCode == TypeCode.String)
{
SerializeStringObject(value.ToString(), format, builder);
return;
}
if (!string.IsNullOrEmpty(format) && value is IFormattable formattable)
{
builder.Append(formattable.ToString(format, formatProvider));
return;
}
switch (convertibleTypeCode)
{
case TypeCode.Boolean:
{
builder.Append(value.ToBoolean(CultureInfo.InvariantCulture) ? "true" : "false");
break;
}
case TypeCode.Char:
{
bool includeQuotes = format != LiteralFormatSymbol;
if (includeQuotes) builder.Append('"');
builder.Append(value.ToChar(CultureInfo.InvariantCulture));
if (includeQuotes) builder.Append('"');
break;
}
case TypeCode.Byte:
case TypeCode.SByte:
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.UInt16:
case TypeCode.UInt32:
case TypeCode.UInt64:
{
if (value is Enum enumValue)
{
AppendEnumAsString(builder, enumValue);
}
else
{
builder.AppendIntegerAsString(value, convertibleTypeCode);
}
break;
}
case TypeCode.Object: // Guid, TimeSpan, DateTimeOffset
default: // Single, Double, Decimal, etc.
SerializeConvertToString(value, formatProvider, builder);
break;
}
}
private static void SerializeConvertToString(object value, IFormatProvider formatProvider, StringBuilder builder)
{
builder.Append(Convert.ToString(value, formatProvider));
}
private static void SerializeStringObject(string stringValue, string format, StringBuilder builder)
{
bool includeQuotes = format != LiteralFormatSymbol;
if (includeQuotes) builder.Append('"');
builder.Append(stringValue);
if (includeQuotes) builder.Append('"');
}
private void AppendEnumAsString(StringBuilder sb, Enum value)
{
if (!_enumCache.TryGetValue(value, out var textValue))
{
textValue = value.ToString();
_enumCache.TryAddValue(value, textValue);
}
sb.Append(textValue);
}
private bool SerializeWithoutCyclicLoop(IEnumerable collection, string format, IFormatProvider formatProvider, StringBuilder builder,
SingleItemOptimizedHashSet<object> objectsInPath, int depth)
{
if (objectsInPath.Contains(collection))
{
return false; // detected reference loop, skip serialization
}
if (depth > MaxRecursionDepth)
{
return false; // reached maximum recursion level, no further serialization
}
IDictionary dictionary = collection as IDictionary;
if (dictionary != null)
{
using (new SingleItemOptimizedHashSet<object>.SingleItemScopedInsert(dictionary, ref objectsInPath, true, _referenceEqualsComparer))
{
return SerializeDictionaryObject(dictionary, format, formatProvider, builder, objectsInPath, depth);
}
}
using (new SingleItemOptimizedHashSet<object>.SingleItemScopedInsert(collection, ref objectsInPath, true, _referenceEqualsComparer))
{
return SerializeCollectionObject(collection, format, formatProvider, builder, objectsInPath, depth);
}
}
/// <summary>
/// Serialize Dictionary as JSON like structure, without { and }
/// </summary>
/// <example>
/// "FirstOrder"=true, "Previous login"=20-12-2017 14:55:32, "number of tries"=1
/// </example>
/// <param name="dictionary"></param>
/// <param name="format">formatstring of an item</param>
/// <param name="formatProvider"></param>
/// <param name="builder"></param>
/// <param name="objectsInPath"></param>
/// <param name="depth"></param>
/// <returns></returns>
private bool SerializeDictionaryObject(IDictionary dictionary, string format, IFormatProvider formatProvider, StringBuilder builder, SingleItemOptimizedHashSet<object> objectsInPath, int depth)
{
bool separator = false;
foreach (var item in new DictionaryEntryEnumerable(dictionary))
{
if (builder.Length > MaxValueLength)
return false;
if (separator) builder.Append(", ");
SerializeCollectionItem(item.Key, format, formatProvider, builder, ref objectsInPath, depth);
builder.Append("=");
SerializeCollectionItem(item.Value, format, formatProvider, builder, ref objectsInPath, depth);
separator = true;
}
return true;
}
private bool SerializeCollectionObject(IEnumerable collection, string format, IFormatProvider formatProvider, StringBuilder builder, SingleItemOptimizedHashSet<object> objectsInPath, int depth)
{
bool separator = false;
foreach (var item in collection)
{
if (builder.Length > MaxValueLength)
return false;
if (separator) builder.Append(", ");
SerializeCollectionItem(item, format, formatProvider, builder, ref objectsInPath, depth);
separator = true;
}
return true;
}
private void SerializeCollectionItem(object item, string format, IFormatProvider formatProvider, StringBuilder builder, ref SingleItemOptimizedHashSet<object> objectsInPath, int depth)
{
if (item is IConvertible convertible)
SerializeConvertibleObject(convertible, format, formatProvider, builder);
else if (item is IEnumerable enumerable)
SerializeWithoutCyclicLoop(enumerable, format, formatProvider, builder, objectsInPath, depth + 1);
else
SerializeSimpleObject(item, format, formatProvider, builder);
}
/// <summary>
/// Convert a value to a string with format and append to <paramref name="builder"/>.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <param name="format">Format sting for the value.</param>
/// <param name="formatProvider">Format provider for the value.</param>
/// <param name="builder">Append to this</param>
public static void FormatToString(object value, string format, IFormatProvider formatProvider, StringBuilder builder)
{
var stringValue = value as string;
if (stringValue != null)
{
builder.Append(stringValue);
}
else
{
var formattable = value as IFormattable;
if (formattable != null)
{
builder.Append(formattable.ToString(format, formatProvider));
}
else
{
builder.Append(Convert.ToString(value, formatProvider));
}
}
}
}
}
| |
using System;
using System.Data;
using FluentNHibernate.Mapping;
using NHibernate.SqlTypes;
using NHibernate.UserTypes;
using NUnit.Framework;
namespace FluentNHibernate.Testing.DomainModel.Mapping
{
[TestFixture]
public class ComponentPropertyMapTester
{
[Test]
public void Map_WithoutColumnName_UsesPropertyNameFor_PropertyColumnAttribute()
{
new MappingTester<PropertyTarget>()
.ForMapping(m => m.Component(x => x.Component, c => c.Map(x => x.Name)))
.Element("//property[@name='Name']/column")
.HasAttribute("name", "Name");
}
[Test]
public void Map_WithoutColumnName_UsesPropertyNameFor_ColumnNameAttribute()
{
new MappingTester<PropertyTarget>()
.ForMapping(m => m.Component(x => x.Component, c => c.Map(x => x.Name)))
.Element("//property/column").HasAttribute("name", "Name");
}
[Test]
public void Map_WithColumnName_UsesColumnNameFor_PropertyColumnAttribute()
{
new MappingTester<PropertyTarget>()
.ForMapping(m => m.Component(x => x.Component, c => c.Map(x => x.Name, "column_name")))
.Element("//property[@name='Name']/column")
.HasAttribute("name", "column_name");
}
[Test]
public void Map_WithColumnName_UsesColumnNameFor_ColumnNameAttribute()
{
new MappingTester<PropertyTarget>()
.ForMapping(m => m.Component(x => x.Component, c => c.Map(x => x.Name, "column_name")))
.Element("//property/column").HasAttribute("name", "column_name");
}
[Test]
public void Map_WithFluentColumnName_UsesColumnNameFor_ColumnNameAttribute()
{
new MappingTester<PropertyTarget>()
.ForMapping(m => m.Component(x => x.Component, c => c.Map(x => x.Name).Column("column_name")))
.Element("//property/column").HasAttribute("name", "column_name");
}
private MappingTester<T> Model<T>(Action<ClassMap<T>> mapping)
{
return new MappingTester<T>()
.ForMapping(mapping);
}
[Test]
public void ShouldAddOnlyOneColumnWhenNotSpecified()
{
Model<PropertyTarget>(m => m.Component(x => x.Component, c => c.Map(x => x.Name)))
.Element("//property[@name='Name']").HasThisManyChildNodes(1);
}
[Test]
public void ShouldAddAllColumns()
{
Model<PropertyTarget>(m => m.Component(x => x.Component, c => c.Map(x => x.Name).Columns.Add("one", "two", "three")))
.Element("//property[@name='Name']").HasThisManyChildNodes(3)
.Element("//property[@name='Name']/column[@name='one']").Exists()
.Element("//property[@name='Name']/column[@name='two']").Exists()
.Element("//property[@name='Name']/column[@name='three']").Exists();
}
[Test]
public void ColumnName_IsPropertyName_WhenNoColumnNameGiven()
{
Model<PropertyTarget>(m => m.Component(x => x.Component, c => c.Map(x => x.Name)))
.Element("//property[@name='Name']/column")
.HasAttribute("name", "Name");
}
[Test]
public void ColumnName_IsColumnName_WhenColumnNameGiven()
{
Model<PropertyTarget>(m => m.Component(x => x.Component, c => c.Map(x => x.Name, "column_name")))
.Element("//property[@name='Name']/column")
.HasAttribute("name", "column_name");
}
[Test]
public void ColumnName_IsColumnName_WhenColumnNameFluentGiven()
{
Model<PropertyTarget>(m => m.Component(x => x.Component, c => c.Map(x => x.Name).Columns.Add("column_name")))
.Element("//property[@name='Name']/column")
.HasAttribute("name", "column_name");
}
[Test]
public void Map_WithFluentLength_OnString_UsesWithLengthOf_PropertyColumnAttribute()
{
new MappingTester<PropertyTarget>()
.ForMapping(m => m.Component(x => x.Component, c => c.Map(x => x.Name).Length(20)))
.Element("//property[@name='Name']/column").HasAttribute("length", "20");
}
[Test]
public void Map_WithFluentLength_AllowOnAnything_PropertyColumnAttribute()
{
new MappingTester<PropertyTarget>()
.ForMapping(m => m.Component(x => x.Component, c => c.Map(x => x.Name).Length(20)))
.Element("//property[@name='Name']/column").HasAttribute("length", "20");
}
[Test]
public void Map_UsesCanNotBeNull_PropertyColumnAttribute()
{
new MappingTester<PropertyTarget>()
.ForMapping(m => m.Component(x => x.Component, c => c.Map(x => x.Name).Not.Nullable()))
.Element("//property[@name='Name']").DoesntHaveAttribute("not-null")
.Element("//property[@name='Name']/column").HasAttribute("not-null", "true");
}
[Test]
public void Map_UsesAsReadOnly_PropertyColumnAttribute()
{
new MappingTester<PropertyTarget>()
.ForMapping(m => m.Component(x => x.Component, c => c.Map(x => x.Name).ReadOnly()))
.Element("//property")
.HasAttribute("insert", "false")
.HasAttribute("update", "false");
}
[Test]
public void Map_UsesUniqueKey_PropertyColumnAttribute()
{
new MappingTester<PropertyTarget>()
.ForMapping(m => m.Component(x => x.Component, c => c.Map(x => x.Name).UniqueKey("uniquekey")))
.Element("//property/column")
.HasAttribute("unique-key", "uniquekey");
}
[Test]
public void Map_UsesNotReadOnly_PropertyColumnAttribute()
{
new MappingTester<PropertyTarget>()
.ForMapping(m => m.Component(x => x.Component, c => c.Map(x => x.Name).Not.ReadOnly()))
.Element("//property")
.HasAttribute("insert", "true")
.HasAttribute("update", "true");
}
[Test]
public void Map_WithFluentFormula_UsesFormula()
{
new MappingTester<PropertyTarget>()
.ForMapping(m => m.Component(x => x.Component, c => c.Map(x => x.Name).Formula("foo(bar)")))
.Element("//property").HasAttribute("formula", "foo(bar)");
}
[Test]
public void CanSpecifyCustomTypeAsDotNetTypeGenerically()
{
new MappingTester<PropertyTarget>()
.ForMapping(m => m.Component(x => x.Component, c => c.Map(x => x.Name).CustomType<custom_type_for_testing>()))
.Element("//property").HasAttribute("type", typeof(custom_type_for_testing).AssemblyQualifiedName);
}
[Test]
public void CanSpecifyCustomTypeAsDotNetType()
{
new MappingTester<PropertyTarget>()
.ForMapping(m => m.Component(x => x.Component, c => c.Map(x => x.Name).CustomType(typeof(custom_type_for_testing))))
.Element("//property").HasAttribute("type", typeof(custom_type_for_testing).AssemblyQualifiedName);
}
[Test]
public void CanSpecifyCustomSqlType()
{
new MappingTester<PropertyTarget>()
.ForMapping(m => m.Component(x => x.Component, c => c.Map(x => x.Name).CustomSqlType("image")))
.Element("//property/column").HasAttribute("sql-type", "image");
}
[Test]
public void CanSetAsUnique()
{
new MappingTester<MappedObject>()
.ForMapping(m => m.Component(x => x.Component, c => c.Map(x => x.Name).Unique()))
.Element("//property").DoesntHaveAttribute("unique")
.Element("//property/column").HasAttribute("unique", "true");
}
[Test]
public void CanSetAsNotUnique()
{
new MappingTester<MappedObject>()
.ForMapping(m => m.Component(x => x.Component, c => c.Map(x => x.Name).Not.Unique()))
.Element("//property").DoesntHaveAttribute("unique")
.Element("//property/column").HasAttribute("unique", "false");
}
#region Custom IUserType impl for testing
public class custom_type_for_testing : IUserType
{
public new bool Equals(object x, object y)
{
throw new System.NotImplementedException();
}
public int GetHashCode(object x)
{
throw new System.NotImplementedException();
}
public object NullSafeGet(IDataReader rs, string[] names, object owner)
{
throw new System.NotImplementedException();
}
public void NullSafeSet(IDbCommand cmd, object value, int index)
{
throw new System.NotImplementedException();
}
public object DeepCopy(object value)
{
throw new System.NotImplementedException();
}
public object Replace(object original, object target, object owner)
{
throw new System.NotImplementedException();
}
public object Assemble(object cached, object owner)
{
throw new System.NotImplementedException();
}
public object Disassemble(object value)
{
throw new System.NotImplementedException();
}
public SqlType[] SqlTypes
{
get { throw new System.NotImplementedException(); }
}
public Type ReturnedType
{
get { throw new System.NotImplementedException(); }
}
public bool IsMutable
{
get { throw new System.NotImplementedException(); }
}
}
#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.
/******************************************************************************
* 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 CompareEqualByte()
{
var test = new SimpleBinaryOpTest__CompareEqualByte();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
// 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();
// 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();
// 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 SimpleBinaryOpTest__CompareEqualByte
{
private const int VectorSize = 16;
private const int ElementCount = VectorSize / sizeof(Byte);
private static Byte[] _data1 = new Byte[ElementCount];
private static Byte[] _data2 = new Byte[ElementCount];
private static Vector128<Byte> _clsVar1;
private static Vector128<Byte> _clsVar2;
private Vector128<Byte> _fld1;
private Vector128<Byte> _fld2;
private SimpleBinaryOpTest__DataTable<Byte> _dataTable;
static SimpleBinaryOpTest__CompareEqualByte()
{
var random = new Random();
for (var i = 0; i < ElementCount; i++) { _data1[i] = (byte)(random.Next(0, byte.MaxValue)); _data2[i] = (byte)(random.Next(0, byte.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar1), ref Unsafe.As<Byte, byte>(ref _data2[0]), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar2), ref Unsafe.As<Byte, byte>(ref _data1[0]), VectorSize);
}
public SimpleBinaryOpTest__CompareEqualByte()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < ElementCount; i++) { _data1[i] = (byte)(random.Next(0, byte.MaxValue)); _data2[i] = (byte)(random.Next(0, byte.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < ElementCount; i++) { _data1[i] = (byte)(random.Next(0, byte.MaxValue)); _data2[i] = (byte)(random.Next(0, byte.MaxValue)); }
_dataTable = new SimpleBinaryOpTest__DataTable<Byte>(_data1, _data2, new Byte[ElementCount], VectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Sse2.CompareEqual(
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Sse2.CompareEqual(
Sse2.LoadVector128((Byte*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Byte*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Sse2.CompareEqual(
Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareEqual), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareEqual), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Byte*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Byte*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareEqual), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Sse2.CompareEqual(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr);
var result = Sse2.CompareEqual(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var left = Sse2.LoadVector128((Byte*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadVector128((Byte*)(_dataTable.inArray2Ptr));
var result = Sse2.CompareEqual(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr));
var result = Sse2.CompareEqual(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleBinaryOpTest__CompareEqualByte();
var result = Sse2.CompareEqual(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Sse2.CompareEqual(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<Byte> left, Vector128<Byte> right, void* result, [CallerMemberName] string method = "")
{
Byte[] inArray1 = new Byte[ElementCount];
Byte[] inArray2 = new Byte[ElementCount];
Byte[] outArray = new Byte[ElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
Byte[] inArray1 = new Byte[ElementCount];
Byte[] inArray2 = new Byte[ElementCount];
Byte[] outArray = new Byte[ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Byte[] left, Byte[] right, Byte[] result, [CallerMemberName] string method = "")
{
if (result[0] != ((left[0] == right[0]) ? unchecked((byte)(-1)) : 0))
{
Succeeded = false;
}
else
{
for (var i = 1; i < left.Length; i++)
{
if (result[i] != ((left[i] == right[i]) ? unchecked((byte)(-1)) : 0))
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Sse2)}.{nameof(Sse2.CompareEqual)}<Byte>: {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
namespace UnityEditor.XCodeEditor
{
public class PBXParser
{
public const string PBX_HEADER_TOKEN = "// !$*UTF8*$!\n";
public const char WHITESPACE_SPACE = ' ';
public const char WHITESPACE_TAB = '\t';
public const char WHITESPACE_NEWLINE = '\n';
public const char WHITESPACE_CARRIAGE_RETURN = '\r';
public const char ARRAY_BEGIN_TOKEN = '(';
public const char ARRAY_END_TOKEN = ')';
public const char ARRAY_ITEM_DELIMITER_TOKEN = ',';
public const char DICTIONARY_BEGIN_TOKEN = '{';
public const char DICTIONARY_END_TOKEN = '}';
public const char DICTIONARY_ASSIGN_TOKEN = '=';
public const char DICTIONARY_ITEM_DELIMITER_TOKEN = ';';
public const char QUOTEDSTRING_BEGIN_TOKEN = '"';
public const char QUOTEDSTRING_END_TOKEN = '"';
public const char QUOTEDSTRING_ESCAPE_TOKEN = '\\';
public const char END_OF_FILE = (char)0x1A;
public const string COMMENT_BEGIN_TOKEN = "/*";
public const string COMMENT_END_TOKEN = "*/";
public const string COMMENT_LINE_TOKEN = "//";
private const int BUILDER_CAPACITY = 20000;
private char[] data;
private int index;
private int indent;
public PBXDictionary Decode( string data )
{
if( !data.StartsWith( PBX_HEADER_TOKEN ) ) {
Debug.Log( "Wrong file format." );
return null;
}
data = data.Substring( 13 );
this.data = data.ToCharArray();
index = 0;
return (PBXDictionary)ParseValue();
}
public string Encode( PBXDictionary pbxData)
{
indent = 0;
StringBuilder builder = new StringBuilder( PBX_HEADER_TOKEN, BUILDER_CAPACITY );
bool success = SerializeValue( pbxData, builder);
return ( success ? builder.ToString() : null );
}
#region Move
private char NextToken()
{
SkipWhitespaces();
return StepForeward();
}
private string Peek( int step = 1 )
{
string sneak = string.Empty;
for( int i = 1; i <= step; i++ ) {
if( data.Length - 1 < index + i ) {
break;
}
sneak += data[ index + i ];
}
return sneak;
}
private bool SkipWhitespaces()
{
bool whitespace = false;
while( Regex.IsMatch( StepForeward().ToString(), @"\s" ) )
whitespace = true;
StepBackward();
if( SkipComments() ) {
whitespace = true;
SkipWhitespaces();
}
return whitespace;
}
private bool SkipComments()
{
string s = string.Empty;
string tag = Peek( 2 );
switch( tag ) {
case COMMENT_BEGIN_TOKEN: {
while( Peek( 2 ).CompareTo( COMMENT_END_TOKEN ) != 0 ) {
s += StepForeward();
}
s += StepForeward( 2 );
break;
}
case COMMENT_LINE_TOKEN: {
while( !Regex.IsMatch( StepForeward().ToString(), @"\n" ) )
continue;
break;
}
default:
return false;
}
return true;
}
private char StepForeward( int step = 1 )
{
index = Math.Min( data.Length, index + step );
return data[ index ];
}
private char StepBackward( int step = 1 )
{
index = Math.Max( 0, index - step );
return data[ index ];
}
#endregion
#region Parse
private object ParseValue()
{
switch( NextToken() ) {
case END_OF_FILE:
Debug.Log( "End of file" );
return null;
case DICTIONARY_BEGIN_TOKEN:
return ParseDictionary();
case ARRAY_BEGIN_TOKEN:
return ParseArray();
case QUOTEDSTRING_BEGIN_TOKEN:
return ParseString();
default:
StepBackward();
return ParseEntity();
}
}
private PBXDictionary ParseDictionary()
{
SkipWhitespaces();
PBXDictionary dictionary = new PBXDictionary();
string keyString = string.Empty;
object valueObject = null;
bool complete = false;
while( !complete ) {
switch( NextToken() ) {
case END_OF_FILE:
Debug.Log( "Error: reached end of file inside a dictionary: " + index );
complete = true;
break;
case DICTIONARY_ITEM_DELIMITER_TOKEN:
keyString = string.Empty;
valueObject = null;
break;
case DICTIONARY_END_TOKEN:
keyString = string.Empty;
valueObject = null;
complete = true;
break;
case DICTIONARY_ASSIGN_TOKEN:
valueObject = ParseValue();
dictionary.Add( keyString, valueObject );
break;
default:
StepBackward();
keyString = ParseValue() as string;
break;
}
}
return dictionary;
}
private PBXList ParseArray()
{
PBXList list = new PBXList();
bool complete = false;
while( !complete ) {
switch( NextToken() ) {
case END_OF_FILE:
Debug.Log( "Error: Reached end of file inside a list: " + list );
complete = true;
break;
case ARRAY_END_TOKEN:
complete = true;
break;
case ARRAY_ITEM_DELIMITER_TOKEN:
break;
default:
StepBackward();
list.Add( ParseValue() );
break;
}
}
return list;
}
private object ParseString()
{
string s = string.Empty;
s += "\"";
char c = StepForeward();
while( c != QUOTEDSTRING_END_TOKEN ) {
s += c;
if( c == QUOTEDSTRING_ESCAPE_TOKEN )
s += StepForeward();
c = StepForeward();
}
s += "\"";
return s;
}
//there has got to be a better way to do this
private string GetDataSubstring(int begin, int length)
{
string res = string.Empty;
for(int i=begin; i<begin+length && i<data.Length; i++)
{
res += data[i];
}
return res;
}
private int CountWhitespace(int pos)
{
int i=0;
for(int currPos=pos; currPos<data.Length && Regex.IsMatch( GetDataSubstring(currPos, 1), @"[;,\s=]" ); i++, currPos++) {}
return i;
}
private string ParseCommentFollowingWhitespace()
{
int currIdx = index+1;
int whitespaceLength = CountWhitespace(currIdx);
currIdx += whitespaceLength;
if(currIdx + 1 >= data.Length)
return "";
if(data[currIdx] == '/' && data[currIdx+1] == '*')
{
while(!GetDataSubstring(currIdx, 2).Equals(COMMENT_END_TOKEN))
{
if(currIdx >= data.Length)
{
Debug.LogError("Unterminated comment found in .pbxproj file. Bad things are probably going to start happening");
return "";
}
currIdx++;
}
return GetDataSubstring (index+1, (currIdx-index+1));
}
else
{
return "";
}
}
private object ParseEntity()
{
string word = string.Empty;
while(!Regex.IsMatch( Peek(), @"[;,\s=]" ))
{
word += StepForeward();
}
string comment = ParseCommentFollowingWhitespace();
if(comment.Length > 0)
{
word += comment;
index += comment.Length;
}
if( word.Length != 24 && Regex.IsMatch( word, @"^\d+$" ) ) {
return Int32.Parse( word );
}
return word;
}
#endregion
#region Serialize
private void AppendNewline(StringBuilder builder)
{
builder.Append(WHITESPACE_NEWLINE);
for(int i=0; i<indent; i++)
{
builder.Append (WHITESPACE_TAB);
}
}
private void AppendLineDelim(StringBuilder builder, bool newline)
{
if(newline)
{
AppendNewline(builder);
}
else
{
builder.Append(WHITESPACE_SPACE);
}
}
private bool SerializeValue( object value, StringBuilder builder)
{
bool internalNewlines = false;
if(value is PBXObject)
{
internalNewlines = ((PBXObject)value).internalNewlines;
}
else if(value is PBXDictionary)
{
internalNewlines = ((PBXDictionary)value).internalNewlines;
}
else if(value is PBXList)
{
internalNewlines = ((PBXList)value).internalNewlines;
}
if( value == null ) {
builder.Append( "null" );
}
else if( value is PBXObject ) {
SerializeDictionary( ((PBXObject)value).data, builder, internalNewlines);
}
else if( value is PBXDictionary ) {
SerializeDictionary( (Dictionary<string, object>)value, builder, internalNewlines);
}
else if( value is Dictionary<string, object> ) {
SerializeDictionary( (Dictionary<string, object>)value, builder, internalNewlines);
}
else if( value.GetType().IsArray ) {
SerializeArray( new ArrayList( (ICollection)value ), builder, internalNewlines);
}
else if( value is ArrayList ) {
SerializeArray( (ArrayList)value, builder, internalNewlines);
}
else if( value is string ) {
SerializeString( (string)value, builder);
}
else if( value is Char ) {
SerializeString( Convert.ToString( (char)value ), builder);
}
else if( value is bool ) {
builder.Append( Convert.ToInt32( value ).ToString() );
}
else if( value.GetType().IsPrimitive ) {
builder.Append( Convert.ToString( value ) );
}
else {
Debug.LogWarning( "Error: unknown object of type " + value.GetType().Name );
return false;
}
return true;
}
private bool SerializeDictionary( Dictionary<string, object> dictionary, StringBuilder builder, bool internalNewlines)
{
builder.Append( DICTIONARY_BEGIN_TOKEN );
if(dictionary.Count > 0)
indent++;
if(internalNewlines)
AppendNewline(builder);
int i=0;
foreach( KeyValuePair<string, object> pair in dictionary ) {
SerializeString( pair.Key, builder );
builder.Append( WHITESPACE_SPACE );
builder.Append( DICTIONARY_ASSIGN_TOKEN );
builder.Append( WHITESPACE_SPACE );
SerializeValue( pair.Value, builder );
builder.Append( DICTIONARY_ITEM_DELIMITER_TOKEN );
if(i == dictionary.Count-1)
indent--;
AppendLineDelim(builder, internalNewlines);
i++;
}
builder.Append( DICTIONARY_END_TOKEN );
return true;
}
private bool SerializeArray( ArrayList anArray, StringBuilder builder, bool internalNewlines)
{
builder.Append( ARRAY_BEGIN_TOKEN );
if(anArray.Count > 0)
indent++;
if(internalNewlines)
AppendNewline(builder);
for( int i = 0; i < anArray.Count; i++ )
{
object value = anArray[i];
if( !SerializeValue( value, builder ) )
{
return false;
}
builder.Append( ARRAY_ITEM_DELIMITER_TOKEN );
if(i == anArray.Count-1)
indent--;
AppendLineDelim(builder, internalNewlines);
}
builder.Append( ARRAY_END_TOKEN );
return true;
}
private bool SerializeString( string aString, StringBuilder builder)
{
// Is a GUID?
if(PBXObject.IsGuid(aString)) {
builder.Append( aString );
return true;
}
// Is an empty string?
if( string.IsNullOrEmpty( aString ) ) {
builder.Append( QUOTEDSTRING_BEGIN_TOKEN );
builder.Append( QUOTEDSTRING_END_TOKEN );
return true;
}
builder.Append( aString );
return true;
}
#endregion
}
}
| |
//
// Options.cs
//
// Authors:
// Jonathan Pryor <jpryor@novell.com>
// Federico Di Gregorio <fog@initd.org>
//
// Copyright (C) 2008 Novell (http://www.novell.com)
// Copyright (C) 2009 Federico Di Gregorio.
//
// 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.
//
// Compile With:
// gmcs -debug+ -r:System.Core Options.cs -o:NDesk.Options.dll
// gmcs -debug+ -d:LINQ -r:System.Core Options.cs -o:NDesk.Options.dll
//
// The LINQ version just changes the implementation of
// OptionSet.Parse(IEnumerable<string>), and confers no semantic changes.
//
// A Getopt::Long-inspired option parsing library for C#.
//
// NDesk.Options.OptionSet is built upon a key/value table, where the
// key is a option format string and the value is a delegate that is
// invoked when the format string is matched.
//
// Option format strings:
// Regex-like BNF Grammar:
// name: .+
// type: [=:]
// sep: ( [^{}]+ | '{' .+ '}' )?
// aliases: ( name type sep ) ( '|' name type sep )*
//
// Each '|'-delimited name is an alias for the associated action. If the
// format string ends in a '=', it has a required value. If the format
// string ends in a ':', it has an optional value. If neither '=' or ':'
// is present, no value is supported. `=' or `:' need only be defined on one
// alias, but if they are provided on more than one they must be consistent.
//
// Each alias portion may also end with a "key/value separator", which is used
// to split option values if the option accepts > 1 value. If not specified,
// it defaults to '=' and ':'. If specified, it can be any character except
// '{' and '}' OR the *string* between '{' and '}'. If no separator should be
// used (i.e. the separate values should be distinct arguments), then "{}"
// should be used as the separator.
//
// Options are extracted either from the current option by looking for
// the option name followed by an '=' or ':', or is taken from the
// following option IFF:
// - The current option does not contain a '=' or a ':'
// - The current option requires a value (i.e. not a Option type of ':')
//
// The `name' used in the option format string does NOT include any leading
// option indicator, such as '-', '--', or '/'. All three of these are
// permitted/required on any named option.
//
// Option bundling is permitted so long as:
// - '-' is used to start the option group
// - all of the bundled options are a single character
// - at most one of the bundled options accepts a value, and the value
// provided starts from the next character to the end of the string.
//
// This allows specifying '-a -b -c' as '-abc', and specifying '-D name=value'
// as '-Dname=value'.
//
// Option processing is disabled by specifying "--". All options after "--"
// are returned by OptionSet.Parse() unchanged and unprocessed.
//
// Unprocessed options are returned from OptionSet.Parse().
//
// Examples:
// int verbose = 0;
// OptionSet p = new OptionSet ()
// .Add ("v", v => ++verbose)
// .Add ("name=|value=", v => Console.WriteLine (v));
// p.Parse (new string[]{"-v", "--v", "/v", "-name=A", "/name", "B", "extra"});
//
// The above would parse the argument string array, and would invoke the
// lambda expression three times, setting `verbose' to 3 when complete.
// It would also print out "A" and "B" to standard output.
// The returned array would contain the string "extra".
//
// C# 3.0 collection initializers are supported and encouraged:
// var p = new OptionSet () {
// { "h|?|help", v => ShowHelp () },
// };
//
// System.ComponentModel.TypeConverter is also supported, allowing the use of
// custom data types in the callback type; TypeConverter.ConvertFromString()
// is used to convert the value option to an instance of the specified
// type:
//
// var p = new OptionSet () {
// { "foo=", (Foo f) => Console.WriteLine (f.ToString ()) },
// };
//
// Random other tidbits:
// - Boolean options (those w/o '=' or ':' in the option format string)
// are explicitly enabled if they are followed with '+', and explicitly
// disabled if they are followed with '-':
// string a = null;
// var p = new OptionSet () {
// { "a", s => a = s },
// };
// p.Parse (new string[]{"-a"}); // sets v != null
// p.Parse (new string[]{"-a+"}); // sets v != null
// p.Parse (new string[]{"-a-"}); // sets v == null
//
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Runtime.Serialization;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
#if LINQ
using System.Linq;
#endif
#if TEST
using NDesk.Options;
#endif
#if NDESK_OPTIONS
namespace NDesk.Options
#else
namespace Mono.Options
#endif
{
static class StringCoda {
public static IEnumerable<string> WrappedLines (string self, params int[] widths)
{
IEnumerable<int> w = widths;
return WrappedLines (self, w);
}
public static IEnumerable<string> WrappedLines (string self, IEnumerable<int> widths)
{
if (widths == null)
throw new ArgumentNullException ("widths");
return CreateWrappedLinesIterator (self, widths);
}
private static IEnumerable<string> CreateWrappedLinesIterator (string self, IEnumerable<int> widths)
{
if (string.IsNullOrEmpty (self)) {
yield return string.Empty;
yield break;
}
using (IEnumerator<int> ewidths = widths.GetEnumerator ()) {
bool? hw = null;
int width = GetNextWidth (ewidths, int.MaxValue, ref hw);
int start = 0, end;
do {
end = GetLineEnd (start, width, self);
char c = self [end-1];
if (char.IsWhiteSpace (c))
--end;
bool needContinuation = end != self.Length && !IsEolChar (c);
string continuation = "";
if (needContinuation) {
--end;
continuation = "-";
}
string line = self.Substring (start, end - start) + continuation;
yield return line;
start = end;
if (char.IsWhiteSpace (c))
++start;
width = GetNextWidth (ewidths, width, ref hw);
} while (start < self.Length);
}
}
private static int GetNextWidth (IEnumerator<int> ewidths, int curWidth, ref bool? eValid)
{
if (!eValid.HasValue || (eValid.HasValue && eValid.Value)) {
curWidth = (eValid = ewidths.MoveNext ()).Value ? ewidths.Current : curWidth;
// '.' is any character, - is for a continuation
const string minWidth = ".-";
if (curWidth < minWidth.Length)
throw new ArgumentOutOfRangeException ("widths",
string.Format ("Element must be >= {0}, was {1}.", minWidth.Length, curWidth));
return curWidth;
}
// no more elements, use the last element.
return curWidth;
}
private static bool IsEolChar (char c)
{
return !char.IsLetterOrDigit (c);
}
private static int GetLineEnd (int start, int length, string description)
{
int end = System.Math.Min (start + length, description.Length);
int sep = -1;
for (int i = start; i < end; ++i) {
if (description [i] == '\n')
return i+1;
if (IsEolChar (description [i]))
sep = i+1;
}
if (sep == -1 || end == description.Length)
return end;
return sep;
}
}
internal class OptionValueCollection : IList, IList<string> {
List<string> values = new List<string> ();
OptionContext c;
internal OptionValueCollection (OptionContext c)
{
this.c = c;
}
#region ICollection
void ICollection.CopyTo (Array array, int index) {(values as ICollection).CopyTo (array, index);}
bool ICollection.IsSynchronized {get {return (values as ICollection).IsSynchronized;}}
object ICollection.SyncRoot {get {return (values as ICollection).SyncRoot;}}
#endregion
#region ICollection<T>
public void Add (string item) {values.Add (item);}
public void Clear () {values.Clear ();}
public bool Contains (string item) {return values.Contains (item);}
public void CopyTo (string[] array, int arrayIndex) {values.CopyTo (array, arrayIndex);}
public bool Remove (string item) {return values.Remove (item);}
public int Count {get {return values.Count;}}
public bool IsReadOnly {get {return false;}}
#endregion
#region IEnumerable
IEnumerator IEnumerable.GetEnumerator () {return values.GetEnumerator ();}
#endregion
#region IEnumerable<T>
public IEnumerator<string> GetEnumerator () {return values.GetEnumerator ();}
#endregion
#region IList
int IList.Add (object value) {return (values as IList).Add (value);}
bool IList.Contains (object value) {return (values as IList).Contains (value);}
int IList.IndexOf (object value) {return (values as IList).IndexOf (value);}
void IList.Insert (int index, object value) {(values as IList).Insert (index, value);}
void IList.Remove (object value) {(values as IList).Remove (value);}
void IList.RemoveAt (int index) {(values as IList).RemoveAt (index);}
bool IList.IsFixedSize {get {return false;}}
object IList.this [int index] {get {return this [index];} set {(values as IList)[index] = value;}}
#endregion
#region IList<T>
public int IndexOf (string item) {return values.IndexOf (item);}
public void Insert (int index, string item) {values.Insert (index, item);}
public void RemoveAt (int index) {values.RemoveAt (index);}
private void AssertValid (int index)
{
if (c.Option == null)
throw new InvalidOperationException ("OptionContext.Option is null.");
if (index >= c.Option.MaxValueCount)
throw new ArgumentOutOfRangeException ("index");
if (c.Option.OptionValueType == OptionValueType.Required &&
index >= values.Count)
throw new OptionException (string.Format (
c.OptionSet.MessageLocalizer ("Missing required value for option '{0}'."), c.OptionName),
c.OptionName);
}
public string this [int index] {
get {
AssertValid (index);
return index >= values.Count ? null : values [index];
}
set {
values [index] = value;
}
}
#endregion
public List<string> ToList ()
{
return new List<string> (values);
}
public string[] ToArray ()
{
return values.ToArray ();
}
public override string ToString ()
{
return string.Join (", ", values.ToArray ());
}
}
internal class OptionContext
{
private Option option;
private string name;
private int index;
private OptionSet set;
private OptionValueCollection c;
public OptionContext (OptionSet set)
{
this.set = set;
this.c = new OptionValueCollection (this);
}
public Option Option {
get {return option;}
set {option = value;}
}
public string OptionName {
get {return name;}
set {name = value;}
}
public int OptionIndex {
get {return index;}
set {index = value;}
}
public OptionSet OptionSet {
get {return set;}
}
public OptionValueCollection OptionValues {
get {return c;}
}
}
internal enum OptionValueType
{
None,
Optional,
Required,
}
internal abstract class Option
{
string prototype, description;
string[] names;
OptionValueType type;
int count;
string[] separators;
protected Option (string prototype, string description)
: this (prototype, description, 1)
{
}
protected Option (string prototype, string description, int maxValueCount)
{
if (prototype == null)
throw new ArgumentNullException ("prototype");
if (prototype.Length == 0)
throw new ArgumentException ("Cannot be the empty string.", "prototype");
if (maxValueCount < 0)
throw new ArgumentOutOfRangeException ("maxValueCount");
this.prototype = prototype;
this.description = description;
this.count = maxValueCount;
this.names = (this is OptionSet.Category)
// append GetHashCode() so that "duplicate" categories have distinct
// names, e.g. adding multiple "" categories should be valid.
? new[]{prototype + this.GetHashCode ()}
: prototype.Split ('|');
if (this is OptionSet.Category)
return;
this.type = ParsePrototype ();
if (this.count == 0 && type != OptionValueType.None)
throw new ArgumentException (
"Cannot provide maxValueCount of 0 for OptionValueType.Required or " +
"OptionValueType.Optional.",
"maxValueCount");
if (this.type == OptionValueType.None && maxValueCount > 1)
throw new ArgumentException (
string.Format ("Cannot provide maxValueCount of {0} for OptionValueType.None.", maxValueCount),
"maxValueCount");
if (Array.IndexOf (names, "<>") >= 0 &&
((names.Length == 1 && this.type != OptionValueType.None) ||
(names.Length > 1 && this.MaxValueCount > 1)))
throw new ArgumentException (
"The default option handler '<>' cannot require values.",
"prototype");
}
public string Prototype {get {return prototype;}}
public string Description {get {return description;}}
public OptionValueType OptionValueType {get {return type;}}
public int MaxValueCount {get {return count;}}
public string[] GetNames ()
{
return (string[]) names.Clone ();
}
public string[] GetValueSeparators ()
{
if (separators == null)
return new string [0];
return (string[]) separators.Clone ();
}
protected static T Parse<T> (string value, OptionContext c)
{
Type tt = typeof (T);
bool nullable = tt.IsValueType && tt.IsGenericType &&
!tt.IsGenericTypeDefinition &&
tt.GetGenericTypeDefinition () == typeof (Nullable<>);
Type targetType = nullable ? tt.GetGenericArguments () [0] : typeof (T);
TypeConverter conv = TypeDescriptor.GetConverter (targetType);
T t = default (T);
try {
if (value != null)
t = (T) conv.ConvertFromString (value);
}
catch (Exception e) {
throw new OptionException (
string.Format (
c.OptionSet.MessageLocalizer ("Could not convert string `{0}' to type {1} for option `{2}'."),
value, targetType.Name, c.OptionName),
c.OptionName, e);
}
return t;
}
internal string[] Names {get {return names;}}
internal string[] ValueSeparators {get {return separators;}}
static readonly char[] NameTerminator = new char[]{'=', ':'};
private OptionValueType ParsePrototype ()
{
char type = '\0';
List<string> seps = new List<string> ();
for (int i = 0; i < names.Length; ++i) {
string name = names [i];
if (name.Length == 0)
throw new ArgumentException ("Empty option names are not supported.", "prototype");
int end = name.IndexOfAny (NameTerminator);
if (end == -1)
continue;
names [i] = name.Substring (0, end);
if (type == '\0' || type == name [end])
type = name [end];
else
throw new ArgumentException (
string.Format ("Conflicting option types: '{0}' vs. '{1}'.", type, name [end]),
"prototype");
AddSeparators (name, end, seps);
}
if (type == '\0')
return OptionValueType.None;
if (count <= 1 && seps.Count != 0)
throw new ArgumentException (
string.Format ("Cannot provide key/value separators for Options taking {0} value(s).", count),
"prototype");
if (count > 1) {
if (seps.Count == 0)
this.separators = new string[]{":", "="};
else if (seps.Count == 1 && seps [0].Length == 0)
this.separators = null;
else
this.separators = seps.ToArray ();
}
return type == '=' ? OptionValueType.Required : OptionValueType.Optional;
}
private static void AddSeparators (string name, int end, ICollection<string> seps)
{
int start = -1;
for (int i = end+1; i < name.Length; ++i) {
switch (name [i]) {
case '{':
if (start != -1)
throw new ArgumentException (
string.Format ("Ill-formed name/value separator found in \"{0}\".", name),
"prototype");
start = i+1;
break;
case '}':
if (start == -1)
throw new ArgumentException (
string.Format ("Ill-formed name/value separator found in \"{0}\".", name),
"prototype");
seps.Add (name.Substring (start, i-start));
start = -1;
break;
default:
if (start == -1)
seps.Add (name [i].ToString ());
break;
}
}
if (start != -1)
throw new ArgumentException (
string.Format ("Ill-formed name/value separator found in \"{0}\".", name),
"prototype");
}
public void Invoke (OptionContext c)
{
OnParseComplete (c);
c.OptionName = null;
c.Option = null;
c.OptionValues.Clear ();
}
protected abstract void OnParseComplete (OptionContext c);
public override string ToString ()
{
return Prototype;
}
}
internal abstract class ArgumentSource {
protected ArgumentSource ()
{
}
public abstract string[] GetNames ();
public abstract string Description { get; }
public abstract bool GetArguments (string value, out IEnumerable<string> replacement);
public static IEnumerable<string> GetArgumentsFromFile (string file)
{
return GetArguments (File.OpenText (file), true);
}
public static IEnumerable<string> GetArguments (TextReader reader)
{
return GetArguments (reader, false);
}
// Cribbed from mcs/driver.cs:LoadArgs(string)
static IEnumerable<string> GetArguments (TextReader reader, bool close)
{
try {
StringBuilder arg = new StringBuilder ();
string line;
while ((line = reader.ReadLine ()) != null) {
int t = line.Length;
for (int i = 0; i < t; i++) {
char c = line [i];
if (c == '"' || c == '\'') {
char end = c;
for (i++; i < t; i++){
c = line [i];
if (c == end)
break;
arg.Append (c);
}
} else if (c == ' ') {
if (arg.Length > 0) {
yield return arg.ToString ();
arg.Length = 0;
}
} else
arg.Append (c);
}
if (arg.Length > 0) {
yield return arg.ToString ();
arg.Length = 0;
}
}
}
finally {
if (close)
reader.Close ();
}
}
}
internal class ResponseFileSource : ArgumentSource
{
public override string[] GetNames ()
{
return new string[]{"@file"};
}
public override string Description {
get {return "Read response file for more options.";}
}
public override bool GetArguments (string value, out IEnumerable<string> replacement)
{
if (string.IsNullOrEmpty (value) || !value.StartsWith ("@")) {
replacement = null;
return false;
}
replacement = ArgumentSource.GetArgumentsFromFile (value.Substring (1));
return true;
}
}
[Serializable]
internal class OptionException : Exception
{
private string option;
public OptionException ()
{
}
public OptionException (string message, string optionName)
: base (message)
{
this.option = optionName;
}
public OptionException (string message, string optionName, Exception innerException)
: base (message, innerException)
{
this.option = optionName;
}
protected OptionException (SerializationInfo info, StreamingContext context)
: base (info, context)
{
this.option = info.GetString ("OptionName");
}
public string OptionName {
get {return this.option;}
}
[SecurityPermission (SecurityAction.LinkDemand, SerializationFormatter = true)]
public override void GetObjectData (SerializationInfo info, StreamingContext context)
{
base.GetObjectData (info, context);
info.AddValue ("OptionName", option);
}
}
internal delegate void OptionAction<TKey, TValue>(TKey key, TValue value);
internal class OptionSet : KeyedCollection<string, Option>
{
public OptionSet ()
: this (delegate (string f) {return f;})
{
}
public OptionSet (Converter<string, string> localizer)
{
this.localizer = localizer;
this.roSources = new ReadOnlyCollection<ArgumentSource>(sources);
}
Converter<string, string> localizer;
public Converter<string, string> MessageLocalizer {
get {return localizer;}
}
List<ArgumentSource> sources = new List<ArgumentSource> ();
ReadOnlyCollection<ArgumentSource> roSources;
public ReadOnlyCollection<ArgumentSource> ArgumentSources {
get {return roSources;}
}
protected override string GetKeyForItem (Option item)
{
if (item == null)
throw new ArgumentNullException ("option");
if (item.Names != null && item.Names.Length > 0)
return item.Names [0];
// This should never happen, as it's invalid for Option to be
// constructed w/o any names.
throw new InvalidOperationException ("Option has no names!");
}
[Obsolete ("Use KeyedCollection.this[string]")]
protected Option GetOptionForName (string option)
{
if (option == null)
throw new ArgumentNullException ("option");
try {
return base [option];
}
catch (KeyNotFoundException) {
return null;
}
}
protected override void InsertItem (int index, Option item)
{
base.InsertItem (index, item);
AddImpl (item);
}
protected override void RemoveItem (int index)
{
Option p = Items [index];
base.RemoveItem (index);
// KeyedCollection.RemoveItem() handles the 0th item
for (int i = 1; i < p.Names.Length; ++i) {
Dictionary.Remove (p.Names [i]);
}
}
protected override void SetItem (int index, Option item)
{
base.SetItem (index, item);
AddImpl (item);
}
private void AddImpl (Option option)
{
if (option == null)
throw new ArgumentNullException ("option");
List<string> added = new List<string> (option.Names.Length);
try {
// KeyedCollection.InsertItem/SetItem handle the 0th name.
for (int i = 1; i < option.Names.Length; ++i) {
Dictionary.Add (option.Names [i], option);
added.Add (option.Names [i]);
}
}
catch (Exception) {
foreach (string name in added)
Dictionary.Remove (name);
throw;
}
}
public OptionSet Add (string header)
{
if (header == null)
throw new ArgumentNullException ("header");
Add (new Category (header));
return this;
}
internal sealed class Category : Option {
// Prototype starts with '=' because this is an invalid prototype
// (see Option.ParsePrototype(), and thus it'll prevent Category
// instances from being accidentally used as normal options.
public Category (string description)
: base ("=:Category:= " + description, description)
{
}
protected override void OnParseComplete (OptionContext c)
{
throw new NotSupportedException ("Category.OnParseComplete should not be invoked.");
}
}
public new OptionSet Add (Option option)
{
base.Add (option);
return this;
}
sealed class ActionOption : Option {
Action<OptionValueCollection> action;
public ActionOption (string prototype, string description, int count, Action<OptionValueCollection> action)
: base (prototype, description, count)
{
if (action == null)
throw new ArgumentNullException ("action");
this.action = action;
}
protected override void OnParseComplete (OptionContext c)
{
action (c.OptionValues);
}
}
public OptionSet Add (string prototype, Action<string> action)
{
return Add (prototype, null, action);
}
public OptionSet Add (string prototype, string description, Action<string> action)
{
if (action == null)
throw new ArgumentNullException ("action");
Option p = new ActionOption (prototype, description, 1,
delegate (OptionValueCollection v) { action (v [0]); });
base.Add (p);
return this;
}
public OptionSet Add (string prototype, OptionAction<string, string> action)
{
return Add (prototype, null, action);
}
public OptionSet Add (string prototype, string description, OptionAction<string, string> action)
{
if (action == null)
throw new ArgumentNullException ("action");
Option p = new ActionOption (prototype, description, 2,
delegate (OptionValueCollection v) {action (v [0], v [1]);});
base.Add (p);
return this;
}
sealed class ActionOption<T> : Option {
Action<T> action;
public ActionOption (string prototype, string description, Action<T> action)
: base (prototype, description, 1)
{
if (action == null)
throw new ArgumentNullException ("action");
this.action = action;
}
protected override void OnParseComplete (OptionContext c)
{
action (Parse<T> (c.OptionValues [0], c));
}
}
sealed class ActionOption<TKey, TValue> : Option {
OptionAction<TKey, TValue> action;
public ActionOption (string prototype, string description, OptionAction<TKey, TValue> action)
: base (prototype, description, 2)
{
if (action == null)
throw new ArgumentNullException ("action");
this.action = action;
}
protected override void OnParseComplete (OptionContext c)
{
action (
Parse<TKey> (c.OptionValues [0], c),
Parse<TValue> (c.OptionValues [1], c));
}
}
public OptionSet Add<T> (string prototype, Action<T> action)
{
return Add (prototype, null, action);
}
public OptionSet Add<T> (string prototype, string description, Action<T> action)
{
return Add (new ActionOption<T> (prototype, description, action));
}
public OptionSet Add<TKey, TValue> (string prototype, OptionAction<TKey, TValue> action)
{
return Add (prototype, null, action);
}
public OptionSet Add<TKey, TValue> (string prototype, string description, OptionAction<TKey, TValue> action)
{
return Add (new ActionOption<TKey, TValue> (prototype, description, action));
}
public OptionSet Add (ArgumentSource source)
{
if (source == null)
throw new ArgumentNullException ("source");
sources.Add (source);
return this;
}
protected virtual OptionContext CreateOptionContext ()
{
return new OptionContext (this);
}
public List<string> Parse (IEnumerable<string> arguments)
{
if (arguments == null)
throw new ArgumentNullException ("arguments");
OptionContext c = CreateOptionContext ();
c.OptionIndex = -1;
bool process = true;
List<string> unprocessed = new List<string> ();
Option def = Contains ("<>") ? this ["<>"] : null;
ArgumentEnumerator ae = new ArgumentEnumerator (arguments);
foreach (string argument in ae) {
++c.OptionIndex;
if (argument == "--") {
process = false;
continue;
}
if (!process) {
Unprocessed (unprocessed, def, c, argument);
continue;
}
if (AddSource (ae, argument))
continue;
if (!Parse (argument, c))
Unprocessed (unprocessed, def, c, argument);
}
if (c.Option != null)
c.Option.Invoke (c);
return unprocessed;
}
class ArgumentEnumerator : IEnumerable<string> {
List<IEnumerator<string>> sources = new List<IEnumerator<string>> ();
public ArgumentEnumerator (IEnumerable<string> arguments)
{
sources.Add (arguments.GetEnumerator ());
}
public void Add (IEnumerable<string> arguments)
{
sources.Add (arguments.GetEnumerator ());
}
public IEnumerator<string> GetEnumerator ()
{
do {
IEnumerator<string> c = sources [sources.Count-1];
if (c.MoveNext ())
yield return c.Current;
else {
c.Dispose ();
sources.RemoveAt (sources.Count-1);
}
} while (sources.Count > 0);
}
IEnumerator IEnumerable.GetEnumerator ()
{
return GetEnumerator ();
}
}
bool AddSource (ArgumentEnumerator ae, string argument)
{
foreach (ArgumentSource source in sources) {
IEnumerable<string> replacement;
if (!source.GetArguments (argument, out replacement))
continue;
ae.Add (replacement);
return true;
}
return false;
}
private static bool Unprocessed (ICollection<string> extra, Option def, OptionContext c, string argument)
{
if (def == null) {
extra.Add (argument);
return false;
}
c.OptionValues.Add (argument);
c.Option = def;
c.Option.Invoke (c);
return false;
}
private readonly Regex ValueOption = new Regex (
@"^(?<flag>--|-|/)(?<name>[^:=]+)((?<sep>[:=])(?<value>.*))?$");
protected bool GetOptionParts (string argument, out string flag, out string name, out string sep, out string value)
{
if (argument == null)
throw new ArgumentNullException ("argument");
flag = name = sep = value = null;
Match m = ValueOption.Match (argument);
if (!m.Success) {
return false;
}
flag = m.Groups ["flag"].Value;
name = m.Groups ["name"].Value;
if (m.Groups ["sep"].Success && m.Groups ["value"].Success) {
sep = m.Groups ["sep"].Value;
value = m.Groups ["value"].Value;
}
return true;
}
protected virtual bool Parse (string argument, OptionContext c)
{
if (c.Option != null) {
ParseValue (argument, c);
return true;
}
string f, n, s, v;
if (!GetOptionParts (argument, out f, out n, out s, out v))
return false;
Option p;
if (Contains (n)) {
p = this [n];
c.OptionName = f + n;
c.Option = p;
switch (p.OptionValueType) {
case OptionValueType.None:
c.OptionValues.Add (n);
c.Option.Invoke (c);
break;
case OptionValueType.Optional:
case OptionValueType.Required:
ParseValue (v, c);
break;
}
return true;
}
// no match; is it a bool option?
if (ParseBool (argument, n, c))
return true;
// is it a bundled option?
if (ParseBundledValue (f, string.Concat (n + s + v), c))
return true;
return false;
}
private void ParseValue (string option, OptionContext c)
{
if (option != null)
foreach (string o in c.Option.ValueSeparators != null
? option.Split (c.Option.ValueSeparators, c.Option.MaxValueCount - c.OptionValues.Count, StringSplitOptions.None)
: new string[]{option}) {
c.OptionValues.Add (o);
}
if (c.OptionValues.Count == c.Option.MaxValueCount ||
c.Option.OptionValueType == OptionValueType.Optional)
c.Option.Invoke (c);
else if (c.OptionValues.Count > c.Option.MaxValueCount) {
throw new OptionException (localizer (string.Format (
"Error: Found {0} option values when expecting {1}.",
c.OptionValues.Count, c.Option.MaxValueCount)),
c.OptionName);
}
}
private bool ParseBool (string option, string n, OptionContext c)
{
Option p;
string rn;
if (n.Length >= 1 && (n [n.Length-1] == '+' || n [n.Length-1] == '-') &&
Contains ((rn = n.Substring (0, n.Length-1)))) {
p = this [rn];
string v = n [n.Length-1] == '+' ? option : null;
c.OptionName = option;
c.Option = p;
c.OptionValues.Add (v);
p.Invoke (c);
return true;
}
return false;
}
private bool ParseBundledValue (string f, string n, OptionContext c)
{
if (f != "-")
return false;
for (int i = 0; i < n.Length; ++i) {
Option p;
string opt = f + n [i].ToString ();
string rn = n [i].ToString ();
if (!Contains (rn)) {
if (i == 0)
return false;
throw new OptionException (string.Format (localizer (
"Cannot bundle unregistered option '{0}'."), opt), opt);
}
p = this [rn];
switch (p.OptionValueType) {
case OptionValueType.None:
Invoke (c, opt, n, p);
break;
case OptionValueType.Optional:
case OptionValueType.Required: {
string v = n.Substring (i+1);
c.Option = p;
c.OptionName = opt;
ParseValue (v.Length != 0 ? v : null, c);
return true;
}
default:
throw new InvalidOperationException ("Unknown OptionValueType: " + p.OptionValueType);
}
}
return true;
}
private static void Invoke (OptionContext c, string name, string value, Option option)
{
c.OptionName = name;
c.Option = option;
c.OptionValues.Add (value);
option.Invoke (c);
}
private const int OptionWidth = 29;
private const int Description_FirstWidth = 80 - OptionWidth;
private const int Description_RemWidth = 80 - OptionWidth - 2;
public void WriteOptionDescriptions (TextWriter o)
{
foreach (Option p in this) {
int written = 0;
Category c = p as Category;
if (c != null) {
WriteDescription (o, p.Description, "", 80, 80);
continue;
}
if (!WriteOptionPrototype (o, p, ref written))
continue;
if (written < OptionWidth)
o.Write (new string (' ', OptionWidth - written));
else {
o.WriteLine ();
o.Write (new string (' ', OptionWidth));
}
WriteDescription (o, p.Description, new string (' ', OptionWidth+2),
Description_FirstWidth, Description_RemWidth);
}
foreach (ArgumentSource s in sources) {
string[] names = s.GetNames ();
if (names == null || names.Length == 0)
continue;
int written = 0;
Write (o, ref written, " ");
Write (o, ref written, names [0]);
for (int i = 1; i < names.Length; ++i) {
Write (o, ref written, ", ");
Write (o, ref written, names [i]);
}
if (written < OptionWidth)
o.Write (new string (' ', OptionWidth - written));
else {
o.WriteLine ();
o.Write (new string (' ', OptionWidth));
}
WriteDescription (o, s.Description, new string (' ', OptionWidth+2),
Description_FirstWidth, Description_RemWidth);
}
}
void WriteDescription (TextWriter o, string value, string prefix, int firstWidth, int remWidth)
{
bool indent = false;
foreach (string line in GetLines (localizer (GetDescription (value)), firstWidth, remWidth)) {
if (indent)
o.Write (prefix);
o.WriteLine (line);
indent = true;
}
}
bool WriteOptionPrototype (TextWriter o, Option p, ref int written)
{
string[] names = p.Names;
int i = GetNextOptionIndex (names, 0);
if (i == names.Length)
return false;
if (names [i].Length == 1) {
Write (o, ref written, " -");
Write (o, ref written, names [0]);
}
else {
Write (o, ref written, " --");
Write (o, ref written, names [0]);
}
for ( i = GetNextOptionIndex (names, i+1);
i < names.Length; i = GetNextOptionIndex (names, i+1)) {
Write (o, ref written, ", ");
Write (o, ref written, names [i].Length == 1 ? "-" : "--");
Write (o, ref written, names [i]);
}
if (p.OptionValueType == OptionValueType.Optional ||
p.OptionValueType == OptionValueType.Required) {
if (p.OptionValueType == OptionValueType.Optional) {
Write (o, ref written, localizer ("["));
}
Write (o, ref written, localizer ("=" + GetArgumentName (0, p.MaxValueCount, p.Description)));
string sep = p.ValueSeparators != null && p.ValueSeparators.Length > 0
? p.ValueSeparators [0]
: " ";
for (int c = 1; c < p.MaxValueCount; ++c) {
Write (o, ref written, localizer (sep + GetArgumentName (c, p.MaxValueCount, p.Description)));
}
if (p.OptionValueType == OptionValueType.Optional) {
Write (o, ref written, localizer ("]"));
}
}
return true;
}
static int GetNextOptionIndex (string[] names, int i)
{
while (i < names.Length && names [i] == "<>") {
++i;
}
return i;
}
static void Write (TextWriter o, ref int n, string s)
{
n += s.Length;
o.Write (s);
}
private static string GetArgumentName (int index, int maxIndex, string description)
{
if (description == null)
return maxIndex == 1 ? "VALUE" : "VALUE" + (index + 1);
string[] nameStart;
if (maxIndex == 1)
nameStart = new string[]{"{0:", "{"};
else
nameStart = new string[]{"{" + index + ":"};
for (int i = 0; i < nameStart.Length; ++i) {
int start, j = 0;
do {
start = description.IndexOf (nameStart [i], j);
} while (start >= 0 && j != 0 ? description [j++ - 1] == '{' : false);
if (start == -1)
continue;
int end = description.IndexOf ("}", start);
if (end == -1)
continue;
return description.Substring (start + nameStart [i].Length, end - start - nameStart [i].Length);
}
return maxIndex == 1 ? "VALUE" : "VALUE" + (index + 1);
}
private static string GetDescription (string description)
{
if (description == null)
return string.Empty;
StringBuilder sb = new StringBuilder (description.Length);
int start = -1;
for (int i = 0; i < description.Length; ++i) {
switch (description [i]) {
case '{':
if (i == start) {
sb.Append ('{');
start = -1;
}
else if (start < 0)
start = i + 1;
break;
case '}':
if (start < 0) {
if ((i+1) == description.Length || description [i+1] != '}')
throw new InvalidOperationException ("Invalid option description: " + description);
++i;
sb.Append ("}");
}
else {
sb.Append (description.Substring (start, i - start));
start = -1;
}
break;
case ':':
if (start < 0)
goto default;
start = i + 1;
break;
default:
if (start < 0)
sb.Append (description [i]);
break;
}
}
return sb.ToString ();
}
private static IEnumerable<string> GetLines (string description, int firstWidth, int remWidth)
{
return StringCoda.WrappedLines (description, firstWidth, remWidth);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
#if FRB_MDX
using Microsoft.DirectX;
using FlatRedBall.Graphics;
#else// FRB_XNA || SILVERLIGHT
using Vector2 = Microsoft.Xna.Framework.Vector2;
using Vector3 = Microsoft.Xna.Framework.Vector3;
using VertexPositionColor = Microsoft.Xna.Framework.Graphics.VertexPositionColor;
using Microsoft.Xna.Framework;
#endif
namespace FlatRedBall.Math.Geometry
{
public struct Segment
{
#region Fields
static Point mPoint;// for speeding up reference calls
/// <summary>
/// The first point of the segment.
/// </summary>
public Point Point1;
#region XML Docs
/// <summary>
/// The second point of the segment.
/// </summary>
#endregion
public Point Point2;
public static Segment ZeroLength = new Segment(0, 0, 0, 0);
#endregion
#region Properties
public double Angle
{
get
{
return System.Math.Atan2(Point2.Y - Point1.Y, Point2.X - Point1.X);
}
}
#region XML Docs
/// <summary>
/// Returns the geometric slope of the segment.
/// </summary>
#endregion
public double Slope
{
get
{
return (Point2.Y - Point1.Y) / (Point2.X - Point1.X);
}
}
#region XML Docs
/// <summary>
/// Returns the y intercept of the slope.
/// </summary>
/// <remarks>
/// This method treats the segment as a line, so this will return a value even
/// though the segment may not cross the x=0 line.
/// </remarks>
#endregion
public double YIntercept
{
get
{
return -Slope * Point1.X + Point1.Y;
}
}
#endregion
#region Methods
#region Constructors
#region XML Docs
/// <summary>
/// Creates a new Segment with the argument points as the endpoints.
/// </summary>
/// <param name="point1">The first Point.</param>
/// <param name="point2">The second Point.</param>
#endregion
public Segment(Point point1, Point point2)
{
this.Point1 = point1;
this.Point2 = point2;
}
public Segment(ref VertexPositionColor point1, ref VertexPositionColor point2)
{
this.Point1 = new Point(point1.Position.X, point1.Position.Y);
this.Point2 = new Point(point2.Position.X, point2.Position.Y);
}
public Segment( Vector3 point1, Vector3 point2)
{
this.Point1 = new Point(point1.X, point1.Y);
this.Point2 = new Point(point2.X, point2.Y);
}
public Segment(double point1X, double point1Y, double point2X, double point2Y)
{
this.Point1 = new Point(point1X, point1Y);
this.Point2 = new Point(point2X, point2Y);
}
#endregion
#region Public Methods
public Ray AsRay()
{
return new Ray(
Point1.ToVector3(), Point2.ToVector3() - Point1.ToVector3());
}
public bool CollideAgainst(Polygon polygon)
{
polygon.UpdateDependencies(TimeManager.CurrentTime);
// Check if one of the segment's endpoints is inside the Polygon
if (polygon.IsPointInside(Point1.X, Point1.Y))
{
polygon.mLastCollisionPoint = Point1;
return true;
}
if (polygon.IsPointInside(Point2.X, Point2.Y))
{
polygon.mLastCollisionPoint = Point2;
return true;
}
Point intersectionPoint;
// Check if one of the polygon's edges intersects the line segment
for (int i = 0; i < polygon.Points.Count - 1; i++)
{
if (Intersects(new Segment(
new Point(polygon.Position.X + polygon.Points[i].X,
polygon.Position.Y + polygon.Points[i].Y),
new Point(polygon.Position.X + polygon.Points[i + 1].X,
polygon.Position.Y + polygon.Points[i + 1].Y)), out intersectionPoint))
{
polygon.mLastCollisionPoint = intersectionPoint;
return true;
}
}
// No collision
return false;
}
public Point ClosestPointTo(Point point)
{
Vector2 unitSegment = new Vector2((float)(this.Point2.X - this.Point1.X), (float)(Point2.Y - Point1.Y));
unitSegment.Normalize();
Vector2 pointVector = new Vector2((float)(point.X - this.Point1.X), (float)(point.Y - Point1.Y));
// Segment pointSegment = new Segment( new Point(0,0),
// new Point(point.x - this.Point1.X, point.y - Point1.Y));
float l = Vector2.Dot(pointVector, unitSegment);
if (l < 0)
{
return this.Point1;
}
else if (l * l > this.GetLengthSquared())
{
return this.Point2;
}
else
{
Point newPoint = new Point(Point1.X + l * unitSegment.X, Point1.Y + l * unitSegment.Y);
return newPoint;
}
}
public float DistanceTo(Point point)
{
return DistanceTo(point.X, point.Y);
}
public float DistanceTo(Polygon polygon)
{
float finalDistance = float.MaxValue;
//loop to check all segment vs. polygon vertices.
foreach (VertexPositionColor v in polygon.Vertices)
{
finalDistance = System.Math.Min(finalDistance, DistanceTo(v.Position.X, v.Position.Y));
}
//loop to check all segment endpoints vs. polygon edges.
finalDistance = System.Math.Min(finalDistance, (float)polygon.VectorFrom(Point1.X, Point1.Y).Length());
finalDistance = System.Math.Min(finalDistance, (float)polygon.VectorFrom(Point2.X, Point2.Y).Length());
//take the minimum distance and return.
return finalDistance;
}
public float DistanceTo(AxisAlignedRectangle rectangle)
{
float finalDistance = float.MaxValue;
finalDistance = System.Math.Min(finalDistance, DistanceTo(rectangle.Left, rectangle.Top));
finalDistance = System.Math.Min(finalDistance, DistanceTo(rectangle.Left, rectangle.Bottom));
finalDistance = System.Math.Min(finalDistance, DistanceTo(rectangle.Right, rectangle.Top));
finalDistance = System.Math.Min(finalDistance, DistanceTo(rectangle.Right, rectangle.Bottom));
Segment rectSegment;
rectSegment = new Segment(rectangle.Left, rectangle.Top, rectangle.Left, rectangle.Bottom);
finalDistance = System.Math.Min(finalDistance, DistanceTo(rectSegment));
rectSegment = new Segment(rectangle.Left, rectangle.Top, rectangle.Right, rectangle.Top);
finalDistance = System.Math.Min(finalDistance, DistanceTo(rectSegment));
rectSegment = new Segment(rectangle.Right, rectangle.Top, rectangle.Right, rectangle.Bottom);
finalDistance = System.Math.Min(finalDistance, DistanceTo(rectSegment));
rectSegment = new Segment(rectangle.Left, rectangle.Bottom, rectangle.Right, rectangle.Bottom);
finalDistance = System.Math.Min(finalDistance, DistanceTo(rectSegment));
return finalDistance;
}
public float DistanceTo(Circle circle)
{
float distanceToCenter = DistanceTo(circle.Position);
return distanceToCenter - circle.Radius;
}
public float DistanceTo(Vector3 vector)
{
return DistanceTo(vector.X, vector.Y);
}
public float DistanceTo(double x, double y)
{
float segmentLength = (float)this.GetLength();
Vector2 normalizedLine = new Vector2(
(float)(Point2.X - Point1.X) / segmentLength,
(float)(Point2.Y - Point1.Y) / segmentLength);
Vector2 pointVector = new Vector2((float)(x - Point1.X), (float)(y - Point1.Y));
float length = Vector2.Dot(pointVector, normalizedLine);
if (length < 0)
{
return (float)(new Segment(x, y, Point1.X, Point1.Y).GetLength());
}
else if (length > segmentLength)
{
return (float)(new Segment(x, y, Point2.X, Point2.Y).GetLength());
}
else
{
normalizedLine.X *= length;
normalizedLine.Y *= length;
float xDistanceSquared = pointVector.X - normalizedLine.X;
xDistanceSquared = xDistanceSquared * xDistanceSquared;
float yDistanceSquared = pointVector.Y - normalizedLine.Y;
yDistanceSquared = yDistanceSquared * yDistanceSquared;
return (float)System.Math.Sqrt(xDistanceSquared + yDistanceSquared);
}
}
public float DistanceTo(Point point, out Segment connectingSegment)
{
double segmentLength = GetLength();
Point normalizedLine = new Point(
(Point2.X - Point1.X) / segmentLength,
(Point2.Y - Point1.Y) / segmentLength);
Point pointVector = new Point(point.X - Point1.X, point.Y - Point1.Y);
double length = Point.Dot(pointVector, normalizedLine);
connectingSegment.Point1 = point;
if (length < 0)
{
connectingSegment.Point2 = Point1;
}
else if (length > segmentLength)
{
connectingSegment.Point2 = Point2;
}
else
{
connectingSegment.Point2 = new Point(Point1.X + length * normalizedLine.X,
Point1.Y + length * normalizedLine.Y);
}
return (float)connectingSegment.GetLength();
}
#region XML Docs
/// <summary>
/// Returns the distance to the argument point as well as
/// the connectin Vector3 from the Point to this.
/// </summary>
/// <param name="point">The point to get the distance to.</param>
/// <param name="connectingVector">The connecting vector from the argument Pointn to this.</param>
/// <returns>The distance between this and the argument Point.</returns>
#endregion
public float DistanceTo(Point point, out Vector3 connectingVector)
{
connectingVector = new Vector3();
float segmentLength = (float)GetLength();
Vector2 normalizedLine = new Vector2(
(float)(Point2.X - Point1.X) / segmentLength,
(float)(Point2.Y - Point1.Y) / segmentLength);
Vector2 pointVector = new Vector2((float)(point.X - Point1.X), (float)(point.Y - Point1.Y));
float length = Vector2.Dot(pointVector, normalizedLine);
if (length < 0)
{
connectingVector.X = (float)(Point1.X - point.X);
connectingVector.Y = (float)(Point1.Y - point.Y);
connectingVector.Z = 0;
return connectingVector.Length();
}
else if (length > segmentLength)
{
connectingVector.X = (float)(Point2.X - point.X);
connectingVector.Y = (float)(Point2.Y - point.Y);
connectingVector.Z = 0;
return connectingVector.Length();
}
else
{
Point tempPoint = new Point(Point1.X + length * normalizedLine.X,
Point1.Y + length * normalizedLine.Y);
connectingVector.X = (float)(tempPoint.X - point.X);
connectingVector.Y = (float)(tempPoint.Y - point.Y);
connectingVector.Z = 0;
return connectingVector.Length();
}
}
public float DistanceTo(Segment otherSegment)
{
if (otherSegment.Intersects(this))
{
return 0;
}
else
{
float minDistance = float.PositiveInfinity;
minDistance = System.Math.Min(minDistance, this.DistanceTo(otherSegment.Point1));
minDistance = System.Math.Min(minDistance, this.DistanceTo(otherSegment.Point2));
minDistance = System.Math.Min(minDistance, otherSegment.DistanceTo(this.Point1));
minDistance = System.Math.Min(minDistance, otherSegment.DistanceTo(this.Point2));
return minDistance;
}
}
public float DistanceToSquared(ref Vector3 vector, out Segment connectingSegment)
{
float segmentLength = (float)this.GetLength();
Vector2 normalizedLine = new Vector2(
(float)(Point2.X - Point1.X) / segmentLength,
(float)(Point2.Y - Point1.Y) / segmentLength);
Vector2 pointVector = new Vector2((float)(vector.X - Point1.X), (float)(vector.Y - Point1.Y));
float length = Vector2.Dot(pointVector, normalizedLine);
if (length < 0)
{
connectingSegment.Point1 = new Point(ref vector);
connectingSegment.Point2 = Point1;
return (float) connectingSegment.GetLengthSquared();
}
else if (length > segmentLength)
{
connectingSegment.Point1 = new Point(ref vector);
connectingSegment.Point2 = Point2;
return (float) connectingSegment.GetLengthSquared();
}
else
{
connectingSegment.Point1 = new Point(ref vector);
connectingSegment.Point2 = new Point(Point1.X + length * normalizedLine.X,
Point1.Y + length * normalizedLine.Y);
return (float)connectingSegment.GetLengthSquared();
}
}
#region XML Docs
/// <summary>
/// Returns the length of the segment.
/// </summary>
#endregion
public double GetLength()
{
return System.Math.Sqrt((Point2.X - Point1.X) * (Point2.X - Point1.X) + (Point2.Y - Point1.Y) * (Point2.Y - Point1.Y));
}
public double GetLengthSquared()
{
return (Point2.X - Point1.X) * (Point2.X - Point1.X) + (Point2.Y - Point1.Y) * (Point2.Y - Point1.Y);
}
static Vector2 sUnitSegmentForIsClosestPointOnEndpoint;
static Vector2 sPointVectorForIsClosestPointOnEndpoint;
#region XML Docs
/// <summary>
/// Determines whether the closest point on the segment lies on one of the endpoints.
/// </summary>
/// <param name="point">The point to test to.</param>
/// <returns>Whether the closest point on this segment to the argument point lies on the endpoints.</returns>
#endregion
public bool IsClosestPointOnEndpoint(ref Point point)
{
sUnitSegmentForIsClosestPointOnEndpoint.X = (float)(this.Point2.X - this.Point1.X);
sUnitSegmentForIsClosestPointOnEndpoint.Y = (float)(Point2.Y - Point1.Y);
sUnitSegmentForIsClosestPointOnEndpoint.Normalize();
sPointVectorForIsClosestPointOnEndpoint.X = (float)(point.X - this.Point1.X);
sPointVectorForIsClosestPointOnEndpoint.Y = (float)(point.Y - Point1.Y);
#if FRB_MDX
float l = Vector2.Dot(sPointVectorForIsClosestPointOnEndpoint, sUnitSegmentForIsClosestPointOnEndpoint);
#else
float l;
Vector2.Dot(ref sPointVectorForIsClosestPointOnEndpoint, ref sUnitSegmentForIsClosestPointOnEndpoint, out l);
#endif
return l < 0 || l*l > this.GetLengthSquared();
}
public bool IsParallelAndTouching(Segment s2, out Point intersectionPoint)
{
double thisAngle = this.Angle;
double otherAngle = s2.Angle;
double distance = this.DistanceTo(s2);
const float maximumAngleVariation = .00001f;
const double maximumDistance = .00001f;
intersectionPoint = new Point(double.NaN, double.NaN);
if (System.Math.Abs(thisAngle - otherAngle) < maximumAngleVariation &&
distance < maximumDistance)
{
if (s2.DistanceTo(this.Point1) < maximumDistance)
{
intersectionPoint = Point1;
}
else if (s2.DistanceTo(this.Point2) < maximumDistance)
{
intersectionPoint = Point2;
}
else if (this.DistanceTo(s2.Point1) < maximumDistance)
{
intersectionPoint = s2.Point1;
}
else// if (this.DistanceTo(s2.Point2) < maximumDistance)
{
intersectionPoint = s2.Point2;
}
// They're parallel and touching
return true;
}
return false;
}
#region XML Docs
/// <summary>
/// Determines whether this segment intersects the argument segment.
/// </summary>
/// <param name="s2">The segment to test for intersection.</param>
/// <returns>Whether the segments intersect (whether they cross).</returns>
#endregion
public bool Intersects(Segment s2)
{
IntersectionPoint(ref s2, out mPoint);
return !double.IsNaN(mPoint.X);
}
public bool Intersects(Segment s2, out Point intersectionPoint)
{
IntersectionPoint(ref s2, out intersectionPoint);
return !double.IsNaN(intersectionPoint.X);
}
#region XML Docs
/// <summary>
/// Returns the point where this segment intersects the argument segment.
/// </summary>
/// <param name="s2">The segment to test for intersection.</param>
/// <returns>The point where this segment intersects the
/// argument segment. If the two segments do not touch, the point
/// will have both values be double.NAN.
/// </returns>
#endregion
public void IntersectionPoint(ref Segment s2, out Point intersectionPoint)
{
// code borrowed from
// http://www.topcoder.com/tc?module=Static&d1=tutorials&d2=geometry2
double A1 = Point2.Y - Point1.Y;
double B1 = Point1.X - Point2.X;
double C1 = A1 * Point1.X + B1 * Point1.Y;
double A2 = s2.Point2.Y - s2.Point1.Y;
double B2 = s2.Point1.X - s2.Point2.X;
double C2 = A2 * s2.Point1.X + B2 * s2.Point1.Y;
double det = A1 * B2 - A2 * B1;
if (det == 0)
{
//Lines are parallel
intersectionPoint.X = double.NaN;
intersectionPoint.Y = double.NaN;
}
else
{
intersectionPoint.X = (B2 * C1 - B1 * C2) / det;
intersectionPoint.Y = (A1 * C2 - A2 * C1) / det;
if (!this.IsClosestPointOnEndpoint(ref intersectionPoint) &&
!s2.IsClosestPointOnEndpoint(ref intersectionPoint))
{
// do nothing
;
}
else
{
// The closest point is on an endpoint, but we may have a situation where
// one segment is touching another one like a T. If that's the case,
// let's still consider it an intersection.
double distanceFromThis = this.DistanceTo(intersectionPoint);
double distanceFromOther = s2.DistanceTo(intersectionPoint);
if (distanceFromOther > .000000001 ||
distanceFromThis > .000000001)
{
intersectionPoint.X = float.NaN;
intersectionPoint.Y = float.NaN;
}
}
}
}
#region XML Docs
/// <summary>
/// Shifts the segment by moving both points by the argument x,y values.
/// </summary>
/// <param name="x">The number of units to shift the segment by on the x axis.</param>
/// <param name="y">The number of units to shift the segment by on the y axis.</param>
#endregion
public void MoveBy(float x, float y)
{
Point1.X += x;
Point1.Y += y;
Point2.X += x;
Point2.Y += y;
}
#region XML Docs
/// <summary>
/// Sets the length of the segment to 1 unit by moving the 2nd point.
/// </summary>
/// <remarks>
/// If the segment has 0 length (the endpoints are equal), the method
/// does not change the segment; length will remain 0.
/// </remarks>
#endregion
public void Normalize()
{
float segmentLength =
(float)GetLength();
if (segmentLength != 0)
{
this.Point2.X = Point1.X + (Point2.X - Point1.X) / segmentLength;
this.Point2.Y = Point1.Y + (Point2.Y - Point1.Y) / segmentLength;
}
}
public void SetPoints(ref VertexPositionColor point1, ref VertexPositionColor point2)
{
this.Point1.X = point1.Position.X;
this.Point1.Y = point1.Position.Y;
this.Point2.X = point2.Position.X;
this.Point2.Y = point2.Position.Y;
}
public void SetPoints(float x1, float y1, float x2, float y2)
{
this.Point1.X = x1;
this.Point1.Y = y1;
this.Point2.X = x2;
this.Point2.Y = y2;
}
public void ScaleBy(float amountToScaleBy)
{
Point midpoint = (Point1 + Point2) / 2.0f;
Point newPoint = Point1 - midpoint;
newPoint *= amountToScaleBy;
Point1 = midpoint + newPoint;
newPoint = Point2 - midpoint;
newPoint *= amountToScaleBy;
Point2 = midpoint + newPoint;
}
public Vector3 ToVector3()
{
return new Vector3(
(float)(Point2.X - Point1.X),
(float)(Point2.Y - Point1.Y),
0);
}
public override string ToString()
{
return string.Format("Point1: {0}, Point2: {1}", Point1.ToString(), Point2.ToString());
}
#endregion // PUBLIC Methods
#endregion
}
}
| |
// The MIT License (MIT)
//
// Copyright (c) 2014-2017, Institute for Software & Systems Engineering
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
namespace ISSE.SafetyChecking.Formula
{
using System;
using Utilities;
/// <summary>
/// Determines whether a <see cref="Formula" /> is structurally equivalent to a given <see cref="Formula" />.
/// </summary>
internal class IsFormulasStructurallyEquivalentVisitor : FormulaVisitor
{
/// <summary>
/// Compares <paramref name="formula" /> with <paramref name="referenceFormula" />.
/// </summary>
public static bool Compare(Formula referenceFormula, Formula formula)
{
Requires.NotNull(referenceFormula, nameof(referenceFormula));
Requires.NotNull(formula, nameof(formula));
var visitor = new IsFormulasStructurallyEquivalentVisitor(referenceFormula);
visitor.Visit(formula);
return visitor.IsEqual;
}
private Formula _referenceFormula;
public bool IsEqual { get; private set; }
private IsFormulasStructurallyEquivalentVisitor(Formula referenceFormula)
{
_referenceFormula = referenceFormula;
IsEqual = true;
}
/// <summary>
/// Visits the <paramref name="formula." />
/// </summary>
public override void VisitUnaryFormula(UnaryFormula formula)
{
var referenceFormula = _referenceFormula as UnaryFormula;
if (referenceFormula == null)
{
IsEqual = false;
}
else
{
if (formula.Operator != referenceFormula.Operator)
{
IsEqual = false;
}
else
{
_referenceFormula = referenceFormula.Operand;
Visit(formula.Operand);
}
}
}
/// <summary>
/// Visits the <paramref name="formula." />
/// </summary>
public override void VisitBinaryFormula(BinaryFormula formula)
{
var referenceFormula = _referenceFormula as BinaryFormula;
if (referenceFormula == null)
{
IsEqual = false;
}
else
{
if (formula.Operator != referenceFormula.Operator)
{
IsEqual = false;
}
else
{
_referenceFormula = referenceFormula.LeftOperand;
Visit(formula.LeftOperand);
if (!IsEqual)
return;
_referenceFormula = referenceFormula.RightOperand;
Visit(formula.RightOperand);
}
}
}
/// <summary>
/// Visits the <paramref name="formula." />
/// </summary>
public override void VisitAtomarPropositionFormula(AtomarPropositionFormula formula)
{
var referenceFormula = _referenceFormula as AtomarPropositionFormula;
if (referenceFormula == null)
{
IsEqual = false;
}
else
{
if (formula.Label != referenceFormula.Label)
{
IsEqual = false;
}
}
}
/// <summary>
/// Visits the <paramref name="formula." />
/// </summary>
public override void VisitBoundedUnaryFormula(BoundedUnaryFormula formula)
{
var referenceFormula = _referenceFormula as BoundedUnaryFormula;
if (referenceFormula == null)
{
IsEqual = false;
}
else
{
if (formula.Operator != referenceFormula.Operator)
{
IsEqual = false;
}
else if (formula.Bound != referenceFormula.Bound)
{
IsEqual = false;
}
else
{
_referenceFormula = referenceFormula.Operand;
Visit(formula.Operand);
}
}
}
/// <summary>
/// Visits the <paramref name="formula." />
/// </summary>
public override void VisitBoundedBinaryFormula(BoundedBinaryFormula formula)
{
var referenceFormula = _referenceFormula as BoundedBinaryFormula;
if (referenceFormula == null)
{
IsEqual = false;
}
else
{
if (formula.Operator != referenceFormula.Operator)
{
IsEqual = false;
}
else if (formula.Bound != referenceFormula.Bound)
{
IsEqual = false;
}
else
{
_referenceFormula = referenceFormula.LeftOperand;
Visit(formula.LeftOperand);
if (!IsEqual)
return;
_referenceFormula = referenceFormula.RightOperand;
Visit(formula.RightOperand);
}
}
}
/// <summary>
/// Visits the <paramref name="formula." />
/// </summary>
public override void VisitRewardFormula(RewardFormula formula)
{
var referenceFormula = _referenceFormula as RewardFormula;
if (referenceFormula == null)
{
IsEqual = false;
}
else
{
throw new NotImplementedException();
}
}
/// <summary>
/// Visits the <paramref name="formula." />
/// </summary>
public override void VisitProbabilisticFormula(ProbabilitisticFormula formula)
{
var referenceFormula = _referenceFormula as ProbabilitisticFormula;
if (referenceFormula == null)
{
IsEqual = false;
}
else
{
if (referenceFormula.Comparator != formula.Comparator || referenceFormula.CompareToValue != formula.CompareToValue)
{
IsEqual = false;
}
else
{
_referenceFormula = referenceFormula.Operand;
Visit(formula.Operand);
}
}
}
}
}
| |
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// Copyright (c) 2008 - 2015 Jb Evain
// Copyright (c) 2008 - 2011 Novell, Inc.
//
// Licensed under the MIT/X11 license.
//
using System;
namespace SquabPie.Mono.Cecil {
public class ExportedType : IMetadataTokenProvider {
string @namespace;
string name;
uint attributes;
IMetadataScope scope;
ModuleDefinition module;
int identifier;
ExportedType declaring_type;
internal MetadataToken token;
public string Namespace {
get { return @namespace; }
set { @namespace = value; }
}
public string Name {
get { return name; }
set { name = value; }
}
public TypeAttributes Attributes {
get { return (TypeAttributes) attributes; }
set { attributes = (uint) value; }
}
public IMetadataScope Scope {
get {
if (declaring_type != null)
return declaring_type.Scope;
return scope;
}
}
public ExportedType DeclaringType {
get { return declaring_type; }
set { declaring_type = value; }
}
public MetadataToken MetadataToken {
get { return token; }
set { token = value; }
}
public int Identifier {
get { return identifier; }
set { identifier = value; }
}
#region TypeAttributes
public bool IsNotPublic {
get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NotPublic); }
set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NotPublic, value); }
}
public bool IsPublic {
get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.Public); }
set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.Public, value); }
}
public bool IsNestedPublic {
get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedPublic); }
set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedPublic, value); }
}
public bool IsNestedPrivate {
get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedPrivate); }
set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedPrivate, value); }
}
public bool IsNestedFamily {
get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedFamily); }
set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedFamily, value); }
}
public bool IsNestedAssembly {
get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedAssembly); }
set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedAssembly, value); }
}
public bool IsNestedFamilyAndAssembly {
get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedFamANDAssem); }
set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedFamANDAssem, value); }
}
public bool IsNestedFamilyOrAssembly {
get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedFamORAssem); }
set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedFamORAssem, value); }
}
public bool IsAutoLayout {
get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.LayoutMask, (uint) TypeAttributes.AutoLayout); }
set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.LayoutMask, (uint) TypeAttributes.AutoLayout, value); }
}
public bool IsSequentialLayout {
get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.LayoutMask, (uint) TypeAttributes.SequentialLayout); }
set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.LayoutMask, (uint) TypeAttributes.SequentialLayout, value); }
}
public bool IsExplicitLayout {
get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.LayoutMask, (uint) TypeAttributes.ExplicitLayout); }
set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.LayoutMask, (uint) TypeAttributes.ExplicitLayout, value); }
}
public bool IsClass {
get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.ClassSemanticMask, (uint) TypeAttributes.Class); }
set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.ClassSemanticMask, (uint) TypeAttributes.Class, value); }
}
public bool IsInterface {
get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.ClassSemanticMask, (uint) TypeAttributes.Interface); }
set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.ClassSemanticMask, (uint) TypeAttributes.Interface, value); }
}
public bool IsAbstract {
get { return attributes.GetAttributes ((uint) TypeAttributes.Abstract); }
set { attributes = attributes.SetAttributes ((uint) TypeAttributes.Abstract, value); }
}
public bool IsSealed {
get { return attributes.GetAttributes ((uint) TypeAttributes.Sealed); }
set { attributes = attributes.SetAttributes ((uint) TypeAttributes.Sealed, value); }
}
public bool IsSpecialName {
get { return attributes.GetAttributes ((uint) TypeAttributes.SpecialName); }
set { attributes = attributes.SetAttributes ((uint) TypeAttributes.SpecialName, value); }
}
public bool IsImport {
get { return attributes.GetAttributes ((uint) TypeAttributes.Import); }
set { attributes = attributes.SetAttributes ((uint) TypeAttributes.Import, value); }
}
public bool IsSerializable {
get { return attributes.GetAttributes ((uint) TypeAttributes.Serializable); }
set { attributes = attributes.SetAttributes ((uint) TypeAttributes.Serializable, value); }
}
public bool IsAnsiClass {
get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.StringFormatMask, (uint) TypeAttributes.AnsiClass); }
set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.StringFormatMask, (uint) TypeAttributes.AnsiClass, value); }
}
public bool IsUnicodeClass {
get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.StringFormatMask, (uint) TypeAttributes.UnicodeClass); }
set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.StringFormatMask, (uint) TypeAttributes.UnicodeClass, value); }
}
public bool IsAutoClass {
get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.StringFormatMask, (uint) TypeAttributes.AutoClass); }
set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.StringFormatMask, (uint) TypeAttributes.AutoClass, value); }
}
public bool IsBeforeFieldInit {
get { return attributes.GetAttributes ((uint) TypeAttributes.BeforeFieldInit); }
set { attributes = attributes.SetAttributes ((uint) TypeAttributes.BeforeFieldInit, value); }
}
public bool IsRuntimeSpecialName {
get { return attributes.GetAttributes ((uint) TypeAttributes.RTSpecialName); }
set { attributes = attributes.SetAttributes ((uint) TypeAttributes.RTSpecialName, value); }
}
public bool HasSecurity {
get { return attributes.GetAttributes ((uint) TypeAttributes.HasSecurity); }
set { attributes = attributes.SetAttributes ((uint) TypeAttributes.HasSecurity, value); }
}
#endregion
public bool IsForwarder {
get { return attributes.GetAttributes ((uint) TypeAttributes.Forwarder); }
set { attributes = attributes.SetAttributes ((uint) TypeAttributes.Forwarder, value); }
}
public string FullName {
get {
var fullname = string.IsNullOrEmpty (@namespace)
? name
: @namespace + '.' + name;
if (declaring_type != null)
return declaring_type.FullName + "/" + fullname;
return fullname;
}
}
public ExportedType (string @namespace, string name, ModuleDefinition module, IMetadataScope scope)
{
this.@namespace = @namespace;
this.name = name;
this.scope = scope;
this.module = module;
}
public override string ToString ()
{
return FullName;
}
public TypeDefinition Resolve ()
{
return module.Resolve (CreateReference ());
}
internal TypeReference CreateReference ()
{
return new TypeReference (@namespace, name, module, scope) {
DeclaringType = declaring_type != null ? declaring_type.CreateReference () : null,
};
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.InteropServices;
using System.DirectoryServices;
using System.Text;
using System.Net;
namespace System.DirectoryServices.AccountManagement
{
internal class SDSUtils
{
// To stop the compiler from autogenerating a constructor for this class
private SDSUtils() { }
[System.Security.SecurityCritical]
static internal Principal SearchResultToPrincipal(SearchResult sr, PrincipalContext owningContext, Type principalType)
{
Principal p;
// Construct an appropriate Principal object.
// Make* constructs a Principal that is marked persisted
// and not loaded (p.unpersisted = false, p.loaded = false).
// Since there should be no more multistore contexts, the owning context IS
// the specific context
// If we know the type we should just construct it ourselves so that we don't need to incur the costs of reflection.
// If this is an extension type then we must reflect teh constructor to create the object.
if (typeof(UserPrincipal) == principalType)
{
p = UserPrincipal.MakeUser(owningContext);
}
else if (typeof(ComputerPrincipal) == principalType)
{
p = ComputerPrincipal.MakeComputer(owningContext);
}
else if (typeof(GroupPrincipal) == principalType)
{
p = GroupPrincipal.MakeGroup(owningContext);
}
else if (null == principalType ||
typeof(AuthenticablePrincipal) == principalType ||
typeof(Principal) == principalType)
{
if (SDSUtils.IsOfObjectClass(sr, "computer"))
{
p = ComputerPrincipal.MakeComputer(owningContext);
}
else if (SDSUtils.IsOfObjectClass(sr, "user"))
{
p = UserPrincipal.MakeUser(owningContext);
}
else if (SDSUtils.IsOfObjectClass(sr, "group"))
{
p = GroupPrincipal.MakeGroup(owningContext);
}
else
{
p = AuthenticablePrincipal.MakeAuthenticablePrincipal(owningContext);
}
}
else
{
p = Principal.MakePrincipal(owningContext, principalType);
}
// The DirectoryEntry we're constructing the Principal from
// will serve as the underlying object for that Principal.
p.UnderlyingSearchObject = sr;
// It's up to our caller to assign an appropriate StoreKey.
// Caller must also populate the underlyingObject field if the P is to be used R/W
return p;
}
// Used to implement StoreCtx.GetAsPrincipal for AD and SAM
[System.Security.SecurityCritical]
static internal Principal DirectoryEntryToPrincipal(DirectoryEntry de, PrincipalContext owningContext, Type principalType)
{
Principal p;
// Construct an appropriate Principal object.
// Make* constructs a Principal that is marked persisted
// and not loaded (p.unpersisted = false, p.loaded = false).
// Since there should be no more multistore contexts, the owning context IS
// the specific context
if (typeof(UserPrincipal) == principalType)
{
p = UserPrincipal.MakeUser(owningContext);
}
else if (typeof(ComputerPrincipal) == principalType)
{
p = ComputerPrincipal.MakeComputer(owningContext);
}
else if (typeof(GroupPrincipal) == principalType)
{
p = GroupPrincipal.MakeGroup(owningContext);
}
else if (null == principalType ||
typeof(AuthenticablePrincipal) == principalType ||
typeof(Principal) == principalType)
{
if (SDSUtils.IsOfObjectClass(de, "computer"))
{
p = ComputerPrincipal.MakeComputer(owningContext);
}
else if (SDSUtils.IsOfObjectClass(de, "user"))
{
p = UserPrincipal.MakeUser(owningContext);
}
else if (SDSUtils.IsOfObjectClass(de, "group"))
{
p = GroupPrincipal.MakeGroup(owningContext);
}
else
{
p = AuthenticablePrincipal.MakeAuthenticablePrincipal(owningContext);
}
}
else
{
p = Principal.MakePrincipal(owningContext, principalType);
}
// The DirectoryEntry we're constructing the Principal from
// will serve as the underlying object for that Principal.
p.UnderlyingObject = de;
// It's up to our caller to assign an appropriate StoreKey.
return p;
}
[System.Security.SecurityCritical]
private static bool IsOfObjectClass(SearchResult sr, string className)
{
Debug.Assert(sr.Path.StartsWith("LDAP:", StringComparison.Ordinal) || sr.Path.StartsWith("GC:", StringComparison.Ordinal));
return ADUtils.IsOfObjectClass(sr, className);
}
[System.Security.SecurityCritical]
private static bool IsOfObjectClass(DirectoryEntry de, string className)
{
if (de.Path.StartsWith("WinNT:", StringComparison.Ordinal))
{
return SAMUtils.IsOfObjectClass(de, className);
}
else
{
Debug.Assert(de.Path.StartsWith("LDAP:", StringComparison.Ordinal));
return ADUtils.IsOfObjectClass(de, className);
}
}
static internal AuthenticationTypes MapOptionsToAuthTypes(ContextOptions options)
{
AuthenticationTypes authTypes = AuthenticationTypes.Secure;
if ((options & ContextOptions.SimpleBind) != 0)
authTypes = AuthenticationTypes.None;
if ((options & ContextOptions.ServerBind) != 0)
authTypes |= AuthenticationTypes.ServerBind;
if ((options & ContextOptions.SecureSocketLayer) != 0)
authTypes |= AuthenticationTypes.SecureSocketsLayer;
if ((options & ContextOptions.Signing) != 0)
authTypes |= AuthenticationTypes.Signing;
if ((options & ContextOptions.Sealing) != 0)
authTypes |= AuthenticationTypes.Sealing;
return authTypes;
}
[System.Security.SecurityCritical]
static internal void MoveDirectoryEntry(DirectoryEntry deToMove, DirectoryEntry newParent, string newName)
{
if (newName != null)
deToMove.MoveTo(newParent, newName);
else
deToMove.MoveTo(newParent);
}
[System.Security.SecurityCritical]
static internal void DeleteDirectoryEntry(DirectoryEntry deToDelete)
{
DirectoryEntry deParent = deToDelete.Parent;
try
{
deParent.Children.Remove(deToDelete);
}
finally
{
deParent.Dispose();
}
}
[System.Security.SecurityCritical]
static internal void InsertPrincipal(
Principal p,
StoreCtx storeCtx,
GroupMembershipUpdater updateGroupMembership,
NetCred credentials,
AuthenticationTypes authTypes,
bool needToSetPassword)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "SDSUtils", "Entering InsertPrincipal");
Debug.Assert(storeCtx != null);
Debug.Assert(storeCtx is ADStoreCtx || storeCtx is SAMStoreCtx);
Debug.Assert(p != null);
if ((!(p is UserPrincipal)) &&
(!(p is GroupPrincipal)) &&
(!(p is AuthenticablePrincipal)) &&
(!(p is ComputerPrincipal)))
{
// It's not a type of Principal that we support
GlobalDebug.WriteLineIf(GlobalDebug.Warn, "SDSUtils", "InsertPrincipal: Bad principal type:" + p.GetType().ToString());
throw new InvalidOperationException(
String.Format(CultureInfo.CurrentCulture, SR.StoreCtxUnsupportedPrincipalTypeForSave, p.GetType().ToString()));
}
// Commit the properties
SDSUtils.ApplyChangesToDirectory(
p,
storeCtx,
updateGroupMembership,
credentials,
authTypes
);
// Handle any saved-off operations
// For SAM, we set password elsewhere prior to creating the principal, so needToSetPassword == false
// For AD, we have to set the password after creating the principal, so needToSetPassword == true
if (needToSetPassword && p.GetChangeStatusForProperty(PropertyNames.PwdInfoPassword))
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "SDSUtils", "InsertPrincipal: Setting password");
// Only AuthenticablePrincipals can have PasswordInfo
Debug.Assert(p is AuthenticablePrincipal);
string password = (string)p.GetValueForProperty(PropertyNames.PwdInfoPassword);
Debug.Assert(password != null); // if null, PasswordInfo should not have indicated it was changed
storeCtx.SetPassword((AuthenticablePrincipal)p, password);
}
if (p.GetChangeStatusForProperty(PropertyNames.PwdInfoExpireImmediately))
{
// Only AuthenticablePrincipals can have PasswordInfo
Debug.Assert(p is AuthenticablePrincipal);
bool expireImmediately = (bool)p.GetValueForProperty(PropertyNames.PwdInfoExpireImmediately);
if (expireImmediately)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "SDSUtils", "InsertPrincipal: Setting pwd expired");
storeCtx.ExpirePassword((AuthenticablePrincipal)p);
}
}
}
internal delegate void GroupMembershipUpdater(Principal p, DirectoryEntry de, NetCred credentials, AuthenticationTypes authTypes);
[System.Security.SecurityCritical]
static internal void ApplyChangesToDirectory(
Principal p,
StoreCtx storeCtx,
GroupMembershipUpdater updateGroupMembership,
NetCred credentials,
AuthenticationTypes authTypes)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "SDSUtils", "Entering ApplyChangesToDirectory");
Debug.Assert(storeCtx != null);
Debug.Assert(storeCtx is ADStoreCtx || storeCtx is SAMStoreCtx || storeCtx is ADAMStoreCtx);
Debug.Assert(p != null);
Debug.Assert(updateGroupMembership != null);
// Update the properties in the DirectoryEntry. Note that this does NOT
// update group membership.
DirectoryEntry de = (DirectoryEntry)storeCtx.PushChangesToNative(p);
Debug.Assert(de == p.UnderlyingObject);
// Commit the property update
try
{
de.CommitChanges();
}
catch (System.Runtime.InteropServices.COMException e)
{
GlobalDebug.WriteLineIf(GlobalDebug.Error, "SDSUtils", "ApplyChangesToDirectory: caught COMException with message " + e.Message);
throw (ExceptionHelper.GetExceptionFromCOMException(e));
}
if ((p is GroupPrincipal) && (p.GetChangeStatusForProperty(PropertyNames.GroupMembers)))
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "SDSUtils", "ApplyChangesToDirectory: Updating group membership");
// It's a group, and it's membership has changed. Commit those membership changes.
// Note that this is an immediate operation, because it goes through IADsGroup,
// and does not require a call to de.CommitChanges().
updateGroupMembership(p, de, credentials, authTypes);
}
}
[System.Security.SecurityCritical]
static internal void SetPassword(DirectoryEntry de, string newPassword)
{
Debug.Assert(newPassword != null); // but it could be an empty string
Debug.Assert(de != null);
try
{
de.Invoke("SetPassword", new object[] { newPassword });
}
catch (System.Reflection.TargetInvocationException e)
{
GlobalDebug.WriteLineIf(GlobalDebug.Error, "SDSUtils", "SetPassword: caught TargetInvocationException with message " + e.Message);
if (e.InnerException is System.Runtime.InteropServices.COMException)
{
if (((System.Runtime.InteropServices.COMException)e.InnerException).ErrorCode == unchecked((int)ExceptionHelper.ERROR_HRESULT_CONSTRAINT_VIOLATION))
{
// We have a special case of constraint violation here. We know this is a password failure to convert to this
// specialized type instead of the generic InvalidOperationException
throw (new PasswordException(((System.Runtime.InteropServices.COMException)e.InnerException).Message, (System.Runtime.InteropServices.COMException)e.InnerException));
}
else
{
throw (ExceptionHelper.GetExceptionFromCOMException((System.Runtime.InteropServices.COMException)e.InnerException));
}
}
// Unknown exception. We don't want to suppress it.
throw;
}
}
[System.Security.SecurityCritical]
static internal void ChangePassword(DirectoryEntry de, string oldPassword, string newPassword)
{
Debug.Assert(newPassword != null); // but it could be an empty string
Debug.Assert(oldPassword != null); // but it could be an empty string
Debug.Assert(de != null);
try
{
de.Invoke("ChangePassword", new object[] { oldPassword, newPassword });
}
catch (System.Reflection.TargetInvocationException e)
{
GlobalDebug.WriteLineIf(GlobalDebug.Error, "SDSUtils", "ChangePassword: caught TargetInvocationException with message " + e.Message);
if (e.InnerException is System.Runtime.InteropServices.COMException)
{
if (((System.Runtime.InteropServices.COMException)e.InnerException).ErrorCode == unchecked((int)ExceptionHelper.ERROR_HRESULT_CONSTRAINT_VIOLATION))
{
// We have a special case of constraint violation here. We know this is a password failure to convert to this
// specialized type instead of the generic InvalidOperationException
throw (new PasswordException(((System.Runtime.InteropServices.COMException)e.InnerException).Message, (System.Runtime.InteropServices.COMException)e.InnerException));
}
else
{
throw (ExceptionHelper.GetExceptionFromCOMException((System.Runtime.InteropServices.COMException)e.InnerException));
}
}
// Unknown exception. We don't want to suppress it.
throw;
}
}
[System.Security.SecurityCritical]
static internal DirectoryEntry BuildDirectoryEntry(string path, NetCred credentials, AuthenticationTypes authTypes)
{
DirectoryEntry de = new DirectoryEntry(path,
credentials != null ? credentials.UserName : null,
credentials != null ? credentials.Password : null,
authTypes);
GlobalDebug.WriteLineIf(GlobalDebug.Info, "SDSUtils", "BuildDirectoryEntry (1): built DE for " + de.Path);
return de;
}
[System.Security.SecurityCritical]
static internal DirectoryEntry BuildDirectoryEntry(NetCred credentials, AuthenticationTypes authTypes)
{
DirectoryEntry de = new DirectoryEntry();
de.Username = credentials != null ? credentials.UserName : null;
de.Password = credentials != null ? credentials.Password : null;
de.AuthenticationType = authTypes;
GlobalDebug.WriteLineIf(GlobalDebug.Info, "SDSUtils", "BuildDirectoryEntry (2): built DE");
return de;
}
[System.Security.SecurityCritical]
static internal void WriteAttribute<T>(string dePath, string attribute, T value, NetCred credentials, AuthenticationTypes authTypes)
{
Debug.Assert(attribute != null && attribute.Length > 0);
// Ideally, we'd just like to set the property in the principal's DirectoryEntry and write
// the changes to the store. However, there might be other changes in the DirectoryEntry,
// and we don't want to write all of them to the store. So we must make
// a fresh DirectoryEntry and write using that.
DirectoryEntry copyOfDe = null;
try
{
copyOfDe = SDSUtils.BuildDirectoryEntry(dePath, credentials, authTypes);
Debug.Assert(copyOfDe != null);
// So we don't do a implicit GetInfo() and retrieve every attribute
copyOfDe.RefreshCache(new string[] { attribute });
copyOfDe.Properties[attribute].Value = value;
copyOfDe.CommitChanges();
}
catch (System.Runtime.InteropServices.COMException e)
{
// ADSI threw an exception trying to write the change
throw ExceptionHelper.GetExceptionFromCOMException(e);
}
finally
{
if (copyOfDe != null)
copyOfDe.Dispose();
}
}
[System.Security.SecurityCritical]
static internal void WriteAttribute(string dePath, string attribute, int value, NetCred credentials, AuthenticationTypes authTypes)
{
GlobalDebug.WriteLineIf(
GlobalDebug.Info,
"SDSUtils",
"WriteAttribute: writing {0} to {1} on {2}",
value.ToString(CultureInfo.InvariantCulture),
attribute,
dePath);
Debug.Assert(attribute != null && attribute.Length > 0);
// Ideally, we'd just like to set the property in the principal's DirectoryEntry and write
// the changes to the store. However, there might be other changes in the DirectoryEntry,
// and we don't want to write all of them to the store. So we must make
// a fresh DirectoryEntry and write using that.
DirectoryEntry copyOfDe = null;
try
{
copyOfDe = SDSUtils.BuildDirectoryEntry(dePath, credentials, authTypes);
Debug.Assert(copyOfDe != null);
// So we don't do a implicit GetInfo() and retrieve every attribute
copyOfDe.RefreshCache(new string[] { attribute });
copyOfDe.Properties[attribute].Value = value;
copyOfDe.CommitChanges();
}
catch (System.Runtime.InteropServices.COMException e)
{
GlobalDebug.WriteLineIf(
GlobalDebug.Error,
"SDSUtils",
"WriteAttribute: caught exception with message '{0}' writing {1} to {2} on {3}",
e.Message,
value.ToString(CultureInfo.InvariantCulture),
attribute,
dePath);
// ADSI threw an exception trying to write the change
throw ExceptionHelper.GetExceptionFromCOMException(e);
}
finally
{
if (copyOfDe != null)
copyOfDe.Dispose();
}
}
//
// S.DS (LDAP or WinNT) --> PAPI conversion routines
//
[System.Security.SecurityCritical]
static internal void SingleScalarFromDirectoryEntry<T>(dSPropertyCollection properties, string suggestedProperty, Principal p, string propertyName)
{
if (properties[suggestedProperty].Count != 0 && properties[suggestedProperty][0] != null)
{
// We're intended to handle single-valued scalar properties
Debug.Assert(properties[suggestedProperty].Count == 1);
Debug.Assert(properties[suggestedProperty][0] is T);
p.LoadValueIntoProperty(propertyName, (T)properties[suggestedProperty][0]);
}
}
[System.Security.SecurityCritical]
static internal void MultiScalarFromDirectoryEntry<T>(dSPropertyCollection properties, string suggestedProperty, Principal p, string propertyName)
{
dSPropertyValueCollection values = properties[suggestedProperty];
List<T> list = new List<T>();
foreach (object value in values)
{
Debug.Assert(value is T);
list.Add((T)value);
}
p.LoadValueIntoProperty(propertyName, list);
}
static internal bool StatusFromAccountControl(int uacValue, string propertyName)
{
bool flag = false;
switch (propertyName)
{
case PropertyNames.AuthenticablePrincipalEnabled:
// UF_ACCOUNTDISABLE
// Note that the logic is inverted on this one. We expose "Enabled",
// but AD/SAM store it as "Disabled".
flag = ((uacValue & 0x2) == 0);
break;
case PropertyNames.AcctInfoSmartcardRequired:
// UF_SMARTCARD_REQUIRED
flag = ((uacValue & 0x40000) != 0);
break;
case PropertyNames.AcctInfoDelegationPermitted:
// UF_NOT_DELEGATED
// Note that the logic is inverted on this one. That's because we expose
// "delegation allowed", but AD represents it as the inverse, "delegation NOT allowed"
flag = ((uacValue & 0x100000) == 0);
break;
case PropertyNames.PwdInfoPasswordNotRequired:
// UF_PASSWD_NOTREQD
flag = ((uacValue & 0x0020) != 0);
break;
case PropertyNames.PwdInfoPasswordNeverExpires:
// UF_DONT_EXPIRE_PASSWD
flag = ((uacValue & 0x10000) != 0);
break;
// This bit doesn't work in userAccountControl
case PropertyNames.PwdInfoCannotChangePassword:
// UF_PASSWD_CANT_CHANGE
flag = ((uacValue & 0x0040) != 0);
break;
case PropertyNames.PwdInfoAllowReversiblePasswordEncryption:
// UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED
flag = ((uacValue & 0x0080) != 0);
break;
default:
Debug.Fail("SDSUtils.AccountControlFromDirectoryEntry: Fell off end looking for " + propertyName);
flag = false;
break;
}
return flag;
}
[System.Security.SecurityCritical]
static internal void AccountControlFromDirectoryEntry(dSPropertyCollection properties, string suggestedProperty, Principal p, string propertyName, bool testCantChangePassword)
{
Debug.Assert(
(!testCantChangePassword && (String.Compare(suggestedProperty, "userAccountControl", StringComparison.OrdinalIgnoreCase) == 0)) ||
(testCantChangePassword && (String.Compare(suggestedProperty, "UserFlags", StringComparison.OrdinalIgnoreCase) == 0))
);
Debug.Assert((String.Compare(propertyName, PropertyNames.PwdInfoCannotChangePassword, StringComparison.OrdinalIgnoreCase) != 0) || testCantChangePassword);
dSPropertyValueCollection values = properties[suggestedProperty];
if (values.Count != 0)
{
Debug.Assert(values.Count == 1);
Debug.Assert(values[0] is int);
int uacValue = (int)values[0];
bool flag;
flag = StatusFromAccountControl(uacValue, propertyName);
p.LoadValueIntoProperty(propertyName, flag);
}
}
//
// PAPI --> S.DS (LDAP or WinNT) conversion routines
//
[System.Security.SecurityCritical]
static internal void MultiStringToDirectoryEntryConverter(Principal p, string propertyName, DirectoryEntry de, string suggestedProperty)
{
PrincipalValueCollection<string> trackingList = (PrincipalValueCollection<string>)p.GetValueForProperty(propertyName);
if (p.unpersisted && trackingList == null)
return;
List<string> insertedValues = trackingList.Inserted;
List<string> removedValues = trackingList.Removed;
List<Pair<string, string>> changedValues = trackingList.ChangedValues;
PropertyValueCollection properties = de.Properties[suggestedProperty];
// We test to make sure the change hasn't already been applied to the PropertyValueCollection,
// because PushChangesToNative can be called multiple times prior to committing the changes and
// we want to maintain idempotency
foreach (string value in removedValues)
{
if (value != null && properties.Contains(value))
properties.Remove(value);
}
foreach (Pair<string, string> changedValue in changedValues)
{
// Remove the original value and add in the new value
Debug.Assert(changedValue.Left != null); // since it came from the system
properties.Remove(changedValue.Left);
if (changedValue.Right != null && !properties.Contains(changedValue.Right))
properties.Add(changedValue.Right);
}
foreach (string value in insertedValues)
{
if (value != null && !properties.Contains(value))
properties.Add(value);
}
}
internal const int AD_DefaultUAC = (int)(0x200 | 0X20 | 0x2); // UF_NORMAL_ACCOUNT | UF_PASSWD_NOTREQD | UF_ACCOUNTDISABLE
internal const int AD_DefaultUAC_Machine = (int)(0x1000 | 0X20 | 0x2); // UF_WORKSTATION_TRUST_ACCOUNT | UF_PASSWD_NOTREQD | UF_ACCOUNTDISABLE
internal const int SAM_DefaultUAC = (int)(0x200 | 0x1); // UF_NORMAL_ACCOUNT | UF_SCRIPT
[System.Security.SecurityCritical]
static internal void AccountControlToDirectoryEntry(
Principal p,
string propertyName,
DirectoryEntry de,
string suggestedProperty,
bool isSAM,
bool isUnpersisted)
{
Debug.Assert(
(!isSAM && (String.Compare(suggestedProperty, "userAccountControl", StringComparison.OrdinalIgnoreCase) == 0)) ||
(isSAM && (String.Compare(suggestedProperty, "UserFlags", StringComparison.OrdinalIgnoreCase) == 0))
);
bool flag = (bool)p.GetValueForProperty(propertyName);
int uacValue = 0;
// We want to get the current value, so we can flip the appropriate bit while leaving the other bits as-is.
// If this is a to-be-inserted Principal, we should have already initialized the userAccountControl property
if (de.Properties[suggestedProperty].Count > 0)
{
Debug.Assert(de.Properties[suggestedProperty].Count == 1);
uacValue = (int)de.Properties[suggestedProperty][0];
// When we write to userAccountControl, we must OR the new value with the value of msDS-User-Account-Control-Computed.
// Otherwise we might mistakenly clear computed bits like UF_LOCKOUT.
if (!isSAM && de.Properties["msDS-User-Account-Control-Computed"].Count > 0)
{
Debug.Assert(de.Properties["msDS-User-Account-Control-Computed"].Count == 1);
uacValue = uacValue | (int)de.Properties["msDS-User-Account-Control-Computed"][0];
}
}
else
{
// We don't have the userAccountControl property, this must be a persisted principal. Perhaps we don't have access
// to it. In that case, we don't want to blindly overwrite whatever other bits might be there.
Debug.Assert(p.unpersisted == false);
throw new PrincipalOperationException(
SR.ADStoreCtxUnableToReadExistingAccountControlFlagsForUpdate);
}
uint bitmask;
// Get the right bitmask for the property
switch (propertyName)
{
case PropertyNames.AuthenticablePrincipalEnabled:
if (!isUnpersisted || isSAM)
{
// UF_ACCOUNTDISABLE
// Note that the logic is inverted on this one. We expose "Enabled",
// but AD/SAM store it as "Disabled".
bitmask = 0x2;
flag = !flag;
}
else
{
// We're writing to an unpersisted AD principal
Debug.Assert(!isSAM && isUnpersisted);
// Nothing to do here. The ADStoreCtx will take care of enabling the
// principal after it's persisted.
bitmask = 0;
}
break;
case PropertyNames.AcctInfoSmartcardRequired:
// UF_SMARTCARD_REQUIRED
bitmask = 0x40000;
break;
case PropertyNames.AcctInfoDelegationPermitted:
// UF_NOT_DELEGATED
// Note that the logic is inverted on this one. That's because we expose
// "delegation allowed", but AD represents it as the inverse, "delegation NOT allowed"
bitmask = 0x100000;
flag = !flag;
break;
case PropertyNames.PwdInfoPasswordNotRequired:
// UF_PASSWD_NOTREQD
bitmask = 0x0020;
break;
case PropertyNames.PwdInfoPasswordNeverExpires:
// UF_DONT_EXPIRE_PASSWD
bitmask = 0x10000;
break;
case PropertyNames.PwdInfoAllowReversiblePasswordEncryption:
// UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED
bitmask = 0x0080;
break;
// This bit doesn't work in userAccountControl
case PropertyNames.PwdInfoCannotChangePassword:
if (isSAM)
{
// UF_PASSWD_CANT_CHANGE
bitmask = 0x0040;
break;
}
else
{
Debug.Fail(
"SDSUtils.AccountControlToDirectoryEntry: At PwdInfoCannotChangePassword but isSAM==false, path=" + de.Path
);
goto default;
}
default:
Debug.Fail("SDSUtils.AccountControlToDirectoryEntry: Fell off end looking for " + propertyName);
bitmask = 0;
break;
}
// Set/clear the "bitmask" bit in "uacValue", based on the value of "flag"
if (flag)
Utils.SetBit(ref uacValue, bitmask);
else
Utils.ClearBit(ref uacValue, bitmask);
de.Properties[suggestedProperty].Value = uacValue;
}
static internal DirectorySearcher ConstructSearcher(DirectoryEntry de)
{
DirectorySearcher ds = new DirectorySearcher(de);
ds.ClientTimeout = new TimeSpan(0, 0, 30);
ds.PageSize = 256;
return ds;
}
[System.Security.SecuritySafeCritical]
static internal bool IsObjectFromGC(string path)
{
return path.StartsWith("GC:", StringComparison.OrdinalIgnoreCase);
}
static internal string ConstructDnsDomainNameFromDn(string dn)
{
// Split the DN into its RDNs
string[] ncComponents = dn.Split(new char[] { ',' });
StringBuilder sb = new StringBuilder();
// Reassemble the RDNs (minus the tag) into the DNS domain name
foreach (string component in ncComponents)
{
if ((component.Length > 3) &&
(String.Compare(component.Substring(0, 3), "DC=", StringComparison.OrdinalIgnoreCase) == 0))
{
sb.Append(component.Substring(3));
sb.Append(".");
}
}
if (sb.Length > 0)
sb.Remove(sb.Length - 1, 1);
return sb.ToString();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.Razor.Compilation;
using Microsoft.AspNetCore.Mvc.Routing;
using Microsoft.AspNetCore.Mvc.ViewEngines;
using Microsoft.AspNetCore.Routing;
using Microsoft.AspNetCore.Testing;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Primitives;
using Microsoft.Extensions.WebEncoders.Testing;
using Moq;
using Xunit;
namespace Microsoft.AspNetCore.Mvc.Razor
{
public class RazorViewEngineTest
{
private static readonly Dictionary<string, object> _areaTestContext = new Dictionary<string, object>()
{
{"area", "foo"},
{"controller", "bar"},
};
private static readonly Dictionary<string, object> _controllerTestContext = new Dictionary<string, object>()
{
{"controller", "bar"},
};
private static readonly Dictionary<string, object> _pageTestContext = new Dictionary<string, object>()
{
{"page", "/Accounts/Index"},
};
public static IEnumerable<object[]> AbsoluteViewPathData
{
get
{
yield return new[] { "~/foo/bar" };
yield return new[] { "/foo/bar" };
yield return new[] { "~/foo/bar.txt" };
yield return new[] { "/foo/bar.txt" };
}
}
[Theory]
[InlineData(null)]
[InlineData("")]
public void FindView_IsMainPage_ThrowsIfViewNameIsNullOrEmpty(string viewName)
{
// Arrange
var viewEngine = CreateViewEngine();
var context = GetActionContext(_controllerTestContext);
// Act & Assert
ExceptionAssert.ThrowsArgumentNullOrEmpty(
() => viewEngine.FindView(context, viewName, isMainPage: true),
"viewName");
}
[Theory]
[MemberData(nameof(AbsoluteViewPathData))]
public void FindView_IsMainPage_WithFullPath_ReturnsNotFound(string viewName)
{
// Arrange
var viewEngine = CreateSuccessfulViewEngine();
var context = GetActionContext(_controllerTestContext);
// Act
var result = viewEngine.FindView(context, viewName, isMainPage: true);
// Assert
Assert.False(result.Success);
}
[Theory]
[MemberData(nameof(AbsoluteViewPathData))]
public void FindView_IsMainPage_WithFullPathAndCshtmlEnding_ReturnsNotFound(string viewName)
{
// Arrange
var viewEngine = CreateSuccessfulViewEngine();
var context = GetActionContext(_controllerTestContext);
viewName += ".cshtml";
// Act
var result = viewEngine.FindView(context, viewName, isMainPage: true);
// Assert
Assert.False(result.Success);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void FindView_WithRelativePath_ReturnsNotFound(bool isMainPage)
{
// Arrange
var viewEngine = CreateSuccessfulViewEngine();
var context = GetActionContext(_controllerTestContext);
// Act
var result = viewEngine.FindView(context, "View.cshtml", isMainPage);
// Assert
Assert.False(result.Success);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void GetView_WithViewName_ReturnsNotFound(bool isMainPage)
{
// Arrange
var viewEngine = CreateSuccessfulViewEngine();
// Act
var result = viewEngine.GetView("~/Home/View1.cshtml", "View2", isMainPage);
// Assert
Assert.False(result.Success);
}
[Fact]
public void FindView_ReturnsRazorView_IfLookupWasSuccessful()
{
// Arrange
var pageFactory = new Mock<IRazorPageFactoryProvider>();
var page = Mock.Of<IRazorPage>();
var viewStart1 = Mock.Of<IRazorPage>();
var viewStart2 = Mock.Of<IRazorPage>();
pageFactory
.Setup(p => p.CreateFactory("/Views/bar/test-view.cshtml"))
.Returns(GetPageFactoryResult(() => page));
pageFactory
.Setup(p => p.CreateFactory("/Views/_ViewStart.cshtml"))
.Returns(GetPageFactoryResult(() => viewStart2));
pageFactory
.Setup(p => p.CreateFactory("/_ViewStart.cshtml"))
.Returns(GetPageFactoryResult(() => viewStart1));
var viewEngine = CreateViewEngine(pageFactory.Object);
var context = GetActionContext(_controllerTestContext);
// Act
var result = viewEngine.FindView(context, "test-view", isMainPage: false);
// Assert
Assert.True(result.Success);
var view = Assert.IsType<RazorView>(result.View);
Assert.Same(page, view.RazorPage);
Assert.Equal("test-view", result.ViewName);
Assert.Empty(view.ViewStartPages);
}
[Fact]
public void FindView_DoesNotExpireCachedResults_IfViewStartsExpire()
{
// Arrange
var pageFactory = new Mock<IRazorPageFactoryProvider>();
var page = Mock.Of<IRazorPage>();
var viewStart = Mock.Of<IRazorPage>();
var cancellationTokenSource = new CancellationTokenSource();
var changeToken = new CancellationChangeToken(cancellationTokenSource.Token);
pageFactory
.Setup(p => p.CreateFactory("/Views/bar/test-view.cshtml"))
.Returns(GetPageFactoryResult(() => page));
pageFactory
.Setup(p => p.CreateFactory("/Views/_ViewStart.cshtml"))
.Returns(GetPageFactoryResult(() => viewStart, new[] { changeToken }));
var viewEngine = CreateViewEngine(pageFactory.Object);
var context = GetActionContext(_controllerTestContext);
// Act - 1
var result1 = viewEngine.FindView(context, "test-view", isMainPage: false);
// Assert - 1
Assert.True(result1.Success);
var view1 = Assert.IsType<RazorView>(result1.View);
Assert.Same(page, view1.RazorPage);
Assert.Equal("test-view", result1.ViewName);
Assert.Empty(view1.ViewStartPages);
// Act - 2
cancellationTokenSource.Cancel();
var result2 = viewEngine.FindView(context, "test-view", isMainPage: false);
// Assert - 2
Assert.True(result2.Success);
var view2 = Assert.IsType<RazorView>(result2.View);
Assert.Same(page, view2.RazorPage);
pageFactory.Verify(p => p.CreateFactory("/Views/bar/test-view.cshtml"), Times.Once());
}
[Theory]
[InlineData(null)]
[InlineData("")]
public void FindView_ThrowsIfViewNameIsNullOrEmpty(string partialViewName)
{
// Arrange
var viewEngine = CreateViewEngine();
var context = GetActionContext(_controllerTestContext);
// Act & Assert
ExceptionAssert.ThrowsArgumentNullOrEmpty(
() => viewEngine.FindView(context, partialViewName, isMainPage: false),
"viewName");
}
[Theory]
[MemberData(nameof(AbsoluteViewPathData))]
public void FindViewWithFullPath_ReturnsNotFound(string partialViewName)
{
// Arrange
var viewEngine = CreateSuccessfulViewEngine();
var context = GetActionContext(_controllerTestContext);
// Act
var result = viewEngine.FindView(context, partialViewName, isMainPage: false);
// Assert
Assert.False(result.Success);
}
[Theory]
[MemberData(nameof(AbsoluteViewPathData))]
public void FindViewWithFullPathAndCshtmlEnding_ReturnsNotFound(string partialViewName)
{
// Arrange
var viewEngine = CreateSuccessfulViewEngine();
var context = GetActionContext(_controllerTestContext);
partialViewName += ".cshtml";
// Act
var result = viewEngine.FindView(context, partialViewName, isMainPage: false);
// Assert
Assert.False(result.Success);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void FindView_FailsButSearchesCorrectLocationsWithAreas(bool isMainPage)
{
// Arrange
var viewEngine = CreateViewEngine();
var context = GetActionContext(_areaTestContext);
// Act
var result = viewEngine.FindView(context, "viewName", isMainPage);
// Assert
Assert.False(result.Success);
Assert.Equal(new[]
{
"/Areas/foo/Views/bar/viewName.cshtml",
"/Areas/foo/Views/Shared/viewName.cshtml",
"/Views/Shared/viewName.cshtml",
}, result.SearchedLocations);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void FindView_FailsButSearchesCorrectLocationsWithoutAreas(bool isMainPage)
{
// Arrange
var viewEngine = CreateViewEngine();
var context = GetActionContext(_controllerTestContext);
// Act
var result = viewEngine.FindView(context, "viewName", isMainPage);
// Assert
Assert.False(result.Success);
Assert.Equal(new[] {
"/Views/bar/viewName.cshtml",
"/Views/Shared/viewName.cshtml",
}, result.SearchedLocations);
}
[Fact]
public void FindView_IsMainPage_ReturnsRazorView_IfLookupWasSuccessful()
{
// Arrange
var pageFactory = new Mock<IRazorPageFactoryProvider>();
var page = Mock.Of<IRazorPage>();
var viewStart1 = Mock.Of<IRazorPage>();
var viewStart2 = Mock.Of<IRazorPage>();
pageFactory
.Setup(p => p.CreateFactory("/Views/bar/test-view.cshtml"))
.Returns(GetPageFactoryResult(() => page));
pageFactory
.Setup(p => p.CreateFactory("/Views/_ViewStart.cshtml"))
.Returns(GetPageFactoryResult(() => viewStart2));
pageFactory
.Setup(p => p.CreateFactory("/_ViewStart.cshtml"))
.Returns(GetPageFactoryResult(() => viewStart1));
var viewEngine = CreateViewEngine(pageFactory.Object);
var context = GetActionContext(_controllerTestContext);
// Act
var result = viewEngine.FindView(context, "test-view", isMainPage: true);
// Assert
Assert.True(result.Success);
var view = Assert.IsType<RazorView>(result.View);
Assert.Equal("test-view", result.ViewName);
Assert.Same(page, view.RazorPage);
// ViewStartPages is not empty as it is in FindView_ReturnsRazorView_IfLookupWasSuccessful() despite
// (faked) existence of the view start files in both tests.
Assert.Equal(new[] { viewStart1, viewStart2 }, view.ViewStartPages);
}
[Fact]
public void FindView_UsesViewLocationFormat_IfRouteDoesNotContainArea()
{
// Arrange
var pageFactory = new Mock<IRazorPageFactoryProvider>();
var page = Mock.Of<IRazorPage>();
pageFactory
.Setup(p => p.CreateFactory("fake-path1/bar/test-view.rzr"))
.Returns(GetPageFactoryResult(() => page))
.Verifiable();
var viewEngine = new TestableRazorViewEngine(
pageFactory.Object,
GetOptionsAccessor(
viewLocationFormats: new[] { "fake-path1/{1}/{0}.rzr" },
areaViewLocationFormats: new[] { "fake-area-path/{2}/{1}/{0}.rzr" }));
var context = GetActionContext(_controllerTestContext);
// Act
var result = viewEngine.FindView(context, "test-view", isMainPage: true);
// Assert
pageFactory.Verify();
var view = Assert.IsType<RazorView>(result.View);
Assert.Same(page, view.RazorPage);
}
[Fact]
public void FindView_UsesAreaViewLocationFormat_IfRouteContainsArea()
{
// Arrange
var viewName = "test-view2";
var expectedViewName = "fake-area-path/foo/bar/test-view2.rzr";
var pageFactory = new Mock<IRazorPageFactoryProvider>();
var page = Mock.Of<IRazorPage>();
pageFactory
.Setup(p => p.CreateFactory(expectedViewName))
.Returns(GetPageFactoryResult(() => page))
.Verifiable();
var viewEngine = new TestableRazorViewEngine(
pageFactory.Object,
GetOptionsAccessor(
viewLocationFormats: new[] { "fake-path1/{1}/{0}.rzr" },
areaViewLocationFormats: new[] { "fake-area-path/{2}/{1}/{0}.rzr" }));
var context = GetActionContext(_areaTestContext);
// Act
var result = viewEngine.FindView(context, viewName, isMainPage: true);
// Assert
Assert.True(result.Success);
Assert.Equal(viewName, result.ViewName);
pageFactory.Verify();
}
[Theory]
[InlineData("Test-View.cshtml")]
[InlineData("/Home/Test-View.cshtml")]
public void GetView_DoesNotUseViewLocationFormat_WithRelativePath_IfRouteDoesNotContainArea(string viewName)
{
// Arrange
var expectedViewName = "/Home/Test-View.cshtml";
var pageFactory = new Mock<IRazorPageFactoryProvider>();
var page = Mock.Of<IRazorPage>();
pageFactory
.Setup(p => p.CreateFactory(expectedViewName))
.Returns(GetPageFactoryResult(() => page))
.Verifiable();
var viewEngine = new TestableRazorViewEngine(
pageFactory.Object,
GetOptionsAccessor());
// Act
var result = viewEngine.GetView("/Home/Page.cshtml", viewName, isMainPage: true);
// Assert
Assert.True(result.Success);
Assert.Equal(viewName, result.ViewName);
pageFactory.Verify();
}
[Theory]
[InlineData("Test-View.cshtml")]
[InlineData("/Home/Test-View.cshtml")]
public void GetView_DoesNotUseViewLocationFormat_WithRelativePath_IfRouteContainArea(string viewName)
{
// Arrange
var expectedViewName = "/Home/Test-View.cshtml";
var pageFactory = new Mock<IRazorPageFactoryProvider>();
var page = Mock.Of<IRazorPage>();
pageFactory
.Setup(p => p.CreateFactory(expectedViewName))
.Returns(GetPageFactoryResult(() => page))
.Verifiable();
var viewEngine = new TestableRazorViewEngine(
pageFactory.Object,
GetOptionsAccessor());
// Act
var result = viewEngine.GetView("/Home/Page.cshtml", viewName, isMainPage: true);
// Assert
Assert.True(result.Success);
Assert.Equal(viewName, result.ViewName);
pageFactory.Verify();
}
[Theory]
[InlineData("/Test-View.cshtml")]
[InlineData("~/Test-View.CSHTML")]
[InlineData("/Home/Test-View.CSHTML")]
[InlineData("~/Home/Test-View.cshtml")]
[InlineData("~/SHARED/TEST-VIEW.CSHTML")]
public void GetView_UsesGivenPath_WithAppRelativePath(string viewName)
{
// Arrange
var pageFactory = new Mock<IRazorPageFactoryProvider>();
var page = Mock.Of<IRazorPage>();
pageFactory
.Setup(p => p.CreateFactory(viewName))
.Returns(GetPageFactoryResult(() => page))
.Verifiable();
var viewEngine = new TestableRazorViewEngine(
pageFactory.Object,
GetOptionsAccessor());
// Act
var result = viewEngine.GetView(executingFilePath: null, viewPath: viewName, isMainPage: true);
// Assert
Assert.True(result.Success);
Assert.Equal(viewName, result.ViewName);
pageFactory.Verify();
}
[Theory]
[InlineData("Test-View.cshtml")]
[InlineData("Test-View.CSHTML")]
[InlineData("PATH/TEST-VIEW.CSHTML")]
[InlineData("Path1/Path2/Test-View.cshtml")]
public void GetView_ResolvesRelativeToCurrentPage_WithRelativePath(string viewName)
{
// Arrange
var expectedViewName = $"/Home/{ viewName }";
var pageFactory = new Mock<IRazorPageFactoryProvider>();
var page = Mock.Of<IRazorPage>();
pageFactory
.Setup(p => p.CreateFactory(expectedViewName))
.Returns(GetPageFactoryResult(() => page))
.Verifiable();
var viewEngine = new TestableRazorViewEngine(
pageFactory.Object,
GetOptionsAccessor());
// Act
var result = viewEngine.GetView("/Home/Page.cshtml", viewName, isMainPage: true);
// Assert
Assert.True(result.Success);
Assert.Equal(viewName, result.ViewName);
pageFactory.Verify();
}
[Theory]
[InlineData("Test-View.cshtml")]
[InlineData("Test-View.CSHTML")]
[InlineData("PATH/TEST-VIEW.CSHTML")]
[InlineData("Path1/Path2/Test-View.cshtml")]
public void GetView_ResolvesRelativeToAppRoot_WithRelativePath_IfNoPageExecuting(string viewName)
{
// Arrange
var expectedViewName = $"/{ viewName }";
var pageFactory = new Mock<IRazorPageFactoryProvider>();
var page = Mock.Of<IRazorPage>();
pageFactory
.Setup(p => p.CreateFactory(expectedViewName))
.Returns(GetPageFactoryResult(() => page))
.Verifiable();
var viewEngine = new TestableRazorViewEngine(
pageFactory.Object,
GetOptionsAccessor());
// Act
var result = viewEngine.GetView(executingFilePath: null, viewPath: viewName, isMainPage: true);
// Assert
Assert.True(result.Success);
Assert.Equal(viewName, result.ViewName);
pageFactory.Verify();
var view = Assert.IsType<RazorView>(result.View);
Assert.Same(page, view.RazorPage);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void FindView_CreatesDifferentCacheEntries_ForAreaViewsAndNonAreaViews(bool isMainPage)
{
// Arrange
var pageFactory = new Mock<IRazorPageFactoryProvider>();
var areaPage = Mock.Of<IRazorPage>();
var nonAreaPage = Mock.Of<IRazorPage>();
pageFactory
.Setup(p => p.CreateFactory("/Areas/Admin/Views/Home/Index.cshtml"))
.Returns(GetPageFactoryResult(() => areaPage));
pageFactory
.Setup(p => p.CreateFactory("/Views/Home/Index.cshtml"))
.Returns(GetPageFactoryResult(() => nonAreaPage));
var viewEngine = new TestableRazorViewEngine(
pageFactory.Object,
GetOptionsAccessor());
// Act 1
var areaContext = GetActionContext(new Dictionary<string, object>()
{
{"area", "Admin"},
{"controller", "Home"},
});
var result1 = viewEngine.FindView(areaContext, "Index", isMainPage);
// Assert 1
Assert.NotNull(result1);
pageFactory.Verify(p => p.CreateFactory("/Areas/Admin/Views/Home/Index.cshtml"), Times.Once());
pageFactory.Verify(p => p.CreateFactory("/Views/Home/Index.cshtml"), Times.Never());
var view1 = Assert.IsType<RazorView>(result1.View);
Assert.Same(areaPage, view1.RazorPage);
// Act 2
var nonAreaContext = GetActionContext(new Dictionary<string, object>()
{
{"controller", "Home"},
});
var result2 = viewEngine.FindView(nonAreaContext, "Index", isMainPage);
// Assert 2
Assert.NotNull(result2);
pageFactory.Verify(p => p.CreateFactory("/Areas/Admin/Views/Home/Index.cshtml"), Times.Once());
pageFactory.Verify(p => p.CreateFactory("/Views/Home/Index.cshtml"), Times.Once());
var view2 = Assert.IsType<RazorView>(result2.View);
Assert.Same(nonAreaPage, view2.RazorPage);
// Act 3
// Ensure we're getting cached results.
var result3 = viewEngine.FindView(areaContext, "Index", isMainPage);
var result4 = viewEngine.FindView(nonAreaContext, "Index", isMainPage);
// Assert 4
pageFactory.Verify(p => p.CreateFactory("/Areas/Admin/Views/Home/Index.cshtml"), Times.Once());
pageFactory.Verify(p => p.CreateFactory("/Views/Home/Index.cshtml"), Times.Once());
var view3 = Assert.IsType<RazorView>(result3.View);
Assert.Same(areaPage, view3.RazorPage);
var view4 = Assert.IsType<RazorView>(result4.View);
Assert.Same(nonAreaPage, view4.RazorPage);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void FindView_CreatesDifferentCacheEntries_ForDifferentAreas(bool isMainPage)
{
// Arrange
var pageFactory = new Mock<IRazorPageFactoryProvider>();
var areaPage1 = Mock.Of<IRazorPage>();
var areaPage2 = Mock.Of<IRazorPage>();
pageFactory
.Setup(p => p.CreateFactory("/Areas/Marketing/Views/Home/Index.cshtml"))
.Returns(GetPageFactoryResult(() => areaPage1));
pageFactory
.Setup(p => p.CreateFactory("/Areas/Sales/Views/Home/Index.cshtml"))
.Returns(GetPageFactoryResult(() => areaPage2));
var viewEngine = new TestableRazorViewEngine(
pageFactory.Object,
GetOptionsAccessor());
// Act 1
var areaContext1 = GetActionContext(new Dictionary<string, object>()
{
{"area", "Marketing"},
{"controller", "Home"},
});
var result1 = viewEngine.FindView(areaContext1, "Index", isMainPage);
// Assert 1
Assert.NotNull(result1);
pageFactory.Verify(p => p.CreateFactory("/Areas/Marketing/Views/Home/Index.cshtml"), Times.Once());
pageFactory.Verify(p => p.CreateFactory("/Areas/Sales/Views/Home/Index.cshtml"), Times.Never());
var view1 = Assert.IsType<RazorView>(result1.View);
Assert.Same(areaPage1, view1.RazorPage);
// Act 2
var areaContext2 = GetActionContext(new Dictionary<string, object>()
{
{"controller", "Home"},
{"area", "Sales"},
});
var result2 = viewEngine.FindView(areaContext2, "Index", isMainPage);
// Assert 2
Assert.NotNull(result2);
pageFactory.Verify(p => p.CreateFactory("/Areas/Marketing/Views/Home/Index.cshtml"), Times.Once());
pageFactory.Verify(p => p.CreateFactory("/Areas/Sales/Views/Home/Index.cshtml"), Times.Once());
var view2 = Assert.IsType<RazorView>(result2.View);
Assert.Same(areaPage2, view2.RazorPage);
// Act 3
// Ensure we're getting cached results.
var result3 = viewEngine.FindView(areaContext1, "Index", isMainPage);
var result4 = viewEngine.FindView(areaContext2, "Index", isMainPage);
// Assert 4
pageFactory.Verify(p => p.CreateFactory("/Areas/Marketing/Views/Home/Index.cshtml"), Times.Once());
pageFactory.Verify(p => p.CreateFactory("/Areas/Sales/Views/Home/Index.cshtml"), Times.Once());
var view3 = Assert.IsType<RazorView>(result3.View);
Assert.Same(areaPage1, view3.RazorPage);
var view4 = Assert.IsType<RazorView>(result4.View);
Assert.Same(areaPage2, view4.RazorPage);
}
[Fact]
public void FindView_UsesViewLocationExpandersToLocateViews()
{
// Arrange
var routeValues = _controllerTestContext;
var expectedSeeds = new[]
{
"/Views/{1}/{0}.cshtml",
"/Views/Shared/{0}.cshtml"
};
var pageFactory = new Mock<IRazorPageFactoryProvider>();
pageFactory
.Setup(p => p.CreateFactory("test-string/bar.cshtml"))
.Returns(GetPageFactoryResult(() => Mock.Of<IRazorPage>()))
.Verifiable();
var expander1Result = new[] { "some-seed" };
var expander1 = new Mock<IViewLocationExpander>();
expander1
.Setup(e => e.PopulateValues(It.IsAny<ViewLocationExpanderContext>()))
.Callback((ViewLocationExpanderContext c) =>
{
Assert.NotNull(c.ActionContext);
c.Values["expander-key"] = expander1.ToString();
})
.Verifiable();
expander1
.Setup(e => e.ExpandViewLocations(
It.IsAny<ViewLocationExpanderContext>(),
It.IsAny<IEnumerable<string>>()))
.Callback((ViewLocationExpanderContext c, IEnumerable<string> seeds) =>
{
Assert.NotNull(c.ActionContext);
Assert.Equal(expectedSeeds, seeds);
})
.Returns(expander1Result)
.Verifiable();
var expander2 = new Mock<IViewLocationExpander>();
expander2
.Setup(e => e.ExpandViewLocations(
It.IsAny<ViewLocationExpanderContext>(),
It.IsAny<IEnumerable<string>>()))
.Callback((ViewLocationExpanderContext c, IEnumerable<string> seeds) =>
{
Assert.Equal(expander1Result, seeds);
})
.Returns(new[] { "test-string/{1}.cshtml" })
.Verifiable();
var viewEngine = CreateViewEngine(
pageFactory.Object,
new[] { expander1.Object, expander2.Object });
var context = GetActionContext(routeValues);
// Act
var result = viewEngine.FindView(context, "test-view", isMainPage: true);
// Assert
Assert.True(result.Success);
Assert.IsAssignableFrom<IView>(result.View);
pageFactory.Verify();
expander1.Verify();
expander2.Verify();
}
[Fact]
public void FindView_UsesViewLocationExpandersToLocateViews_ForAreas()
{
// Arrange
var routeValues = _areaTestContext;
var expectedSeeds = new[]
{
"/Areas/{2}/Views/{1}/{0}.cshtml",
"/Areas/{2}/Views/Shared/{0}.cshtml",
"/Views/Shared/{0}.cshtml"
};
var pageFactory = new Mock<IRazorPageFactoryProvider>();
pageFactory
.Setup(p => p.CreateFactory("test-string/bar.cshtml"))
.Returns(GetPageFactoryResult(() => Mock.Of<IRazorPage>()))
.Verifiable();
var expander1Result = new[] { "some-seed" };
var expander1 = new Mock<IViewLocationExpander>();
expander1
.Setup(e => e.PopulateValues(It.IsAny<ViewLocationExpanderContext>()))
.Callback((ViewLocationExpanderContext c) =>
{
Assert.NotNull(c.ActionContext);
c.Values["expander-key"] = expander1.ToString();
})
.Verifiable();
expander1
.Setup(e => e.ExpandViewLocations(
It.IsAny<ViewLocationExpanderContext>(),
It.IsAny<IEnumerable<string>>()))
.Callback((ViewLocationExpanderContext c, IEnumerable<string> seeds) =>
{
Assert.NotNull(c.ActionContext);
Assert.Equal(expectedSeeds, seeds);
})
.Returns(expander1Result)
.Verifiable();
var expander2 = new Mock<IViewLocationExpander>();
expander2
.Setup(e => e.ExpandViewLocations(
It.IsAny<ViewLocationExpanderContext>(),
It.IsAny<IEnumerable<string>>()))
.Callback((ViewLocationExpanderContext c, IEnumerable<string> seeds) =>
{
Assert.Equal(expander1Result, seeds);
})
.Returns(new[] { "test-string/{1}.cshtml" })
.Verifiable();
var viewEngine = CreateViewEngine(
pageFactory.Object,
new[] { expander1.Object, expander2.Object });
var context = GetActionContext(routeValues);
// Act
var result = viewEngine.FindView(context, "test-view", isMainPage: true);
// Assert
Assert.True(result.Success);
Assert.IsAssignableFrom<IView>(result.View);
pageFactory.Verify();
expander1.Verify();
expander2.Verify();
}
[Fact]
public void FindView_NormalizesPaths_ReturnedByViewLocationExpanders()
{
// Arrange
var pageFactory = new Mock<IRazorPageFactoryProvider>();
pageFactory
.Setup(p => p.CreateFactory(@"Views\Home\Index.cshtml"))
.Returns(GetPageFactoryResult(() => Mock.Of<IRazorPage>()))
.Verifiable();
var expander = new Mock<IViewLocationExpander>();
expander
.Setup(e => e.ExpandViewLocations(
It.IsAny<ViewLocationExpanderContext>(),
It.IsAny<IEnumerable<string>>()))
.Returns(new[] { @"Views\Home\Index.cshtml" });
var viewEngine = CreateViewEngine(
pageFactory.Object,
new[] { expander.Object });
var context = GetActionContext(new Dictionary<string, object>());
// Act
var result = viewEngine.FindView(context, "test-view", isMainPage: true);
// Assert
Assert.True(result.Success);
Assert.IsAssignableFrom<IView>(result.View);
pageFactory.Verify();
}
[Fact]
public void FindView_CachesValuesIfViewWasFound()
{
// Arrange
var page = Mock.Of<IRazorPage>();
var pageFactory = new Mock<IRazorPageFactoryProvider>();
pageFactory
.Setup(p => p.CreateFactory("/Views/bar/baz.cshtml"))
.Returns(GetPageFactoryResult(factory: null))
.Verifiable();
pageFactory
.Setup(p => p.CreateFactory("/Views/Shared/baz.cshtml"))
.Returns(GetPageFactoryResult(() => page))
.Verifiable();
var viewEngine = CreateViewEngine(pageFactory.Object);
var context = GetActionContext(_controllerTestContext);
// Act 1
var result1 = viewEngine.FindView(context, "baz", isMainPage: true);
// Assert 1
Assert.True(result1.Success);
var view1 = Assert.IsType<RazorView>(result1.View);
Assert.Same(page, view1.RazorPage);
pageFactory.Verify();
// Act 2
pageFactory
.Setup(p => p.CreateFactory(It.IsAny<string>()))
.Throws(new Exception("Shouldn't be called"));
var result2 = viewEngine.FindView(context, "baz", isMainPage: true);
// Assert 2
Assert.True(result2.Success);
var view2 = Assert.IsType<RazorView>(result2.View);
Assert.Same(page, view2.RazorPage);
pageFactory.Verify();
}
[Fact]
public void FindView_CachesValuesIfViewWasFound_ForPages()
{
// Arrange
var page = Mock.Of<IRazorPage>();
var pageFactory = new Mock<IRazorPageFactoryProvider>();
pageFactory
.Setup(p => p.CreateFactory("/Views/Shared/baz.cshtml"))
.Returns(GetPageFactoryResult(() => page))
.Verifiable();
var viewEngine = CreateViewEngine(pageFactory.Object);
var context = GetActionContext(_pageTestContext);
// Act 1
var result1 = viewEngine.FindView(context, "baz", isMainPage: false);
// Assert 1
Assert.True(result1.Success);
var view1 = Assert.IsType<RazorView>(result1.View);
Assert.Same(page, view1.RazorPage);
pageFactory.Verify();
// Act 2
pageFactory
.Setup(p => p.CreateFactory(It.IsAny<string>()))
.Throws(new Exception("Shouldn't be called"));
var result2 = viewEngine.FindView(context, "baz", isMainPage: false);
// Assert 2
Assert.True(result2.Success);
var view2 = Assert.IsType<RazorView>(result2.View);
Assert.Same(page, view2.RazorPage);
pageFactory.Verify();
}
[Fact]
public void FindView_InvokesPageFactoryIfChangeTokenExpired()
{
// Arrange
var page1 = Mock.Of<IRazorPage>();
var page2 = Mock.Of<IRazorPage>();
var sequence = new MockSequence();
var cancellationTokenSource = new CancellationTokenSource();
var changeToken = new CancellationChangeToken(cancellationTokenSource.Token);
var pageFactory = new Mock<IRazorPageFactoryProvider>();
pageFactory
.InSequence(sequence)
.Setup(p => p.CreateFactory("/Views/bar/baz.cshtml"))
.Returns(GetPageFactoryResult(factory: null, changeTokens: new[] { changeToken }));
pageFactory
.InSequence(sequence)
.Setup(p => p.CreateFactory("/Views/Shared/baz.cshtml"))
.Returns(GetPageFactoryResult(() => page1))
.Verifiable();
pageFactory
.InSequence(sequence)
.Setup(p => p.CreateFactory("/Views/bar/baz.cshtml"))
.Returns(GetPageFactoryResult(() => page2));
var viewEngine = CreateViewEngine(pageFactory.Object);
var context = GetActionContext(_controllerTestContext);
// Act 1
var result1 = viewEngine.FindView(context, "baz", isMainPage: true);
// Assert 1
Assert.True(result1.Success);
var view1 = Assert.IsType<RazorView>(result1.View);
Assert.Same(page1, view1.RazorPage);
// Act 2
cancellationTokenSource.Cancel();
var result2 = viewEngine.FindView(context, "baz", isMainPage: true);
// Assert 2
Assert.True(result2.Success);
var view2 = Assert.IsType<RazorView>(result2.View);
Assert.Same(page2, view2.RazorPage);
pageFactory.Verify();
}
// This test validates an important perf scenario of RazorViewEngine not constructing
// multiple strings for views that do not exist in the file system on a per-request basis.
[Fact]
public void FindView_DoesNotInvokeViewLocationExpanders_IfChangeTokenHasNotExpired()
{
// Arrange
var pageFactory = Mock.Of<IRazorPageFactoryProvider>();
var expander = new Mock<IViewLocationExpander>();
var expandedLocations = new[]
{
"viewlocation1",
"viewlocation2",
"viewlocation3",
};
expander
.Setup(v => v.PopulateValues(It.IsAny<ViewLocationExpanderContext>()))
.Callback((ViewLocationExpanderContext expanderContext) =>
{
expanderContext.Values["somekey"] = "somevalue";
})
.Verifiable();
expander
.Setup(v => v.ExpandViewLocations(
It.IsAny<ViewLocationExpanderContext>(),
It.IsAny<IEnumerable<string>>()))
.Returns(expandedLocations)
.Verifiable();
var viewEngine = CreateViewEngine(
pageFactory,
expanders: new[] { expander.Object });
var context = GetActionContext(_controllerTestContext);
// Act - 1
var result = viewEngine.FindView(context, "myview", isMainPage: true);
// Assert - 1
Assert.False(result.Success);
Assert.Equal(expandedLocations, result.SearchedLocations);
expander.Verify();
// Act - 2
result = viewEngine.FindView(context, "myview", isMainPage: true);
// Assert - 2
Assert.False(result.Success);
Assert.Equal(expandedLocations, result.SearchedLocations);
expander.Verify(
v => v.PopulateValues(It.IsAny<ViewLocationExpanderContext>()),
Times.Exactly(2));
expander.Verify(
v => v.ExpandViewLocations(It.IsAny<ViewLocationExpanderContext>(), It.IsAny<IEnumerable<string>>()),
Times.Once());
}
[Fact]
public void FindView_InvokesViewLocationExpanders_IfChangeTokenExpires()
{
// Arrange
var cancellationTokenSource = new CancellationTokenSource();
var changeToken = new CancellationChangeToken(cancellationTokenSource.Token);
var page = Mock.Of<IRazorPage>();
var pageFactory = new Mock<IRazorPageFactoryProvider>();
pageFactory
.Setup(p => p.CreateFactory("viewlocation3"))
.Returns(GetPageFactoryResult(factory: null, changeTokens: new[] { changeToken }));
var expander = new Mock<IViewLocationExpander>();
var expandedLocations = new[]
{
"viewlocation1",
"viewlocation2",
"viewlocation3",
};
expander
.Setup(v => v.PopulateValues(It.IsAny<ViewLocationExpanderContext>()))
.Callback((ViewLocationExpanderContext expanderContext) =>
{
expanderContext.Values["somekey"] = "somevalue";
})
.Verifiable();
expander
.Setup(v => v.ExpandViewLocations(
It.IsAny<ViewLocationExpanderContext>(),
It.IsAny<IEnumerable<string>>()))
.Returns(expandedLocations)
.Verifiable();
var viewEngine = CreateViewEngine(
pageFactory.Object,
expanders: new[] { expander.Object });
var context = GetActionContext(_controllerTestContext);
// Act - 1
var result = viewEngine.FindView(context, "MyView", isMainPage: true);
// Assert - 1
Assert.False(result.Success);
Assert.Equal(expandedLocations, result.SearchedLocations);
expander.Verify();
// Act - 2
pageFactory
.Setup(p => p.CreateFactory("viewlocation3"))
.Returns(GetPageFactoryResult(() => page));
cancellationTokenSource.Cancel();
result = viewEngine.FindView(context, "MyView", isMainPage: true);
// Assert - 2
Assert.True(result.Success);
var view = Assert.IsType<RazorView>(result.View);
Assert.Same(page, view.RazorPage);
expander.Verify(
v => v.PopulateValues(It.IsAny<ViewLocationExpanderContext>()),
Times.Exactly(2));
expander.Verify(
v => v.ExpandViewLocations(It.IsAny<ViewLocationExpanderContext>(), It.IsAny<IEnumerable<string>>()),
Times.Exactly(2));
}
[Theory]
[MemberData(nameof(AbsoluteViewPathData))]
public void FindPage_WithFullPath_ReturnsNotFound(string viewName)
{
// Arrange
var viewEngine = CreateSuccessfulViewEngine();
var context = GetActionContext(_controllerTestContext);
// Act
var result = viewEngine.FindPage(context, viewName);
// Assert
Assert.Null(result.Page);
}
[Theory]
[MemberData(nameof(AbsoluteViewPathData))]
public void FindPage_WithFullPathAndCshtmlEnding_ReturnsNotFound(string viewName)
{
// Arrange
var viewEngine = CreateSuccessfulViewEngine();
var context = GetActionContext(_controllerTestContext);
viewName += ".cshtml";
// Act
var result = viewEngine.FindPage(context, viewName);
// Assert
Assert.Null(result.Page);
}
[Fact]
public void FindPage_WithRelativePath_ReturnsNotFound()
{
// Arrange
var viewEngine = CreateSuccessfulViewEngine();
var context = GetActionContext(_controllerTestContext);
// Act
var result = viewEngine.FindPage(context, "View.cshtml");
// Assert
Assert.Null(result.Page);
}
[Fact]
public void GetPage_WithViewName_ReturnsNotFound()
{
// Arrange
var viewEngine = CreateSuccessfulViewEngine();
// Act
var result = viewEngine.GetPage("~/Home/View1.cshtml", "View2");
// Assert
Assert.Null(result.Page);
}
[Theory]
[InlineData(null)]
[InlineData("")]
public void FindPage_ThrowsIfNameIsNullOrEmpty(string pageName)
{
// Arrange
var viewEngine = CreateViewEngine();
var context = GetActionContext(_controllerTestContext);
// Act & Assert
ExceptionAssert.ThrowsArgumentNullOrEmpty(
() => viewEngine.FindPage(context, pageName),
"pageName");
}
[Fact]
public void FindPage_UsesViewLocationExpander_ToExpandPaths()
{
// Arrange
var routeValues = _controllerTestContext;
var expectedSeeds = new[]
{
"/Views/{1}/{0}.cshtml",
"/Views/Shared/{0}.cshtml"
};
var page = Mock.Of<IRazorPage>();
var pageFactory = new Mock<IRazorPageFactoryProvider>();
pageFactory
.Setup(p => p.CreateFactory("expanded-path/bar-layout"))
.Returns(GetPageFactoryResult(() => page))
.Verifiable();
var expander = new Mock<IViewLocationExpander>();
expander
.Setup(e => e.PopulateValues(It.IsAny<ViewLocationExpanderContext>()))
.Callback((ViewLocationExpanderContext c) =>
{
Assert.NotNull(c.ActionContext);
c.Values["expander-key"] = expander.ToString();
})
.Verifiable();
expander
.Setup(e => e.ExpandViewLocations(
It.IsAny<ViewLocationExpanderContext>(),
It.IsAny<IEnumerable<string>>()))
.Returns((ViewLocationExpanderContext c, IEnumerable<string> seeds) =>
{
Assert.NotNull(c.ActionContext);
Assert.Equal(expectedSeeds, seeds);
Assert.Equal(expander.ToString(), c.Values["expander-key"]);
return new[] { "expanded-path/bar-{0}" };
})
.Verifiable();
var viewEngine = CreateViewEngine(
pageFactory.Object,
new[] { expander.Object });
var context = GetActionContext(routeValues);
// Act
var result = viewEngine.FindPage(context, "layout");
// Assert
Assert.Equal("layout", result.Name);
Assert.Same(page, result.Page);
Assert.Null(result.SearchedLocations);
pageFactory.Verify();
expander.Verify();
}
[Fact]
public void FindPage_UsesViewLocationExpander_ToExpandPaths_ForAreas()
{
// Arrange
var routeValues = _areaTestContext;
var expectedSeeds = new[]
{
"/Areas/{2}/Views/{1}/{0}.cshtml",
"/Areas/{2}/Views/Shared/{0}.cshtml",
"/Views/Shared/{0}.cshtml"
};
var page = Mock.Of<IRazorPage>();
var pageFactory = new Mock<IRazorPageFactoryProvider>();
pageFactory
.Setup(p => p.CreateFactory("expanded-path/bar-layout"))
.Returns(GetPageFactoryResult(() => page))
.Verifiable();
var expander = new Mock<IViewLocationExpander>();
expander
.Setup(e => e.PopulateValues(It.IsAny<ViewLocationExpanderContext>()))
.Callback((ViewLocationExpanderContext c) =>
{
Assert.NotNull(c.ActionContext);
c.Values["expander-key"] = expander.ToString();
})
.Verifiable();
expander
.Setup(e => e.ExpandViewLocations(
It.IsAny<ViewLocationExpanderContext>(),
It.IsAny<IEnumerable<string>>()))
.Returns((ViewLocationExpanderContext c, IEnumerable<string> seeds) =>
{
Assert.NotNull(c.ActionContext);
Assert.Equal(expectedSeeds, seeds);
Assert.Equal(expander.ToString(), c.Values["expander-key"]);
return new[] { "expanded-path/bar-{0}" };
})
.Verifiable();
var viewEngine = CreateViewEngine(
pageFactory.Object,
new[] { expander.Object });
var context = GetActionContext(routeValues);
// Act
var result = viewEngine.FindPage(context, "layout");
// Assert
Assert.Equal("layout", result.Name);
Assert.Same(page, result.Page);
Assert.Null(result.SearchedLocations);
pageFactory.Verify();
expander.Verify();
}
[Fact]
public void FindPage_ReturnsSearchedLocationsIfPageCannotBeFound()
{
// Arrange
var expected = new[]
{
"/Views/bar/layout.cshtml",
"/Views/Shared/layout.cshtml",
};
var viewEngine = CreateViewEngine();
var context = GetActionContext(_controllerTestContext);
// Act
var result = viewEngine.FindPage(context, "layout");
// Assert
Assert.Equal("layout", result.Name);
Assert.Null(result.Page);
Assert.Equal(expected, result.SearchedLocations);
}
[Fact]
public void FindPage_SelectsActionCaseInsensitively()
{
// The ActionDescriptor contains "Foo" and the RouteData contains "foo"
// which matches the case of the constructor thus searching in the appropriate location.
// Arrange
var routeValues = new Dictionary<string, object>
{
{ "controller", "foo" }
};
var page = new Mock<IRazorPage>(MockBehavior.Strict);
var pageFactory = new Mock<IRazorPageFactoryProvider>();
pageFactory
.Setup(p => p.CreateFactory("/Views/Foo/details.cshtml"))
.Returns(GetPageFactoryResult(() => page.Object))
.Verifiable();
var viewEngine = CreateViewEngine(pageFactory.Object);
var routesInActionDescriptor = new Dictionary<string, string>()
{
{ "controller", "Foo" }
};
var context = GetActionContextWithActionDescriptor(
routeValues,
routesInActionDescriptor);
// Act
var result = viewEngine.FindPage(context, "details");
// Assert
Assert.Equal("details", result.Name);
Assert.Same(page.Object, result.Page);
Assert.Null(result.SearchedLocations);
pageFactory.Verify();
}
[Fact]
public void FindPage_LooksForPages_UsingActionDescriptor_Controller()
{
// Arrange
var expected = new[]
{
"/Views/bar/foo.cshtml",
"/Views/Shared/foo.cshtml",
};
var routeValues = new Dictionary<string, object>
{
{ "controller", "Bar" }
};
var routesInActionDescriptor = new Dictionary<string, string>()
{
{ "controller", "bar" }
};
var viewEngine = CreateViewEngine();
var context = GetActionContextWithActionDescriptor(
routeValues,
routesInActionDescriptor);
// Act
var result = viewEngine.FindPage(context, "foo");
// Assert
Assert.Equal("foo", result.Name);
Assert.Null(result.Page);
Assert.Equal(expected, result.SearchedLocations);
}
[Fact]
public void FindPage_LooksForPages_UsingActionDescriptor_Areas()
{
// Arrange
var expected = new[]
{
"/Areas/world/Views/bar/foo.cshtml",
"/Areas/world/Views/Shared/foo.cshtml",
"/Views/Shared/foo.cshtml"
};
var routeValues = new Dictionary<string, object>
{
{ "controller", "Bar" },
{ "area", "World" }
};
var routesInActionDescriptor = new Dictionary<string, string>()
{
{ "controller", "bar" },
{ "area", "world" }
};
var viewEngine = CreateViewEngine();
var context = GetActionContextWithActionDescriptor(
routeValues,
routesInActionDescriptor);
// Act
var result = viewEngine.FindPage(context, "foo");
// Assert
Assert.Equal("foo", result.Name);
Assert.Null(result.Page);
Assert.Equal(expected, result.SearchedLocations);
}
[Fact]
public void FindPage_LooksForPages_UsesRouteValuesAsFallback()
{
// Arrange
var expected = new[]
{
"/Views/foo/bar.cshtml",
"/Views/Shared/bar.cshtml",
};
var routeValues = new Dictionary<string, object>()
{
{ "controller", "foo" }
};
var viewEngine = CreateViewEngine();
var context = GetActionContextWithActionDescriptor(
routeValues,
new Dictionary<string, string>());
// Act
var result = viewEngine.FindPage(context, "bar");
// Assert
Assert.Equal("bar", result.Name);
Assert.Null(result.Page);
Assert.Equal(expected, result.SearchedLocations);
}
[Theory]
[InlineData("/Test-View.cshtml")]
[InlineData("~/Test-View.CSHTML")]
[InlineData("/Home/Test-View.CSHTML")]
[InlineData("~/Home/Test-View.cshtml")]
[InlineData("~/SHARED/TEST-VIEW.CSHTML")]
public void GetPage_UsesGivenPath_WithAppRelativePath(string pageName)
{
// Arrange
var pageFactory = new Mock<IRazorPageFactoryProvider>();
var page = Mock.Of<IRazorPage>();
pageFactory
.Setup(p => p.CreateFactory(pageName))
.Returns(GetPageFactoryResult(() => page))
.Verifiable();
var viewEngine = new TestableRazorViewEngine(
pageFactory.Object,
GetOptionsAccessor());
// Act
var result = viewEngine.GetPage("~/Another/Place.cshtml", pagePath: pageName);
// Assert
Assert.Same(page, result.Page);
Assert.Equal(pageName, result.Name);
pageFactory.Verify();
}
[Theory]
[InlineData("Test-View.cshtml")]
[InlineData("Test-View.CSHTML")]
[InlineData("PATH/TEST-VIEW.CSHTML")]
[InlineData("Path1/Path2/Test-View.cshtml")]
public void GetPage_ResolvesRelativeToCurrentPage_WithRelativePath(string pageName)
{
// Arrange
var expectedPageName = $"/Home/{ pageName }";
var pageFactory = new Mock<IRazorPageFactoryProvider>();
var page = Mock.Of<IRazorPage>();
pageFactory
.Setup(p => p.CreateFactory(expectedPageName))
.Returns(GetPageFactoryResult(() => page))
.Verifiable();
var viewEngine = new TestableRazorViewEngine(
pageFactory.Object,
GetOptionsAccessor());
// Act
var result = viewEngine.GetPage("/Home/Page.cshtml", pageName);
// Assert
Assert.Same(page, result.Page);
Assert.Equal(pageName, result.Name);
pageFactory.Verify();
}
[Theory]
[InlineData("Test-View.cshtml")]
[InlineData("Test-View.CSHTML")]
[InlineData("PATH/TEST-VIEW.CSHTML")]
[InlineData("Path1/Path2/Test-View.cshtml")]
public void GetPage_ResolvesRelativeToAppRoot_WithRelativePath_IfNoPageExecuting(string pageName)
{
// Arrange
var expectedPageName = $"/{ pageName }";
var pageFactory = new Mock<IRazorPageFactoryProvider>();
var page = Mock.Of<IRazorPage>();
pageFactory
.Setup(p => p.CreateFactory(expectedPageName))
.Returns(GetPageFactoryResult(() => page))
.Verifiable();
var viewEngine = new TestableRazorViewEngine(
pageFactory.Object,
GetOptionsAccessor());
// Act
var result = viewEngine.GetPage(executingFilePath: null, pagePath: pageName);
// Assert
Assert.Same(page, result.Page);
Assert.Equal(pageName, result.Name);
pageFactory.Verify();
}
[Theory]
[InlineData(null, null)]
[InlineData(null, "")]
[InlineData(null, "Page")]
[InlineData(null, "Folder/Page")]
[InlineData(null, "Folder1/Folder2/Page")]
[InlineData("/Home/Index.cshtml", null)]
[InlineData("/Home/Index.cshtml", "")]
[InlineData("/Home/Index.cshtml", "Page")]
[InlineData("/Home/Index.cshtml", "Folder/Page")]
[InlineData("/Home/Index.cshtml", "Folder1/Folder2/Page")]
public void GetAbsolutePath_ReturnsPagePathUnchanged_IfNotAPath(string executingFilePath, string pagePath)
{
// Arrange
var viewEngine = CreateViewEngine();
// Act
var result = viewEngine.GetAbsolutePath(executingFilePath, pagePath);
// Assert
Assert.Same(pagePath, result);
}
[Theory]
[InlineData("/Views/Home/Index.cshtml", "../Shared/_Partial.cshtml")]
[InlineData("/Views/Home/Index.cshtml", "..\\Shared\\_Partial.cshtml")]
[InlineData("/Areas/MyArea/Views/Home/Index.cshtml", "../../../../Views/Shared/_Partial.cshtml")]
[InlineData("/Views/Accounts/Users.cshtml", "../Test/../Shared/_Partial.cshtml")]
[InlineData("Views/Accounts/Users.cshtml", "./../Shared/./_Partial.cshtml")]
public void GetAbsolutePath_ResolvesPathTraversals(string executingFilePath, string pagePath)
{
// Arrange
var viewEngine = CreateViewEngine();
// Act
var result = viewEngine.GetAbsolutePath(executingFilePath, pagePath);
// Assert
Assert.Equal("/Views/Shared/_Partial.cshtml", result);
}
[Theory]
[InlineData("../Shared/_Layout.cshtml")]
[InlineData("Folder1/../Folder2/../../File.cshtml")]
public void GetAbsolutePath_DoesNotResolvePathIfTraversalsEscapeTheRoot(string pagePath)
{
// Arrange
var expected = '/' + pagePath;
var viewEngine = CreateViewEngine();
// Act
var result = viewEngine.GetAbsolutePath("/Index.cshtml", pagePath);
// Assert
Assert.Equal(expected, result);
}
[Theory]
[InlineData(null, "/Page")]
[InlineData(null, "~/Folder/Page.cshtml")]
[InlineData(null, "/Folder1/Folder2/Page.rzr")]
[InlineData("/Home/Index.cshtml", "~/Page")]
[InlineData("/Home/Index.cshtml", "/Folder/Page.cshtml")]
[InlineData("/Home/Index.cshtml", "~/Folder1/Folder2/Page.rzr")]
public void GetAbsolutePath_ReturnsPagePathUnchanged_IfAppRelative(string executingFilePath, string pagePath)
{
// Arrange
var viewEngine = CreateViewEngine();
// Act
var result = viewEngine.GetAbsolutePath(executingFilePath, pagePath);
// Assert
Assert.Same(pagePath, result);
}
[Theory]
[InlineData("Page.cshtml")]
[InlineData("Folder/Page.cshtml")]
[InlineData("../../Folder1/Folder2/Page.cshtml")]
public void GetAbsolutePath_ResolvesRelativeToExecutingPage(string pagePath)
{
// Arrange
var expectedPagePath = "/Home/" + pagePath;
var viewEngine = CreateViewEngine();
// Act
var result = viewEngine.GetAbsolutePath("/Home/Page.cshtml", pagePath);
// Assert
Assert.Equal(expectedPagePath, result);
}
[Theory]
[InlineData("Page.cshtml")]
[InlineData("Folder/Page.cshtml")]
[InlineData("../../Folder1/Folder2/Page.cshtml")]
public void GetAbsolutePath_ResolvesRelativeToAppRoot_IfNoPageExecuting(string pagePath)
{
// Arrange
var expectedPagePath = "/" + pagePath;
var viewEngine = CreateViewEngine();
// Act
var result = viewEngine.GetAbsolutePath(executingFilePath: null, pagePath: pagePath);
// Assert
Assert.Equal(expectedPagePath, result);
}
[Fact]
public void GetNormalizedRouteValue_ReturnsValueFromRouteValues()
{
// Arrange
var key = "some-key";
var actionDescriptor = new ActionDescriptor();
actionDescriptor.RouteValues.Add(key, "Route-Value");
var actionContext = new ActionContext
{
ActionDescriptor = actionDescriptor,
RouteData = new RouteData()
};
actionContext.RouteData.Values[key] = "route-value";
// Act
var result = RazorViewEngine.GetNormalizedRouteValue(actionContext, key);
// Assert
Assert.Equal("Route-Value", result);
}
[Fact]
[ReplaceCulture("de-CH", "de-CH")]
public void GetNormalizedRouteValue_UsesInvariantCulture()
{
// Arrange
var key = "some-key";
var actionDescriptor = new ActionDescriptor();
actionDescriptor.RouteValues.Add(key, "Route-Value");
var actionContext = new ActionContext
{
ActionDescriptor = actionDescriptor,
RouteData = new RouteData()
};
actionContext.RouteData.Values[key] = new DateTimeOffset(2018, 10, 31, 7, 37, 38, TimeSpan.FromHours(-7));
// Act
var result = RazorViewEngine.GetNormalizedRouteValue(actionContext, key);
// Assert
Assert.Equal("10/31/2018 07:37:38 -07:00", result);
}
[Fact]
public void GetNormalizedRouteValue_ReturnsRouteValue_IfValueDoesNotMatch()
{
// Arrange
var key = "some-key";
var actionDescriptor = new ActionDescriptor();
actionDescriptor.RouteValues.Add(key, "different-value");
var actionContext = new ActionContext
{
ActionDescriptor = actionDescriptor,
RouteData = new RouteData()
};
actionContext.RouteData.Values[key] = "route-value";
// Act
var result = RazorViewEngine.GetNormalizedRouteValue(actionContext, key);
// Assert
Assert.Equal("route-value", result);
}
[Fact]
public void GetNormalizedRouteValue_ReturnsNonNormalizedValue_IfActionRouteValueIsNull()
{
// Arrange
var key = "some-key";
var actionDescriptor = new ActionDescriptor();
actionDescriptor.RouteValues.Add(key, null);
var actionContext = new ActionContext
{
ActionDescriptor = actionDescriptor,
RouteData = new RouteData()
};
actionContext.RouteData.Values[key] = "route-value";
// Act
var result = RazorViewEngine.GetNormalizedRouteValue(actionContext, key);
// Assert
Assert.Equal("route-value", result);
}
[Fact]
public void GetNormalizedRouteValue_ConvertsRouteValueToString()
{
using (new CultureReplacer())
{
// Arrange
var key = "some-key";
var actionDescriptor = new ActionDescriptor
{
AttributeRouteInfo = new AttributeRouteInfo(),
};
var actionContext = new ActionContext
{
ActionDescriptor = actionDescriptor,
RouteData = new RouteData()
};
actionContext.RouteData.Values[key] = 43;
// Act
var result = RazorViewEngine.GetNormalizedRouteValue(actionContext, key);
// Assert
Assert.Equal("43", result);
}
}
[Fact]
public void GetViewLocationFormats_ForControllerWithoutArea_ReturnsDefaultSet()
{
// Arrange
var expected = new string[] { "expected", };
var viewEngine = new TestableRazorViewEngine(
Mock.Of<IRazorPageFactoryProvider>(),
GetOptionsAccessor(viewLocationFormats: expected));
var context = new ViewLocationExpanderContext(
new ActionContext(),
"Index.cshtml",
controllerName: "Home",
areaName: null,
pageName: "ignored",
isMainPage: true);
// Act
var actual = viewEngine.GetViewLocationFormats(context);
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void GetViewLocationFormats_ForControllerWithArea_ReturnsAreaSet()
{
// Arrange
var expected = new string[] { "expected", };
var viewEngine = new TestableRazorViewEngine(
Mock.Of<IRazorPageFactoryProvider>(),
GetOptionsAccessor(areaViewLocationFormats: expected));
var context = new ViewLocationExpanderContext(
new ActionContext(),
"Index.cshtml",
controllerName: "Home",
areaName: "Admin",
pageName: "ignored",
isMainPage: true);
// Act
var actual = viewEngine.GetViewLocationFormats(context);
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void GetViewLocationFormats_ForPage_ReturnsPageSet()
{
// Arrange
var expected = new string[] { "expected", };
var viewEngine = new TestableRazorViewEngine(
Mock.Of<IRazorPageFactoryProvider>(),
GetOptionsAccessor(pageViewLocationFormats: expected));
var context = new ViewLocationExpanderContext(
new ActionContext(),
"Index.cshtml",
controllerName: null,
areaName: null,
pageName: "/Some/Page",
isMainPage: true);
// Act
var actual = viewEngine.GetViewLocationFormats(context);
// Assert
Assert.Equal(expected, actual);
}
// This isn't a real case we expect to hit in an app, just making sure we have a reasonable default
// for a weird configuration. In this case we preserve what we did in 1.0.0.
[Fact]
public void GetViewLocationFormats_NoRouteValues_ReturnsDefaultSet()
{
// Arrange
var expected = new string[] { "expected", };
var viewEngine = new TestableRazorViewEngine(
Mock.Of<IRazorPageFactoryProvider>(),
GetOptionsAccessor(viewLocationFormats: expected));
var context = new ViewLocationExpanderContext(
new ActionContext(),
"Index.cshtml",
controllerName: null,
areaName: null,
pageName: null,
isMainPage: true);
// Act
var actual = viewEngine.GetViewLocationFormats(context);
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void ViewEngine_DoesNotSetPageValue_IfItIsNotSpecifiedInRouteValues()
{
// Arrange
var routeValues = new Dictionary<string, object>
{
{ "controller", "MyController" },
{ "action", "MyAction" }
};
var expected = new[] { "some-seed" };
var expander = new Mock<IViewLocationExpander>();
expander
.Setup(e => e.PopulateValues(It.IsAny<ViewLocationExpanderContext>()))
.Callback((ViewLocationExpanderContext c) =>
{
Assert.Equal("MyController", c.ControllerName);
Assert.Null(c.PageName);
})
.Verifiable();
expander
.Setup(e => e.ExpandViewLocations(
It.IsAny<ViewLocationExpanderContext>(),
It.IsAny<IEnumerable<string>>()))
.Returns(expected);
var viewEngine = CreateViewEngine(expanders: new[] { expander.Object });
var context = GetActionContext(routeValues);
// Act
viewEngine.FindView(context, viewName: "Test-view", isMainPage: true);
// Assert
expander.Verify();
}
[Fact]
public void ViewEngine_SetsPageValue_IfItIsSpecifiedInRouteValues()
{
// Arrange
var routeValues = new Dictionary<string, object>
{
{ "page", "MyPage" },
};
var expected = new[] { "some-seed" };
var expander = new Mock<IViewLocationExpander>();
expander
.Setup(e => e.PopulateValues(It.IsAny<ViewLocationExpanderContext>()))
.Callback((ViewLocationExpanderContext c) =>
{
Assert.Equal("MyPage", c.PageName);
})
.Verifiable();
expander
.Setup(e => e.ExpandViewLocations(
It.IsAny<ViewLocationExpanderContext>(),
It.IsAny<IEnumerable<string>>()))
.Returns(expected);
var viewEngine = CreateViewEngine(expanders: new[] { expander.Object });
var context = GetActionContext(routeValues);
context.ActionDescriptor.RouteValues["page"] = "MyPage";
// Act
viewEngine.FindView(context, viewName: "MyView", isMainPage: true);
// Assert
expander.Verify();
}
[Fact]
public void FindView_ResolvesDirectoryTraversalsPriorToInvokingPageFactory()
{
// Arrange
var pageFactory = new Mock<IRazorPageFactoryProvider>();
pageFactory.Setup(p => p.CreateFactory("/Views/Shared/_Partial.cshtml"))
.Returns(GetPageFactoryResult(() => Mock.Of<IRazorPage>()))
.Verifiable();
var viewEngine = CreateViewEngine(pageFactory.Object);
var context = GetActionContext(new Dictionary<string, object>());
// Act
var result = viewEngine.FindView(context, "../Shared/_Partial", isMainPage: false);
// Assert
pageFactory.Verify();
}
[Fact]
public void FindPage_ResolvesDirectoryTraversalsPriorToInvokingPageFactory()
{
// Arrange
var pageFactory = new Mock<IRazorPageFactoryProvider>();
pageFactory.Setup(p => p.CreateFactory("/Views/Shared/_Partial.cshtml"))
.Returns(GetPageFactoryResult(() => Mock.Of<IRazorPage>()))
.Verifiable();
var viewEngine = CreateViewEngine(pageFactory.Object);
var context = GetActionContext(new Dictionary<string, object>());
// Act
var result = viewEngine.FindPage(context, "../Shared/_Partial");
// Assert
pageFactory.Verify();
}
// Tests to verify fix for https://github.com/aspnet/Mvc/issues/6672
// Without normalizing the path, the view engine would have attempted to lookup "/Views//MyView.cshtml"
// which works for PhysicalFileProvider but fails for exact lookups performed during precompilation.
// We normalize it to "/Views/MyView.cshtml" to avoid this discrepancy.
[Fact]
public void FindView_ResolvesNormalizesSlashesPriorToInvokingPageFactory()
{
// Arrange
var pageFactory = new Mock<IRazorPageFactoryProvider>();
pageFactory.Setup(p => p.CreateFactory("/Views/MyView.cshtml"))
.Returns(GetPageFactoryResult(() => Mock.Of<IRazorPage>()))
.Verifiable();
var viewEngine = CreateViewEngine(pageFactory.Object);
var context = GetActionContext(new Dictionary<string, object>());
// Act
var result = viewEngine.FindView(context, "MyView", isMainPage: true);
// Assert
pageFactory.Verify();
}
[Fact]
public void FindPage_ResolvesNormalizesSlashesPriorToInvokingPageFactory()
{
// Arrange
var pageFactory = new Mock<IRazorPageFactoryProvider>();
pageFactory.Setup(p => p.CreateFactory("/Views/MyPage.cshtml"))
.Returns(GetPageFactoryResult(() => Mock.Of<IRazorPage>()))
.Verifiable();
var viewEngine = CreateViewEngine(pageFactory.Object);
var context = GetActionContext(new Dictionary<string, object>());
// Act
var result = viewEngine.FindPage(context, "MyPage");
// Assert
pageFactory.Verify();
}
[Fact]
public void FindView_Succeeds_AfterClearCache()
{
// Arrange
var pageFactory = new Mock<IRazorPageFactoryProvider>();
var page = Mock.Of<IRazorPage>();
var hotReloadedPage = Mock.Of<IRazorPage>();
pageFactory
.Setup(p => p.CreateFactory("/Views/bar/Index.cshtml"))
.Returns(GetPageFactoryResult(() => page));
var viewEngine = CreateViewEngine(pageFactory.Object);
var context = GetActionContext(_controllerTestContext);
// Act - 1
// First verify results are typically cached
for (var i = 0; i < 3; i++)
{
var result = viewEngine.FindView(context, "Index", isMainPage: false);
// Assert - 1
Assert.True(result.Success);
var view = Assert.IsType<RazorView>(result.View);
Assert.Same(page, view.RazorPage);
pageFactory.Verify(p => p.CreateFactory("/Views/bar/Index.cshtml"), Times.Once());
}
// Now verify that the page factory is re-invoked after cache clear
viewEngine.ClearCache();
pageFactory
.Setup(p => p.CreateFactory("/Views/bar/Index.cshtml"))
.Returns(GetPageFactoryResult(() => hotReloadedPage));
{
// Act - 2
var result = viewEngine.FindView(context, "Index", isMainPage: false);
// Assert - 2
Assert.True(result.Success);
var view = Assert.IsType<RazorView>(result.View);
Assert.Same(hotReloadedPage, view.RazorPage);
pageFactory.Verify(p => p.CreateFactory("/Views/bar/Index.cshtml"), Times.Exactly(2));
}
}
// Return RazorViewEngine with a page factory provider that is always successful.
private RazorViewEngine CreateSuccessfulViewEngine()
{
var pageFactory = new Mock<IRazorPageFactoryProvider>(MockBehavior.Strict);
pageFactory
.Setup(f => f.CreateFactory(It.IsAny<string>()))
.Returns(GetPageFactoryResult(() => Mock.Of<IRazorPage>()));
return CreateViewEngine(pageFactory.Object);
}
private static RazorPageFactoryResult GetPageFactoryResult(
Func<IRazorPage> factory,
IList<IChangeToken> changeTokens = null,
string path = "/Views/Home/Index.cshtml")
{
var descriptor = new CompiledViewDescriptor
{
ExpirationTokens = changeTokens ?? Array.Empty<IChangeToken>(),
RelativePath = path,
};
return new RazorPageFactoryResult(descriptor, factory);
}
private TestableRazorViewEngine CreateViewEngine(
IRazorPageFactoryProvider pageFactory = null,
IEnumerable<IViewLocationExpander> expanders = null)
{
pageFactory = pageFactory ?? Mock.Of<IRazorPageFactoryProvider>();
return new TestableRazorViewEngine(pageFactory, GetOptionsAccessor(expanders));
}
private static IOptions<RazorViewEngineOptions> GetOptionsAccessor(
IEnumerable<IViewLocationExpander> expanders = null,
IEnumerable<string> viewLocationFormats = null,
IEnumerable<string> areaViewLocationFormats = null,
IEnumerable<string> pageViewLocationFormats = null)
{
var optionsSetup = new RazorViewEngineOptionsSetup();
var options = new RazorViewEngineOptions();
optionsSetup.Configure(options);
options.PageViewLocationFormats.Add("/Views/Shared/{0}.cshtml");
options.PageViewLocationFormats.Add("/Pages/Shared/{0}.cshtml");
if (expanders != null)
{
foreach (var expander in expanders)
{
options.ViewLocationExpanders.Add(expander);
}
}
if (viewLocationFormats != null)
{
options.ViewLocationFormats.Clear();
foreach (var location in viewLocationFormats)
{
options.ViewLocationFormats.Add(location);
}
}
if (areaViewLocationFormats != null)
{
options.AreaViewLocationFormats.Clear();
foreach (var location in areaViewLocationFormats)
{
options.AreaViewLocationFormats.Add(location);
}
}
if (pageViewLocationFormats != null)
{
options.PageViewLocationFormats.Clear();
foreach (var location in pageViewLocationFormats)
{
options.PageViewLocationFormats.Add(location);
}
}
var optionsAccessor = new Mock<IOptions<RazorViewEngineOptions>>();
optionsAccessor
.SetupGet(v => v.Value)
.Returns(options);
return optionsAccessor.Object;
}
private static ActionContext GetActionContext(IDictionary<string, object> routeValues)
{
var httpContext = new DefaultHttpContext();
var routeData = new RouteData();
foreach (var kvp in routeValues)
{
routeData.Values.Add(kvp.Key, kvp.Value);
}
var actionDescriptor = new ActionDescriptor();
return new ActionContext(httpContext, routeData, actionDescriptor);
}
private static ActionContext GetActionContextWithActionDescriptor(
IDictionary<string, object> routeValues,
IDictionary<string, string> actionRouteValues)
{
var httpContext = new DefaultHttpContext();
var routeData = new RouteData();
foreach (var kvp in routeValues)
{
routeData.Values.Add(kvp.Key, kvp.Value);
}
var actionDescriptor = new ActionDescriptor();
foreach (var kvp in actionRouteValues)
{
actionDescriptor.RouteValues.Add(kvp.Key, kvp.Value);
}
return new ActionContext(httpContext, routeData, actionDescriptor);
}
private class TestableRazorViewEngine : RazorViewEngine
{
public TestableRazorViewEngine(
IRazorPageFactoryProvider pageFactory,
IOptions<RazorViewEngineOptions> optionsAccessor)
: base(pageFactory, Mock.Of<IRazorPageActivator>(), new HtmlTestEncoder(), optionsAccessor, NullLoggerFactory.Instance, new DiagnosticListener("Microsoft.AspNetCore.Mvc.Razor"))
{
}
public IMemoryCache ViewLookupCachePublic => ViewLookupCache;
}
}
}
| |
namespace CSharpSerialConnection
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.btnConnect = new System.Windows.Forms.Button();
this.Commandline = new System.Windows.Forms.RichTextBox();
this.btnForward = new System.Windows.Forms.Button();
this.btnLeft = new System.Windows.Forms.Button();
this.btnRight = new System.Windows.Forms.Button();
this.btnBackward = new System.Windows.Forms.Button();
this.btnGetSpeed = new System.Windows.Forms.Button();
this.btnGetFuelLevels = new System.Windows.Forms.Button();
this.tmrLifetime = new System.Windows.Forms.Timer(this.components);
this.button1 = new System.Windows.Forms.Button();
this.btnNewStats = new System.Windows.Forms.Button();
this.Feedback = new System.Windows.Forms.RichTextBox();
this.btnStop = new System.Windows.Forms.Button();
this.trackBar1 = new System.Windows.Forms.TrackBar();
((System.ComponentModel.ISupportInitialize)(this.trackBar1)).BeginInit();
this.SuspendLayout();
//
// btnConnect
//
this.btnConnect.Location = new System.Drawing.Point(12, 12);
this.btnConnect.Name = "btnConnect";
this.btnConnect.Size = new System.Drawing.Size(130, 25);
this.btnConnect.TabIndex = 0;
this.btnConnect.Text = "Connect to Vehicle";
this.btnConnect.UseVisualStyleBackColor = true;
this.btnConnect.Click += new System.EventHandler(this.btnConnect_Click);
//
// Commandline
//
this.Commandline.Location = new System.Drawing.Point(12, 43);
this.Commandline.Name = "Commandline";
this.Commandline.Size = new System.Drawing.Size(384, 32);
this.Commandline.TabIndex = 3;
this.Commandline.Text = "";
//
// btnForward
//
this.btnForward.Location = new System.Drawing.Point(595, 41);
this.btnForward.Name = "btnForward";
this.btnForward.Size = new System.Drawing.Size(75, 75);
this.btnForward.TabIndex = 4;
this.btnForward.Text = "Forward";
this.btnForward.UseVisualStyleBackColor = true;
this.btnForward.Click += new System.EventHandler(this.btnForward_Click);
//
// btnLeft
//
this.btnLeft.Location = new System.Drawing.Point(500, 126);
this.btnLeft.Name = "btnLeft";
this.btnLeft.Size = new System.Drawing.Size(75, 75);
this.btnLeft.TabIndex = 4;
this.btnLeft.Text = "Left";
this.btnLeft.UseVisualStyleBackColor = true;
this.btnLeft.Click += new System.EventHandler(this.btnLeft_Click);
//
// btnRight
//
this.btnRight.Location = new System.Drawing.Point(686, 126);
this.btnRight.Name = "btnRight";
this.btnRight.Size = new System.Drawing.Size(75, 75);
this.btnRight.TabIndex = 4;
this.btnRight.Text = "Right";
this.btnRight.UseVisualStyleBackColor = true;
this.btnRight.Click += new System.EventHandler(this.btnRight_Click);
//
// btnBackward
//
this.btnBackward.Location = new System.Drawing.Point(595, 213);
this.btnBackward.Name = "btnBackward";
this.btnBackward.Size = new System.Drawing.Size(75, 75);
this.btnBackward.TabIndex = 4;
this.btnBackward.Text = "Backward";
this.btnBackward.UseVisualStyleBackColor = true;
this.btnBackward.Click += new System.EventHandler(this.btnBackward_Click);
//
// btnGetSpeed
//
this.btnGetSpeed.Location = new System.Drawing.Point(402, 41);
this.btnGetSpeed.Name = "btnGetSpeed";
this.btnGetSpeed.Size = new System.Drawing.Size(173, 34);
this.btnGetSpeed.TabIndex = 5;
this.btnGetSpeed.Text = "Get Top Speed Achieved";
this.btnGetSpeed.UseVisualStyleBackColor = true;
this.btnGetSpeed.Click += new System.EventHandler(this.btnGetSpeed_Click);
//
// btnGetFuelLevels
//
this.btnGetFuelLevels.Location = new System.Drawing.Point(686, 43);
this.btnGetFuelLevels.Name = "btnGetFuelLevels";
this.btnGetFuelLevels.Size = new System.Drawing.Size(127, 34);
this.btnGetFuelLevels.TabIndex = 5;
this.btnGetFuelLevels.Text = "Get Fuel Levels";
this.btnGetFuelLevels.UseVisualStyleBackColor = true;
this.btnGetFuelLevels.Click += new System.EventHandler(this.btnGetFuelLevels_Click);
//
// tmrLifetime
//
this.tmrLifetime.Enabled = true;
this.tmrLifetime.Interval = 1000;
this.tmrLifetime.Tick += new System.EventHandler(this.tmrLifetime_Tick);
//
// button1
//
this.button1.Location = new System.Drawing.Point(148, 12);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(130, 25);
this.button1.TabIndex = 0;
this.button1.Text = "Disconnect from Vehicle";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.btnConnect_Click);
//
// btnNewStats
//
this.btnNewStats.Location = new System.Drawing.Point(423, 312);
this.btnNewStats.Name = "btnNewStats";
this.btnNewStats.Size = new System.Drawing.Size(134, 23);
this.btnNewStats.TabIndex = 6;
this.btnNewStats.Text = "Reset Stats/ New Rent";
this.btnNewStats.UseVisualStyleBackColor = true;
//
// Feedback
//
this.Feedback.Location = new System.Drawing.Point(12, 81);
this.Feedback.Name = "Feedback";
this.Feedback.ReadOnly = true;
this.Feedback.ShortcutsEnabled = false;
this.Feedback.Size = new System.Drawing.Size(383, 254);
this.Feedback.TabIndex = 7;
this.Feedback.Text = "";
//
// btnStop
//
this.btnStop.Location = new System.Drawing.Point(595, 126);
this.btnStop.Name = "btnStop";
this.btnStop.Size = new System.Drawing.Size(75, 75);
this.btnStop.TabIndex = 8;
this.btnStop.Text = "STOP";
this.btnStop.UseVisualStyleBackColor = true;
this.btnStop.Click += new System.EventHandler(this.btnStop_Click);
//
// trackBar1
//
this.trackBar1.Location = new System.Drawing.Point(595, 312);
this.trackBar1.Maximum = 100;
this.trackBar1.Minimum = 5;
this.trackBar1.Name = "trackBar1";
this.trackBar1.Size = new System.Drawing.Size(191, 45);
this.trackBar1.TabIndex = 9;
this.trackBar1.Value = 5;
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(819, 347);
this.Controls.Add(this.trackBar1);
this.Controls.Add(this.btnStop);
this.Controls.Add(this.Feedback);
this.Controls.Add(this.btnNewStats);
this.Controls.Add(this.btnGetFuelLevels);
this.Controls.Add(this.btnGetSpeed);
this.Controls.Add(this.btnBackward);
this.Controls.Add(this.btnRight);
this.Controls.Add(this.btnLeft);
this.Controls.Add(this.btnForward);
this.Controls.Add(this.Commandline);
this.Controls.Add(this.button1);
this.Controls.Add(this.btnConnect);
this.Name = "Form1";
this.Text = "Form1";
((System.ComponentModel.ISupportInitialize)(this.trackBar1)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button btnConnect;
private System.Windows.Forms.RichTextBox Commandline;
private System.Windows.Forms.Button btnForward;
private System.Windows.Forms.Button btnLeft;
private System.Windows.Forms.Button btnRight;
private System.Windows.Forms.Button btnBackward;
private System.Windows.Forms.Button btnGetSpeed;
private System.Windows.Forms.Button btnGetFuelLevels;
private System.Windows.Forms.Timer tmrLifetime;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Button btnNewStats;
private System.Windows.Forms.RichTextBox Feedback;
private System.Windows.Forms.Button btnStop;
private System.Windows.Forms.TrackBar trackBar1;
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
namespace socketSrv
{
class Client
{
TcpClient tcpClient = new TcpClient(AddressFamily.InterNetwork);
peerInstance myServer = new peerInstance();
NetworkStream clientStream;
Timer timer = new Timer();
public List<commandMessage> clientQueue = new List<commandMessage>();
public void setServer(peerInstance p)
{
myServer.peerIP = p.peerIP;
myServer.peerPort = p.peerPort;
}
public bool isClientMessage()
{
bool returnBool = false;
if (clientQueue.Count > 0)
returnBool = true;
return returnBool;
}
public List<commandMessage> returnClientQueue()
{
checkForData();
List<commandMessage> tempQueue = new List<commandMessage>();
tempQueue = clientQueue;
if (clientQueue.Count > 1)
{
//lock(serverQueue)
//{
clientQueue.Clear();
//}
}
return tempQueue;
}
public void checkForData()
{
commandMessage cmd = new commandMessage();
cmd.command = Int32.MaxValue;
int bufSize = 1500;
byte[] buffer = new byte[bufSize];
if (clientStream.DataAvailable)
{
byte [] messageSizeBytes = new byte[4];
byte[] addressBytes = new byte[4];
byte[] portBytes = new byte[4];
byte [] cmdBytes = new byte[4];
byte [] fileSizeBytes = new byte[4];
byte [] fileNameSizeBytes = new byte[4];
int messageSize, fileSize, fileNameSize, cmdNum, byteCnt;
IPAddress cmdIP;
string fileName;
//gotta process the data
int bytesRead = clientStream.Read(buffer,0,bufSize);
if (bytesRead > 0)
{
byteCnt = 0;
System.Buffer.BlockCopy(buffer, byteCnt, messageSizeBytes, 0, messageSizeBytes.Length);
byteCnt += messageSizeBytes.Length;
messageSize = BitConverter.ToInt32(messageSizeBytes,0);
//messageSize should never be greater than 1500 in this case
System.Buffer.BlockCopy(buffer, byteCnt, addressBytes, 0, addressBytes.Length);
byteCnt += addressBytes.Length;
//cmdIP = IPAddress.Parse(
string address = "";
if (addressBytes.Length == 4)
{
address = addressBytes[0].ToString() + "." + addressBytes[1].ToString() + "." +
addressBytes[2].ToString() + "." + addressBytes[3].ToString();
}
cmd.peerIP = IPAddress.Parse(address);
System.Buffer.BlockCopy(buffer, byteCnt, portBytes, 0, portBytes.Length);
byteCnt += portBytes.Length;
cmd.port = BitConverter.ToInt32(portBytes,0);
System.Buffer.BlockCopy(buffer, byteCnt, cmdBytes, 0, cmdBytes.Length);
byteCnt += cmdBytes.Length;
cmd.command = BitConverter.ToInt32(cmdBytes,0);
System.Buffer.BlockCopy(buffer, byteCnt, fileSizeBytes, 0, fileSizeBytes.Length);
byteCnt += fileSizeBytes.Length;
fileSize = BitConverter.ToInt32(fileSizeBytes, 0);
System.Buffer.BlockCopy(buffer, byteCnt, fileNameSizeBytes, 0, fileNameSizeBytes.Length);
byteCnt += fileNameSizeBytes.Length;
fileNameSize = BitConverter.ToInt32(fileNameSizeBytes, 0);
UTF8Encoding utf8 = new UTF8Encoding();
byte[] fileNameBytes = new byte[fileNameSize];
System.Buffer.BlockCopy(buffer, byteCnt, fileNameBytes, 0, fileNameSize);
cmd.fileName = utf8.GetString(fileNameBytes);
clientQueue.Add(cmd);
}
}
}
public void connectToServer()
{
IPHostEntry serverIP = Dns.GetHostEntry(myServer.peerIP.ToString());
tcpClient = new TcpClient(serverIP.HostName, myServer.peerPort);
clientStream = tcpClient.GetStream();
//Int32 messageID = 1; //add client
//int clientMsgStreamLength = (int)(4 * sizeof(Int32));
//byte[] buffer = new byte[4096];
//byte[] intBytes = BitConverter.GetBytes(clientMsgStreamLength);
//byte[] addressBytes = ServerExperiment.Program.myAddress.GetAddressBytes();
//byte[] portBytes = BitConverter.GetBytes(ServerExperiment.Program.myPort);
//byte[] messageBytes = BitConverter.GetBytes(messageID);
//System.Buffer.BlockCopy(intBytes, 0, buffer, 0, intBytes.Length); //prepends length to buffer
//System.Buffer.BlockCopy(addressBytes, 0, buffer, 4, addressBytes.Length);
//System.Buffer.BlockCopy(portBytes, 0, buffer, 8, portBytes.Length);
//System.Buffer.BlockCopy(messageBytes, 0, buffer, 12, messageBytes.Length);
//clientStream.Write(buffer, 0, clientMsgStreamLength);
//clientStream.Flush();
////wait for ACK from server
//int bytesRead = clientStream.Read(buffer, 0, 4096);
//byte[] message = new byte[4092];
//byte[] messageLength = new byte[4];
//int numMessageBytes = 0;
//int nextMsgBytesRead = 0;
//if (bytesRead > 3)
//{
// //strip off first 4 bytes and get the message length
// System.Buffer.BlockCopy(buffer, 0, messageLength, 0, sizeof(Int32));
// numMessageBytes = BitConverter.ToInt32(messageLength, 0);
//}
//while (bytesRead < numMessageBytes)
//{
// nextMsgBytesRead = clientStream.Read(buffer, bytesRead, 4096 - bytesRead);
// bytesRead += nextMsgBytesRead;
// //bugbug - need a watchdog timer for timeouts
// //bugbug - need to handle the case of more data than expected from the network
//}
//byte[] ackMessage = new byte[4];
//int ackNum = -99;
//System.Buffer.BlockCopy(buffer, 4, ackMessage, 0, 4);
//ackNum = BitConverter.ToInt32(ackMessage, 0);
}
public void SendCmd (socketSrv.commandMessage cmd)
{
byte [] buffer = new byte[1500];
byte [] cmdBytes = new byte[4];
byte [] msgLenBytes = new byte[4];
byte [] addressBytes = new byte[4];
byte [] portBytes = new byte[4];
byte[] fileNameBytes = new byte[75];
byte[] fileNameSizeBytes = new byte[4];
byte[] fileSizeBytes = new byte[4];
switch( cmd.command)
{
case 2: //get file
//Console.WriteLine("\nSent request to server machine");
//int basicCmdLen = 16;
int byteCnt = 4;
cmdBytes = BitConverter.GetBytes(cmd.command);
//msgLenBytes = BitConverter.GetBytes(basicCmdLen);
addressBytes = cmd.peerIP.GetAddressBytes();
portBytes = BitConverter.GetBytes(cmd.port);
//System.Buffer.BlockCopy(msgLenBytes, 0, buffer, byteCnt, msgLenBytes.Length);
//byteCnt += msgLenBytes.Length;
System.Buffer.BlockCopy(addressBytes, 0, buffer, byteCnt, addressBytes.Length);
byteCnt += addressBytes.Length;
System.Buffer.BlockCopy(portBytes, 0, buffer, byteCnt, portBytes.Length);
byteCnt += portBytes.Length;
System.Buffer.BlockCopy(cmdBytes, 0, buffer, byteCnt, cmdBytes.Length);
byteCnt += cmdBytes.Length;
UTF8Encoding utf8 = new UTF8Encoding();
fileNameBytes = utf8.GetBytes(cmd.fileName);
int fileNameLen = utf8.GetByteCount(cmd.fileName);
fileSizeBytes = BitConverter.GetBytes(0);
fileNameSizeBytes = BitConverter.GetBytes(fileNameLen);
System.Buffer.BlockCopy(fileSizeBytes, 0, buffer, byteCnt, fileSizeBytes.Length);
byteCnt += fileSizeBytes.Length;
System.Buffer.BlockCopy(fileNameSizeBytes, 0, buffer, byteCnt, fileNameSizeBytes.Length);
byteCnt += fileNameSizeBytes.Length;
System.Buffer.BlockCopy(fileNameBytes, 0, buffer, byteCnt, fileNameLen);
int msgLen = byteCnt + fileNameLen;
msgLenBytes = BitConverter.GetBytes(msgLen);
System.Buffer.BlockCopy(msgLenBytes, 0, buffer, 0, msgLenBytes.Length);
clientStream.Write(buffer, 0, msgLen);
Console.WriteLine("Sent a message of {0} bytes asking for file", msgLen);
break;
case 3: //put file
Console.WriteLine("got a put");
break;
}
}
void timer_Elapsed(object sender, ElapsedEventArgs e)
{
Console.WriteLine("Sent data");
Int32 messageID = 0;
int clientMsgStreamLength = (int)(2 * sizeof(Int32));
byte[] buffer = new byte[4096];
byte[] intBytes = BitConverter.GetBytes(clientMsgStreamLength);
byte[] messageBytes = BitConverter.GetBytes(messageID);
System.Buffer.BlockCopy(intBytes, 0, buffer, 0, 4); //prepends length to buffer
System.Buffer.BlockCopy(messageBytes, 0, buffer, 4, messageBytes.Length);
clientStream.Write(buffer, 0, clientMsgStreamLength);
clientStream.Flush();
}
}
}
| |
/********************************************************************
The Multiverse Platform is made available under the MIT License.
Copyright (c) 2012 The Multiverse Foundation
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify,
merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
OR OTHER DEALINGS IN THE SOFTWARE.
*********************************************************************/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.IO;
using Microsoft.Win32;
namespace MVImportTool
{
public partial class SourceFileSelector : UserControl
{
#region Properties set by the user
/// <summary>
/// This is the folder selected by the user for source files. The
/// property is writable to restore saved settings.
/// </summary>
public string Folder
{
get { return SourceFolderControl.FolderPath; }
set { SetSourceFileFolder( value ); }
}
/// <summary>
/// This is a regular expression that filters files selected in the
/// source folder. The property is writable to restore saved settings.
/// </summary>
public string FileFilter
{
get { return FilterTextBox.Text; }
set
{
FilterTextBox.Text = value;
PopulateSourceFileList();
}
}
/// <summary>
/// This gets the files that are checked in the UI. The list is not
/// saved in the settings, so it is not writable.
/// </summary>
public List<FileInfo> CheckedFiles
{
get
{
List<FileInfo> files = new List<FileInfo>();
foreach( FileInfo info in SourceFileListBox.CheckedItems )
{
files.Add( info );
}
return files;
}
}
#endregion Properties set by the user
FileSystemWatcher m_FileWatcher = new FileSystemWatcher();
public SourceFileSelector()
{
InitializeComponent();
}
private void SourceFileSelector_Load( object sender, EventArgs e )
{
SourceFolderControl.Description = "Select a folder containing COLLADA (.dae) files to convert";
SourceFolderControl.FolderChanged += OnFolderChanged;
ColladaFilesToolTip.SetToolTip( this.FilterTextBox,
"Regular Expression that filters the files \n" +
"displayed from the selected folder." );
m_FileWatcher.BeginInit();
m_FileWatcher.Created += OnFileAddedOrRemoved;
m_FileWatcher.Deleted += OnFileAddedOrRemoved;
m_FileWatcher.Renamed += OnFileRenamed;
m_FileWatcher.EndInit();
}
private void OnFolderChanged( object sender, DirectoryControl.StringEventArgs args )
{
SetSourceFileFolder( args.Value );
}
private void OnFileAddedOrRemoved( object source, FileSystemEventArgs args )
{
CrossThreadPopulateSourceFileList();
}
private void OnFileRenamed( object source, RenamedEventArgs args )
{
CrossThreadPopulateSourceFileList();
}
private void SetSourceFileFolder( string folderPath )
{
m_FileWatcher.EnableRaisingEvents = false;
SourceFolderControl.FolderPath = folderPath;
if( Directory.Exists( folderPath ) )
{
PopulateSourceFileList();
m_FileWatcher.Path = folderPath;
m_FileWatcher.EnableRaisingEvents = true;
}
}
// Add files in the selected directory to the checked list box; items
// are added unchecked, the assumption being that the common action is
// to work on one file at a time.
//
// Files in the selected directory are filtered by the 'File Filter'
// string, which is treated as a regular expression. If the filter
// is empty, it is considered to be the same as '*'.
private void PopulateSourceFileList()
{
if( SourceFolderControl.FolderPath.Equals( String.Empty ) )
{
// Early exit for uninitialized path
return;
}
DirectoryInfo dirInfo = new DirectoryInfo( SourceFolderControl.FolderPath );
if( dirInfo.Exists )
{
SourceFileListBox.BeginUpdate();
SourceFileListBox.Items.Clear();
string fileFilter =
FilterTextBox.Text.Equals( String.Empty )
? "*" : FilterTextBox.Text;
foreach( FileInfo fileInfo in dirInfo.GetFiles( fileFilter ) )
{
SourceFileListBox.Items.Add( fileInfo, false );
}
SourceFileListBox.EndUpdate();
}
}
// This is a wrapper that allows a control to be updated in response to
// an event on a different thread from the one that owns the list box.
// This comes up when the file watcher issues events.
private delegate void PopulateCallback();
private void CrossThreadPopulateSourceFileList()
{
if( this.SourceFileListBox.InvokeRequired )
{
PopulateCallback pcb = new PopulateCallback( CrossThreadPopulateSourceFileList );
this.Invoke( pcb );
}
else
{
PopulateSourceFileList();
}
}
private void FilterTextBox_KeyDown( object sender, KeyEventArgs e )
{
if( e.KeyValue.Equals( '\r' ) )
{
PopulateSourceFileList();
}
}
private void CheckAllButton_Click( object sender, EventArgs e )
{
for( int i = 0; i < SourceFileListBox.Items.Count; i++ )
{
SourceFileListBox.SetItemCheckState( i, CheckState.Checked );
}
}
private void ClearAllButton_Click( object sender, EventArgs e )
{
for( int i = 0; i < SourceFileListBox.Items.Count; i++ )
{
SourceFileListBox.SetItemCheckState( i, CheckState.Unchecked );
}
}
}
}
| |
using System;
using System.Linq;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media.Animation;
using Windows.UI.Xaml.Navigation;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
using Windows.ApplicationModel.Background;
using AppStudio.Views;
using AppStudio.Services;
#if WINDOWS_APP
using Windows.UI.ApplicationSettings;
#endif
#if WINDOWS_PHONE_APP
using Windows.Phone.UI.Input;
#endif
namespace AppStudio
{
/// <summary>
/// Provides application-specific behavior to supplement the default Application class.
/// </summary>
public sealed partial class App : Application
{
public const string APP_NAME = "HeroProApp";
#if WINDOWS_PHONE_APP
private TransitionCollection transitions;
#endif
/// <summary>
/// Initializes the singleton application object. This is the first line of authored code
/// executed, and as such is the logical equivalent of main() or WinMain().
/// </summary>
public App()
{
this.InitializeComponent();
this.Suspending += this.OnSuspending;
#if WINDOWS_PHONE_APP
HardwareButtons.BackPressed += OnBackPressed;
#endif
}
static public Frame RootFrame { get; private set; }
#if WINDOWS_PHONE_APP
/// <summary>
/// Handles back button press. If app is at the root page of app, don't go back and the
/// system will suspend the app.
/// </summary>
/// <param name="sender">The source of the BackPressed event.</param>
/// <param name="e">Details for the BackPressed event.</param>
private void OnBackPressed(object sender, BackPressedEventArgs e)
{
RootFrame = Window.Current.Content as Frame;
if (RootFrame == null)
{
return;
}
if (RootFrame.CanGoBack)
{
RootFrame.GoBack();
e.Handled = true;
}
}
#endif
/// <summary>
/// Invoked when the application is launched normally by the end user. Other entry points
/// will be used when the application is launched to open a specific file, to display
/// search results, and so forth.
/// </summary>
/// <param name="e">Details about the launch request and process.</param>
protected override void OnLaunched(LaunchActivatedEventArgs e)
{
#if DEBUG
if (System.Diagnostics.Debugger.IsAttached)
{
this.DebugSettings.EnableFrameRateCounter = true;
}
#endif
RootFrame = Window.Current.Content as Frame;
// Do not repeat app initialization when the Window already has content,
// just ensure that the window is active
if (RootFrame == null)
{
UpdateAppTiles();
// Create a Frame to act as the navigation context and navigate to the first page
RootFrame = new Frame();
// TODO: change this value to a cache size that is appropriate for your application
RootFrame.CacheSize = 1;
if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
{
// TODO: Load state from previously suspended application
}
// Place the frame in the current Window
Window.Current.Content = RootFrame;
}
if (RootFrame.Content == null)
{
#if WINDOWS_PHONE_APP
// Removes the turnstile navigation for startup.
if (RootFrame.ContentTransitions != null)
{
this.transitions = new TransitionCollection();
foreach (var c in RootFrame.ContentTransitions)
{
this.transitions.Add(c);
}
}
RootFrame.ContentTransitions = null;
RootFrame.Navigated += this.RootFrame_FirstNavigated;
#endif
// When the navigation stack isn't restored navigate to the first page,
// configuring the new page by passing required information as a navigation
// parameter
if (!RootFrame.Navigate(typeof(Views.MainPage), e.Arguments))
{
throw new Exception("Failed to create initial page");
}
}
// Ensure the current window is active
Window.Current.Activate();
}
#if WINDOWS_PHONE_APP
/// <summary>
/// Restores the content transitions after the app has launched.
/// </summary>
/// <param name="sender">The object where the handler is attached.</param>
/// <param name="e">Details about the navigation event.</param>
private void RootFrame_FirstNavigated(object sender, NavigationEventArgs e)
{
var rootFrame = sender as Frame;
rootFrame.ContentTransitions = this.transitions ?? new TransitionCollection() { new NavigationThemeTransition() };
rootFrame.Navigated -= this.RootFrame_FirstNavigated;
}
#endif
/// <summary>
/// Invoked when application execution is being suspended. Application state is saved
/// without knowing whether the application will be terminated or resumed with the contents
/// of memory still intact.
/// </summary>
/// <param name="sender">The source of the suspend request.</param>
/// <param name="e">Details about the suspend request.</param>
private void OnSuspending(object sender, SuspendingEventArgs e)
{
var deferral = e.SuspendingOperation.GetDeferral();
// TODO: Save application state and stop any background activity
deferral.Complete();
}
#if WINDOWS_APP
protected override void OnWindowCreated(WindowCreatedEventArgs args)
{
SettingsPane.GetForCurrentView().CommandsRequested += OnCommandsRequested;
base.OnWindowCreated(args);
}
private void OnCommandsRequested(SettingsPane sender, SettingsPaneCommandsRequestedEventArgs args)
{
args.Request.ApplicationCommands.Add(new SettingsCommand("License", "License", (handler) => ShowLicenseSettingFlyout()));
args.Request.ApplicationCommands.Add(new SettingsCommand("Privacy", "Privacy", (handler) => ShowPrivacySettingFlyout()));
}
private void ShowLicenseSettingFlyout()
{
var flyout = new LicenseFlyout();
flyout.Show();
}
private void ShowPrivacySettingFlyout()
{
var flyout = new PrivacyFlyout();
flyout.Show();
}
#endif
#region App Tiles
private void UpdateAppTiles()
{
TileServices.CreateFlipTile("", "GoPro, be a HERO!", "DataImages/FlipSquareTile.jpg", "DataImages/FlipWideTile.jpg");
}
#endregion
}
}
| |
using JetBrains.Annotations;
using Nuke.Common;
using Nuke.Common.CI;
using Nuke.Common.Execution;
using Nuke.Common.Git;
using Nuke.Common.IO;
using Nuke.Common.ProjectModel;
using Nuke.Common.Tooling;
using Nuke.Common.Tools.DotNet;
using Nuke.Common.Tools.Git;
using Nuke.Common.Tools.GitVersion;
using Nuke.Common.Utilities;
using Nuke.Common.Utilities.Collections;
using Nuke.GitHub;
using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using static Nuke.Common.IO.CompressionTasks;
using static Nuke.Common.IO.FileSystemTasks;
using static Nuke.Common.IO.PathConstruction;
using static Nuke.Common.Tools.DotNet.DotNetTasks;
using static Nuke.GitHub.GitHubTasks;
using static Nuke.Common.ChangeLog.ChangelogTasks;
[CheckBuildProjectConfigurations]
[ShutdownDotNetAfterServerBuild]
[SuppressMessage("ReSharper", "InconsistentNaming")]
class Build : NukeBuild
{
/// Support plugins are available for:
/// - JetBrains ReSharper https://nuke.build/resharper
/// - JetBrains Rider https://nuke.build/rider
/// - Microsoft VisualStudio https://nuke.build/visualstudio
/// - Microsoft VSCode https://nuke.build/vscode
public static int Main() => Execute<Build>(x => x.Default);
static readonly string[] DefaultPublishTargets =
{
"win-x64",
// "linux-x64"
};
const string NuGetDefaultUrl = "https://api.nuget.org/v3/index.json";
[Parameter("NuGet Source - Defaults to the value of the environment variable 'NUGET_SOURCE' or '" + NuGetDefaultUrl + "'")]
string NuGetSource;
[Parameter("NuGet API Key - Defaults to the value of the environment variable 'NUGET_API_KEY'")]
string NuGetApiKey;
[Parameter("Publish Target Runtime Identifiers for building self-contained applications - Default is ['win-x64', 'linux-x64']")]
string[] PublishTargets = DefaultPublishTargets;
[Parameter("Skip Tests - Default is 'false'")]
readonly bool SkipTests;
[Parameter("Configuration to build - Default is 'Debug' (local) or 'Release' (server)")]
readonly Configuration Configuration = IsLocalBuild ? Configuration.Debug : Configuration.Release;
[Parameter("(Optional) GitHub Authentication Token for uploading releases - Defaults to the value of the GITHUB_API_TOKEN environment variable")]
string GitHubAuthenticationToken;
[Parameter("(Optional) Git remote id override")]
string GitRepositoryRemoteId;
[Parameter("(Optional) Path to the release notes for NuGet packages and GitHub releases.")]
AbsolutePath PackageReleaseNotesFile;
[Solution]
readonly Solution Solution;
GitRepository GitRepository;
[GitVersion(NoFetch = true, Framework = "net5.0")]
readonly GitVersion GitVersion;
string ChangeLogFile => RootDirectory / "CHANGELOG.md";
AbsolutePath SourceDirectory => RootDirectory / "src";
AbsolutePath SamplesDirectory => RootDirectory / "samples";
AbsolutePath ArtifactsDirectory => RootDirectory / "output";
AbsolutePath ArtifactsArchiveDirectory => RootDirectory / "build-artefacts";
AbsolutePath NuGetTargetDirectory => ArtifactsArchiveDirectory / GitVersion.SemVer / "nuget";
public Build()
{ }
protected override void OnBuildInitialized()
{
base.OnBuildInitialized();
if (string.IsNullOrEmpty(GitRepositoryRemoteId))
{
GitRepositoryRemoteId = "origin";
}
GitRepository = GitRepository.FromLocalDirectory(RootDirectory, null, GitRepositoryRemoteId);
PublishTargets ??= DefaultPublishTargets;
NuGetApiKey ??= Environment.GetEnvironmentVariable("NUGET_API_KEY");
NuGetSource ??= Environment.GetEnvironmentVariable("NUGET_SOURCE") ?? NuGetDefaultUrl;
GitHubAuthenticationToken ??= Environment.GetEnvironmentVariable("GITHUB_API_TOKEN");
}
Target Clean => _ => _
.Before(Restore)
.Executes(() =>
{
EnsureCleanDirectory(ArtifactsDirectory);
DotNetClean(s => s.SetProject(Solution)
.SetConfiguration(Configuration)
.SetAssemblyVersion(GitVersion.AssemblySemVer)
.SetFileVersion(GitVersion.AssemblySemFileVer)
.SetInformationalVersion(GitVersion.InformationalVersion));
});
Target Restore => _ => _
.Executes(() =>
{
DotNetRestore(s => s.SetProjectFile(Solution));
});
Target Compile => _ =>
_
.DependsOn(Restore)
.Executes(() =>
{
Logger.Info($"Building with version {GitVersion.AssemblySemFileVer}");
DotNetBuild(s => s
.SetProjectFile(Solution)
.SetConfiguration(Configuration)
.SetAssemblyVersion(GitVersion.AssemblySemVer)
.SetFileVersion(GitVersion.AssemblySemFileVer)
.SetInformationalVersion(GitVersion.InformationalVersion)
.EnableNoRestore());
});
Target Test => _ =>
_
.DependsOn(Compile)
.Executes(() =>
{
if (SkipTests)
{
return;
}
DotNetTest(s => s.SetProjectFile(Solution)
.SetConfiguration(Configuration)
.EnableNoRestore());
});
Target Pack => _ =>
_.DependsOn(Test)
.Executes(() =>
{
string releaseNotes = null;
if (!string.IsNullOrEmpty(PackageReleaseNotesFile) && File.Exists(PackageReleaseNotesFile))
{
releaseNotes = TextTasks.ReadAllText(PackageReleaseNotesFile);
}
DotNetPack(s => s.SetProject(Solution)
.SetConfiguration(Configuration)
.SetVersion(GitVersion.NuGetVersionV2)
.SetSymbolPackageFormat(DotNetSymbolPackageFormat.snupkg)
.EnableIncludeSymbols()
.EnableIncludeSource()
.EnableNoRestore()
.When(!string.IsNullOrEmpty(releaseNotes), x => x.SetPackageReleaseNotes(releaseNotes)));
GlobFiles(ArtifactsDirectory, "**/*.nupkg")
.NotEmpty()
.ForEach(absPath =>
{
Logger.Info(absPath);
var fileName = Path.GetFileName(absPath);
CopyFile(absPath, NuGetTargetDirectory / fileName, FileExistsPolicy.OverwriteIfNewer);
});
GlobFiles(ArtifactsDirectory, "**/*.snupkg")
.NotEmpty()
.ForEach(absPath =>
{
Logger.Info(absPath);
var fileName = Path.GetFileName(absPath);
CopyFile(absPath, NuGetTargetDirectory / fileName, FileExistsPolicy.OverwriteIfNewer);
});
});
Target Publish => _ =>
_.DependsOn(Test)
.Executes(() =>
{
var projects = GlobFiles(SourceDirectory, "**/*.csproj")
.Concat(GlobFiles(SamplesDirectory, "**/*.csproj"));
foreach (var target in PublishTargets)
{
var runtimeValue = target;
foreach (var projectFile in projects)
{
Logger.Info("Processing " + projectFile);
// parsing MSBuild projects is pretty much broken thanks to some
// buggy behaviour with MSBuild itself. For some reason MSBuild
// cannot load its own runtime and then simply crashes wildly
//
// https://github.com/dotnet/msbuild/issues/5706#issuecomment-687625355
// https://github.com/microsoft/MSBuildLocator/pull/79
//
// That issue is still active.
var project = new ProjectParser().Parse(projectFile, Configuration, runtimeValue);
if (project.OutputType != "WinExe" &&
project.OutputType != "Exe")
{
continue;
}
if (!project.IsValidPlatformFor(runtimeValue))
{
continue;
}
foreach (var framework in project.TargetFrameworks)
{
Logger.Info($"Processing {project.Name} with runtime {runtimeValue}");
DotNetPublish(s => s.SetProject(projectFile)
.SetAssemblyVersion(GitVersion.AssemblySemVer)
.SetFileVersion(GitVersion.AssemblySemFileVer)
.SetInformationalVersion(GitVersion.InformationalVersion)
.SetRuntime(runtimeValue)
.EnableSelfContained());
var buildTargetDir = ArtifactsDirectory / project.Name / "bin" / Configuration / framework;
var archiveTargetDir = ArtifactsArchiveDirectory / GitVersion.SemVer / "builds" / runtimeValue / framework;
var archiveFile = archiveTargetDir / $"{project.Name}-{GitVersion.SemVer}.zip";
DeleteFile(archiveFile);
CompressZip(buildTargetDir, archiveFile);
}
}
}
});
Target PushNuGet => _ =>
_.Description("Uploads all generated NuGet files to the configured NuGet server")
.OnlyWhenDynamic(() => !string.IsNullOrEmpty(NuGetSource))
.OnlyWhenDynamic(() => !string.IsNullOrEmpty(NuGetApiKey))
.Executes(() =>
{
GlobFiles(NuGetTargetDirectory, "*.nupkg")
.Where(x => !x.EndsWith(".symbols.nupkg"))
.ForEach(x =>
{
DotNetNuGetPush(s => s.SetTargetPath(x)
.EnableSkipDuplicate()
.EnableNoServiceEndpoint()
.SetSource(NuGetSource)
.SetApiKey(NuGetApiKey));
});
});
Target PublishGitHubRelease => _ =>
_.Description("Uploads all generated package files to GitHub")
.OnlyWhenDynamic(() => !string.IsNullOrEmpty(GitHubAuthenticationToken))
.OnlyWhenDynamic(() => IsGitHubRepository())
.Executes<Task>(async () =>
{
var releaseTag = $"v{GitVersion.MajorMinorPatch}";
string releaseNotes = null;
if (!string.IsNullOrEmpty(PackageReleaseNotesFile) && File.Exists(PackageReleaseNotesFile))
{
releaseNotes = TextTasks.ReadAllText(PackageReleaseNotesFile);
}
var repositoryInfo = GetGitHubRepositoryInfo(GitRepository);
var releaseArtefacts = GlobFiles(NuGetTargetDirectory, "*.nupkg")
.Concat(GlobFiles(NuGetTargetDirectory, "*.snupkg"))
.Concat(GlobFiles(ArtifactsArchiveDirectory / GitVersion.SemVer / "builds", "**/*.zip"))
.ToArray();
if (releaseArtefacts.Length > 0)
{
await PublishRelease(x => x.SetArtifactPaths(releaseArtefacts)
.SetCommitSha(GitVersion.Sha)
.SetReleaseNotes(releaseNotes)
.SetRepositoryName(repositoryInfo.repositoryName)
.SetRepositoryOwner(repositoryInfo.gitHubOwner)
.SetTag(releaseTag)
.SetToken(GitHubAuthenticationToken));
}
});
bool IsGitHubRepository()
{
return string.Equals(GitRepository?.Endpoint, "github.com");
}
Target Default => _ =>
_.Description("Builds the project and produces all release artefacts")
.DependsOn(Clean)
.DependsOn(Publish)
.DependsOn(Pack);
Target Upload => _ =>
_.Description("Uploads all generated release artefacts to the NuGet repository and GitHub")
.DependsOn(PushNuGet)
.DependsOn(PublishGitHubRelease);
}
| |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// Template Source: Templates\CSharp\Requests\EntityCollectionRequest.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Linq.Expressions;
/// <summary>
/// The type GroupSettingsCollectionRequest.
/// </summary>
public partial class GroupSettingsCollectionRequest : BaseRequest, IGroupSettingsCollectionRequest
{
/// <summary>
/// Constructs a new GroupSettingsCollectionRequest.
/// </summary>
/// <param name="requestUrl">The URL for the built request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
/// <param name="options">Query and header option name value pairs for the request.</param>
public GroupSettingsCollectionRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
}
/// <summary>
/// Adds the specified GroupSetting to the collection via POST.
/// </summary>
/// <param name="groupSetting">The GroupSetting to add.</param>
/// <returns>The created GroupSetting.</returns>
public System.Threading.Tasks.Task<GroupSetting> AddAsync(GroupSetting groupSetting)
{
return this.AddAsync(groupSetting, CancellationToken.None);
}
/// <summary>
/// Adds the specified GroupSetting to the collection via POST.
/// </summary>
/// <param name="groupSetting">The GroupSetting to add.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The created GroupSetting.</returns>
public System.Threading.Tasks.Task<GroupSetting> AddAsync(GroupSetting groupSetting, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "POST";
return this.SendAsync<GroupSetting>(groupSetting, cancellationToken);
}
/// <summary>
/// Gets the collection page.
/// </summary>
/// <returns>The collection page.</returns>
public System.Threading.Tasks.Task<IGroupSettingsCollectionPage> GetAsync()
{
return this.GetAsync(CancellationToken.None);
}
/// <summary>
/// Gets the collection page.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The collection page.</returns>
public async System.Threading.Tasks.Task<IGroupSettingsCollectionPage> GetAsync(CancellationToken cancellationToken)
{
this.Method = "GET";
var response = await this.SendAsync<GroupSettingsCollectionResponse>(null, cancellationToken).ConfigureAwait(false);
if (response != null && response.Value != null && response.Value.CurrentPage != null)
{
if (response.AdditionalData != null)
{
object nextPageLink;
response.AdditionalData.TryGetValue("@odata.nextLink", out nextPageLink);
var nextPageLinkString = nextPageLink as string;
if (!string.IsNullOrEmpty(nextPageLinkString))
{
response.Value.InitializeNextPageRequest(
this.Client,
nextPageLinkString);
}
// Copy the additional data collection to the page itself so that information is not lost
response.Value.AdditionalData = response.AdditionalData;
}
return response.Value;
}
return null;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
public IGroupSettingsCollectionRequest Expand(string value)
{
this.QueryOptions.Add(new QueryOption("$expand", value));
return this;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="expandExpression">The expression from which to calculate the expand value.</param>
/// <returns>The request object to send.</returns>
public IGroupSettingsCollectionRequest Expand(Expression<Func<GroupSetting, object>> expandExpression)
{
if (expandExpression == null)
{
throw new ArgumentNullException(nameof(expandExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(expandExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$expand", value));
}
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
public IGroupSettingsCollectionRequest Select(string value)
{
this.QueryOptions.Add(new QueryOption("$select", value));
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="selectExpression">The expression from which to calculate the select value.</param>
/// <returns>The request object to send.</returns>
public IGroupSettingsCollectionRequest Select(Expression<Func<GroupSetting, object>> selectExpression)
{
if (selectExpression == null)
{
throw new ArgumentNullException(nameof(selectExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(selectExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$select", value));
}
return this;
}
/// <summary>
/// Adds the specified top value to the request.
/// </summary>
/// <param name="value">The top value.</param>
/// <returns>The request object to send.</returns>
public IGroupSettingsCollectionRequest Top(int value)
{
this.QueryOptions.Add(new QueryOption("$top", value.ToString()));
return this;
}
/// <summary>
/// Adds the specified filter value to the request.
/// </summary>
/// <param name="value">The filter value.</param>
/// <returns>The request object to send.</returns>
public IGroupSettingsCollectionRequest Filter(string value)
{
this.QueryOptions.Add(new QueryOption("$filter", value));
return this;
}
/// <summary>
/// Adds the specified skip value to the request.
/// </summary>
/// <param name="value">The skip value.</param>
/// <returns>The request object to send.</returns>
public IGroupSettingsCollectionRequest Skip(int value)
{
this.QueryOptions.Add(new QueryOption("$skip", value.ToString()));
return this;
}
/// <summary>
/// Adds the specified orderby value to the request.
/// </summary>
/// <param name="value">The orderby value.</param>
/// <returns>The request object to send.</returns>
public IGroupSettingsCollectionRequest OrderBy(string value)
{
this.QueryOptions.Add(new QueryOption("$orderby", value));
return this;
}
}
}
| |
// This file is part of the C5 Generic Collection Library for C# and CLI
// See https://github.com/sestoft/C5/blob/master/LICENSE for licensing details.
using System;
using SCG = System.Collections.Generic;
namespace C5
{
/// <summary>
/// A bag collection based on a hash table of (item,count) pairs.
/// </summary>
[Serializable]
public class HashBag<T> : CollectionBase<T>, ICollection<T>
{
#region Fields
private HashSet<System.Collections.Generic.KeyValuePair<T, int>> dict;
#endregion
#region Events
/// <summary>
///
/// </summary>
/// <value></value>
public override EventType ListenableEvents => EventType.Basic;
#endregion
#region Constructors
/// <summary>
/// Create a hash bag with the default item equalityComparer.
/// </summary>
public HashBag() : this(EqualityComparer<T>.Default) { }
/// <summary>
/// Create a hash bag with an external item equalityComparer.
/// </summary>
/// <param name="itemequalityComparer">The external item equalityComparer.</param>
public HashBag(SCG.IEqualityComparer<T> itemequalityComparer)
: base(itemequalityComparer)
{
dict = new HashSet<System.Collections.Generic.KeyValuePair<T, int>>(new KeyValuePairEqualityComparer<T, int>(itemequalityComparer));
}
/// <summary>
/// Create a hash bag with external item equalityComparer, prescribed initial table size and default fill threshold (66%)
/// </summary>
/// <param name="capacity">Initial table size (rounded to power of 2, at least 16)</param>
/// <param name="itemequalityComparer">The external item equalitySCG.Comparer</param>
public HashBag(int capacity, SCG.IEqualityComparer<T> itemequalityComparer)
: base(itemequalityComparer)
{
dict = new HashSet<System.Collections.Generic.KeyValuePair<T, int>>(capacity, new KeyValuePairEqualityComparer<T, int>(itemequalityComparer));
}
/// <summary>
/// Create a hash bag with external item equalityComparer, prescribed initial table size and fill threshold.
/// </summary>
/// <param name="capacity">Initial table size (rounded to power of 2, at least 16)</param>
/// <param name="fill">Fill threshold (valid range 10% to 90%)</param>
/// <param name="itemequalityComparer">The external item equalitySCG.Comparer</param>
public HashBag(int capacity, double fill, SCG.IEqualityComparer<T> itemequalityComparer)
: base(itemequalityComparer)
{
dict = new HashSet<System.Collections.Generic.KeyValuePair<T, int>>(capacity, fill, new KeyValuePairEqualityComparer<T, int>(itemequalityComparer));
}
#endregion
#region IEditableCollection<T> Members
/// <summary>
/// The complexity of the Contains operation
/// </summary>
/// <value>Always returns Speed.Constant</value>
public virtual Speed ContainsSpeed => Speed.Constant;
/// <summary>
/// Check if an item is in the bag
/// </summary>
/// <param name="item">The item to look for</param>
/// <returns>True if bag contains item</returns>
public virtual bool Contains(T item)
{
return dict.Contains(new System.Collections.Generic.KeyValuePair<T, int>(item, 0));
}
/// <summary>
/// Check if an item (collection equal to a given one) is in the bag and
/// if so report the actual item object found.
/// </summary>
/// <param name="item">On entry, the item to look for.
/// On exit the item found, if any</param>
/// <returns>True if bag contains item</returns>
public virtual bool Find(ref T item)
{
System.Collections.Generic.KeyValuePair<T, int> p = new System.Collections.Generic.KeyValuePair<T, int>(item, 0);
if (dict.Find(ref p))
{
item = p.Key;
return true;
}
return false;
}
/// <summary>
/// Check if an item (collection equal to a given one) is in the bag and
/// if so replace the item object in the bag with the supplied one.
/// </summary>
/// <param name="item">The item object to update with</param>
/// <returns>True if item was found (and updated)</returns>
public virtual bool Update(T item)
{
return Update(item, out _);
}
/// <summary>
///
/// </summary>
/// <param name="item"></param>
/// <param name="olditem"></param>
/// <returns></returns>
public virtual bool Update(T item, out T olditem)
{
SCG.KeyValuePair<T, int> p = new SCG.KeyValuePair<T, int>(item, 0);
UpdateCheck();
//Note: we cannot just do dict.Update: we have to lookup the count before we
//know what to update with. There is of course a way around if we use the
//implementation of hashset -which we do not want to do.
//The hashbag is moreover mainly a proof of concept
if (dict.Find(ref p))
{
olditem = p.Key;
p = new SCG.KeyValuePair<T, int>(item, p.Value);
dict.Update(p);
if (ActiveEvents != 0)
{
RaiseForUpdate(item, olditem, p.Value);
}
return true;
}
olditem = default;
return false;
}
/// <summary>
/// Check if an item (collection equal to a given one) is in the bag.
/// If found, report the actual item object in the bag,
/// else add the supplied one.
/// </summary>
/// <param name="item">On entry, the item to look for or add.
/// On exit the actual object found, if any.</param>
/// <returns>True if item was found</returns>
public virtual bool FindOrAdd(ref T item)
{
UpdateCheck();
if (Find(ref item))
{
return true;
}
Add(item);
return false;
}
/// <summary>
/// Check if an item (collection equal to a supplied one) is in the bag and
/// if so replace the item object in the set with the supplied one; else
/// add the supplied one.
/// </summary>
/// <param name="item">The item to look for and update or add</param>
/// <returns>True if item was updated</returns>
public virtual bool UpdateOrAdd(T item)
{
UpdateCheck();
if (Update(item))
{
return true;
}
Add(item);
return false;
}
/// <summary>
///
/// </summary>
/// <param name="item"></param>
/// <param name="olditem"></param>
/// <returns></returns>
public virtual bool UpdateOrAdd(T item, out T olditem)
{
UpdateCheck();
if (Update(item, out olditem))
{
return true;
}
Add(item);
return false;
}
/// <summary>
/// Remove one copy of an item from the bag
/// </summary>
/// <param name="item">The item to remove</param>
/// <returns>True if item was (found and) removed </returns>
public virtual bool Remove(T item)
{
var p = new SCG.KeyValuePair<T, int>(item, 0);
UpdateCheck();
if (dict.Find(ref p))
{
size--;
if (p.Value == 1)
{
dict.Remove(p);
}
else
{
p = new SCG.KeyValuePair<T, int>(p.Key, p.Value - 1);
dict.Update(p);
}
if (ActiveEvents != 0)
{
RaiseForRemove(p.Key);
}
return true;
}
return false;
}
/// <summary>
/// Remove one copy of an item from the bag, reporting the actual matching item object.
/// </summary>
/// <param name="item">The value to remove.</param>
/// <param name="removeditem">The removed value.</param>
/// <returns>True if item was found.</returns>
public virtual bool Remove(T item, out T removeditem)
{
UpdateCheck();
SCG.KeyValuePair<T, int> p = new SCG.KeyValuePair<T, int>(item, 0);
if (dict.Find(ref p))
{
removeditem = p.Key;
size--;
if (p.Value == 1)
{
dict.Remove(p);
}
else
{
p = new SCG.KeyValuePair<T, int>(p.Key, p.Value - 1);
dict.Update(p);
}
if (ActiveEvents != 0)
{
RaiseForRemove(removeditem);
}
return true;
}
removeditem = default;
return false;
}
/// <summary>
/// Remove all items in a supplied collection from this bag, counting multiplicities.
/// </summary>
/// <param name="items">The items to remove.</param>
public virtual void RemoveAll(SCG.IEnumerable<T> items)
{
#warning Improve if items is a counting bag
UpdateCheck();
bool mustRaise = (ActiveEvents & (EventType.Changed | EventType.Removed)) != 0;
RaiseForRemoveAllHandler? raiseHandler = mustRaise ? new RaiseForRemoveAllHandler(this) : null;
foreach (T item in items)
{
SCG.KeyValuePair<T, int> p = new SCG.KeyValuePair<T, int>(item, 0);
if (dict.Find(ref p))
{
size--;
if (p.Value == 1)
{
dict.Remove(p);
}
else
{
p = new SCG.KeyValuePair<T, int>(p.Key, p.Value - 1);
dict.Update(p);
}
if (mustRaise)
{
raiseHandler?.Remove(p.Key);
}
}
}
if (mustRaise)
{
raiseHandler?.Raise();
}
}
/// <summary>
/// Remove all items from the bag, resetting internal table to initial size.
/// </summary>
public virtual void Clear()
{
UpdateCheck();
if (size == 0)
{
return;
}
dict.Clear();
int oldsize = size;
size = 0;
if ((ActiveEvents & EventType.Cleared) != 0)
{
RaiseCollectionCleared(true, oldsize);
}
if ((ActiveEvents & EventType.Changed) != 0)
{
RaiseCollectionChanged();
}
}
/// <summary>
/// Remove all items *not* in a supplied collection from this bag,
/// counting multiplicities.
/// </summary>
/// <param name="items">The items to retain</param>
public virtual void RetainAll(SCG.IEnumerable<T> items)
{
UpdateCheck();
HashBag<T> res = new HashBag<T>(itemequalityComparer);
foreach (T item in items)
{
SCG.KeyValuePair<T, int> p = new SCG.KeyValuePair<T, int>(item, default);
if (dict.Find(ref p))
{
SCG.KeyValuePair<T, int> q = p;
if (res.dict.Find(ref q))
{
if (q.Value < p.Value)
{
q = new SCG.KeyValuePair<T, int>(q.Key, q.Value + 1);
res.dict.Update(q);
res.size++;
}
}
else
{
q = new SCG.KeyValuePair<T, int>(q.Key, 1);
res.dict.Add(q);
res.size++;
}
}
}
if (size == res.size)
{
return;
}
CircularQueue<T>? wasRemoved = null;
if ((ActiveEvents & EventType.Removed) != 0)
{
wasRemoved = new CircularQueue<T>();
foreach (SCG.KeyValuePair<T, int> p in dict)
{
int removed = p.Value - res.ContainsCount(p.Key);
if (removed > 0)
{
#warning We could send bag events here easily using a CircularQueue of (should?)
for (int i = 0; i < removed; i++)
{
wasRemoved.Enqueue(p.Key);
}
}
}
}
dict = res.dict;
size = res.size;
if ((ActiveEvents & EventType.Removed) != 0)
{
RaiseForRemoveAll(wasRemoved);
}
else if ((ActiveEvents & EventType.Changed) != 0)
{
RaiseCollectionChanged();
}
}
/// <summary>
/// Check if all items in a supplied collection is in this bag
/// (counting multiplicities).
/// </summary>
/// <param name="items">The items to look for.</param>
/// <returns>True if all items are found.</returns>
public virtual bool ContainsAll(SCG.IEnumerable<T> items)
{
HashBag<T> res = new HashBag<T>(itemequalityComparer);
foreach (T item in items)
{
if (res.ContainsCount(item) < ContainsCount(item))
{
res.Add(item);
}
else
{
return false;
}
}
return true;
}
/// <summary>
/// Create an array containing all items in this bag (in enumeration order).
/// </summary>
/// <returns>The array</returns>
public override T[] ToArray()
{
T[] res = new T[size];
int ind = 0;
foreach (System.Collections.Generic.KeyValuePair<T, int> p in dict)
{
for (int i = 0; i < p.Value; i++)
{
res[ind++] = p.Key;
}
}
return res;
}
/// <summary>
/// Count the number of times an item is in this set.
/// </summary>
/// <param name="item">The item to look for.</param>
/// <returns>The count</returns>
public virtual int ContainsCount(T item)
{
System.Collections.Generic.KeyValuePair<T, int> p = new System.Collections.Generic.KeyValuePair<T, int>(item, 0);
if (dict.Find(ref p))
{
return p.Value;
}
return 0;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public virtual ICollectionValue<T> UniqueItems() { return new DropMultiplicity<T>(dict); }
/// <summary>
///
/// </summary>
/// <returns></returns>
public virtual ICollectionValue<System.Collections.Generic.KeyValuePair<T, int>> ItemMultiplicities()
{
return new GuardedCollectionValue<System.Collections.Generic.KeyValuePair<T, int>>(dict);
}
/// <summary>
/// Remove all copies of item from this set.
/// </summary>
/// <param name="item">The item to remove</param>
public virtual void RemoveAllCopies(T item)
{
UpdateCheck();
System.Collections.Generic.KeyValuePair<T, int> p = new System.Collections.Generic.KeyValuePair<T, int>(item, 0);
if (dict.Find(ref p))
{
size -= p.Value;
dict.Remove(p);
if ((ActiveEvents & EventType.Removed) != 0)
{
RaiseItemsRemoved(p.Key, p.Value);
}
if ((ActiveEvents & EventType.Changed) != 0)
{
RaiseCollectionChanged();
}
}
}
#endregion
#region ICollection<T> Members
/// <summary>
/// Copy the items of this bag to part of an array.
/// <exception cref="ArgumentOutOfRangeException"/> if i is negative.
/// <exception cref="ArgumentException"/> if the array does not have room for the items.
/// </summary>
/// <param name="array">The array to copy to</param>
/// <param name="index">The starting index.</param>
public override void CopyTo(T[] array, int index)
{
if (index < 0 || index + Count > array.Length)
{
throw new ArgumentOutOfRangeException();
}
foreach (System.Collections.Generic.KeyValuePair<T, int> p in dict)
{
for (int j = 0; j < p.Value; j++)
{
array[index++] = p.Key;
}
}
}
#endregion
#region IExtensible<T> Members
/// <summary>
/// Report if this is a set collection.
/// </summary>
/// <value>Always true</value>
public virtual bool AllowsDuplicates => true;
/// <summary>
/// By convention this is true for any collection with set semantics.
/// </summary>
/// <value>True if only one representative of a group of equal items
/// is kept in the collection together with the total count.</value>
public virtual bool DuplicatesByCounting => true;
/// <summary>
/// Add an item to this bag.
/// </summary>
/// <param name="item">The item to add.</param>
/// <returns>Always true</returns>
public virtual bool Add(T item)
{
UpdateCheck();
Add(ref item);
if (ActiveEvents != 0)
{
RaiseForAdd(item);
}
return true;
}
/// <summary>
/// Add an item to this bag.
/// </summary>
/// <param name="item">The item to add.</param>
void SCG.ICollection<T>.Add(T item)
{
Add(item);
}
private void Add(ref T item)
{
var p = new SCG.KeyValuePair<T, int>(item, 1);
if (dict.Find(ref p))
{
p = new SCG.KeyValuePair<T, int>(item, p.Value + 1);
dict.Update(p);
item = p.Key;
}
else
{
dict.Add(p);
}
size++;
}
/// <summary>
/// Add the elements from another collection with a more specialized item type
/// to this collection.
/// </summary>
/// <param name="items">The items to add</param>
public virtual void AddAll(SCG.IEnumerable<T> items)
{
UpdateCheck();
#warning We could easily raise bag events
bool mustRaiseAdded = (ActiveEvents & EventType.Added) != 0;
CircularQueue<T>? wasAdded = mustRaiseAdded ? new CircularQueue<T>() : null;
bool wasChanged = false;
foreach (T item in items)
{
T jtem = item;
Add(ref jtem);
wasChanged = true;
if (mustRaiseAdded)
{
wasAdded?.Enqueue(jtem);
}
}
if (!wasChanged)
{
return;
}
if (mustRaiseAdded)
{
if (wasAdded != null)
{
foreach (T item in wasAdded)
{
RaiseItemsAdded(item, 1);
}
}
}
if ((ActiveEvents & EventType.Changed) != 0)
{
RaiseCollectionChanged();
}
}
#endregion
#region IEnumerable<T> Members
/// <summary>
/// Choose some item of this collection.
/// </summary>
/// <exception cref="NoSuchItemException">if collection is empty.</exception>
/// <returns></returns>
public override T Choose()
{
return dict.Choose().Key;
}
/// <summary>
/// Create an enumerator for this bag.
/// </summary>
/// <returns>The enumerator</returns>
public override SCG.IEnumerator<T> GetEnumerator()
{
int left;
int mystamp = stamp;
foreach (System.Collections.Generic.KeyValuePair<T, int> p in dict)
{
left = p.Value;
while (left > 0)
{
if (mystamp != stamp)
{
throw new CollectionModifiedException();
}
left--;
yield return p.Key;
}
}
}
#endregion
#region Diagnostics
/// <summary>
/// Test internal structure of data (invariants)
/// </summary>
/// <returns>True if pass</returns>
public virtual bool Check()
{
bool retval = dict.Check();
int count = 0;
foreach (System.Collections.Generic.KeyValuePair<T, int> p in dict)
{
count += p.Value;
}
if (count != size)
{
Logger.Log(string.Format("count({0}) != size({1})", count, size));
retval = false;
}
return retval;
}
#endregion
}
}
| |
// ByteFX.Data data access components for .Net
// Copyright (C) 2002-2003 ByteFX, Inc.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using System;
using System.Net;
using System.Net.Sockets;
using System.IO;
using ICSharpCode.SharpZipLib.Zip.Compression;
using ICSharpCode.SharpZipLib.Zip.Compression.Streams;
using System.Security.Cryptography;
using ByteFX.Data.Common;
using System.Collections;
using System.Text;
namespace ByteFX.Data.MySqlClient
{
/// <summary>
/// Summary description for Driver.
/// </summary>
internal class Driver
{
protected const int HEADER_LEN = 4;
protected const int MIN_COMPRESS_LENGTH = 50;
protected const int MAX_PACKET_SIZE = 256*256*256-1;
protected Stream stream;
protected BufferedStream writer;
protected Encoding encoding;
protected byte packetSeq;
protected long maxPacketSize;
protected DBVersion serverVersion;
protected bool isOpen;
protected string versionString;
protected Packet peekedPacket;
protected int protocol;
protected uint threadID;
protected String encryptionSeed;
protected int serverCaps;
protected bool useCompression = false;
public Driver()
{
packetSeq = 0;
encoding = System.Text.Encoding.Default;
isOpen = false;
}
public Encoding Encoding
{
get { return encoding; }
set { encoding = value; }
}
public long MaxPacketSize
{
get { return maxPacketSize; }
set { maxPacketSize = value; }
}
public string VersionString
{
get { return versionString; }
}
public DBVersion Version
{
get { return serverVersion; }
}
public void Open( MySqlConnectionString settings )
{
// connect to one of our specified hosts
try
{
StreamCreator sc = new StreamCreator( settings.Server, settings.Port, settings.PipeName );
stream = sc.GetStream( settings.ConnectionTimeout );
}
catch (Exception ex)
{
throw new MySqlException("Unable to connect to any of the specified MySQL hosts", ex);
}
if (stream == null)
throw new MySqlException("Unable to connect to any of the specified MySQL hosts");
writer = new BufferedStream( stream );
// read off the welcome packet and parse out it's values
Packet packet = ReadPacket();
protocol = packet.ReadByte();
versionString = packet.ReadString();
serverVersion = DBVersion.Parse( versionString );
threadID = (uint)packet.ReadInteger(4);
encryptionSeed = packet.ReadString();
// read in Server capabilities if they are provided
serverCaps = 0;
if (packet.HasMoreData)
serverCaps = (int)packet.ReadInteger(2);
Authenticate( settings.UserId, settings.Password, settings.UseCompression );
// if we are using compression, then we use our CompressedStream class
// to hide the ugliness of managing the compression
if (settings.UseCompression)
{
stream = new CompressedStream( stream );
writer = new BufferedStream( stream );
}
isOpen = true;
}
private Packet CreatePacket( byte[] buf )
{
if (buf == null)
return new Packet( serverVersion.isAtLeast(3, 22, 5) );
return new Packet( buf, serverVersion.isAtLeast(3, 22, 5 ));
}
private void Authenticate( String userid, String password, bool UseCompression )
{
ClientParam clientParam = ClientParam.CLIENT_FOUND_ROWS | ClientParam.CLIENT_LONG_FLAG;
if ((serverCaps & (int)ClientParam.CLIENT_COMPRESS) != 0 && UseCompression)
{
clientParam |= ClientParam.CLIENT_COMPRESS;
}
clientParam |= ClientParam.CLIENT_LONG_PASSWORD;
clientParam |= ClientParam.CLIENT_LOCAL_FILES;
// if (serverVersion.isAtLeast(4,1,0))
// clientParam |= ClientParam.CLIENT_PROTOCOL_41;
// if ( (serverCaps & (int)ClientParam.CLIENT_SECURE_CONNECTION ) != 0 && password.Length > 0 )
// clientParam |= ClientParam.CLIENT_SECURE_CONNECTION;
int packetLength = userid.Length + 16 + 6 + 4; // Passwords can be 16 chars long
Packet packet = CreatePacket(null);
if ((clientParam & ClientParam.CLIENT_PROTOCOL_41) != 0)
{
packet.WriteInteger( (int)clientParam, 4 );
packet.WriteInteger( (256*256*256)-1, 4 );
}
else
{
packet.WriteInteger( (int)clientParam, 2 );
packet.WriteInteger( 255*255*255, 3 );
}
packet.WriteString( userid, encoding );
if ( (clientParam & ClientParam.CLIENT_SECURE_CONNECTION ) != 0 )
{
// use the new authentication system
AuthenticateSecurely( packet, password );
}
else
{
// use old authentication system
packet.WriteString( EncryptPassword(password, encryptionSeed, protocol > 9), encoding );
// pad zeros out to packetLength for auth
for (int i=0; i < (packetLength-packet.Length); i++)
packet.WriteByte(0);
SendPacket(packet);
}
packet = ReadPacket();
if ((clientParam & ClientParam.CLIENT_COMPRESS) != 0)
useCompression = true;
}
/// <summary>
/// AuthenticateSecurity implements the new 4.1 authentication scheme
/// </summary>
/// <param name="packet">The in-progress packet we use to complete the authentication</param>
/// <param name="password">The password of the user to use</param>
private void AuthenticateSecurely( Packet packet, string password )
{
packet.WriteString("xxxxxxxx", encoding );
SendPacket(packet);
packet = ReadPacket();
// compute pass1 hash
string newPass = password.Replace(" ","").Replace("\t","");
SHA1 sha = new SHA1CryptoServiceProvider();
byte[] firstPassBytes = sha.ComputeHash( System.Text.Encoding.Default.GetBytes(newPass));
byte[] salt = packet.GetBuffer();
byte[] input = new byte[ firstPassBytes.Length + 4 ];
salt.CopyTo( input, 0 );
firstPassBytes.CopyTo( input, 4 );
byte[] outPass = new byte[100];
byte[] secondPassBytes = sha.ComputeHash( input );
byte[] cryptSalt = new byte[20];
Security.ArrayCrypt( salt, 4, cryptSalt, 0, secondPassBytes, 20 );
Security.ArrayCrypt( cryptSalt, 0, firstPassBytes, 0, firstPassBytes, 20 );
// send the packet
packet = CreatePacket(null);
packet.Write( firstPassBytes, 0, 20 );
SendPacket(packet);
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public Packet PeekPacket()
{
if (peekedPacket != null)
return peekedPacket;
peekedPacket = ReadPacket();
return peekedPacket;
}
/// <summary>
/// ReadBuffer continuously loops until it has read the entire
/// requested data
/// </summary>
/// <param name="buf">Buffer to read data into</param>
/// <param name="offset">Offset to place the data</param>
/// <param name="length">Number of bytes to read</param>
private void ReadBuffer( byte[] buf, int offset, int length )
{
while (length > 0)
{
int amountRead = stream.Read( buf, offset, length );
if (amountRead == 0)
throw new MySqlException("Unexpected end of data encountered");
length -= amountRead;
offset += amountRead;
}
}
private Packet ReadPacketFromServer()
{
int len = stream.ReadByte() + (stream.ReadByte() << 8) +
(stream.ReadByte() << 16);
byte seq = (byte)stream.ReadByte();
byte[] buf = new byte[ len ];
ReadBuffer( buf, 0, len );
if (seq != packetSeq)
throw new MySqlException("Unknown transmission status: sequence out of order");
packetSeq++;
Packet p = CreatePacket(buf);
p.Encoding = this.Encoding;
if (p.Length == MAX_PACKET_SIZE && serverVersion.isAtLeast(4,0,0))
p.Append( ReadPacketFromServer() );
return p;
}
/// <summary>
/// Reads a single packet off the stream
/// </summary>
/// <returns></returns>
public Packet ReadPacket()
{
// if we have peeked at a packet, then return it
if (peekedPacket != null)
{
Packet packet = peekedPacket;
peekedPacket = null;
return packet;
}
Packet p = ReadPacketFromServer();
// if this is an error packet, then throw the exception
if (p[0] == 0xff)
{
p.ReadByte();
int errorCode = (int)p.ReadInteger(2);
string msg = p.ReadString();
throw new MySqlException( msg, errorCode );
}
return p;
}
protected MemoryStream CompressBuffer(byte[] buf, int index, int length)
{
if (length < MIN_COMPRESS_LENGTH) return null;
MemoryStream ms = new MemoryStream(buf.Length);
DeflaterOutputStream dos = new DeflaterOutputStream(ms);
dos.WriteByte( (byte)(length & 0xff ));
dos.WriteByte( (byte)((length >> 8) & 0xff ));
dos.WriteByte( (byte)((length >> 16) & 0xff ));
dos.WriteByte( 0 );
dos.Write( buf, index, length );
dos.Finish();
if (ms.Length > length+4) return null;
return ms;
}
private void WriteInteger( int v, int numbytes )
{
int val = v;
if (numbytes < 1 || numbytes > 4)
throw new ArgumentOutOfRangeException("Wrong byte count for WriteInteger");
for (int x=0; x < numbytes; x++)
{
writer.WriteByte( (byte)(val&0xff) );
val >>= 8;
}
}
/// <summary>
/// Send a buffer to the server in a compressed form
/// </summary>
/// <param name="buf">Byte buffer to send</param>
/// <param name="index">Location in buffer to start sending</param>
/// <param name="length">Amount of data to send</param>
protected void SendCompressedBuffer(byte[] buf, int index, int length)
{
MemoryStream compressed_bytes = CompressBuffer(buf, index, length);
int comp_len = compressed_bytes == null ? length+HEADER_LEN : (int)compressed_bytes.Length;
int ucomp_len = compressed_bytes == null ? 0 : length+HEADER_LEN;
WriteInteger( comp_len, 3 );
writer.WriteByte( packetSeq++ );
WriteInteger( ucomp_len, 3 );
if (compressed_bytes != null)
writer.Write( compressed_bytes.GetBuffer(), 0, (int)compressed_bytes.Length );
else
{
WriteInteger( length, 3 );
writer.WriteByte( 0 );
writer.Write( buf, index, length );
}
stream.Flush();
}
protected void SendBuffer( byte[] buf, int offset, int length )
{
while (length > 0)
{
int amount = Math.Min( 1024, length );
writer.Write( buf, offset, amount );
writer.Flush();
offset += amount;
length -= amount;
}
}
/// <summary>
/// Send a single packet to the server.
/// </summary>
/// <param name="packet">Packet to send to the server</param>
/// <remarks>This method will send a single packet to the server
/// possibly breaking the packet up into smaller packets that are
/// smaller than max_allowed_packet. This method will always send at
/// least one packet to the server</remarks>
protected void SendPacket(Packet packet)
{
byte[] buf = packet.GetBuffer();
int len = packet.Length;
int index = 0;
bool oneSent = false;
// make sure we are not trying to send too much
if (packet.Length > maxPacketSize && maxPacketSize > 0)
throw new MySqlException("Packet size too large. This MySQL server cannot accept rows larger than " + maxPacketSize + " bytes.");
try
{
while (len > 0 || ! oneSent)
{
int lenToSend = Math.Min( len, MAX_PACKET_SIZE );
// send the data
if (useCompression)
SendCompressedBuffer( buf, index, lenToSend );
else
{
WriteInteger( lenToSend, 3 );
writer.WriteByte( packetSeq++ );
writer.Write( buf, index, lenToSend );
writer.Flush();
}
len -= lenToSend;
index += lenToSend;
oneSent = true;
}
writer.Flush();
}
catch (Exception ex)
{
Console.WriteLine( ex.Message );
}
}
public void Close()
{
if (stream != null)
stream.Close();
}
/// <summary>
/// Sends the specified command to the database
/// </summary>
/// <param name="command">Command to execute</param>
/// <param name="text">Text attribute of command</param>
/// <returns>Result packet returned from database server</returns>
public void Send( DBCmd command, String text )
{
CommandResult result = Send( command, this.Encoding.GetBytes( text ) );
if (result.IsResultSet)
throw new MySqlException("SendCommand failed for command " + text );
}
public CommandResult Send( DBCmd cmd, byte[] bytes )
{
// string s = Encoding.GetString( bytes );
Packet packet = CreatePacket(null);
packetSeq = 0;
packet.WriteByte( (byte)cmd );
if (bytes != null)
packet.Write( bytes, 0, bytes.Length );
SendPacket( packet );
packet = ReadPacket();
// first check to see if this is a LOAD DATA LOCAL callback
// if so, send the file and then read the results
long fieldcount = packet.ReadLenInteger();
if (fieldcount == Packet.NULL_LEN)
{
string filename = packet.ReadString();
SendFileToServer( filename );
packet = ReadPacket();
}
else
packet.Position = 0;
return new CommandResult(packet, this);
}
/// <summary>
/// Sends the specified file to the server.
/// This supports the LOAD DATA LOCAL INFILE
/// </summary>
/// <param name="filename"></param>
private void SendFileToServer( string filename )
{
Packet p = CreatePacket(null);
byte[] buffer = new byte[4092];
FileStream fs = null;
try
{
fs = new FileStream( filename, FileMode.Open );
int count = fs.Read( buffer, 0, buffer.Length );
while (count != 0)
{
if ((p.Length + count) > MAX_PACKET_SIZE)
{
SendPacket( p );
p.Clear();
}
p.Write( buffer, 0, count );
count = fs.Read( buffer, 0, buffer.Length );
}
fs.Close();
// send any remaining data
if (p.Length > 0)
{
SendPacket(p);
p.Clear();
}
}
catch (Exception ex)
{
throw new MySqlException("Error during LOAD DATA LOCAL INFILE", ex);
}
finally
{
if (fs != null)
fs.Close();
// empty packet signals end of file
p.Clear();
SendPacket(p);
}
}
#region PasswordStuff
private static double rand(ref long seed1, ref long seed2)
{
seed1 = (seed1 * 3) + seed2;
seed1 %= 0x3fffffff;
seed2 = (seed1 + seed2 + 33) % 0x3fffffff;
return (seed1 / (double)0x3fffffff);
}
/// <summary>
/// Encrypts a password using the MySql encryption scheme
/// </summary>
/// <param name="password">The password to encrypt</param>
/// <param name="message">The encryption seed the server gave us</param>
/// <param name="new_ver">Indicates if we should use the old or new encryption scheme</param>
/// <returns></returns>
public static String EncryptPassword(String password, String message, bool new_ver)
{
if (password == null || password.Length == 0)
return password;
long[] hash_message = Hash(message);
long[] hash_pass = Hash(password);
long seed1 = (hash_message[0]^hash_pass[0]) % 0x3fffffff;
long seed2 = (hash_message[1]^hash_pass[1]) % 0x3fffffff;
char[] scrambled = new char[message.Length];
for (int x=0; x < message.Length; x++)
{
double r = rand(ref seed1, ref seed2);
scrambled[x] = (char)(Math.Floor(r*31) + 64);
}
if (new_ver)
{ /* Make it harder to break */
char extra = (char)Math.Floor( rand(ref seed1, ref seed2) * 31 );
for (int x=0; x < scrambled.Length; x++)
scrambled[x] ^= extra;
}
return new string(scrambled);
}
/// <summary>
///
/// </summary>
/// <param name="P"></param>
/// <returns></returns>
static long[] Hash(String P)
{
long val1 = 1345345333;
long val2 = 0x12345671;
long inc = 7;
for (int i=0; i < P.Length; i++)
{
if (P[i] == ' ' || P[i] == '\t') continue;
long temp = (long)(0xff & P[i]);
val1 ^= (((val1 & 63)+inc)*temp) + (val1 << 8);
val2 += (val2 << 8) ^ val1;
inc += temp;
}
long[] hash = new long[2];
hash[0] = val1 & 0x7fffffff;
hash[1] = val2 & 0x7fffffff;
return hash;
}
#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.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq.Expressions;
namespace System.Runtime.CompilerServices
{
/// <summary>
/// Builder for read only collections.
/// </summary>
/// <typeparam name="T">The type of the collection element.</typeparam>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
public sealed class ReadOnlyCollectionBuilder<T> : IList<T>, IList
{
private const int DefaultCapacity = 4;
private T[] _items;
private int _size;
private int _version;
/// <summary>
/// Constructs a <see cref="ReadOnlyCollectionBuilder{T}"/>.
/// </summary>
public ReadOnlyCollectionBuilder()
{
_items = Array.Empty<T>();
}
/// <summary>
/// Constructs a <see cref="ReadOnlyCollectionBuilder{T}"/> with a given initial capacity.
/// The contents are empty but builder will have reserved room for the given
/// number of elements before any reallocations are required.
/// </summary>
/// <param name="capacity">Initial capacity of the builder.</param>
public ReadOnlyCollectionBuilder(int capacity)
{
if (capacity < 0)
throw new ArgumentOutOfRangeException(nameof(capacity));
_items = new T[capacity];
}
/// <summary>
/// Constructs a <see cref="ReadOnlyCollectionBuilder{T}"/>, copying contents of the given collection.
/// </summary>
/// <param name="collection">The collection whose elements to copy to the builder.</param>
public ReadOnlyCollectionBuilder(IEnumerable<T> collection)
{
if (collection == null)
throw new ArgumentNullException(nameof(collection));
ICollection<T> c = collection as ICollection<T>;
if (c != null)
{
int count = c.Count;
_items = new T[count];
c.CopyTo(_items, 0);
_size = count;
}
else
{
_size = 0;
_items = new T[DefaultCapacity];
using (IEnumerator<T> en = collection.GetEnumerator())
{
while (en.MoveNext())
{
Add(en.Current);
}
}
}
}
/// <summary>
/// Gets and sets the capacity of this <see cref="ReadOnlyCollectionBuilder{T}"/>.
/// </summary>
public int Capacity
{
get { return _items.Length; }
set
{
if (value < _size)
throw new ArgumentOutOfRangeException(nameof(value));
if (value != _items.Length)
{
if (value > 0)
{
T[] newItems = new T[value];
if (_size > 0)
{
Array.Copy(_items, 0, newItems, 0, _size);
}
_items = newItems;
}
else
{
_items = Array.Empty<T>();
}
}
}
}
/// <summary>
/// Returns number of elements in the <see cref="ReadOnlyCollectionBuilder{T}"/>.
/// </summary>
public int Count => _size;
#region IList<T> Members
/// <summary>
/// Returns the index of the first occurrence of a given value in the builder.
/// </summary>
/// <param name="item">An item to search for.</param>
/// <returns>The index of the first occurrence of an item.</returns>
public int IndexOf(T item)
{
return Array.IndexOf(_items, item, 0, _size);
}
/// <summary>
/// Inserts an item to the <see cref="ReadOnlyCollectionBuilder{T}"/> at the specified index.
/// </summary>
/// <param name="index">The zero-based index at which item should be inserted.</param>
/// <param name="item">The object to insert into the <see cref="ReadOnlyCollectionBuilder{T}"/>.</param>
public void Insert(int index, T item)
{
if (index > _size)
throw new ArgumentOutOfRangeException(nameof(index));
if (_size == _items.Length)
{
EnsureCapacity(_size + 1);
}
if (index < _size)
{
Array.Copy(_items, index, _items, index + 1, _size - index);
}
_items[index] = item;
_size++;
_version++;
}
/// <summary>
/// Removes the <see cref="ReadOnlyCollectionBuilder{T}"/> item at the specified index.
/// </summary>
/// <param name="index">The zero-based index of the item to remove.</param>
public void RemoveAt(int index)
{
if (index < 0 || index >= _size)
throw new ArgumentOutOfRangeException(nameof(index));
_size--;
if (index < _size)
{
Array.Copy(_items, index + 1, _items, index, _size - index);
}
_items[_size] = default(T);
_version++;
}
/// <summary>
/// Gets or sets the element at the specified index.
/// </summary>
/// <param name="index">The zero-based index of the element to get or set.</param>
/// <returns>The element at the specified index.</returns>
public T this[int index]
{
get
{
if (index >= _size)
throw new ArgumentOutOfRangeException(nameof(index));
return _items[index];
}
set
{
if (index >= _size)
throw new ArgumentOutOfRangeException(nameof(index));
_items[index] = value;
_version++;
}
}
#endregion
#region ICollection<T> Members
/// <summary>
/// Adds an item to the <see cref="ReadOnlyCollectionBuilder{T}"/>.
/// </summary>
/// <param name="item">The object to add to the <see cref="ReadOnlyCollectionBuilder{T}"/>.</param>
public void Add(T item)
{
if (_size == _items.Length)
{
EnsureCapacity(_size + 1);
}
_items[_size++] = item;
_version++;
}
/// <summary>
/// Removes all items from the <see cref="ReadOnlyCollectionBuilder{T}"/>.
/// </summary>
public void Clear()
{
if (_size > 0)
{
Array.Clear(_items, 0, _size);
_size = 0;
}
_version++;
}
/// <summary>
/// Determines whether the <see cref="ReadOnlyCollectionBuilder{T}"/> contains a specific value
/// </summary>
/// <param name="item">the object to locate in the <see cref="ReadOnlyCollectionBuilder{T}"/>.</param>
/// <returns>true if item is found in the <see cref="ReadOnlyCollectionBuilder{T}"/>; otherwise, false.</returns>
public bool Contains(T item)
{
if ((object)item == null)
{
for (int i = 0; i < _size; i++)
{
if ((object)_items[i] == null)
{
return true;
}
}
return false;
}
else
{
EqualityComparer<T> c = EqualityComparer<T>.Default;
for (int i = 0; i < _size; i++)
{
if (c.Equals(_items[i], item))
{
return true;
}
}
return false;
}
}
/// <summary>
/// Copies the elements of the <see cref="ReadOnlyCollectionBuilder{T}"/> to an <see cref="Array"/>,
/// starting at particular <see cref="Array"/> index.
/// </summary>
/// <param name="array">The one-dimensional <see cref="Array"/> that is the destination of the elements copied from <see cref="ReadOnlyCollectionBuilder{T}"/>.</param>
/// <param name="arrayIndex">The zero-based index in array at which copying begins.</param>
public void CopyTo(T[] array, int arrayIndex)
{
Array.Copy(_items, 0, array, arrayIndex, _size);
}
bool ICollection<T>.IsReadOnly => false;
/// <summary>
/// Removes the first occurrence of a specific object from the <see cref="ReadOnlyCollectionBuilder{T}"/>.
/// </summary>
/// <param name="item">The object to remove from the <see cref="ReadOnlyCollectionBuilder{T}"/>.</param>
/// <returns>true if item was successfully removed from the <see cref="ReadOnlyCollectionBuilder{T}"/>;
/// otherwise, false. This method also returns false if item is not found in the original <see cref="ReadOnlyCollectionBuilder{T}"/>.
/// </returns>
public bool Remove(T item)
{
int index = IndexOf(item);
if (index >= 0)
{
RemoveAt(index);
return true;
}
return false;
}
#endregion
#region IEnumerable<T> Members
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection.</returns>
public IEnumerator<T> GetEnumerator() => new Enumerator(this);
#endregion
#region IEnumerable Members
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
#endregion
#region IList Members
bool IList.IsReadOnly => false;
int IList.Add(object value)
{
ValidateNullValue(value, nameof(value));
try
{
Add((T)value);
}
catch (InvalidCastException)
{
throw Error.InvalidTypeException(value, typeof(T), nameof(value));
}
return Count - 1;
}
bool IList.Contains(object value)
{
if (IsCompatibleObject(value))
{
return Contains((T)value);
}
else return false;
}
int IList.IndexOf(object value)
{
if (IsCompatibleObject(value))
{
return IndexOf((T)value);
}
return -1;
}
void IList.Insert(int index, object value)
{
ValidateNullValue(value, nameof(value));
try
{
Insert(index, (T)value);
}
catch (InvalidCastException)
{
throw Error.InvalidTypeException(value, typeof(T), nameof(value));
}
}
bool IList.IsFixedSize => false;
void IList.Remove(object value)
{
if (IsCompatibleObject(value))
{
Remove((T)value);
}
}
object IList.this[int index]
{
get
{
return this[index];
}
set
{
ValidateNullValue(value, nameof(value));
try
{
this[index] = (T)value;
}
catch (InvalidCastException)
{
throw Error.InvalidTypeException(value, typeof(T), nameof(value));
}
}
}
#endregion
#region ICollection Members
void ICollection.CopyTo(Array array, int index)
{
if (array == null)
throw new ArgumentNullException(nameof(array));
if (array.Rank != 1)
throw new ArgumentException(nameof(array));
Array.Copy(_items, 0, array, index, _size);
}
bool ICollection.IsSynchronized => false;
object ICollection.SyncRoot => this;
#endregion
/// <summary>
/// Reverses the order of the elements in the entire <see cref="ReadOnlyCollectionBuilder{T}"/>.
/// </summary>
public void Reverse()
{
Reverse(0, Count);
}
/// <summary>
/// Reverses the order of the elements in the specified range.
/// </summary>
/// <param name="index">The zero-based starting index of the range to reverse.</param>
/// <param name="count">The number of elements in the range to reverse.</param>
public void Reverse(int index, int count)
{
if (index < 0)
throw new ArgumentOutOfRangeException(nameof(index));
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count));
Array.Reverse(_items, index, count);
_version++;
}
/// <summary>
/// Copies the elements of the <see cref="ReadOnlyCollectionBuilder{T}"/> to a new array.
/// </summary>
/// <returns>An array containing copies of the elements of the <see cref="ReadOnlyCollectionBuilder{T}"/>.</returns>
public T[] ToArray()
{
T[] array = new T[_size];
Array.Copy(_items, 0, array, 0, _size);
return array;
}
/// <summary>
/// Creates a <see cref="ReadOnlyCollection{T}"/> containing all of the elements of the <see cref="ReadOnlyCollectionBuilder{T}"/>,
/// avoiding copying the elements to the new array if possible. Resets the <see cref="ReadOnlyCollectionBuilder{T}"/> after the
/// <see cref="ReadOnlyCollection{T}"/> has been created.
/// </summary>
/// <returns>A new instance of <see cref="ReadOnlyCollection{T}"/>.</returns>
public ReadOnlyCollection<T> ToReadOnlyCollection()
{
// Can we use the stored array?
T[] items;
if (_size == _items.Length)
{
items = _items;
}
else
{
items = ToArray();
}
_items = Array.Empty<T>();
_size = 0;
_version++;
return new TrueReadOnlyCollection<T>(items);
}
private void EnsureCapacity(int min)
{
if (_items.Length < min)
{
int newCapacity = DefaultCapacity;
if (_items.Length > 0)
{
newCapacity = _items.Length * 2;
}
if (newCapacity < min)
{
newCapacity = min;
}
Capacity = newCapacity;
}
}
private static bool IsCompatibleObject(object value)
{
return ((value is T) || (value == null && default(T) == null));
}
private static void ValidateNullValue(object value, string argument)
{
if (value == null && default(T) != null)
{
throw Error.InvalidNullValue(typeof(T), argument);
}
}
private class Enumerator : IEnumerator<T>, IEnumerator
{
private readonly ReadOnlyCollectionBuilder<T> _builder;
private readonly int _version;
private int _index;
private T _current;
internal Enumerator(ReadOnlyCollectionBuilder<T> builder)
{
_builder = builder;
_version = builder._version;
_index = 0;
_current = default(T);
}
#region IEnumerator<T> Members
public T Current => _current;
#endregion
#region IDisposable Members
public void Dispose()
{
}
#endregion
#region IEnumerator Members
object IEnumerator.Current
{
get
{
if (_index == 0 || _index > _builder._size)
{
throw Error.EnumerationIsDone();
}
return _current;
}
}
public bool MoveNext()
{
if (_version == _builder._version)
{
if (_index < _builder._size)
{
_current = _builder._items[_index++];
return true;
}
else
{
_index = _builder._size + 1;
_current = default(T);
return false;
}
}
else
{
throw Error.CollectionModifiedWhileEnumerating();
}
}
#endregion
#region IEnumerator Members
void IEnumerator.Reset()
{
if (_version != _builder._version)
{
throw Error.CollectionModifiedWhileEnumerating();
}
_index = 0;
_current = default(T);
}
#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.
/******************************************************************************
* 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 AlignRightUInt648()
{
var test = new ImmBinaryOpTest__AlignRightUInt648();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class ImmBinaryOpTest__AlignRightUInt648
{
private struct TestStruct
{
public Vector256<UInt64> _fld1;
public Vector256<UInt64> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt64>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt64>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt64>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt64>>());
return testStruct;
}
public void RunStructFldScenario(ImmBinaryOpTest__AlignRightUInt648 testClass)
{
var result = Avx2.AlignRight(_fld1, _fld2, 8);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<UInt64>>() / sizeof(UInt64);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<UInt64>>() / sizeof(UInt64);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<UInt64>>() / sizeof(UInt64);
private static UInt64[] _data1 = new UInt64[Op1ElementCount];
private static UInt64[] _data2 = new UInt64[Op2ElementCount];
private static Vector256<UInt64> _clsVar1;
private static Vector256<UInt64> _clsVar2;
private Vector256<UInt64> _fld1;
private Vector256<UInt64> _fld2;
private SimpleBinaryOpTest__DataTable<UInt64, UInt64, UInt64> _dataTable;
static ImmBinaryOpTest__AlignRightUInt648()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt64>, byte>(ref _clsVar1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt64>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt64>, byte>(ref _clsVar2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt64>>());
}
public ImmBinaryOpTest__AlignRightUInt648()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt64>, byte>(ref _fld1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt64>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt64>, byte>(ref _fld2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt64>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); }
_dataTable = new SimpleBinaryOpTest__DataTable<UInt64, UInt64, UInt64>(_data1, _data2, new UInt64[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Avx2.AlignRight(
Unsafe.Read<Vector256<UInt64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<UInt64>>(_dataTable.inArray2Ptr),
8
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Avx2.AlignRight(
Avx.LoadVector256((UInt64*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((UInt64*)(_dataTable.inArray2Ptr)),
8
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Avx2.AlignRight(
Avx.LoadAlignedVector256((UInt64*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((UInt64*)(_dataTable.inArray2Ptr)),
8
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Avx2).GetMethod(nameof(Avx2.AlignRight), new Type[] { typeof(Vector256<UInt64>), typeof(Vector256<UInt64>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<UInt64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<UInt64>>(_dataTable.inArray2Ptr),
(byte)8
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx2).GetMethod(nameof(Avx2.AlignRight), new Type[] { typeof(Vector256<UInt64>), typeof(Vector256<UInt64>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadVector256((UInt64*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((UInt64*)(_dataTable.inArray2Ptr)),
(byte)8
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx2).GetMethod(nameof(Avx2.AlignRight), new Type[] { typeof(Vector256<UInt64>), typeof(Vector256<UInt64>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((UInt64*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((UInt64*)(_dataTable.inArray2Ptr)),
(byte)8
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx2.AlignRight(
_clsVar1,
_clsVar2,
8
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var left = Unsafe.Read<Vector256<UInt64>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector256<UInt64>>(_dataTable.inArray2Ptr);
var result = Avx2.AlignRight(left, right, 8);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var left = Avx.LoadVector256((UInt64*)(_dataTable.inArray1Ptr));
var right = Avx.LoadVector256((UInt64*)(_dataTable.inArray2Ptr));
var result = Avx2.AlignRight(left, right, 8);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var left = Avx.LoadAlignedVector256((UInt64*)(_dataTable.inArray1Ptr));
var right = Avx.LoadAlignedVector256((UInt64*)(_dataTable.inArray2Ptr));
var result = Avx2.AlignRight(left, right, 8);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new ImmBinaryOpTest__AlignRightUInt648();
var result = Avx2.AlignRight(test._fld1, test._fld2, 8);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx2.AlignRight(_fld1, _fld2, 8);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Avx2.AlignRight(test._fld1, test._fld2, 8);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector256<UInt64> left, Vector256<UInt64> right, void* result, [CallerMemberName] string method = "")
{
UInt64[] inArray1 = new UInt64[Op1ElementCount];
UInt64[] inArray2 = new UInt64[Op2ElementCount];
UInt64[] outArray = new UInt64[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray1[0]), left);
Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<UInt64>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
UInt64[] inArray1 = new UInt64[Op1ElementCount];
UInt64[] inArray2 = new UInt64[Op2ElementCount];
UInt64[] outArray = new UInt64[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), (uint)Unsafe.SizeOf<Vector256<UInt64>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), (uint)Unsafe.SizeOf<Vector256<UInt64>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<UInt64>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(UInt64[] left, UInt64[] right, UInt64[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (result[0] != right[1])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != (i < 2 ? (i == 1 ? left[0] : right[i+1]) : (i == 3 ? left[2] : right[i+1])))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.AlignRight)}<UInt64>(Vector256<UInt64>.8, Vector256<UInt64>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using QuantConnect.Securities.Future;
namespace QuantConnect.Data.Market
{
/// <summary>
/// Represents an entire chain of futures contracts for a single underlying
/// This type is <see cref="IEnumerable{FuturesContract}"/>
/// </summary>
public class FuturesChain : BaseData, IEnumerable<FuturesContract>
{
private readonly Dictionary<Type, Dictionary<Symbol, List<BaseData>>> _auxiliaryData = new Dictionary<Type, Dictionary<Symbol, List<BaseData>>>();
/// <summary>
/// Gets the most recent trade information for the underlying. This may
/// be a <see cref="Tick"/> or a <see cref="TradeBar"/>
/// </summary>
public BaseData Underlying
{
get; internal set;
}
/// <summary>
/// Gets all ticks for every futures contract in this chain, keyed by symbol
/// </summary>
public Ticks Ticks
{
get; private set;
}
/// <summary>
/// Gets all trade bars for every futures contract in this chain, keyed by symbol
/// </summary>
public TradeBars TradeBars
{
get; private set;
}
/// <summary>
/// Gets all quote bars for every futures contract in this chain, keyed by symbol
/// </summary>
public QuoteBars QuoteBars
{
get; private set;
}
/// <summary>
/// Gets all contracts in the chain, keyed by symbol
/// </summary>
public FuturesContracts Contracts
{
get; private set;
}
/// <summary>
/// Gets the set of symbols that passed the <see cref="Future.ContractFilter"/>
/// </summary>
public HashSet<Symbol> FilteredContracts
{
get; private set;
}
/// <summary>
/// Initializes a new default instance of the <see cref="FuturesChain"/> class
/// </summary>
private FuturesChain()
{
DataType = MarketDataType.FuturesChain;
}
/// <summary>
/// Initializes a new instance of the <see cref="FuturesChain"/> class
/// </summary>
/// <param name="canonicalFutureSymbol">The symbol for this chain.</param>
/// <param name="time">The time of this chain</param>
public FuturesChain(Symbol canonicalFutureSymbol, DateTime time)
{
Time = time;
Symbol = canonicalFutureSymbol;
DataType = MarketDataType.FuturesChain;
Ticks = new Ticks(time);
TradeBars = new TradeBars(time);
QuoteBars = new QuoteBars(time);
Contracts = new FuturesContracts(time);
FilteredContracts = new HashSet<Symbol>();
}
/// <summary>
/// Initializes a new instance of the <see cref="FuturesChain"/> class
/// </summary>
/// <param name="canonicalFutureSymbol">The symbol for this chain.</param>
/// <param name="time">The time of this chain</param>
/// <param name="trades">All trade data for the entire futures chain</param>
/// <param name="quotes">All quote data for the entire futures chain</param>
/// <param name="contracts">All contracts for this futures chain</param>
/// <param name="filteredContracts">The filtered list of contracts for this futures chain</param>
public FuturesChain(Symbol canonicalFutureSymbol, DateTime time, IEnumerable<BaseData> trades, IEnumerable<BaseData> quotes, IEnumerable<FuturesContract> contracts, IEnumerable<Symbol> filteredContracts)
{
Time = time;
Symbol = canonicalFutureSymbol;
DataType = MarketDataType.FuturesChain;
FilteredContracts = filteredContracts.ToHashSet();
Ticks = new Ticks(time);
TradeBars = new TradeBars(time);
QuoteBars = new QuoteBars(time);
Contracts = new FuturesContracts(time);
foreach (var trade in trades)
{
var tick = trade as Tick;
if (tick != null)
{
List<Tick> ticks;
if (!Ticks.TryGetValue(tick.Symbol, out ticks))
{
ticks = new List<Tick>();
Ticks[tick.Symbol] = ticks;
}
ticks.Add(tick);
continue;
}
var bar = trade as TradeBar;
if (bar != null)
{
TradeBars[trade.Symbol] = bar;
}
}
foreach (var quote in quotes)
{
var tick = quote as Tick;
if (tick != null)
{
List<Tick> ticks;
if (!Ticks.TryGetValue(tick.Symbol, out ticks))
{
ticks = new List<Tick>();
Ticks[tick.Symbol] = ticks;
}
ticks.Add(tick);
continue;
}
var bar = quote as QuoteBar;
if (bar != null)
{
QuoteBars[quote.Symbol] = bar;
}
}
foreach (var contract in contracts)
{
Contracts[contract.Symbol] = contract;
}
}
/// <summary>
/// Gets the auxiliary data with the specified type and symbol
/// </summary>
/// <typeparam name="T">The type of auxiliary data</typeparam>
/// <param name="symbol">The symbol of the auxiliary data</param>
/// <returns>The last auxiliary data with the specified type and symbol</returns>
public T GetAux<T>(Symbol symbol)
{
List<BaseData> list;
Dictionary<Symbol, List<BaseData>> dictionary;
if (!_auxiliaryData.TryGetValue(typeof(T), out dictionary) || !dictionary.TryGetValue(symbol, out list))
{
return default(T);
}
return list.OfType<T>().LastOrDefault();
}
/// <summary>
/// Gets all auxiliary data of the specified type as a dictionary keyed by symbol
/// </summary>
/// <typeparam name="T">The type of auxiliary data</typeparam>
/// <returns>A dictionary containing all auxiliary data of the specified type</returns>
public DataDictionary<T> GetAux<T>()
{
Dictionary<Symbol, List<BaseData>> d;
if (!_auxiliaryData.TryGetValue(typeof(T), out d))
{
return new DataDictionary<T>();
}
var dictionary = new DataDictionary<T>();
foreach (var kvp in d)
{
var item = kvp.Value.OfType<T>().LastOrDefault();
if (item != null)
{
dictionary.Add(kvp.Key, item);
}
}
return dictionary;
}
/// <summary>
/// Gets all auxiliary data of the specified type as a dictionary keyed by symbol
/// </summary>
/// <typeparam name="T">The type of auxiliary data</typeparam>
/// <returns>A dictionary containing all auxiliary data of the specified type</returns>
public Dictionary<Symbol, List<BaseData>> GetAuxList<T>()
{
Dictionary<Symbol, List<BaseData>> dictionary;
if (!_auxiliaryData.TryGetValue(typeof(T), out dictionary))
{
return new Dictionary<Symbol, List<BaseData>>();
}
return dictionary;
}
/// <summary>
/// Gets a list of auxiliary data with the specified type and symbol
/// </summary>
/// <typeparam name="T">The type of auxiliary data</typeparam>
/// <param name="symbol">The symbol of the auxiliary data</param>
/// <returns>The list of auxiliary data with the specified type and symbol</returns>
public List<T> GetAuxList<T>(Symbol symbol)
{
List<BaseData> list;
Dictionary<Symbol, List<BaseData>> dictionary;
if (!_auxiliaryData.TryGetValue(typeof(T), out dictionary) || !dictionary.TryGetValue(symbol, out list))
{
return new List<T>();
}
return list.OfType<T>().ToList();
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// An enumerator that can be used to iterate through the collection.
/// </returns>
public IEnumerator<FuturesContract> GetEnumerator()
{
return Contracts.Values.GetEnumerator();
}
/// <summary>
/// Returns an enumerator that iterates through a collection.
/// </summary>
/// <returns>
/// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection.
/// </returns>
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
/// <summary>
/// Return a new instance clone of this object, used in fill forward
/// </summary>
/// <returns>A clone of the current object</returns>
public override BaseData Clone()
{
return new FuturesChain
{
Ticks = Ticks,
Contracts = Contracts,
QuoteBars = QuoteBars,
TradeBars = TradeBars,
FilteredContracts = FilteredContracts,
Symbol = Symbol,
Time = Time,
DataType = DataType,
Value = Value
};
}
/// <summary>
/// Adds the specified auxiliary data to this futures chain
/// </summary>
/// <param name="baseData">The auxiliary data to be added</param>
internal void AddAuxData(BaseData baseData)
{
var type = baseData.GetType();
Dictionary<Symbol, List<BaseData>> dictionary;
if (!_auxiliaryData.TryGetValue(type, out dictionary))
{
dictionary = new Dictionary<Symbol, List<BaseData>>();
_auxiliaryData[type] = dictionary;
}
List<BaseData> list;
if (!dictionary.TryGetValue(baseData.Symbol, out list))
{
list = new List<BaseData>();
dictionary[baseData.Symbol] = list;
}
list.Add(baseData);
}
}
}
| |
// 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.CompilerServices;
using System.Text;
namespace System.Numerics
{
/// <summary>
/// A structure encapsulating four single precision floating point values and provides hardware accelerated methods.
/// </summary>
public partial struct Vector4 : IEquatable<Vector4>, IFormattable
{
#region Public Static Properties
/// <summary>
/// Returns the vector (0,0,0,0).
/// </summary>
public static Vector4 Zero { get { return new Vector4(); } }
/// <summary>
/// Returns the vector (1,1,1,1).
/// </summary>
public static Vector4 One { get { return new Vector4(1.0f, 1.0f, 1.0f, 1.0f); } }
/// <summary>
/// Returns the vector (1,0,0,0).
/// </summary>
public static Vector4 UnitX { get { return new Vector4(1.0f, 0.0f, 0.0f, 0.0f); } }
/// <summary>
/// Returns the vector (0,1,0,0).
/// </summary>
public static Vector4 UnitY { get { return new Vector4(0.0f, 1.0f, 0.0f, 0.0f); } }
/// <summary>
/// Returns the vector (0,0,1,0).
/// </summary>
public static Vector4 UnitZ { get { return new Vector4(0.0f, 0.0f, 1.0f, 0.0f); } }
/// <summary>
/// Returns the vector (0,0,0,1).
/// </summary>
public static Vector4 UnitW { get { return new Vector4(0.0f, 0.0f, 0.0f, 1.0f); } }
#endregion Public Static Properties
#region Public instance methods
/// <summary>
/// Returns the hash code for this instance.
/// </summary>
/// <returns>The hash code.</returns>
public override int GetHashCode()
{
int hash = this.X.GetHashCode();
hash = HashCodeHelper.CombineHashCodes(hash, this.Y.GetHashCode());
hash = HashCodeHelper.CombineHashCodes(hash, this.Z.GetHashCode());
hash = HashCodeHelper.CombineHashCodes(hash, this.W.GetHashCode());
return hash;
}
/// <summary>
/// Returns a boolean indicating whether the given Object is equal to this Vector4 instance.
/// </summary>
/// <param name="obj">The Object to compare against.</param>
/// <returns>True if the Object is equal to this Vector4; False otherwise.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override bool Equals(object obj)
{
if (!(obj is Vector4))
return false;
return Equals((Vector4)obj);
}
/// <summary>
/// Returns a String representing this Vector4 instance.
/// </summary>
/// <returns>The string representation.</returns>
public override string ToString()
{
return ToString("G", CultureInfo.CurrentCulture);
}
/// <summary>
/// Returns a String representing this Vector4 instance, using the specified format to format individual elements.
/// </summary>
/// <param name="format">The format of individual elements.</param>
/// <returns>The string representation.</returns>
public string ToString(string format)
{
return ToString(format, CultureInfo.CurrentCulture);
}
/// <summary>
/// Returns a String representing this Vector4 instance, using the specified format to format individual elements
/// and the given IFormatProvider.
/// </summary>
/// <param name="format">The format of individual elements.</param>
/// <param name="formatProvider">The format provider to use when formatting elements.</param>
/// <returns>The string representation.</returns>
public string ToString(string format, IFormatProvider formatProvider)
{
StringBuilder sb = new StringBuilder();
string separator = NumberFormatInfo.GetInstance(formatProvider).NumberGroupSeparator + " ";
sb.Append("<");
sb.Append(this.X.ToString(format, formatProvider));
sb.Append(separator);
sb.Append(this.Y.ToString(format, formatProvider));
sb.Append(separator);
sb.Append(this.Z.ToString(format, formatProvider));
sb.Append(separator);
sb.Append(this.W.ToString(format, formatProvider));
sb.Append(">");
return sb.ToString();
}
/// <summary>
/// Returns the length of the vector. This operation is cheaper than Length().
/// </summary>
/// <returns>The vector's length.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public float Length()
{
if (Vector.IsHardwareAccelerated)
{
float ls = Vector4.Dot(this, this);
return (float)System.Math.Sqrt(ls);
}
else
{
float ls = X * X + Y * Y + Z * Z + W * W;
return (float)Math.Sqrt((double)ls);
}
}
/// <summary>
/// Returns the length of the vector squared.
/// </summary>
/// <returns>The vector's length squared.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public float LengthSquared()
{
if (Vector.IsHardwareAccelerated)
{
return Vector4.Dot(this, this);
}
else
{
return X * X + Y * Y + Z * Z + W * W;
}
}
#endregion Public Instance Methods
#region Public Static Methods
/// <summary>
/// Returns the Euclidean distance between the two given points.
/// </summary>
/// <param name="value1">The first point.</param>
/// <param name="value2">The second point.</param>
/// <returns>The distance.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float Distance(Vector4 value1, Vector4 value2)
{
if (Vector.IsHardwareAccelerated)
{
Vector4 difference = value1 - value2;
float ls = Vector4.Dot(difference, difference);
return (float)System.Math.Sqrt(ls);
}
else
{
float dx = value1.X - value2.X;
float dy = value1.Y - value2.Y;
float dz = value1.Z - value2.Z;
float dw = value1.W - value2.W;
float ls = dx * dx + dy * dy + dz * dz + dw * dw;
return (float)Math.Sqrt((double)ls);
}
}
/// <summary>
/// Returns the Euclidean distance squared between the two given points.
/// </summary>
/// <param name="value1">The first point.</param>
/// <param name="value2">The second point.</param>
/// <returns>The distance squared.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float DistanceSquared(Vector4 value1, Vector4 value2)
{
if (Vector.IsHardwareAccelerated)
{
Vector4 difference = value1 - value2;
return Vector4.Dot(difference, difference);
}
else
{
float dx = value1.X - value2.X;
float dy = value1.Y - value2.Y;
float dz = value1.Z - value2.Z;
float dw = value1.W - value2.W;
return dx * dx + dy * dy + dz * dz + dw * dw;
}
}
/// <summary>
/// Returns a vector with the same direction as the given vector, but with a length of 1.
/// </summary>
/// <param name="vector">The vector to normalize.</param>
/// <returns>The normalized vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector4 Normalize(Vector4 vector)
{
if (Vector.IsHardwareAccelerated)
{
float length = vector.Length();
return vector / length;
}
else
{
float ls = vector.X * vector.X + vector.Y * vector.Y + vector.Z * vector.Z + vector.W * vector.W;
float invNorm = 1.0f / (float)Math.Sqrt((double)ls);
return new Vector4(
vector.X * invNorm,
vector.Y * invNorm,
vector.Z * invNorm,
vector.W * invNorm);
}
}
/// <summary>
/// Restricts a vector between a min and max value.
/// </summary>
/// <param name="value1">The source vector.</param>
/// <param name="min">The minimum value.</param>
/// <param name="max">The maximum value.</param>
/// <returns>The restricted vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector4 Clamp(Vector4 value1, Vector4 min, Vector4 max)
{
// This compare order is very important!!!
// We must follow HLSL behavior in the case user specified min value is bigger than max value.
float x = value1.X;
x = (x > max.X) ? max.X : x;
x = (x < min.X) ? min.X : x;
float y = value1.Y;
y = (y > max.Y) ? max.Y : y;
y = (y < min.Y) ? min.Y : y;
float z = value1.Z;
z = (z > max.Z) ? max.Z : z;
z = (z < min.Z) ? min.Z : z;
float w = value1.W;
w = (w > max.W) ? max.W : w;
w = (w < min.W) ? min.W : w;
return new Vector4(x, y, z, w);
}
/// <summary>
/// Linearly interpolates between two vectors based on the given weighting.
/// </summary>
/// <param name="value1">The first source vector.</param>
/// <param name="value2">The second source vector.</param>
/// <param name="amount">Value between 0 and 1 indicating the weight of the second source vector.</param>
/// <returns>The interpolated vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector4 Lerp(Vector4 value1, Vector4 value2, float amount)
{
return new Vector4(
value1.X + (value2.X - value1.X) * amount,
value1.Y + (value2.Y - value1.Y) * amount,
value1.Z + (value2.Z - value1.Z) * amount,
value1.W + (value2.W - value1.W) * amount);
}
/// <summary>
/// Transforms a vector by the given matrix.
/// </summary>
/// <param name="position">The source vector.</param>
/// <param name="matrix">The transformation matrix.</param>
/// <returns>The transformed vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector4 Transform(Vector2 position, Matrix4x4 matrix)
{
return new Vector4(
position.X * matrix.M11 + position.Y * matrix.M21 + matrix.M41,
position.X * matrix.M12 + position.Y * matrix.M22 + matrix.M42,
position.X * matrix.M13 + position.Y * matrix.M23 + matrix.M43,
position.X * matrix.M14 + position.Y * matrix.M24 + matrix.M44);
}
/// <summary>
/// Transforms a vector by the given matrix.
/// </summary>
/// <param name="position">The source vector.</param>
/// <param name="matrix">The transformation matrix.</param>
/// <returns>The transformed vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector4 Transform(Vector3 position, Matrix4x4 matrix)
{
return new Vector4(
position.X * matrix.M11 + position.Y * matrix.M21 + position.Z * matrix.M31 + matrix.M41,
position.X * matrix.M12 + position.Y * matrix.M22 + position.Z * matrix.M32 + matrix.M42,
position.X * matrix.M13 + position.Y * matrix.M23 + position.Z * matrix.M33 + matrix.M43,
position.X * matrix.M14 + position.Y * matrix.M24 + position.Z * matrix.M34 + matrix.M44);
}
/// <summary>
/// Transforms a vector by the given matrix.
/// </summary>
/// <param name="vector">The source vector.</param>
/// <param name="matrix">The transformation matrix.</param>
/// <returns>The transformed vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector4 Transform(Vector4 vector, Matrix4x4 matrix)
{
return new Vector4(
vector.X * matrix.M11 + vector.Y * matrix.M21 + vector.Z * matrix.M31 + vector.W * matrix.M41,
vector.X * matrix.M12 + vector.Y * matrix.M22 + vector.Z * matrix.M32 + vector.W * matrix.M42,
vector.X * matrix.M13 + vector.Y * matrix.M23 + vector.Z * matrix.M33 + vector.W * matrix.M43,
vector.X * matrix.M14 + vector.Y * matrix.M24 + vector.Z * matrix.M34 + vector.W * matrix.M44);
}
/// <summary>
/// Transforms a vector by the given Quaternion rotation value.
/// </summary>
/// <param name="value">The source vector to be rotated.</param>
/// <param name="rotation">The rotation to apply.</param>
/// <returns>The transformed vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector4 Transform(Vector2 value, Quaternion rotation)
{
float x2 = rotation.X + rotation.X;
float y2 = rotation.Y + rotation.Y;
float z2 = rotation.Z + rotation.Z;
float wx2 = rotation.W * x2;
float wy2 = rotation.W * y2;
float wz2 = rotation.W * z2;
float xx2 = rotation.X * x2;
float xy2 = rotation.X * y2;
float xz2 = rotation.X * z2;
float yy2 = rotation.Y * y2;
float yz2 = rotation.Y * z2;
float zz2 = rotation.Z * z2;
return new Vector4(
value.X * (1.0f - yy2 - zz2) + value.Y * (xy2 - wz2),
value.X * (xy2 + wz2) + value.Y * (1.0f - xx2 - zz2),
value.X * (xz2 - wy2) + value.Y * (yz2 + wx2),
1.0f);
}
/// <summary>
/// Transforms a vector by the given Quaternion rotation value.
/// </summary>
/// <param name="value">The source vector to be rotated.</param>
/// <param name="rotation">The rotation to apply.</param>
/// <returns>The transformed vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector4 Transform(Vector3 value, Quaternion rotation)
{
float x2 = rotation.X + rotation.X;
float y2 = rotation.Y + rotation.Y;
float z2 = rotation.Z + rotation.Z;
float wx2 = rotation.W * x2;
float wy2 = rotation.W * y2;
float wz2 = rotation.W * z2;
float xx2 = rotation.X * x2;
float xy2 = rotation.X * y2;
float xz2 = rotation.X * z2;
float yy2 = rotation.Y * y2;
float yz2 = rotation.Y * z2;
float zz2 = rotation.Z * z2;
return new Vector4(
value.X * (1.0f - yy2 - zz2) + value.Y * (xy2 - wz2) + value.Z * (xz2 + wy2),
value.X * (xy2 + wz2) + value.Y * (1.0f - xx2 - zz2) + value.Z * (yz2 - wx2),
value.X * (xz2 - wy2) + value.Y * (yz2 + wx2) + value.Z * (1.0f - xx2 - yy2),
1.0f);
}
/// <summary>
/// Transforms a vector by the given Quaternion rotation value.
/// </summary>
/// <param name="value">The source vector to be rotated.</param>
/// <param name="rotation">The rotation to apply.</param>
/// <returns>The transformed vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector4 Transform(Vector4 value, Quaternion rotation)
{
float x2 = rotation.X + rotation.X;
float y2 = rotation.Y + rotation.Y;
float z2 = rotation.Z + rotation.Z;
float wx2 = rotation.W * x2;
float wy2 = rotation.W * y2;
float wz2 = rotation.W * z2;
float xx2 = rotation.X * x2;
float xy2 = rotation.X * y2;
float xz2 = rotation.X * z2;
float yy2 = rotation.Y * y2;
float yz2 = rotation.Y * z2;
float zz2 = rotation.Z * z2;
return new Vector4(
value.X * (1.0f - yy2 - zz2) + value.Y * (xy2 - wz2) + value.Z * (xz2 + wy2),
value.X * (xy2 + wz2) + value.Y * (1.0f - xx2 - zz2) + value.Z * (yz2 - wx2),
value.X * (xz2 - wy2) + value.Y * (yz2 + wx2) + value.Z * (1.0f - xx2 - yy2),
value.W);
}
#endregion Public Static Methods
#region Public operator methods
// All these methods should be inlines as they are implemented
// over JIT intrinsics
/// <summary>
/// Adds two vectors together.
/// </summary>
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <returns>The summed vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector4 Add(Vector4 left, Vector4 right)
{
return left + right;
}
/// <summary>
/// Subtracts the second vector from the first.
/// </summary>
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <returns>The difference vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector4 Subtract(Vector4 left, Vector4 right)
{
return left - right;
}
/// <summary>
/// Multiplies two vectors together.
/// </summary>
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <returns>The product vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector4 Multiply(Vector4 left, Vector4 right)
{
return left * right;
}
/// <summary>
/// Multiplies a vector by the given scalar.
/// </summary>
/// <param name="left">The source vector.</param>
/// <param name="right">The scalar value.</param>
/// <returns>The scaled vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector4 Multiply(Vector4 left, Single right)
{
return left * new Vector4(right, right, right, right);
}
/// <summary>
/// Multiplies a vector by the given scalar.
/// </summary>
/// <param name="left">The scalar value.</param>
/// <param name="right">The source vector.</param>
/// <returns>The scaled vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector4 Multiply(Single left, Vector4 right)
{
return new Vector4(left, left, left, left) * right;
}
/// <summary>
/// Divides the first vector by the second.
/// </summary>
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <returns>The vector resulting from the division.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector4 Divide(Vector4 left, Vector4 right)
{
return left / right;
}
/// <summary>
/// Divides the vector by the given scalar.
/// </summary>
/// <param name="left">The source vector.</param>
/// <param name="divisor">The scalar value.</param>
/// <returns>The result of the division.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector4 Divide(Vector4 left, Single divisor)
{
return left / divisor;
}
/// <summary>
/// Negates a given vector.
/// </summary>
/// <param name="value">The source vector.</param>
/// <returns>The negated vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector4 Negate(Vector4 value)
{
return -value;
}
#endregion Public operator methods
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.RecoveryServices.Backup
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Azure.Management.RecoveryServices;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Microsoft.Rest.Serialization;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
/// <summary>
/// Open API 2.0 Specs for Azure RecoveryServices Backup service
/// </summary>
public partial class RecoveryServicesBackupClient : ServiceClient<RecoveryServicesBackupClient>, IRecoveryServicesBackupClient, 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>
/// The subscription Id.
/// </summary>
public string SubscriptionId { get; set; }
/// <summary>
/// Gets or sets the preferred language for the response.
/// </summary>
public string AcceptLanguage { get; set; }
/// <summary>
/// Gets or sets the retry timeout in seconds for Long Running Operations.
/// Default value is 30.
/// </summary>
public int? LongRunningOperationRetryTimeout { get; set; }
/// <summary>
/// When set to true a unique x-ms-client-request-id value is generated and
/// included in each request. Default is true.
/// </summary>
public bool? GenerateClientRequestId { get; set; }
/// <summary>
/// Gets the IOperations.
/// </summary>
public virtual IOperations Operations { get; private set; }
/// <summary>
/// Gets the IBackupResourceVaultConfigsOperations.
/// </summary>
public virtual IBackupResourceVaultConfigsOperations BackupResourceVaultConfigs { get; private set; }
/// <summary>
/// Gets the IBackupEnginesOperations.
/// </summary>
public virtual IBackupEnginesOperations BackupEngines { get; private set; }
/// <summary>
/// Gets the IProtectionContainerRefreshOperationResultsOperations.
/// </summary>
public virtual IProtectionContainerRefreshOperationResultsOperations ProtectionContainerRefreshOperationResults { get; private set; }
/// <summary>
/// Gets the IProtectionContainersOperations.
/// </summary>
public virtual IProtectionContainersOperations ProtectionContainers { get; private set; }
/// <summary>
/// Gets the IProtectionContainerOperationResultsOperations.
/// </summary>
public virtual IProtectionContainerOperationResultsOperations ProtectionContainerOperationResults { get; private set; }
/// <summary>
/// Gets the IProtectedItemsOperations.
/// </summary>
public virtual IProtectedItemsOperations ProtectedItems { get; private set; }
/// <summary>
/// Gets the IBackupsOperations.
/// </summary>
public virtual IBackupsOperations Backups { get; private set; }
/// <summary>
/// Gets the IProtectedItemOperationResultsOperations.
/// </summary>
public virtual IProtectedItemOperationResultsOperations ProtectedItemOperationResults { get; private set; }
/// <summary>
/// Gets the IProtectedItemOperationStatusesOperations.
/// </summary>
public virtual IProtectedItemOperationStatusesOperations ProtectedItemOperationStatuses { get; private set; }
/// <summary>
/// Gets the IRecoveryPointsOperations.
/// </summary>
public virtual IRecoveryPointsOperations RecoveryPoints { get; private set; }
/// <summary>
/// Gets the IItemLevelRecoveryConnectionsOperations.
/// </summary>
public virtual IItemLevelRecoveryConnectionsOperations ItemLevelRecoveryConnections { get; private set; }
/// <summary>
/// Gets the IRestoresOperations.
/// </summary>
public virtual IRestoresOperations Restores { get; private set; }
/// <summary>
/// Gets the IBackupJobsOperations.
/// </summary>
public virtual IBackupJobsOperations BackupJobs { get; private set; }
/// <summary>
/// Gets the IJobDetailsOperations.
/// </summary>
public virtual IJobDetailsOperations JobDetails { get; private set; }
/// <summary>
/// Gets the IJobCancellationsOperations.
/// </summary>
public virtual IJobCancellationsOperations JobCancellations { get; private set; }
/// <summary>
/// Gets the IJobOperationResultsOperations.
/// </summary>
public virtual IJobOperationResultsOperations JobOperationResults { get; private set; }
/// <summary>
/// Gets the IExportJobsOperationResultsOperations.
/// </summary>
public virtual IExportJobsOperationResultsOperations ExportJobsOperationResults { get; private set; }
/// <summary>
/// Gets the IJobsOperations.
/// </summary>
public virtual IJobsOperations Jobs { get; private set; }
/// <summary>
/// Gets the IBackupOperationResultsOperations.
/// </summary>
public virtual IBackupOperationResultsOperations BackupOperationResults { get; private set; }
/// <summary>
/// Gets the IBackupOperationStatusesOperations.
/// </summary>
public virtual IBackupOperationStatusesOperations BackupOperationStatuses { get; private set; }
/// <summary>
/// Gets the IBackupPoliciesOperations.
/// </summary>
public virtual IBackupPoliciesOperations BackupPolicies { get; private set; }
/// <summary>
/// Gets the IProtectionPoliciesOperations.
/// </summary>
public virtual IProtectionPoliciesOperations ProtectionPolicies { get; private set; }
/// <summary>
/// Gets the IProtectionPolicyOperationResultsOperations.
/// </summary>
public virtual IProtectionPolicyOperationResultsOperations ProtectionPolicyOperationResults { get; private set; }
/// <summary>
/// Gets the IProtectionPolicyOperationStatusesOperations.
/// </summary>
public virtual IProtectionPolicyOperationStatusesOperations ProtectionPolicyOperationStatuses { get; private set; }
/// <summary>
/// Gets the IBackupProtectableItemsOperations.
/// </summary>
public virtual IBackupProtectableItemsOperations BackupProtectableItems { get; private set; }
/// <summary>
/// Gets the IBackupProtectedItemsOperations.
/// </summary>
public virtual IBackupProtectedItemsOperations BackupProtectedItems { get; private set; }
/// <summary>
/// Gets the IBackupProtectionContainersOperations.
/// </summary>
public virtual IBackupProtectionContainersOperations BackupProtectionContainers { get; private set; }
/// <summary>
/// Gets the ISecurityPINsOperations.
/// </summary>
public virtual ISecurityPINsOperations SecurityPINs { get; private set; }
/// <summary>
/// Gets the IBackupResourceStorageConfigsOperations.
/// </summary>
public virtual IBackupResourceStorageConfigsOperations BackupResourceStorageConfigs { get; private set; }
/// <summary>
/// Gets the IBackupUsageSummariesOperations.
/// </summary>
public virtual IBackupUsageSummariesOperations BackupUsageSummaries { get; private set; }
/// <summary>
/// Initializes a new instance of the RecoveryServicesBackupClient class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected RecoveryServicesBackupClient(params DelegatingHandler[] handlers) : base(handlers)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the RecoveryServicesBackupClient 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 RecoveryServicesBackupClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the RecoveryServicesBackupClient 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 RecoveryServicesBackupClient(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 RecoveryServicesBackupClient 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 RecoveryServicesBackupClient(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 RecoveryServicesBackupClient 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 RecoveryServicesBackupClient(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 RecoveryServicesBackupClient 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 RecoveryServicesBackupClient(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 RecoveryServicesBackupClient 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 RecoveryServicesBackupClient(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 RecoveryServicesBackupClient 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 RecoveryServicesBackupClient(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()
{
Operations = new Operations(this);
BackupResourceVaultConfigs = new BackupResourceVaultConfigsOperations(this);
BackupEngines = new BackupEnginesOperations(this);
ProtectionContainerRefreshOperationResults = new ProtectionContainerRefreshOperationResultsOperations(this);
ProtectionContainers = new ProtectionContainersOperations(this);
ProtectionContainerOperationResults = new ProtectionContainerOperationResultsOperations(this);
ProtectedItems = new ProtectedItemsOperations(this);
Backups = new BackupsOperations(this);
ProtectedItemOperationResults = new ProtectedItemOperationResultsOperations(this);
ProtectedItemOperationStatuses = new ProtectedItemOperationStatusesOperations(this);
RecoveryPoints = new RecoveryPointsOperations(this);
ItemLevelRecoveryConnections = new ItemLevelRecoveryConnectionsOperations(this);
Restores = new RestoresOperations(this);
BackupJobs = new BackupJobsOperations(this);
JobDetails = new JobDetailsOperations(this);
JobCancellations = new JobCancellationsOperations(this);
JobOperationResults = new JobOperationResultsOperations(this);
ExportJobsOperationResults = new ExportJobsOperationResultsOperations(this);
Jobs = new JobsOperations(this);
BackupOperationResults = new BackupOperationResultsOperations(this);
BackupOperationStatuses = new BackupOperationStatusesOperations(this);
BackupPolicies = new BackupPoliciesOperations(this);
ProtectionPolicies = new ProtectionPoliciesOperations(this);
ProtectionPolicyOperationResults = new ProtectionPolicyOperationResultsOperations(this);
ProtectionPolicyOperationStatuses = new ProtectionPolicyOperationStatusesOperations(this);
BackupProtectableItems = new BackupProtectableItemsOperations(this);
BackupProtectedItems = new BackupProtectedItemsOperations(this);
BackupProtectionContainers = new BackupProtectionContainersOperations(this);
SecurityPINs = new SecurityPINsOperations(this);
BackupResourceStorageConfigs = new BackupResourceStorageConfigsOperations(this);
BackupUsageSummaries = new BackupUsageSummariesOperations(this);
BaseUri = new System.Uri("https://management.azure.com");
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()
}
};
SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<SchedulePolicy>("schedulePolicyType"));
DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<SchedulePolicy>("schedulePolicyType"));
SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<RetentionPolicy>("retentionPolicyType"));
DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<RetentionPolicy>("retentionPolicyType"));
SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<BackupEngineBase>("backupEngineType"));
DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<BackupEngineBase>("backupEngineType"));
SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<BackupRequest>("objectType"));
DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<BackupRequest>("objectType"));
SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<ILRRequest>("objectType"));
DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<ILRRequest>("objectType"));
SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<Job>("jobType"));
DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<Job>("jobType"));
SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<OperationResultInfoBase>("objectType"));
DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<OperationResultInfoBase>("objectType"));
SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<OperationStatusExtendedInfo>("objectType"));
DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<OperationStatusExtendedInfo>("objectType"));
SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<ProtectedItem>("protectedItemType"));
DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<ProtectedItem>("protectedItemType"));
SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<ProtectionContainer>("protectableObjectType"));
DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<ProtectionContainer>("protectableObjectType"));
SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<ProtectionPolicy>("backupManagementType"));
DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<ProtectionPolicy>("backupManagementType"));
SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<RecoveryPoint>("objectType"));
DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<RecoveryPoint>("objectType"));
SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<RestoreRequest>("objectType"));
DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<RestoreRequest>("objectType"));
SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<WorkloadProtectableItem>("protectableItemType"));
DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<WorkloadProtectableItem>("protectableItemType"));
CustomInitialize();
DeserializationSettings.Converters.Add(new CloudErrorJsonConverter());
}
}
}
| |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading;
using System.Linq.Expressions;
/// <summary>
/// The type WorkbookChartPointRequest.
/// </summary>
public partial class WorkbookChartPointRequest : BaseRequest, IWorkbookChartPointRequest
{
/// <summary>
/// Constructs a new WorkbookChartPointRequest.
/// </summary>
/// <param name="requestUrl">The URL for the built request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
/// <param name="options">Query and header option name value pairs for the request.</param>
public WorkbookChartPointRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
}
/// <summary>
/// Creates the specified WorkbookChartPoint using POST.
/// </summary>
/// <param name="workbookChartPointToCreate">The WorkbookChartPoint to create.</param>
/// <returns>The created WorkbookChartPoint.</returns>
public System.Threading.Tasks.Task<WorkbookChartPoint> CreateAsync(WorkbookChartPoint workbookChartPointToCreate)
{
return this.CreateAsync(workbookChartPointToCreate, CancellationToken.None);
}
/// <summary>
/// Creates the specified WorkbookChartPoint using POST.
/// </summary>
/// <param name="workbookChartPointToCreate">The WorkbookChartPoint to create.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The created WorkbookChartPoint.</returns>
public async System.Threading.Tasks.Task<WorkbookChartPoint> CreateAsync(WorkbookChartPoint workbookChartPointToCreate, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "POST";
var newEntity = await this.SendAsync<WorkbookChartPoint>(workbookChartPointToCreate, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(newEntity);
return newEntity;
}
/// <summary>
/// Deletes the specified WorkbookChartPoint.
/// </summary>
/// <returns>The task to await.</returns>
public System.Threading.Tasks.Task DeleteAsync()
{
return this.DeleteAsync(CancellationToken.None);
}
/// <summary>
/// Deletes the specified WorkbookChartPoint.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The task to await.</returns>
public async System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken)
{
this.Method = "DELETE";
await this.SendAsync<WorkbookChartPoint>(null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the specified WorkbookChartPoint.
/// </summary>
/// <returns>The WorkbookChartPoint.</returns>
public System.Threading.Tasks.Task<WorkbookChartPoint> GetAsync()
{
return this.GetAsync(CancellationToken.None);
}
/// <summary>
/// Gets the specified WorkbookChartPoint.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The WorkbookChartPoint.</returns>
public async System.Threading.Tasks.Task<WorkbookChartPoint> GetAsync(CancellationToken cancellationToken)
{
this.Method = "GET";
var retrievedEntity = await this.SendAsync<WorkbookChartPoint>(null, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(retrievedEntity);
return retrievedEntity;
}
/// <summary>
/// Updates the specified WorkbookChartPoint using PATCH.
/// </summary>
/// <param name="workbookChartPointToUpdate">The WorkbookChartPoint to update.</param>
/// <returns>The updated WorkbookChartPoint.</returns>
public System.Threading.Tasks.Task<WorkbookChartPoint> UpdateAsync(WorkbookChartPoint workbookChartPointToUpdate)
{
return this.UpdateAsync(workbookChartPointToUpdate, CancellationToken.None);
}
/// <summary>
/// Updates the specified WorkbookChartPoint using PATCH.
/// </summary>
/// <param name="workbookChartPointToUpdate">The WorkbookChartPoint to update.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The updated WorkbookChartPoint.</returns>
public async System.Threading.Tasks.Task<WorkbookChartPoint> UpdateAsync(WorkbookChartPoint workbookChartPointToUpdate, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "PATCH";
var updatedEntity = await this.SendAsync<WorkbookChartPoint>(workbookChartPointToUpdate, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(updatedEntity);
return updatedEntity;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookChartPointRequest Expand(string value)
{
this.QueryOptions.Add(new QueryOption("$expand", value));
return this;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="expandExpression">The expression from which to calculate the expand value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookChartPointRequest Expand(Expression<Func<WorkbookChartPoint, object>> expandExpression)
{
if (expandExpression == null)
{
throw new ArgumentNullException(nameof(expandExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(expandExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$expand", value));
}
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookChartPointRequest Select(string value)
{
this.QueryOptions.Add(new QueryOption("$select", value));
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="selectExpression">The expression from which to calculate the select value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookChartPointRequest Select(Expression<Func<WorkbookChartPoint, object>> selectExpression)
{
if (selectExpression == null)
{
throw new ArgumentNullException(nameof(selectExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(selectExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$select", value));
}
return this;
}
/// <summary>
/// Initializes any collection properties after deserialization, like next requests for paging.
/// </summary>
/// <param name="workbookChartPointToInitialize">The <see cref="WorkbookChartPoint"/> with the collection properties to initialize.</param>
private void InitializeCollectionProperties(WorkbookChartPoint workbookChartPointToInitialize)
{
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.IO;
using System.Collections.Generic;
using log4net.Config;
using NUnit.Framework;
using NUnit.Framework.Constraints;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Tests.Common;
using log4net;
using System.Data;
using System.Data.Common;
using System.Reflection;
namespace OpenSim.Data.Tests
{
/// <summary>This is a base class for testing any Data service for any DBMS.
/// Requires NUnit 2.5 or better (to support the generics).
/// </summary>
/// <remarks>
/// FIXME: Should extend OpenSimTestCase but compile on mono 2.4.3 currently fails with
/// AssetTests`2 : System.MemberAccessException : Cannot create an instance of OpenSim.Data.Tests.AssetTests`2[TConn,TAssetData] because Type.ContainsGenericParameters is true.
/// and similar on EstateTests, InventoryTests and RegionTests.
/// Runs fine with mono 2.10.8.1, so easiest thing is to wait until min Mono version uplifts.
/// </remarks>
/// <typeparam name="TConn"></typeparam>
/// <typeparam name="TService"></typeparam>
public class BasicDataServiceTest<TConn, TService>
where TConn : DbConnection, new()
where TService : class, new()
{
protected string m_connStr;
private TService m_service;
private string m_file;
// TODO: Is this in the right place here?
// Later: apparently it's not, but does it matter here?
// protected static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected ILog m_log; // doesn't matter here that it's not static, init to correct type in instance .ctor
public BasicDataServiceTest()
: this("")
{
}
public BasicDataServiceTest(string conn)
{
m_connStr = !String.IsNullOrEmpty(conn) ? conn : DefaultTestConns.Get(typeof(TConn));
m_log = LogManager.GetLogger(this.GetType());
OpenSim.Tests.Common.TestLogging.LogToConsole(); // TODO: Is that right?
}
/// <summary>
/// To be overridden in derived classes. Do whatever init with the m_service, like setting the conn string to it.
/// You'd probably want to to cast the 'service' to a more specific type and store it in a member var.
/// This framework takes care of disposing it, if it's disposable.
/// </summary>
/// <param name="service">The service being tested</param>
protected virtual void InitService(object service)
{
}
[TestFixtureSetUp]
public void Init()
{
// Sorry, some SQLite-specific stuff goes here (not a big deal, as its just some file ops)
if (typeof(TConn).Name.StartsWith("Sqlite"))
{
// SQLite doesn't work on power or z linux
if (Directory.Exists("/proc/ppc64") || Directory.Exists("/proc/dasd"))
Assert.Ignore();
if (Util.IsWindows())
Util.LoadArchSpecificWindowsDll("sqlite3.dll");
// for SQLite, if no explicit conn string is specified, use a temp file
if (String.IsNullOrEmpty(m_connStr))
{
m_file = Path.GetTempFileName() + ".db";
m_connStr = "URI=file:" + m_file + ",version=3";
}
}
if (String.IsNullOrEmpty(m_connStr))
{
string msg = String.Format("Connection string for {0} is not defined, ignoring tests", typeof(TConn).Name);
m_log.Warn(msg);
Assert.Ignore(msg);
}
// Try the connection, ignore tests if Open() fails
using (TConn conn = new TConn())
{
conn.ConnectionString = m_connStr;
try
{
conn.Open();
conn.Close();
}
catch
{
string msg = String.Format("{0} is unable to connect to the database, ignoring tests", typeof(TConn).Name);
m_log.Warn(msg);
Assert.Ignore(msg);
}
}
// If we manage to connect to the database with the user
// and password above it is our test database, and run
// these tests. If anything goes wrong, ignore these
// tests.
try
{
m_service = new TService();
InitService(m_service);
}
catch (Exception e)
{
m_log.Error(e.ToString());
Assert.Ignore();
}
}
[TestFixtureTearDown]
public void Cleanup()
{
if (m_service != null)
{
if (m_service is IDisposable)
((IDisposable)m_service).Dispose();
m_service = null;
}
if (!String.IsNullOrEmpty(m_file) && File.Exists(m_file))
File.Delete(m_file);
}
protected virtual DbConnection Connect()
{
DbConnection cnn = new TConn();
cnn.ConnectionString = m_connStr;
cnn.Open();
return cnn;
}
protected virtual void ExecuteSql(string sql)
{
using (DbConnection dbcon = Connect())
{
using (DbCommand cmd = dbcon.CreateCommand())
{
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
}
}
}
protected delegate bool ProcessRow(IDataReader reader);
protected virtual int ExecQuery(string sql, bool bSingleRow, ProcessRow action)
{
int nRecs = 0;
using (DbConnection dbcon = Connect())
{
using (DbCommand cmd = dbcon.CreateCommand())
{
cmd.CommandText = sql;
CommandBehavior cb = bSingleRow ? CommandBehavior.SingleRow : CommandBehavior.Default;
using (DbDataReader rdr = cmd.ExecuteReader(cb))
{
while (rdr.Read())
{
nRecs++;
if (!action(rdr))
break;
}
}
}
}
return nRecs;
}
/// <summary>Drop tables (listed as parameters). There is no "DROP IF EXISTS" syntax common for all
/// databases, so we just DROP and ignore an exception.
/// </summary>
/// <param name="tables"></param>
protected virtual void DropTables(params string[] tables)
{
foreach (string tbl in tables)
{
try
{
ExecuteSql("DROP TABLE " + tbl + ";");
}catch
{
}
}
}
/// <summary>Clear tables listed as parameters (without dropping them).
/// </summary>
/// <param name="tables"></param>
protected virtual void ResetMigrations(params string[] stores)
{
string lst = "";
foreach (string store in stores)
{
string s = "'" + store + "'";
if (lst == "")
lst = s;
else
lst += ", " + s;
}
string sCond = stores.Length > 1 ? ("in (" + lst + ")") : ("=" + lst);
try
{
ExecuteSql("DELETE FROM migrations where name " + sCond);
}
catch
{
}
}
/// <summary>Clear tables listed as parameters (without dropping them).
/// </summary>
/// <param name="tables"></param>
protected virtual void ClearTables(params string[] tables)
{
foreach (string tbl in tables)
{
try
{
ExecuteSql("DELETE FROM " + tbl + ";");
}
catch
{
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using GoCardless.Internals;
namespace GoCardless.Resources
{
/// <summary>
/// Represents a payer authorisation resource.
///
/// <p class="restricted-notice">
/// Payer Authorisations is deprecated in favour of
/// <a
/// href="https://developer.gocardless.com/getting-started/billing-requests/overview/">
/// Billing Requests</a>. Please consider using Billing Requests to build
/// any
/// future integrations.
/// </p>
///
/// Payer Authorisation resource acts as a wrapper for creating customer,
/// bank account and mandate details in a single request.
/// PayerAuthorisation API enables the integrators to build their own custom
/// payment pages.
///
/// The process to use the Payer Authorisation API is as follows:
///
/// 1. Create a Payer Authorisation, either empty or with already
/// available information
/// 2. Update the authorisation with additional information or fix any
/// mistakes
/// 3. Submit the authorisation, after the payer has reviewed their
/// information
/// 4. [coming soon] Redirect the payer to the verification mechanisms
/// from the response of the Submit request (this will be introduced as a
/// non-breaking change)
/// 5. Confirm the authorisation to indicate that the resources can be
/// created
///
/// After the Payer Authorisation is confirmed, resources will eventually be
/// created as it's an asynchronous process.
///
/// To retrieve the status and ID of the linked resources you can do one of
/// the following:
/// <ol>
/// <li> Listen to <code> payer_authorisation_completed </code> <a
/// href="#appendix-webhooks"> webhook</a> (recommended)</li>
/// <li> Poll the GET <a
/// href="#payer-authorisations-get-a-single-payer-authorisation">
/// endpoint</a></li>
/// <li> Poll the GET events API
/// <code>https://api.gocardless.com/events?payer_authorisation={id}&action=completed</code>
/// </li>
/// </ol>
///
/// <p class="notice">
/// Note that the `create` and `update` endpoints behave differently than
/// other existing `create` and `update` endpoints. The Payer
/// Authorisation is still saved if incomplete data is provided.
/// We return the list of incomplete data in the `incomplete_fields` along
/// with the resources in the body of the response.
/// The bank account details(account_number, bank_code & branch_code) must
/// be sent together rather than splitting across different request for both
/// `create` and `update` endpoints.
/// <br><br>
/// The API is designed to be flexible and allows you to collect
/// information in multiple steps without storing any sensitive data in the
/// browser or in your servers.
/// </p>
/// </summary>
public class PayerAuthorisation
{
/// <summary>
/// All details required for the creation of a
/// [Customer Bank Account](#core-endpoints-customer-bank-accounts).
/// </summary>
[JsonProperty("bank_account")]
public PayerAuthorisationBankAccount BankAccount { get; set; }
/// <summary>
/// [Timestamp](#api-usage-time-zones--dates), recording when this Payer
/// Authorisation was created.
/// </summary>
[JsonProperty("created_at")]
public DateTimeOffset? CreatedAt { get; set; }
/// <summary>
/// All details required for the creation of a
/// [Customer](#core-endpoints-customers).
/// </summary>
[JsonProperty("customer")]
public PayerAuthorisationCustomer Customer { get; set; }
/// <summary>
/// Unique identifier, beginning with "PA".
/// </summary>
[JsonProperty("id")]
public string Id { get; set; }
/// <summary>
/// An array of fields which are missing and is required to set up the
/// mandate.
/// </summary>
[JsonProperty("incomplete_fields")]
public List<PayerAuthorisationIncompleteField> IncompleteFields { get; set; }
/// <summary>
/// Resources linked to this PayerAuthorisation.
/// </summary>
[JsonProperty("links")]
public PayerAuthorisationLinks Links { get; set; }
/// <summary>
/// All details required for the creation of a
/// [Mandate](#core-endpoints-mandates).
/// </summary>
[JsonProperty("mandate")]
public PayerAuthorisationMandate Mandate { get; set; }
/// <summary>
/// One of:
/// <ul>
/// <li>`created`: The PayerAuthorisation has been created, and not been
/// confirmed yet</li>
/// <li>`submitted`: The payer information has been submitted</li>
/// <li>`confirmed`: PayerAuthorisation is confirmed and resources are
/// ready to be created</li>
/// <li>`completed`: The PayerAuthorisation has been completed and
/// customer, bank_account and mandate has been created</li>
/// <li>`failed`: The PayerAuthorisation has failed and customer,
/// bank_account and mandate is not created</li>
/// </ul>
/// </summary>
[JsonProperty("status")]
public PayerAuthorisationStatus? Status { get; set; }
}
/// <summary>
/// Represents a payer authorisation bank account resource.
///
/// All details required for the creation of a
/// [Customer Bank Account](#core-endpoints-customer-bank-accounts).
/// </summary>
public class PayerAuthorisationBankAccount
{
/// <summary>
/// Name of the account holder, as known by the bank. Usually this is
/// the same as the name stored with the linked
/// [creditor](#core-endpoints-creditors). This field will be
/// transliterated, upcased and truncated to 18 characters. This field
/// is required unless the request includes a [customer bank account
/// token](#javascript-flow-customer-bank-account-tokens).
/// </summary>
[JsonProperty("account_holder_name")]
public string AccountHolderName { get; set; }
/// <summary>
/// Bank account number - see [local
/// details](#appendix-local-bank-details) for more information.
/// Alternatively you can provide an `iban`.
/// </summary>
[JsonProperty("account_number")]
public string AccountNumber { get; set; }
/// <summary>
/// The last few digits of the account number. Currently 4 digits for
/// NZD bank accounts and 2 digits for other currencies.
/// </summary>
[JsonProperty("account_number_ending")]
public string AccountNumberEnding { get; set; }
/// <summary>
/// Account number suffix (only for bank accounts denominated in NZD) -
/// see [local details](#local-bank-details-new-zealand) for more
/// information.
/// </summary>
[JsonProperty("account_number_suffix")]
public string AccountNumberSuffix { get; set; }
/// <summary>
/// Bank account type. Required for USD-denominated bank accounts. Must
/// not be provided for bank accounts in other currencies. See [local
/// details](#local-bank-details-united-states) for more information.
/// </summary>
[JsonProperty("account_type")]
public PayerAuthorisationBankAccountAccountType? AccountType { get; set; }
/// <summary>
/// Bank code - see [local details](#appendix-local-bank-details) for
/// more information. Alternatively you can provide an `iban`.
/// </summary>
[JsonProperty("bank_code")]
public string BankCode { get; set; }
/// <summary>
/// Branch code - see [local details](#appendix-local-bank-details) for
/// more information. Alternatively you can provide an `iban`.
/// </summary>
[JsonProperty("branch_code")]
public string BranchCode { get; set; }
/// <summary>
/// [ISO 3166-1 alpha-2
/// code](http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2#Officially_assigned_code_elements).
/// Defaults to the country code of the `iban` if supplied, otherwise is
/// required.
/// </summary>
[JsonProperty("country_code")]
public string CountryCode { get; set; }
/// <summary>
/// [ISO 4217](http://en.wikipedia.org/wiki/ISO_4217#Active_codes)
/// currency code. Currently "AUD", "CAD", "DKK", "EUR", "GBP", "NZD",
/// "SEK" and "USD" are supported.
/// </summary>
[JsonProperty("currency")]
public string Currency { get; set; }
/// <summary>
/// International Bank Account Number. Alternatively you can provide
/// [local details](#appendix-local-bank-details). IBANs are not
/// accepted for Swedish bank accounts denominated in SEK - you must
/// supply [local details](#local-bank-details-sweden).
/// </summary>
[JsonProperty("iban")]
public string Iban { get; set; }
/// <summary>
/// Key-value store of custom data. Up to 3 keys are permitted, with key
/// names up to 50 characters and values up to 500 characters.
/// </summary>
[JsonProperty("metadata")]
public IDictionary<string, string> Metadata { get; set; }
}
/// <summary>
/// Bank account type. Required for USD-denominated bank accounts. Must not be provided for bank
/// accounts in other currencies. See [local details](#local-bank-details-united-states) for
/// more information.
/// </summary>
[JsonConverter(typeof(GcStringEnumConverter), (int)Unknown)]
public enum PayerAuthorisationBankAccountAccountType {
/// <summary>Unknown status</summary>
[EnumMember(Value = "unknown")]
Unknown = 0,
/// <summary>`account_type` with a value of "savings"</summary>
[EnumMember(Value = "savings")]
Savings,
/// <summary>`account_type` with a value of "checking"</summary>
[EnumMember(Value = "checking")]
Checking,
}
/// <summary>
/// Represents a payer authorisation customer resource.
///
/// All details required for the creation of a
/// [Customer](#core-endpoints-customers).
/// </summary>
public class PayerAuthorisationCustomer
{
/// <summary>
/// The first line of the customer's address.
/// </summary>
[JsonProperty("address_line1")]
public string AddressLine1 { get; set; }
/// <summary>
/// The second line of the customer's address.
/// </summary>
[JsonProperty("address_line2")]
public string AddressLine2 { get; set; }
/// <summary>
/// The third line of the customer's address.
/// </summary>
[JsonProperty("address_line3")]
public string AddressLine3 { get; set; }
/// <summary>
/// The city of the customer's address.
/// </summary>
[JsonProperty("city")]
public string City { get; set; }
/// <summary>
/// Customer's company name. Required unless a `given_name` and
/// `family_name` are provided. For Canadian customers, the use of a
/// `company_name` value will mean that any mandate created from this
/// customer will be considered to be a "Business PAD" (otherwise, any
/// mandate will be considered to be a "Personal PAD").
/// </summary>
[JsonProperty("company_name")]
public string CompanyName { get; set; }
/// <summary>
/// [ISO 3166-1 alpha-2
/// code.](http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2#Officially_assigned_code_elements)
/// </summary>
[JsonProperty("country_code")]
public string CountryCode { get; set; }
/// <summary>
/// For Danish customers only. The civic/company number (CPR or CVR) of
/// the customer. Must be supplied if the customer's bank account is
/// denominated in Danish krone (DKK).
/// </summary>
[JsonProperty("danish_identity_number")]
public string DanishIdentityNumber { get; set; }
/// <summary>
/// Customer's email address. Required in most cases, as this allows
/// GoCardless to send notifications to this customer.
/// </summary>
[JsonProperty("email")]
public string Email { get; set; }
/// <summary>
/// Customer's surname. Required unless a `company_name` is provided.
/// </summary>
[JsonProperty("family_name")]
public string FamilyName { get; set; }
/// <summary>
/// Customer's first name. Required unless a `company_name` is provided.
/// </summary>
[JsonProperty("given_name")]
public string GivenName { get; set; }
/// <summary>
/// An [IETF Language Tag](https://tools.ietf.org/html/rfc5646), used
/// for both language
/// and regional variations of our product.
///
/// </summary>
[JsonProperty("locale")]
public string Locale { get; set; }
/// <summary>
/// Key-value store of custom data. Up to 3 keys are permitted, with key
/// names up to 50 characters and values up to 500 characters.
/// </summary>
[JsonProperty("metadata")]
public IDictionary<string, string> Metadata { get; set; }
/// <summary>
/// The customer's postal code.
/// </summary>
[JsonProperty("postal_code")]
public string PostalCode { get; set; }
/// <summary>
/// The customer's address region, county or department. For US
/// customers a 2 letter
/// [ISO3166-2:US](https://en.wikipedia.org/wiki/ISO_3166-2:US) state
/// code is required (e.g. `CA` for California).
/// </summary>
[JsonProperty("region")]
public string Region { get; set; }
/// <summary>
/// For Swedish customers only. The civic/company number (personnummer,
/// samordningsnummer, or organisationsnummer) of the customer. Must be
/// supplied if the customer's bank account is denominated in Swedish
/// krona (SEK). This field cannot be changed once it has been set.
/// </summary>
[JsonProperty("swedish_identity_number")]
public string SwedishIdentityNumber { get; set; }
}
/// <summary>
/// An array of fields which are missing and is required to set up the
/// mandate.
/// </summary>
public class PayerAuthorisationIncompleteField
{
/// <summary>
/// The root resource.
/// </summary>
[JsonProperty("field")]
public string Field { get; set; }
/// <summary>
/// A localised error message
/// </summary>
[JsonProperty("message")]
public string Message { get; set; }
/// <summary>
/// The path to the field e.g. "/payer_authorisations/customer/city"
/// </summary>
[JsonProperty("request_pointer")]
public string RequestPointer { get; set; }
}
/// <summary>
/// Represents a payer authorisation link resource.
///
/// IDs of the created resources. Available after the Payer Authorisation is
/// completed.
/// </summary>
public class PayerAuthorisationLinks
{
/// <summary>
/// Unique identifier, beginning with "BA".
/// </summary>
[JsonProperty("bank_account")]
public string BankAccount { get; set; }
/// <summary>
/// Unique identifier, beginning with "CU".
/// </summary>
[JsonProperty("customer")]
public string Customer { get; set; }
/// <summary>
/// Unique identifier, beginning with "MD". Note that this prefix may
/// not apply to mandates created before 2016.
/// </summary>
[JsonProperty("mandate")]
public string Mandate { get; set; }
}
/// <summary>
/// Represents a payer authorisation mandate resource.
///
/// All details required for the creation of a
/// [Mandate](#core-endpoints-mandates).
/// </summary>
public class PayerAuthorisationMandate
{
/// <summary>
/// Key-value store of custom data. Up to 3 keys are permitted, with key
/// names up to 50 characters and values up to 500 characters.
/// </summary>
[JsonProperty("metadata")]
public IDictionary<string, string> Metadata { get; set; }
/// <summary>
/// For ACH customers only. Required for ACH customers. A string
/// containing the IP address of the payer to whom the mandate belongs
/// (i.e. as a result of their completion of a mandate setup flow in
/// their browser).
/// </summary>
[JsonProperty("payer_ip_address")]
public string PayerIpAddress { get; set; }
/// <summary>
/// Unique reference. Different schemes have different length and
/// [character set](#appendix-character-sets) requirements. GoCardless
/// will generate a unique reference satisfying the different scheme
/// requirements if this field is left blank.
/// </summary>
[JsonProperty("reference")]
public string Reference { get; set; }
/// <summary>
/// A Direct Debit scheme. Currently "ach", "autogiro", "bacs", "becs",
/// "becs_nz", "betalingsservice", "pad" and "sepa_core" are supported.
/// </summary>
[JsonProperty("scheme")]
public PayerAuthorisationMandateScheme? Scheme { get; set; }
}
/// <summary>
/// A Direct Debit scheme. Currently "ach", "autogiro", "bacs", "becs", "becs_nz",
/// "betalingsservice", "pad" and "sepa_core" are supported.
/// </summary>
[JsonConverter(typeof(GcStringEnumConverter), (int)Unknown)]
public enum PayerAuthorisationMandateScheme {
/// <summary>Unknown status</summary>
[EnumMember(Value = "unknown")]
Unknown = 0,
/// <summary>`scheme` with a value of "ach"</summary>
[EnumMember(Value = "ach")]
Ach,
/// <summary>`scheme` with a value of "autogiro"</summary>
[EnumMember(Value = "autogiro")]
Autogiro,
/// <summary>`scheme` with a value of "bacs"</summary>
[EnumMember(Value = "bacs")]
Bacs,
/// <summary>`scheme` with a value of "becs"</summary>
[EnumMember(Value = "becs")]
Becs,
/// <summary>`scheme` with a value of "becs_nz"</summary>
[EnumMember(Value = "becs_nz")]
BecsNz,
/// <summary>`scheme` with a value of "betalingsservice"</summary>
[EnumMember(Value = "betalingsservice")]
Betalingsservice,
/// <summary>`scheme` with a value of "pad"</summary>
[EnumMember(Value = "pad")]
Pad,
/// <summary>`scheme` with a value of "sepa_core"</summary>
[EnumMember(Value = "sepa_core")]
SepaCore,
}
/// <summary>
/// One of:
/// <ul>
/// <li>`created`: The PayerAuthorisation has been created, and not been confirmed yet</li>
/// <li>`submitted`: The payer information has been submitted</li>
/// <li>`confirmed`: PayerAuthorisation is confirmed and resources are ready to be created</li>
/// <li>`completed`: The PayerAuthorisation has been completed and customer, bank_account and
/// mandate has been created</li>
/// <li>`failed`: The PayerAuthorisation has failed and customer, bank_account and mandate is
/// not created</li>
/// </ul>
/// </summary>
[JsonConverter(typeof(GcStringEnumConverter), (int)Unknown)]
public enum PayerAuthorisationStatus {
/// <summary>Unknown status</summary>
[EnumMember(Value = "unknown")]
Unknown = 0,
/// <summary>`status` with a value of "created"</summary>
[EnumMember(Value = "created")]
Created,
/// <summary>`status` with a value of "submitted"</summary>
[EnumMember(Value = "submitted")]
Submitted,
/// <summary>`status` with a value of "confirmed"</summary>
[EnumMember(Value = "confirmed")]
Confirmed,
/// <summary>`status` with a value of "completed"</summary>
[EnumMember(Value = "completed")]
Completed,
/// <summary>`status` with a value of "failed"</summary>
[EnumMember(Value = "failed")]
Failed,
}
}
| |
//
// mdsetup.cs
//
// Author:
// Lluis Sanchez Gual
//
// Copyright (C) 2007 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Xml;
using System.Collections;
using Mono.Addins;
using Mono.Addins.Setup.ProgressMonitoring;
using Mono.Addins.Setup;
using System.IO;
using Mono.Addins.Description;
using System.Linq;
namespace Mono.Addins.Setup
{
/// <summary>
/// A command line add-in manager.
/// </summary>
/// <remarks>
/// This class can be used to provide an add-in management command line tool to applications.
/// </remarks>
public class SetupTool
{
Hashtable options = new Hashtable ();
string[] arguments;
string applicationName = "Mono";
SetupService service;
AddinRegistry registry;
ArrayList commands = new ArrayList ();
string setupAppName = "";
int uniqueId = 0;
int verbose = 1;
/// <summary>
/// Creates a new instance
/// </summary>
/// <param name="registry">
/// Add-in registry to manage.
/// </param>
public SetupTool (AddinRegistry registry)
{
this.registry = registry;
service = new SetupService (registry);
CreateCommands ();
}
/// <summary>
/// Display name of the host application
/// </summary>
public string ApplicationName {
get { return applicationName; }
set { applicationName = value; }
}
/// <summary>
/// Default add-in namespace of the application (optional). If set, only add-ins that belong to that namespace
/// will be shown in add-in lists.
/// </summary>
public string ApplicationNamespace {
get { return service.ApplicationNamespace; }
set { service.ApplicationNamespace = value; }
}
/// <summary>
/// Enables or disables verbose output
/// </summary>
public bool VerboseOutput {
get { return verbose > 1; }
set { verbose = value ? 2 : 1; }
}
/// <summary>
/// Sets or gets the verbose output level (0: normal output, 1:verbose, 2+:extra verbose)
/// </summary>
public int VerboseOutputLevel {
get { return verbose; }
set { verbose = value; }
}
/// <summary>
/// Runs the command line tool.
/// </summary>
/// <param name="args">
/// Array that contains the command line arguments
/// </param>
/// <param name="firstArgumentIndex">
/// Index of the arguments array that has the first argument for the management tool
/// </param>
/// <returns>
/// 0 if it succeeds. != 0 otherwise
/// </returns>
public int Run (string[] args, int firstArgumentIndex)
{
string[] aa = new string [args.Length - firstArgumentIndex];
Array.Copy (args, firstArgumentIndex, aa, 0, aa.Length);
return Run (aa);
}
/// <summary>
/// Runs the command line tool.
/// </summary>
/// <param name="args">
/// Command line arguments
/// </param>
/// <returns>
/// 0 if it succeeds. != 0 otherwise
/// </returns>
public int Run (string[] args)
{
if (args.Length == 0) {
PrintHelp ();
return 0;
}
string[] parms = new string [args.Length - 1];
Array.Copy (args, 1, parms, 0, args.Length - 1);
try {
ReadOptions (parms);
if (HasOption ("v"))
verbose++;
return RunCommand (args [0], parms);
} catch (InstallException ex) {
Console.WriteLine (ex.Message);
return -1;
}
}
int RunCommand (string cmd, string[] parms)
{
SetupCommand cc = FindCommand (cmd);
if (cc != null) {
cc.Handler (parms);
return 0;
}
else {
Console.WriteLine ("Unknown command: " + cmd);
return 1;
}
}
void Install (string[] args)
{
bool prompt = !args.Any (a => a == "-y");
var addins = args.Where (a => a != "-y");
if (!addins.Any ()) {
PrintHelp ("install");
return;
}
PackageCollection packs = new PackageCollection ();
foreach (string arg in addins) {
if (File.Exists (arg)) {
packs.Add (AddinPackage.FromFile (arg));
} else {
string aname = Addin.GetIdName (GetFullId (arg));
string aversion = Addin.GetIdVersion (arg);
if (aversion.Length == 0) aversion = null;
AddinRepositoryEntry[] ads = service.Repositories.GetAvailableAddin (aname, aversion);
if (ads.Length == 0)
throw new InstallException ("The addin '" + arg + "' is not available for install.");
packs.Add (AddinPackage.FromRepository (ads[ads.Length-1]));
}
}
Install (packs, prompt);
}
void CheckInstall (string[] args)
{
if (args.Length < 1) {
PrintHelp ("check-install");
return;
}
PackageCollection packs = new PackageCollection ();
for (int n=0; n<args.Length; n++) {
Addin addin = registry.GetAddin (GetFullId (args[n]));
if (addin != null)
continue;
string aname = Addin.GetIdName (GetFullId (args[n]));
string aversion = Addin.GetIdVersion (args[n]);
if (aversion.Length == 0) aversion = null;
AddinRepositoryEntry[] ads = service.Repositories.GetAvailableAddin (aname, aversion);
if (ads.Length == 0)
throw new InstallException ("The addin '" + args[n] + "' is not available for install.");
packs.Add (AddinPackage.FromRepository (ads[ads.Length-1]));
}
Install (packs, false);
}
void Install (PackageCollection packs, bool prompt)
{
PackageCollection toUninstall;
DependencyCollection unresolved;
IProgressStatus m = new ConsoleProgressStatus (verbose);
int n = packs.Count;
if (!service.Store.ResolveDependencies (m, packs, out toUninstall, out unresolved))
throw new InstallException ("Not all dependencies could be resolved.");
bool ask = false;
if (prompt && (packs.Count != n || toUninstall.Count != 0)) {
Console.WriteLine ("The following packages will be installed:");
foreach (Package p in packs)
Console.WriteLine (" - " + p.Name);
ask = true;
}
if (prompt && (toUninstall.Count != 0)) {
Console.WriteLine ("The following packages need to be uninstalled:");
foreach (Package p in toUninstall)
Console.WriteLine (" - " + p.Name);
ask = true;
}
if (ask) {
Console.WriteLine ();
Console.Write ("Are you sure you want to continue? (y/N): ");
string res = Console.ReadLine ();
if (res != "y" && res != "Y")
return;
}
if (!service.Store.Install (m, packs)) {
Console.WriteLine ("Install operation failed.");
}
}
void Uninstall (string[] args)
{
bool prompt = !args.Any (a => a == "-y");
var addins = args.Where (a => a != "-y");
if (!addins.Any ())
throw new InstallException ("The add-in id is required.");
if (addins.Count () > 1)
throw new InstallException ("Only one add-in id can be provided.");
string id = addins.First ();
Addin ads = registry.GetAddin (GetFullId (id));
if (ads == null)
throw new InstallException ("The add-in '" + id + "' is not installed.");
if (!ads.Description.CanUninstall)
throw new InstallException ("The add-in '" + id + "' is protected and can't be uninstalled.");
if (prompt) {
Console.WriteLine ("The following add-ins will be uninstalled:");
Console.WriteLine (" - " + ads.Description.Name);
foreach (Addin si in service.GetDependentAddins (id, true))
Console.WriteLine (" - " + si.Description.Name);
Console.WriteLine ();
Console.Write ("Are you sure you want to continue? (y/N): ");
string res = Console.ReadLine ();
if (res != "y" && res != "Y")
return;
}
service.Uninstall (new ConsoleProgressStatus (verbose), ads.Id);
}
bool IsHidden (Addin ainfo)
{
return service.ApplicationNamespace != null && !(ainfo.Namespace + ".").StartsWith (service.ApplicationNamespace + ".") || ainfo.Description.IsHidden;
}
bool IsHidden (AddinHeader ainfo)
{
return service.ApplicationNamespace != null && !(ainfo.Namespace + ".").StartsWith (service.ApplicationNamespace + ".");
}
string GetId (AddinHeader ainfo)
{
if (service.ApplicationNamespace != null && (ainfo.Namespace + ".").StartsWith (service.ApplicationNamespace + "."))
return ainfo.Id.Substring (service.ApplicationNamespace.Length + 1);
else
return ainfo.Id;
}
string GetFullId (string id)
{
if (service.ApplicationNamespace != null)
return service.ApplicationNamespace + "." + id;
else
return id;
}
void ListInstalled (string[] args)
{
IList alist = args;
bool showAll = alist.Contains ("-a");
Console.WriteLine ("Installed add-ins:");
ArrayList list = new ArrayList ();
list.AddRange (registry.GetAddins ());
if (alist.Contains ("-r"))
list.AddRange (registry.GetAddinRoots ());
foreach (Addin addin in list) {
if (!showAll && IsHidden (addin))
continue;
Console.Write (" - " + addin.Name + " " + addin.Version);
if (showAll)
Console.Write (" (" + addin.AddinFile + ")");
Console.WriteLine ();
}
}
void ListAvailable (string[] args)
{
bool showAll = args.Length > 0 && args [0] == "-a";
Console.WriteLine ("Available add-ins:");
AddinRepositoryEntry[] addins = service.Repositories.GetAvailableAddins ();
foreach (PackageRepositoryEntry addin in addins) {
if (!showAll && IsHidden (addin.Addin))
continue;
Console.WriteLine (" - " + GetId (addin.Addin) + " (" + addin.Repository.Name + ")");
}
}
void ListUpdates (string[] args)
{
bool showAll = args.Length > 0 && args [0] == "-a";
Console.WriteLine ("Looking for updates...");
service.Repositories.UpdateAllRepositories (null);
Console.WriteLine ("Available add-in updates:");
AddinRepositoryEntry[] addins = service.Repositories.GetAvailableAddins ();
bool found = false;
foreach (PackageRepositoryEntry addin in addins) {
Addin sinfo = registry.GetAddin (addin.Addin.Id);
if (!showAll && IsHidden (sinfo))
continue;
if (sinfo != null && Addin.CompareVersions (sinfo.Version, addin.Addin.Version) == 1) {
Console.WriteLine (" - " + addin.Addin.Id + " " + addin.Addin.Version + " (" + addin.Repository.Name + ")");
found = true;
}
}
if (!found)
Console.WriteLine ("No updates found.");
}
void Update (string [] args)
{
bool showAll = args.Length > 0 && args [0] == "-a";
Console.WriteLine ("Looking for updates...");
service.Repositories.UpdateAllRepositories (null);
PackageCollection packs = new PackageCollection ();
AddinRepositoryEntry[] addins = service.Repositories.GetAvailableAddins ();
foreach (PackageRepositoryEntry addin in addins) {
Addin sinfo = registry.GetAddin (addin.Addin.Id);
if (!showAll && IsHidden (sinfo))
continue;
if (sinfo != null && Addin.CompareVersions (sinfo.Version, addin.Addin.Version) == 1)
packs.Add (AddinPackage.FromRepository (addin));
}
if (packs.Count > 0)
Install (packs, true);
else
Console.WriteLine ("No updates found.");
}
void UpdateAvailableAddins (string[] args)
{
service.Repositories.UpdateAllRepositories (new ConsoleProgressStatus (verbose));
}
void AddRepository (string[] args)
{
foreach (string rep in args)
service.Repositories.RegisterRepository (new ConsoleProgressStatus (verbose), rep);
}
string GetRepositoryUrl (string url)
{
AddinRepository[] reps = GetRepositoryList ();
int nr;
if (int.TryParse (url, out nr)) {
if (nr < 0 || nr >= reps.Length)
throw new InstallException ("Invalid repository number.");
return reps[nr].Url;
} else {
if (!service.Repositories.ContainsRepository (url))
throw new InstallException ("Repository not registered.");
return url;
}
}
void RemoveRepository (string[] args)
{
foreach (string rep in args) {
service.Repositories.RemoveRepository (GetRepositoryUrl (rep));
}
}
void EnableRepository (string[] args)
{
foreach (string rep in args)
service.Repositories.SetRepositoryEnabled (GetRepositoryUrl(rep), true);
}
void DisableRepository (string[] args)
{
foreach (string rep in args)
service.Repositories.SetRepositoryEnabled (GetRepositoryUrl(rep), false);
}
AddinRepository[] GetRepositoryList ()
{
AddinRepository[] reps = service.Repositories.GetRepositories ();
Array.Sort (reps, (r1,r2) => r1.Title.CompareTo(r2.Title));
return reps;
}
void ListRepositories (string[] args)
{
AddinRepository[] reps = GetRepositoryList ();
if (reps.Length == 0) {
Console.WriteLine ("No repositories have been registered.");
return;
}
int n = 0;
Console.WriteLine ("Registered repositories:");
foreach (RepositoryRecord rep in reps) {
string num = n.ToString ();
Console.Write (num + ") ");
if (!rep.Enabled)
Console.Write ("(Disabled) ");
Console.WriteLine (rep.Title);
if (rep.Title != rep.Url)
Console.WriteLine (new string (' ', num.Length + 2) + rep.Url);
n++;
}
}
void BuildRepository (string[] args)
{
if (args.Length < 1)
throw new InstallException ("A directory name is required.");
service.BuildRepository (new ConsoleProgressStatus (verbose), args[0]);
}
void BuildPackage (string[] args)
{
if (args.Length < 1)
throw new InstallException ("A file name is required.");
service.BuildPackage (new ConsoleProgressStatus (verbose), GetOption ("d", "."), GetArguments ());
}
void PrintLibraries (string[] args)
{
if (GetArguments ().Length < 1)
throw new InstallException ("An add-in id is required.");
bool refFormat = HasOption ("r");
System.Text.StringBuilder sb = new System.Text.StringBuilder ();
foreach (string id in GetArguments ()) {
Addin addin = service.Registry.GetAddin (id);
if (addin != null) {
foreach (string asm in addin.Description.MainModule.Assemblies) {
string file = Path.Combine (addin.Description.BasePath, asm);
if (sb.Length > 0)
sb.Append (' ');
if (refFormat)
sb.Append ("-r:");
sb.Append (file);
}
}
}
Console.WriteLine (sb);
}
void PrintApplications (string[] args)
{
foreach (Application app in SetupService.GetExtensibleApplications ()) {
string line = app.Name;
if (!string.IsNullOrEmpty (app.Description))
line += " - " + app.Description;
Console.WriteLine (line);
}
}
void UpdateRegistry (string[] args)
{
registry.Update (new ConsoleProgressStatus (verbose));
}
void RepairRegistry (string[] args)
{
registry.Rebuild (new ConsoleProgressStatus (verbose));
}
void DumpRegistryFile (string[] args)
{
if (args.Length < 1)
throw new InstallException ("A file name is required.");
registry.DumpFile (args[0]);
}
void PrintAddinInfo (string[] args)
{
bool generateXml = false;
bool generateAll = false;
bool pickNamespace = false;
bool extensionModel = true;
ArrayList addins = new ArrayList ();
ArrayList namespaces = new ArrayList ();
foreach (string a in args) {
if (pickNamespace) {
namespaces.Add (a);
pickNamespace = false;
continue;
}
if (a == "--xml") {
generateXml = true;
continue;
}
if (a == "--namespace" || a == "-n") {
pickNamespace = true;
continue;
}
if (a == "--all") {
generateAll = true;
continue;
}
if (a == "--full") {
extensionModel = false;
continue;
}
AddinDescription desc = null;
if (File.Exists (args[0]))
desc = registry.GetAddinDescription (new Mono.Addins.ConsoleProgressStatus (verbose), args[0]);
else {
Addin addin = registry.GetAddin (args [0]);
if (addin != null)
desc = addin.Description;
}
if (desc == null)
throw new InstallException (string.Format ("Add-in '{0}' not found.", a));
if (desc != null)
addins.Add (desc);
}
if (generateAll) {
ArrayList list = new ArrayList ();
list.AddRange (registry.GetAddinRoots ());
list.AddRange (registry.GetAddins ());
foreach (Addin addin in list) {
if (namespaces.Count > 0) {
foreach (string ns in namespaces) {
if (addin.Id.StartsWith (ns + ".")) {
addins.Add (addin.Description);
break;
}
}
} else {
addins.Add (addin.Description);
}
}
}
if (addins.Count == 0)
throw new InstallException ("A file name or add-in ID is required.");
if (generateXml) {
XmlTextWriter tw = new XmlTextWriter (Console.Out);
tw.Formatting = Formatting.Indented;
tw.WriteStartElement ("Addins");
foreach (AddinDescription desc in addins) {
if (extensionModel && desc.ExtensionPoints.Count == 0)
continue;
PrintAddinXml (tw, desc);
}
tw.Close ();
}
else {
foreach (AddinDescription des in addins)
PrintAddin (des);
}
}
void PrintAddinXml (XmlWriter tw, AddinDescription desc)
{
tw.WriteStartElement ("Addin");
tw.WriteAttributeString ("name", desc.Name);
tw.WriteAttributeString ("addinId", desc.LocalId);
tw.WriteAttributeString ("fullId", desc.AddinId);
tw.WriteAttributeString ("id", "addin_" + uniqueId);
uniqueId++;
if (desc.Namespace.Length > 0)
tw.WriteAttributeString ("namespace", desc.Namespace);
tw.WriteAttributeString ("isroot", desc.IsRoot.ToString ());
tw.WriteAttributeString ("version", desc.Version);
if (desc.CompatVersion.Length > 0)
tw.WriteAttributeString ("compatVersion", desc.CompatVersion);
if (desc.Author.Length > 0)
tw.WriteAttributeString ("author", desc.Author);
if (desc.Category.Length > 0)
tw.WriteAttributeString ("category", desc.Category);
if (desc.Copyright.Length > 0)
tw.WriteAttributeString ("copyright", desc.Copyright);
if (desc.Url.Length > 0)
tw.WriteAttributeString ("url", desc.Url);
if (desc.Description.Length > 0)
tw.WriteElementString ("Description", desc.Description);
if (desc.ExtensionPoints.Count > 0) {
ArrayList list = new ArrayList ();
Hashtable visited = new Hashtable ();
foreach (ExtensionPoint ep in desc.ExtensionPoints) {
tw.WriteStartElement ("ExtensionPoint");
tw.WriteAttributeString ("path", ep.Path);
if (ep.Name.Length > 0)
tw.WriteAttributeString ("name", ep.Name);
else
tw.WriteAttributeString ("name", ep.Path);
if (ep.Description.Length > 0)
tw.WriteElementString ("Description", ep.Description);
PrintExtensionNodeSetXml (tw, desc, ep.NodeSet, list, visited);
tw.WriteEndElement ();
}
for (int n=0; n<list.Count; n++) {
ExtensionNodeType nt = (ExtensionNodeType) list [n];
tw.WriteStartElement ("ExtensionNodeType");
tw.WriteAttributeString ("name", nt.Id);
tw.WriteAttributeString ("id", visited [nt.Id + " " + nt.TypeName].ToString ());
if (nt.Description.Length > 0)
tw.WriteElementString ("Description", nt.Description);
if (nt.Attributes.Count > 0) {
tw.WriteStartElement ("Attributes");
foreach (NodeTypeAttribute att in nt.Attributes) {
tw.WriteStartElement ("Attribute");
tw.WriteAttributeString ("name", att.Name);
tw.WriteAttributeString ("type", att.Type);
tw.WriteAttributeString ("required", att.Required.ToString ());
tw.WriteAttributeString ("localizable", att.Localizable.ToString ());
if (att.Description.Length > 0)
tw.WriteElementString ("Description", att.Description);
tw.WriteEndElement ();
}
tw.WriteEndElement ();
}
if (nt.NodeTypes.Count > 0 || nt.NodeSets.Count > 0) {
tw.WriteStartElement ("ChildNodes");
PrintExtensionNodeSetXml (tw, desc, nt, list, visited);
tw.WriteEndElement ();
}
tw.WriteEndElement ();
}
}
tw.WriteEndElement ();
}
void PrintExtensionNodeSetXml (XmlWriter tw, AddinDescription desc, ExtensionNodeSet nset, ArrayList list, Hashtable visited)
{
foreach (ExtensionNodeType nt in nset.GetAllowedNodeTypes ()) {
tw.WriteStartElement ("ExtensionNode");
tw.WriteAttributeString ("name", nt.Id);
string id = RegisterNodeXml (nt, list, visited);
tw.WriteAttributeString ("id", id.ToString ());
if (nt.Description.Length > 0)
tw.WriteElementString ("Description", nt.Description);
tw.WriteEndElement ();
}
}
string RegisterNodeXml (ExtensionNodeType nt, ArrayList list, Hashtable visited)
{
string key = nt.Id + " " + nt.TypeName;
if (visited.Contains (key))
return (string) visited [key];
string k = "ntype_" + uniqueId;
uniqueId++;
visited [key] = k;
list.Add (nt);
return k;
}
void PrintAddin (AddinDescription desc)
{
Console.WriteLine ();
Console.WriteLine ("Addin Header");
Console.WriteLine ("------------");
Console.WriteLine ();
Console.WriteLine ("Name: " + desc.Name);
Console.WriteLine ("Id: " + desc.LocalId);
if (desc.Namespace.Length > 0)
Console.WriteLine ("Namespace: " + desc.Namespace);
Console.Write ("Version: " + desc.Version);
if (desc.CompatVersion.Length > 0)
Console.WriteLine (" (compatible with: " + desc.CompatVersion + ")");
else
Console.WriteLine ();
if (desc.AddinFile.Length > 0)
Console.WriteLine ("File: " + desc.AddinFile);
if (desc.Author.Length > 0)
Console.WriteLine ("Author: " + desc.Author);
if (desc.Category.Length > 0)
Console.WriteLine ("Category: " + desc.Category);
if (desc.Copyright.Length > 0)
Console.WriteLine ("Copyright: " + desc.Copyright);
if (desc.Url.Length > 0)
Console.WriteLine ("Url: " + desc.Url);
if (desc.Description.Length > 0) {
Console.WriteLine ();
Console.WriteLine ("Description: \n" + desc.Description);
}
if (desc.ExtensionPoints.Count > 0) {
Console.WriteLine ();
Console.WriteLine ("Extenstion Points");
Console.WriteLine ("-----------------");
foreach (ExtensionPoint ep in desc.ExtensionPoints)
PrintExtensionPoint (desc, ep);
}
}
void PrintExtensionPoint (AddinDescription desc, ExtensionPoint ep)
{
Console.WriteLine ();
Console.WriteLine ("* Extension Point: " + ep.Path);
if (ep.Description.Length > 0)
Console.WriteLine (ep.Description);
ArrayList list = new ArrayList ();
Hashtable visited = new Hashtable ();
Console.WriteLine ();
Console.WriteLine (" Extension nodes:");
GetNodes (desc, ep.NodeSet, list, new Hashtable ());
foreach (ExtensionNodeType nt in list)
Console.WriteLine (" - " + nt.Id + ": " + nt.Description);
Console.WriteLine ();
Console.WriteLine (" Node description:");
string sind = " ";
for (int n=0; n<list.Count; n++) {
ExtensionNodeType nt = (ExtensionNodeType) list [n];
if (visited.Contains (nt.Id + " " + nt.TypeName))
continue;
visited.Add (nt.Id + " " + nt.TypeName, nt);
Console.WriteLine ();
Console.WriteLine (sind + "- " + nt.Id + ": " + nt.Description);
string nsind = sind + " ";
if (nt.Attributes.Count > 0) {
Console.WriteLine (nsind + "Attributes:");
foreach (NodeTypeAttribute att in nt.Attributes) {
string req = att.Required ? " (required)" : "";
Console.WriteLine (nsind + " " + att.Name + " (" + att.Type + "): " + att.Description + req);
}
}
if (nt.NodeTypes.Count > 0 || nt.NodeSets.Count > 0) {
Console.WriteLine (nsind + "Child nodes:");
ArrayList newList = new ArrayList ();
GetNodes (desc, nt, newList, new Hashtable ());
list.AddRange (newList);
foreach (ExtensionNodeType cnt in newList)
Console.WriteLine (" " + cnt.Id + ": " + cnt.Description);
}
}
Console.WriteLine ();
}
void GetNodes (AddinDescription desc, ExtensionNodeSet nset, ArrayList list, Hashtable visited)
{
if (visited.Contains (nset))
return;
visited.Add (nset, nset);
foreach (ExtensionNodeType nt in nset.NodeTypes) {
if (!visited.Contains (nt.Id + " " + nt.TypeName)) {
list.Add (nt);
visited.Add (nt.Id + " " + nt.TypeName, nt);
}
}
foreach (string nsid in nset.NodeSets) {
ExtensionNodeSet rset = desc.ExtensionNodeSets [nsid];
if (rset != null)
GetNodes (desc, rset, list, visited);
}
}
string[] GetArguments ()
{
return arguments;
}
bool HasOption (string key)
{
return options.Contains (key);
}
string GetOption (string key, string defValue)
{
object val = options [key];
if (val == null || val == (object) this)
return defValue;
else
return (string) val;
}
void ReadOptions (string[] args)
{
options = new Hashtable ();
ArrayList list = new ArrayList ();
foreach (string arg in args) {
if (arg.StartsWith ("-")) {
int i = arg.IndexOf (':');
if (i == -1)
options [arg.Substring (1)] = this;
else
options [arg.Substring (1, i-1)] = arg.Substring (i+1);
} else
list.Add (arg);
}
arguments = (string[]) list.ToArray (typeof(string));
}
/// <summary>
/// Adds a custom command to the add-in manager
/// </summary>
/// <param name="category">
/// Category under which the command has to be shown in the help text
/// </param>
/// <param name="command">
/// Name of the command
/// </param>
/// <param name="shortName">
/// Short name of the command (it's an alias of the normal name)
/// </param>
/// <param name="arguments">
/// Formal description of the arguments that the command accepts. For example: "[addin-id|addin-file] [--xml] [--all] [--full] [--namespace <namespace>]"
/// </param>
/// <param name="description">
/// Short description of the command
/// </param>
/// <param name="longDescription">
/// Long description of the command
/// </param>
/// <param name="handler">
/// Delegate to be invoked to run the command
/// </param>
public void AddCommand (string category, string command, string shortName, string arguments, string description, string longDescription, SetupCommandHandler handler)
{
SetupCommand cmd = new SetupCommand (category, command, shortName, handler);
cmd.Usage = arguments;
cmd.Description = description;
cmd.LongDescription = longDescription;
int lastCatPos = -1;
for (int n=0; n<commands.Count; n++) {
SetupCommand ec = (SetupCommand) commands [n];
if (ec.Category == category)
lastCatPos = n;
}
if (lastCatPos == -1)
commands.Add (cmd);
else
commands.Insert (lastCatPos+1, cmd);
}
SetupCommand FindCommand (string id)
{
foreach (SetupCommand cmd in commands)
if (cmd.Command == id || cmd.ShortCommand == id)
return cmd;
return null;
}
/// <summary>
/// Prints help about the add-in management tool, or about a specific command
/// </summary>
/// <param name="parms">
/// Optional command name and arguments
/// </param>
public void PrintHelp (params string[] parms)
{
if (parms.Length == 0) {
string lastCat = null;
foreach (SetupCommand cmd in commands) {
if (cmd.Command == "help")
continue;
if (lastCat != cmd.Category) {
Console.WriteLine ();
Console.WriteLine (cmd.Category + ":");
lastCat = cmd.Category;
}
string cc = cmd.CommandDesc;
if (cc.Length < 16)
cc += new string (' ', 16 - cc.Length);
Console.WriteLine (" " + cc + " " + cmd.Description);
}
Console.WriteLine ();
Console.WriteLine ("Run '" + setupAppName + "help <command>' to get help about a specific command.");
Console.WriteLine ();
return;
}
else {
Console.WriteLine ();
SetupCommand cmd = FindCommand (parms [0]);
if (cmd != null) {
Console.WriteLine ("{0}: {1}", cmd.CommandDesc, cmd.Description);
Console.WriteLine ();
Console.WriteLine ("Usage: {0}{1}", setupAppName, cmd.Usage);
Console.WriteLine ();
TextFormatter fm = new TextFormatter ();
fm.Wrap = WrappingType.Word;
fm.Append (cmd.LongDescription);
Console.WriteLine (fm.ToString ());
}
else
Console.WriteLine ("Unknown command: " + parms [0]);
Console.WriteLine ();
}
}
void CreateCommands ()
{
SetupCommand cmd;
string cat = "Add-in commands";
cmd = new SetupCommand (cat, "install", "i", new SetupCommandHandler (Install));
cmd.Description = "Installs add-ins.";
cmd.Usage = "[-y] [package-name|package-file] ...";
cmd.AppendDesc ("Installs an add-in or set of addins. The command argument is a list");
cmd.AppendDesc ("of files and/or package names. If a package name is provided");
cmd.AppendDesc ("the package will be looked up in the registered repositories.");
cmd.AppendDesc ("A specific add-in version can be specified by appending it to.");
cmd.AppendDesc ("the package name using '/' as a separator, like in this example:");
cmd.AppendDesc ("MonoDevelop.SourceEditor/0.9.1\n");
cmd.AppendDesc ("-y: Don't ask for confirmation.");
commands.Add (cmd);
cmd = new SetupCommand (cat, "uninstall", "u", new SetupCommandHandler (Uninstall));
cmd.Description = "Uninstalls add-ins.";
cmd.Usage = "[-y] <package-name>";
cmd.AppendDesc ("Uninstalls an add-in. The command argument is the name");
cmd.AppendDesc ("of the add-in to uninstall.\n");
cmd.AppendDesc ("-y: Don't ask for confirmation.");
commands.Add (cmd);
cmd = new SetupCommand (cat, "check-install", "ci", new SetupCommandHandler (CheckInstall));
cmd.Description = "Checks installed add-ins.";
cmd.Usage = "[package-name|package-file] ...";
cmd.AppendDesc ("Checks if a package is installed. If it is not, it looks for");
cmd.AppendDesc ("the package in the registered repositories, and if found");
cmd.AppendDesc ("the package is downloaded and installed, including all");
cmd.AppendDesc ("needed dependencies.");
commands.Add (cmd);
cmd = new SetupCommand (cat, "update", "up", new SetupCommandHandler (Update));
cmd.Description = "Updates installed add-ins.";
cmd.AppendDesc ("Downloads and installs available updates for installed add-ins.");
commands.Add (cmd);
cmd = new SetupCommand (cat, "list", "l", new SetupCommandHandler (ListInstalled));
cmd.Description = "Lists installed add-ins.";
cmd.AppendDesc ("Prints a list of all installed add-ins.");
commands.Add (cmd);
cmd = new SetupCommand (cat, "list-av", "la", new SetupCommandHandler (ListAvailable));
cmd.Description = "Lists add-ins available in registered repositories.";
cmd.AppendDesc ("Prints a list of add-ins available to install in the");
cmd.AppendDesc ("registered repositories.");
commands.Add (cmd);
cmd = new SetupCommand (cat, "list-update", "lu", new SetupCommandHandler (ListUpdates));
cmd.Description = "Lists available add-in updates.";
cmd.AppendDesc ("Prints a list of available add-in updates in the registered repositories.");
commands.Add (cmd);
cat = "Repository Commands";
cmd = new SetupCommand (cat, "rep-add", "ra", new SetupCommandHandler (AddRepository));
cmd.Description = "Registers repositories.";
cmd.Usage = "<url> ...";
cmd.AppendDesc ("Registers an add-in repository. Several URLs can be provided.");
commands.Add (cmd);
cmd = new SetupCommand (cat, "rep-remove", "rr", new SetupCommandHandler (RemoveRepository));
cmd.Description = "Unregisters repositories.";
cmd.Usage = "<url or number> ...";
cmd.AppendDesc ("Unregisters an add-in repository. Several URLs can be provided.");
cmd.AppendDesc ("Instead of an url, a repository number can be used (repository numbers are");
cmd.AppendDesc ("shown by the rep-list command.");
commands.Add (cmd);
cmd = new SetupCommand (cat, "rep-enable", "re", new SetupCommandHandler (EnableRepository));
cmd.Description = "Enables repositories.";
cmd.Usage = "<url or number> ...";
cmd.AppendDesc ("Enables an add-in repository which has been disabled. Several URLs can be");
cmd.AppendDesc ("provided. Instead of an url, a repository number can be used (repository");
cmd.AppendDesc ("numbers are shown by the rep-list command.");
commands.Add (cmd);
cmd = new SetupCommand (cat, "rep-disable", "rd", new SetupCommandHandler (DisableRepository));
cmd.Description = "Disables repositories.";
cmd.Usage = "<url> ...";
cmd.AppendDesc ("Disables an add-in repository. Several URLs can be provided");
cmd.AppendDesc ("When a repository is disabled, it will be ignored when using the update and");
cmd.AppendDesc ("install commands.");
cmd.AppendDesc ("Instead of an url, a repository number can be used (repository numbers are");
cmd.AppendDesc ("shown by the rep-list command.");
commands.Add (cmd);
cmd = new SetupCommand (cat, "rep-update", "ru", new SetupCommandHandler (UpdateAvailableAddins));
cmd.Description = "Updates the lists of available addins.";
cmd.AppendDesc ("Updates the lists of addins available in all registered repositories.");
commands.Add (cmd);
cmd = new SetupCommand (cat, "rep-list", "rl", new SetupCommandHandler (ListRepositories));
cmd.Description = "Lists registered repositories.";
cmd.AppendDesc ("Shows a list of all registered repositories.");
commands.Add (cmd);
cat = "Add-in Registry Commands";
cmd = new SetupCommand (cat, "reg-update", "rgu", new SetupCommandHandler (UpdateRegistry));
cmd.Description = "Updates the add-in registry.";
cmd.AppendDesc ("Looks for changes in add-in directories and updates the registry.");
cmd.AppendDesc ("New add-ins will be added and deleted add-ins will be removed.");
commands.Add (cmd);
cmd = new SetupCommand (cat, "reg-build", "rgb", new SetupCommandHandler (RepairRegistry));
cmd.Description = "Rebuilds the add-in registry.";
cmd.AppendDesc ("Regenerates the add-in registry");
commands.Add (cmd);
cmd = new SetupCommand (cat, "info", null, new SetupCommandHandler (PrintAddinInfo));
cmd.Usage = "[addin-id|addin-file] [--xml] [--all] [--full] [--namespace <namespace>]";
cmd.Description = "Prints information about add-ins.";
cmd.AppendDesc ("Prints information about add-ins. Options:\n");
cmd.AppendDesc (" --xml: Dump the information using an XML format.\n");
cmd.AppendDesc (" --all: Dump information from all add-ins.\n");
cmd.AppendDesc (" --full: Include add-ins which don't define extension points.\n");
cmd.AppendDesc (" --namespace ns: Include only add-ins from the specified 'ns' namespace.");
commands.Add (cmd);
cat = "Packaging Commands";
cmd = new SetupCommand (cat, "rep-build", "rb", new SetupCommandHandler (BuildRepository));
cmd.Description = "Creates a repository index file for a directory structure.";
cmd.Usage = "<path>";
cmd.AppendDesc ("Scans the provided directory and generates a set of index files with entries");
cmd.AppendDesc ("for all add-in packages found in the directory tree. The resulting file");
cmd.AppendDesc ("structure is an add-in repository that can be published in a web site or a");
cmd.AppendDesc ("shared directory.");
commands.Add (cmd);
cmd = new SetupCommand (cat, "pack", "p", new SetupCommandHandler (BuildPackage));
cmd.Description = "Creates a package from an add-in configuration file.";
cmd.Usage = "<file-path> [-d:output-directory]";
cmd.AppendDesc ("Creates an add-in package (.mpack file) which includes all files ");
cmd.AppendDesc ("needed to deploy an add-in. The command parameter is the path to");
cmd.AppendDesc ("the add-in's configuration file.");
commands.Add (cmd);
cmd = new SetupCommand (cat, "help", "h", new SetupCommandHandler (PrintHelp));
cmd.Description = "Shows help about a command.";
cmd.Usage = "<command>";
commands.Add (cmd);
cat = "Build Commands";
cmd = new SetupCommand (cat, "libraries", "libs", new SetupCommandHandler (PrintLibraries));
cmd.Description = "Lists add-in assemblies.";
cmd.Usage = "[-r] <addin-id> ...";
cmd.AppendDesc ("Prints a list of assemblies exported by the add-in or add-ins provided");
cmd.AppendDesc ("as arguments. This list of assemblies can be used as references for");
cmd.AppendDesc ("building add-ins that depend on them. If the -r option is specified,");
cmd.AppendDesc ("each assembly is prefixed with '-r:'.");
commands.Add (cmd);
cmd = new SetupCommand (cat, "applications", "apps", new SetupCommandHandler (PrintApplications));
cmd.Description = "Lists extensible applications.";
cmd.AppendDesc ("Prints a list of registered extensible applications.");
commands.Add (cmd);
cat = "Debug Commands";
cmd = new SetupCommand (cat, "dump-file", null, new SetupCommandHandler (DumpRegistryFile));
cmd.Description = "Prints the contents of a registry file.";
cmd.Usage = "<file-path>";
cmd.AppendDesc ("Prints the contents of a registry file for debugging.");
commands.Add (cmd);
}
}
class SetupCommand
{
string usage;
public SetupCommand (string cat, string cmd, string shortCmd, SetupCommandHandler handler)
{
Category = cat;
Command = cmd;
ShortCommand = shortCmd;
Handler = handler;
}
public void AppendDesc (string s)
{
LongDescription += s + " ";
}
public string Category;
public string Command;
public string ShortCommand;
public SetupCommandHandler Handler;
public string Usage {
get { return usage != null ? Command + " " + usage : Command; }
set { usage = value; }
}
public string CommandDesc {
get {
if (ShortCommand != null && ShortCommand.Length > 0)
return Command + " (" + ShortCommand + ")";
else
return Command;
}
}
public string Description = "";
public string LongDescription = "";
}
/// <summary>
/// A command handler
/// </summary>
public delegate void SetupCommandHandler (string[] args);
}
| |
using System;
using System.Globalization;
using System.Collections.Generic;
using Sasoma.Utils;
using Sasoma.Microdata.Interfaces;
using Sasoma.Languages.Core;
using Sasoma.Microdata.Properties;
namespace Sasoma.Microdata.Types
{
/// <summary>
/// A golf course.
/// </summary>
public class GolfCourse_Core : TypeCore, ISportsActivityLocation
{
public GolfCourse_Core()
{
this._TypeId = 115;
this._Id = "GolfCourse";
this._Schema_Org_Url = "http://schema.org/GolfCourse";
string label = "";
GetLabel(out label, "GolfCourse", typeof(GolfCourse_Core));
this._Label = label;
this._Ancestors = new int[]{266,193,155,246};
this._SubTypes = new int[0];
this._SuperTypes = new int[]{246};
this._Properties = new int[]{67,108,143,229,5,10,49,85,91,98,115,135,159,199,196,47,75,77,94,95,130,137,36,60,152,156,167};
}
/// <summary>
/// Physical address of the item.
/// </summary>
private Address_Core address;
public Address_Core Address
{
get
{
return address;
}
set
{
address = value;
SetPropertyInstance(address);
}
}
/// <summary>
/// The overall rating, based on a collection of reviews or ratings, of the item.
/// </summary>
private Properties.AggregateRating_Core aggregateRating;
public Properties.AggregateRating_Core AggregateRating
{
get
{
return aggregateRating;
}
set
{
aggregateRating = value;
SetPropertyInstance(aggregateRating);
}
}
/// <summary>
/// The larger organization that this local business is a branch of, if any.
/// </summary>
private BranchOf_Core branchOf;
public BranchOf_Core BranchOf
{
get
{
return branchOf;
}
set
{
branchOf = value;
SetPropertyInstance(branchOf);
}
}
/// <summary>
/// A contact point for a person or organization.
/// </summary>
private ContactPoints_Core contactPoints;
public ContactPoints_Core ContactPoints
{
get
{
return contactPoints;
}
set
{
contactPoints = value;
SetPropertyInstance(contactPoints);
}
}
/// <summary>
/// The basic containment relation between places.
/// </summary>
private ContainedIn_Core containedIn;
public ContainedIn_Core ContainedIn
{
get
{
return containedIn;
}
set
{
containedIn = value;
SetPropertyInstance(containedIn);
}
}
/// <summary>
/// The currency accepted (in <a href=\http://en.wikipedia.org/wiki/ISO_4217\ target=\new\>ISO 4217 currency format</a>).
/// </summary>
private CurrenciesAccepted_Core currenciesAccepted;
public CurrenciesAccepted_Core CurrenciesAccepted
{
get
{
return currenciesAccepted;
}
set
{
currenciesAccepted = value;
SetPropertyInstance(currenciesAccepted);
}
}
/// <summary>
/// A short description of the item.
/// </summary>
private Description_Core description;
public Description_Core Description
{
get
{
return description;
}
set
{
description = value;
SetPropertyInstance(description);
}
}
/// <summary>
/// Email address.
/// </summary>
private Email_Core email;
public Email_Core Email
{
get
{
return email;
}
set
{
email = value;
SetPropertyInstance(email);
}
}
/// <summary>
/// People working for this organization.
/// </summary>
private Employees_Core employees;
public Employees_Core Employees
{
get
{
return employees;
}
set
{
employees = value;
SetPropertyInstance(employees);
}
}
/// <summary>
/// Upcoming or past events associated with this place or organization.
/// </summary>
private Events_Core events;
public Events_Core Events
{
get
{
return events;
}
set
{
events = value;
SetPropertyInstance(events);
}
}
/// <summary>
/// The fax number.
/// </summary>
private FaxNumber_Core faxNumber;
public FaxNumber_Core FaxNumber
{
get
{
return faxNumber;
}
set
{
faxNumber = value;
SetPropertyInstance(faxNumber);
}
}
/// <summary>
/// A person who founded this organization.
/// </summary>
private Founders_Core founders;
public Founders_Core Founders
{
get
{
return founders;
}
set
{
founders = value;
SetPropertyInstance(founders);
}
}
/// <summary>
/// The date that this organization was founded.
/// </summary>
private FoundingDate_Core foundingDate;
public FoundingDate_Core FoundingDate
{
get
{
return foundingDate;
}
set
{
foundingDate = value;
SetPropertyInstance(foundingDate);
}
}
/// <summary>
/// The geo coordinates of the place.
/// </summary>
private Geo_Core geo;
public Geo_Core Geo
{
get
{
return geo;
}
set
{
geo = value;
SetPropertyInstance(geo);
}
}
/// <summary>
/// URL of an image of the item.
/// </summary>
private Image_Core image;
public Image_Core Image
{
get
{
return image;
}
set
{
image = value;
SetPropertyInstance(image);
}
}
/// <summary>
/// A count of a specific user interactions with this item\u2014for example, <code>20 UserLikes</code>, <code>5 UserComments</code>, or <code>300 UserDownloads</code>. The user interaction type should be one of the sub types of <a href=\http://schema.org/UserInteraction\>UserInteraction</a>.
/// </summary>
private InteractionCount_Core interactionCount;
public InteractionCount_Core InteractionCount
{
get
{
return interactionCount;
}
set
{
interactionCount = value;
SetPropertyInstance(interactionCount);
}
}
/// <summary>
/// The location of the event or organization.
/// </summary>
private Location_Core location;
public Location_Core Location
{
get
{
return location;
}
set
{
location = value;
SetPropertyInstance(location);
}
}
/// <summary>
/// A URL to a map of the place.
/// </summary>
private Maps_Core maps;
public Maps_Core Maps
{
get
{
return maps;
}
set
{
maps = value;
SetPropertyInstance(maps);
}
}
/// <summary>
/// A member of this organization.
/// </summary>
private Members_Core members;
public Members_Core Members
{
get
{
return members;
}
set
{
members = value;
SetPropertyInstance(members);
}
}
/// <summary>
/// The name of the item.
/// </summary>
private Name_Core name;
public Name_Core Name
{
get
{
return name;
}
set
{
name = value;
SetPropertyInstance(name);
}
}
/// <summary>
/// The opening hours for a business. Opening hours can be specified as a weekly time range, starting with days, then times per day. Multiple days can be listed with commas ',' separating each day. Day or time ranges are specified using a hyphen '-'.<br/>- Days are specified using the following two-letter combinations: <code>Mo</code>, <code>Tu</code>, <code>We</code>, <code>Th</code>, <code>Fr</code>, <code>Sa</code>, <code>Su</code>.<br/>- Times are specified using 24:00 time. For example, 3pm is specified as <code>15:00</code>. <br/>- Here is an example: <code><time itemprop=\openingHours\ datetime=\Tu,Th 16:00-20:00\>Tuesdays and Thursdays 4-8pm</time></code>. <br/>- If a business is open 7 days a week, then it can be specified as <code><time itemprop=\openingHours\ datetime=\Mo-Su\>Monday through Sunday, all day</time></code>.
/// </summary>
private OpeningHours_Core openingHours;
public OpeningHours_Core OpeningHours
{
get
{
return openingHours;
}
set
{
openingHours = value;
SetPropertyInstance(openingHours);
}
}
/// <summary>
/// Cash, credit card, etc.
/// </summary>
private PaymentAccepted_Core paymentAccepted;
public PaymentAccepted_Core PaymentAccepted
{
get
{
return paymentAccepted;
}
set
{
paymentAccepted = value;
SetPropertyInstance(paymentAccepted);
}
}
/// <summary>
/// Photographs of this place.
/// </summary>
private Photos_Core photos;
public Photos_Core Photos
{
get
{
return photos;
}
set
{
photos = value;
SetPropertyInstance(photos);
}
}
/// <summary>
/// The price range of the business, for example <code>$$$</code>.
/// </summary>
private PriceRange_Core priceRange;
public PriceRange_Core PriceRange
{
get
{
return priceRange;
}
set
{
priceRange = value;
SetPropertyInstance(priceRange);
}
}
/// <summary>
/// Review of the item.
/// </summary>
private Reviews_Core reviews;
public Reviews_Core Reviews
{
get
{
return reviews;
}
set
{
reviews = value;
SetPropertyInstance(reviews);
}
}
/// <summary>
/// The telephone number.
/// </summary>
private Telephone_Core telephone;
public Telephone_Core Telephone
{
get
{
return telephone;
}
set
{
telephone = value;
SetPropertyInstance(telephone);
}
}
/// <summary>
/// URL of the item.
/// </summary>
private Properties.URL_Core uRL;
public Properties.URL_Core URL
{
get
{
return uRL;
}
set
{
uRL = value;
SetPropertyInstance(uRL);
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.